eswardivi commited on
Commit
71ff1f9
·
1 Parent(s): 61274f0

Create New File

Browse files
Files changed (1) hide show
  1. app.py +289 -0
app.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn import datasets, ensemble
2
+ from sklearn.inspection import permutation_importance
3
+ from sklearn.metrics import mean_squared_error
4
+ from sklearn.model_selection import train_test_split
5
+ import plotly.graph_objs as go
6
+ import numpy as np
7
+ import plotly.express as px
8
+ import pandas as pd
9
+
10
+
11
+ import gradio as gr
12
+
13
+
14
+ diabetes = datasets.load_diabetes(as_frame=True)
15
+ X, y = diabetes.data, diabetes.target
16
+
17
+
18
+ def display_table(row_number):
19
+ X, y = diabetes.data, diabetes.target
20
+ XX = pd.concat([X, y], axis=1)
21
+ temp_df = XX[row_number : row_number + 15]
22
+ Statement = f"Displayed Rows From Row Number {row_number} to {row_number+15}"
23
+ return Statement, temp_df
24
+
25
+
26
+ def train_model(
27
+ test_split,
28
+ learning_rate,
29
+ n_estimators,
30
+ max_depth,
31
+ min_samples_split,
32
+ loss,
33
+ duration,
34
+ ):
35
+ X, y = diabetes.data, diabetes.target
36
+ X_train, X_test, y_train, y_test = train_test_split(
37
+ X, y, test_size=test_split, random_state=42
38
+ )
39
+ params = {
40
+ "n_estimators": n_estimators,
41
+ "max_depth": max_depth,
42
+ "min_samples_split": min_samples_split,
43
+ "learning_rate": learning_rate,
44
+ "loss": loss,
45
+ }
46
+ global reg
47
+ reg = ensemble.GradientBoostingRegressor(**params)
48
+ reg.fit(X_train, y_train)
49
+
50
+ mse = mean_squared_error(y_test, reg.predict(X_test))
51
+
52
+ x = np.arange(params["n_estimators"]) + 1
53
+ train_score = reg.train_score_
54
+ test_score = np.zeros((params["n_estimators"],), dtype=np.float64)
55
+ for i, y_pred in enumerate(reg.staged_predict(X_test)):
56
+ test_score[i] = mean_squared_error(y_test, y_pred)
57
+
58
+ test_score = test_score
59
+
60
+ fig = go.Figure()
61
+
62
+ fig.add_trace(
63
+ go.Scatter(
64
+ x=x,
65
+ y=train_score,
66
+ mode="lines",
67
+ name="Training Set Deviance",
68
+ line=dict(color="blue"),
69
+ )
70
+ )
71
+ fig.add_trace(
72
+ go.Scatter(
73
+ x=x,
74
+ y=test_score,
75
+ mode="lines",
76
+ name="Test Set Deviance",
77
+ line=dict(color="red"),
78
+ )
79
+ )
80
+
81
+ frames = [
82
+ go.Frame(
83
+ data=[
84
+ go.Scatter(
85
+ x=x[: k + 1],
86
+ y=train_score[: k + 1],
87
+ mode="lines",
88
+ line=dict(color="blue"),
89
+ ),
90
+ go.Scatter(
91
+ x=x[: k + 1],
92
+ y=test_score[: k + 1],
93
+ mode="lines",
94
+ line=dict(color="red"),
95
+ ),
96
+ ],
97
+ name=f"frame{k}",
98
+ )
99
+ for k in range(1, len(x))
100
+ ]
101
+
102
+ fig.frames = frames
103
+
104
+ fig.update_layout(
105
+ title="Deviance",
106
+ xaxis_title="Boosting Iterations",
107
+ yaxis_title="Deviance",
108
+ legend=dict(x=0, y=1),
109
+ updatemenus=[
110
+ dict(
111
+ type="buttons",
112
+ showactive=False,
113
+ direction="right",
114
+ pad={"r": 10},
115
+ buttons=[
116
+ dict(
117
+ label="Play",
118
+ method="animate",
119
+ args=[
120
+ None,
121
+ dict(
122
+ frame=dict(duration=duration, redraw=True),
123
+ fromcurrent=True,
124
+ transition=dict(duration=0),
125
+ ),
126
+ ],
127
+ ),
128
+ dict(
129
+ label="Pause",
130
+ method="animate",
131
+ args=[
132
+ [None],
133
+ dict(
134
+ frame=dict(duration=0, redraw=False),
135
+ mode="immediate",
136
+ transition=dict(duration=0),
137
+ ),
138
+ ],
139
+ ),
140
+ ],
141
+ x=0.5,
142
+ y=-0.2,
143
+ )
144
+ ],
145
+ )
146
+
147
+ return fig, mse
148
+
149
+
150
+ def Plot_featue_importance(test_split):
151
+ try:
152
+ feature_importance = reg.feature_importances_
153
+ except:
154
+ # return blank figures
155
+ fig = go.Figure()
156
+ fig.update_layout(title="Train Your Model to See Plots")
157
+ return fig, fig
158
+
159
+ sorted_idx = np.argsort(feature_importance)
160
+
161
+ fig = px.bar(
162
+ pd.DataFrame(
163
+ {
164
+ "Importance": feature_importance[sorted_idx],
165
+ "Feature": np.array(diabetes.feature_names)[sorted_idx],
166
+ }
167
+ ),
168
+ x="Importance",
169
+ y="Feature",
170
+ orientation="h",
171
+ title="Feature Importance (MDI)",
172
+ )
173
+
174
+ X, y = diabetes.data, diabetes.target
175
+ X_train, X_test, y_train, y_test = train_test_split(
176
+ X, y, test_size=test_split, random_state=42
177
+ )
178
+ result = permutation_importance(
179
+ reg, X_test, y_test, n_repeats=10, random_state=42, n_jobs=2
180
+ )
181
+
182
+ fig1 = px.box(
183
+ pd.DataFrame(result.importances.T, columns=diabetes.feature_names),
184
+ title="Permutation Importance (test set)",
185
+ )
186
+
187
+ return fig, fig1
188
+
189
+
190
+ with gr.Blocks() as demo:
191
+ gr.Markdown("# Gradient Boosting regression")
192
+ gr.Markdown(
193
+ "Demo is Based on [Gradient Boosting regression](https://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_regression.html) Example.This example demonstrates Gradient Boosting to produce a predictive model from an ensemble of weak predictive models. Gradient boosting can be used for regression and classification problems. Here, we will train a model to tackle a diabetes regression task."
194
+ )
195
+
196
+ with gr.Tab("Data"):
197
+ gr.Markdown("## Below is the Diabetes Dataset used in this Demo")
198
+ gr.Markdown("### Feel free to change the number of rows to display")
199
+ gr.Markdown(
200
+ "The diabetes dataset consists of ten baseline variables, age, sex, body mass index (BMI), average blood pressure (BP), and six blood serum measurements for 442 diabetes patients. The target variable is a quantitative measure of disease progression one year after baseline."
201
+ )
202
+ total_rows = X.shape[0]
203
+ rows_number = gr.Slider(
204
+ 0, total_rows, label="Displaying Rows", value=15, step=15
205
+ )
206
+
207
+ rows_number.change(
208
+ fn=display_table,
209
+ inputs=[rows_number],
210
+ outputs=[gr.Text(label="Rows Information"), gr.DataFrame()],
211
+ )
212
+
213
+ with gr.Tab("Trian Your Model"):
214
+ gr.Markdown(
215
+ "# Play with the parameters to see how the model Performance changes"
216
+ )
217
+
218
+ gr.Markdown(
219
+ """
220
+ ### `Number of Estimators` : the number of boosting stages that will be performed. Later, we will plot deviance against boosting iterations.
221
+
222
+ ### `Max Depth` : limits the number of nodes in the tree. The best value depends on the interaction of the input variables.
223
+
224
+ ### `Min Samples Split` : the minimum number of samples required to split an internal node.
225
+
226
+ ### `learning_rate` : how much the contribution of each tree will shrink.
227
+
228
+ ### `loss` : loss function to optimize.
229
+
230
+ ### `Test Split` : the percentage of the dataset to include in the test split.
231
+
232
+ ### `Animation Speed for Deviance Plot` : the duration of the animation of Deviation Plot.
233
+ """
234
+ )
235
+ with gr.Row():
236
+ test_split = gr.Slider(0.1, 0.9, label="Test Split", value=0.2, step=0.1)
237
+ learning_rate = gr.Slider(
238
+ 0.01, 0.5, label="Learning Rate", value=0.1, step=0.01
239
+ )
240
+ n_estimators = gr.Slider(
241
+ 10, 1000, label="Number of Estimators", value=100, step=10
242
+ )
243
+ max_depth = gr.Slider(1, 10, label="Max Depth", value=3, step=1)
244
+ min_samples_split = gr.Slider(
245
+ 2, 10, label="Min Samples Split", value=2, step=1
246
+ )
247
+ loss = gr.Dropdown(
248
+ ["squared_error", "absolute_error", "huber", "quantile"],
249
+ label="Loss",
250
+ value="squared_error",
251
+ )
252
+
253
+ duration = gr.Slider(
254
+ 0, 100, label="Animation Speed for Deviance Plot", value=25, step=10
255
+ )
256
+
257
+ model_btn = gr.Button("Train Model")
258
+ gr.Markdown(
259
+ "### Finally, we will visualize the results. To do that we will first compute the test set deviance and then plot it against boosting iterations."
260
+ )
261
+ model_btn.click(
262
+ fn=train_model,
263
+ inputs=[
264
+ test_split,
265
+ learning_rate,
266
+ n_estimators,
267
+ max_depth,
268
+ min_samples_split,
269
+ loss,
270
+ duration,
271
+ ],
272
+ outputs=[gr.Plot(), gr.Text(label="MSE")],
273
+ )
274
+
275
+ with gr.Tab("Feature Importance"):
276
+ gr.Markdown("## Feature Importance (MDI) and Permutation Importance (test set)")
277
+ gr.Markdown(
278
+ "For this example, the impurity-based and permutation methods identify the same 2 strongly predictive features but not in the same order. The third most predictive feature, “bp”, is also the same for the 2 methods. The remaining features are less predictive and the error bars of the permutation plot show that they overlap with 0."
279
+ )
280
+ feat_imp_btn = gr.Button("Plot Feature Importance")
281
+ with gr.Row():
282
+ feat_imp_btn.click(
283
+ fn=Plot_featue_importance,
284
+ inputs=[test_split],
285
+ outputs=[gr.Plot(), gr.Plot()],
286
+ )
287
+
288
+
289
+ demo.launch()