Nsubuga commited on
Commit
4f14d68
·
verified ·
1 Parent(s): 58bd284

feat: added logging to dataidea

Browse files
Files changed (1) hide show
  1. app.py +180 -166
app.py CHANGED
@@ -1,167 +1,181 @@
1
- import gradio as gr
2
- import joblib
3
- import numpy as np
4
- import pandas as pd
5
- from sklearn.ensemble import RandomForestRegressor
6
- from sklearn.preprocessing import MinMaxScaler
7
-
8
- # Define the ScalableModel class
9
- class ScalableModel:
10
- def __init__(self, model, feature_scaler=None, target_scaler=None):
11
- self.model = model
12
- self.feature_scaler = feature_scaler if feature_scaler else MinMaxScaler()
13
- self.target_scaler = target_scaler if target_scaler else MinMaxScaler()
14
-
15
- def predict(self, X_test):
16
- X_test_scaled = self.feature_scaler.transform(X_test)
17
- predictions_scaled = self.model.predict(X_test_scaled).reshape(-1, 1)
18
- return self.target_scaler.inverse_transform(predictions_scaled).flatten()
19
-
20
- # Load the trained model and scalers
21
- xgboost_model = joblib.load("XGBoost_Model_v1.pkl") # Ensure the model is saved
22
-
23
-
24
- # Feature names (MUST match your training data exactly)
25
- feature_names = [
26
- 'garlic_kgs_organic_pesticides', #
27
- 'ginger_kgs_organic_pesticides', #
28
- 'plastic_tanks_120_ltrs_liquid_manure', #
29
- 'sacks_liquid_manure', #
30
- 'hoes_tools', #
31
- 'spades_tools', #
32
- 'pick_axes_tools', #
33
- 'forked_hoes_tools', #
34
- 'pangas_tools', #
35
- 'wheelbarrows_tools', #
36
- 'trowels_tools', #
37
- 'watering_cans_tools', #
38
- 'spray_pumps_tools', #
39
- 'Beans_seeds', #
40
- 'Maize_seeds', #
41
- 'Soyabean_seeds', #
42
- 'Gnuts_seeds', #
43
- 'Irish Potatoes_seeds', #
44
- # 'Cassava (bags)',
45
- # 'Mugavu tree seedlings',
46
- # 'Onions (Kg)_seeds',
47
- # 'Millet.1_seeds',
48
- 'GPS-Altitude',
49
- 'Land_size_agriculture',
50
- 'Time_to_collect_Water_for_Household_use_Minutes',
51
- 'Beans_total_yield', #
52
- 'Cassava_total_yield',
53
- 'Maize_total_yield',
54
- 'Sweet_potatoes_total_yield',
55
- 'Food_banana_total_yield',
56
- 'Coffee_total_yield'
57
- ]
58
-
59
-
60
- # Define prediction function
61
- def predict_agriculture_value(*features):
62
- input_data = np.array(features).reshape(1, -1)
63
- # Check if all input values are zero
64
- if np.all(input_data == 0):
65
- return 0.0 # Return zero directly
66
-
67
- df_input = pd.DataFrame(input_data, columns=feature_names)
68
-
69
- # Use the model's built-in predict function
70
- prediction = xgboost_model.predict(df_input)
71
-
72
- return float(prediction[0])
73
-
74
- # Create Gradio interface
75
- input_components = [gr.Number(label=feature) for feature in feature_names]
76
-
77
- iface = gr.Interface(
78
- fn=predict_agriculture_value,
79
- inputs=input_components,
80
- outputs=gr.Number(label="Predicted Agriculture Value (USD)"),
81
- title="Agriculture Value Prediction",
82
- description="Enter input values to predict Agriculture Value (USD) using the trained XGBoost model."
83
- )
84
-
85
- # Run the Gradio app
86
- if __name__ == "__main__":
87
- iface.launch()
88
-
89
-
90
- # # XGBoost Model
91
-
92
- # import gradio as gr
93
- # import joblib
94
- # import numpy as np
95
- # import pandas as pd
96
- # from xgboost import XGBRegressor
97
- # from sklearn.preprocessing import MinMaxScaler
98
-
99
- # # Define ScalableModel class
100
- # class ScalableModel:
101
- # def __init__(self, model, feature_scaler=None, target_scaler=None):
102
- # self.model = model
103
- # self.feature_scaler = feature_scaler if feature_scaler else MinMaxScaler()
104
- # self.target_scaler = target_scaler if target_scaler else MinMaxScaler()
105
-
106
- # def fit(self, X_train, y_train):
107
- # self.feature_scaler.fit(X_train)
108
- # self.target_scaler.fit(y_train.values.reshape(-1, 1))
109
- # self.model.fit(self.feature_scaler.transform(X_train), self.target_scaler.transform(y_train.values.reshape(-1, 1)).flatten())
110
-
111
- # def predict(self, X_test):
112
- # X_test_scaled = self.feature_scaler.transform(X_test)
113
- # predictions_scaled = self.model.predict(X_test_scaled)
114
- # return self.target_scaler.inverse_transform(predictions_scaled.reshape(-1, 1)).flatten()
115
-
116
- # # Load the trained XGBoost model
117
- # xgboost_model = joblib.load("XGBoost_Model_v1.pkl")
118
-
119
- # # Load the scalers
120
- # scalers = joblib.load("Scalers_XGBoost.pkl")
121
- # feature_scaler = scalers["feature_scaler"]
122
- # target_scaler = scalers["target_scaler"]
123
-
124
- # # Define feature names (must match training data)
125
- # feature_names = [
126
- # 'garlic_kgs_organic_pesticides', 'ginger_kgs_organic_pesticides',
127
- # 'plastic_tanks_120_ltrs_liquid_manure', 'sacks_liquid_manure',
128
- # 'hoes_tools', 'spades_tools', 'pick_axes_tools', 'forked_hoes_tools',
129
- # 'pangas_tools', 'wheelbarrows_tools', 'trowels_tools', 'watering_cans_tools',
130
- # 'spray_pumps_tools', 'Beans_seeds', 'Maize_seeds', 'Soyabean_seeds',
131
- # 'Gnuts_seeds', 'Irish Potatoes_seeds', 'GPS-Altitude', 'Land_size_agriculture',
132
- # 'Time_to_collect_Water_for_Household_use_Minutes', 'Beans_total_yield',
133
- # 'Cassava_total_yield', 'Maize_total_yield', 'Sweet_potatoes_total_yield',
134
- # 'Food_banana_total_yield', 'Coffee_total_yield'
135
- # ]
136
-
137
- # # Define prediction function
138
- # def predict_agriculture_value(*features):
139
- # input_data = np.array(features).reshape(1, -1)
140
-
141
- # # Scale the input features
142
- # input_data_scaled = feature_scaler.transform(input_data)
143
-
144
- # # Get scaled predictions
145
- # prediction_scaled = xgboost_model.predict(input_data_scaled).reshape(-1, 1)
146
-
147
- # # Inverse transform to get predictions in original scale
148
- # prediction = target_scaler.inverse_transform(prediction_scaled).flatten()
149
-
150
- # return float(prediction[0])
151
-
152
- # # Create Gradio interface
153
- # input_components = [gr.Number(label=feature) for feature in feature_names]
154
-
155
- # iface = gr.Interface(
156
- # fn=predict_agriculture_value,
157
- # inputs=input_components,
158
- # outputs=gr.Number(label="Predicted Agriculture Value (USD)"),
159
- # title="Agriculture Value Prediction",
160
- # description="Enter input values to predict Agriculture Value (USD) using the trained XGBoost model."
161
- # )
162
-
163
- # # Run the Gradio app
164
- # if __name__ == "__main__":
165
- # iface.launch()
166
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  # print("Expected feature order:", feature_names)
 
1
+ import gradio as gr
2
+ import joblib
3
+ import numpy as np
4
+ import pandas as pd
5
+ from sklearn.ensemble import RandomForestRegressor
6
+ from sklearn.preprocessing import MinMaxScaler
7
+ from dataidea.logger import event_log
8
+
9
+ # Define the ScalableModel class
10
+ class ScalableModel:
11
+ def __init__(self, model, feature_scaler=None, target_scaler=None):
12
+ self.model = model
13
+ self.feature_scaler = feature_scaler if feature_scaler else MinMaxScaler()
14
+ self.target_scaler = target_scaler if target_scaler else MinMaxScaler()
15
+
16
+ def predict(self, X_test):
17
+ X_test_scaled = self.feature_scaler.transform(X_test)
18
+ predictions_scaled = self.model.predict(X_test_scaled).reshape(-1, 1)
19
+ return self.target_scaler.inverse_transform(predictions_scaled).flatten()
20
+
21
+ # Load the trained model and scalers
22
+ xgboost_model = joblib.load("XGBoost_Model_v1.pkl") # Ensure the model is saved
23
+
24
+
25
+ # Feature names (MUST match your training data exactly)
26
+ feature_names = [
27
+ 'garlic_kgs_organic_pesticides', #
28
+ 'ginger_kgs_organic_pesticides', #
29
+ 'plastic_tanks_120_ltrs_liquid_manure', #
30
+ 'sacks_liquid_manure', #
31
+ 'hoes_tools', #
32
+ 'spades_tools', #
33
+ 'pick_axes_tools', #
34
+ 'forked_hoes_tools', #
35
+ 'pangas_tools', #
36
+ 'wheelbarrows_tools', #
37
+ 'trowels_tools', #
38
+ 'watering_cans_tools', #
39
+ 'spray_pumps_tools', #
40
+ 'Beans_seeds', #
41
+ 'Maize_seeds', #
42
+ 'Soyabean_seeds', #
43
+ 'Gnuts_seeds', #
44
+ 'Irish Potatoes_seeds', #
45
+ # 'Cassava (bags)',
46
+ # 'Mugavu tree seedlings',
47
+ # 'Onions (Kg)_seeds',
48
+ # 'Millet.1_seeds',
49
+ 'GPS-Altitude',
50
+ 'Land_size_agriculture',
51
+ 'Time_to_collect_Water_for_Household_use_Minutes',
52
+ 'Beans_total_yield', #
53
+ 'Cassava_total_yield',
54
+ 'Maize_total_yield',
55
+ 'Sweet_potatoes_total_yield',
56
+ 'Food_banana_total_yield',
57
+ 'Coffee_total_yield'
58
+ ]
59
+
60
+
61
+ # Define prediction function
62
+ def predict_agriculture_value(*features):
63
+ input_data = np.array(features).reshape(1, -1)
64
+ # Check if all input values are zero
65
+ if np.all(input_data == 0):
66
+ return 0.0 # Return zero directly
67
+
68
+ df_input = pd.DataFrame(input_data, columns=feature_names)
69
+
70
+ # Use the model's built-in predict function
71
+ prediction = xgboost_model.predict(df_input)
72
+
73
+ event_log({
74
+ 'api_key': '1968c15b-ed45-4a2d-a7dc-90ce623324b8',
75
+ 'project_name': 'IDS',
76
+ 'user_id': 'Emmanuel Nsubuga',
77
+ 'message': 'Prediction Log',
78
+ 'level': 'info',
79
+ 'metadata': {
80
+ 'input_data': input_data.tolist(),
81
+ 'prediction': prediction.tolist(),
82
+ 'source': 'gradio'
83
+ }
84
+ })
85
+
86
+ return float(prediction[0])
87
+
88
+ # Create Gradio interface
89
+ input_components = [gr.Number(label=feature) for feature in feature_names]
90
+
91
+ iface = gr.Interface(
92
+ fn=predict_agriculture_value,
93
+ inputs=input_components,
94
+ outputs=gr.Number(label="Predicted Agriculture Value (USD)"),
95
+ title="Agriculture Value Prediction",
96
+ description="Enter input values to predict Agriculture Value (USD) using the trained XGBoost model."
97
+ )
98
+
99
+ # Run the Gradio app
100
+ if __name__ == "__main__":
101
+ iface.launch()
102
+
103
+
104
+ # # XGBoost Model
105
+
106
+ # import gradio as gr
107
+ # import joblib
108
+ # import numpy as np
109
+ # import pandas as pd
110
+ # from xgboost import XGBRegressor
111
+ # from sklearn.preprocessing import MinMaxScaler
112
+
113
+ # # Define ScalableModel class
114
+ # class ScalableModel:
115
+ # def __init__(self, model, feature_scaler=None, target_scaler=None):
116
+ # self.model = model
117
+ # self.feature_scaler = feature_scaler if feature_scaler else MinMaxScaler()
118
+ # self.target_scaler = target_scaler if target_scaler else MinMaxScaler()
119
+
120
+ # def fit(self, X_train, y_train):
121
+ # self.feature_scaler.fit(X_train)
122
+ # self.target_scaler.fit(y_train.values.reshape(-1, 1))
123
+ # self.model.fit(self.feature_scaler.transform(X_train), self.target_scaler.transform(y_train.values.reshape(-1, 1)).flatten())
124
+
125
+ # def predict(self, X_test):
126
+ # X_test_scaled = self.feature_scaler.transform(X_test)
127
+ # predictions_scaled = self.model.predict(X_test_scaled)
128
+ # return self.target_scaler.inverse_transform(predictions_scaled.reshape(-1, 1)).flatten()
129
+
130
+ # # Load the trained XGBoost model
131
+ # xgboost_model = joblib.load("XGBoost_Model_v1.pkl")
132
+
133
+ # # Load the scalers
134
+ # scalers = joblib.load("Scalers_XGBoost.pkl")
135
+ # feature_scaler = scalers["feature_scaler"]
136
+ # target_scaler = scalers["target_scaler"]
137
+
138
+ # # Define feature names (must match training data)
139
+ # feature_names = [
140
+ # 'garlic_kgs_organic_pesticides', 'ginger_kgs_organic_pesticides',
141
+ # 'plastic_tanks_120_ltrs_liquid_manure', 'sacks_liquid_manure',
142
+ # 'hoes_tools', 'spades_tools', 'pick_axes_tools', 'forked_hoes_tools',
143
+ # 'pangas_tools', 'wheelbarrows_tools', 'trowels_tools', 'watering_cans_tools',
144
+ # 'spray_pumps_tools', 'Beans_seeds', 'Maize_seeds', 'Soyabean_seeds',
145
+ # 'Gnuts_seeds', 'Irish Potatoes_seeds', 'GPS-Altitude', 'Land_size_agriculture',
146
+ # 'Time_to_collect_Water_for_Household_use_Minutes', 'Beans_total_yield',
147
+ # 'Cassava_total_yield', 'Maize_total_yield', 'Sweet_potatoes_total_yield',
148
+ # 'Food_banana_total_yield', 'Coffee_total_yield'
149
+ # ]
150
+
151
+ # # Define prediction function
152
+ # def predict_agriculture_value(*features):
153
+ # input_data = np.array(features).reshape(1, -1)
154
+
155
+ # # Scale the input features
156
+ # input_data_scaled = feature_scaler.transform(input_data)
157
+
158
+ # # Get scaled predictions
159
+ # prediction_scaled = xgboost_model.predict(input_data_scaled).reshape(-1, 1)
160
+
161
+ # # Inverse transform to get predictions in original scale
162
+ # prediction = target_scaler.inverse_transform(prediction_scaled).flatten()
163
+
164
+ # return float(prediction[0])
165
+
166
+ # # Create Gradio interface
167
+ # input_components = [gr.Number(label=feature) for feature in feature_names]
168
+
169
+ # iface = gr.Interface(
170
+ # fn=predict_agriculture_value,
171
+ # inputs=input_components,
172
+ # outputs=gr.Number(label="Predicted Agriculture Value (USD)"),
173
+ # title="Agriculture Value Prediction",
174
+ # description="Enter input values to predict Agriculture Value (USD) using the trained XGBoost model."
175
+ # )
176
+
177
+ # # Run the Gradio app
178
+ # if __name__ == "__main__":
179
+ # iface.launch()
180
+
181
  # print("Expected feature order:", feature_names)