Mehak-Mazhar commited on
Commit
66c203c
·
verified ·
1 Parent(s): 90b6905

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +232 -25
app.py CHANGED
@@ -1,36 +1,243 @@
 
 
 
 
1
  import pandas as pd
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
 
4
- # File loading function
5
- def load_csv(file_path):
6
  try:
7
- return pd.read_csv(file_path), None
8
- except Exception as e_csv:
9
- try:
10
- return pd.read_excel(file_path), None
11
- except Exception as e_xls:
12
- return None, f"Failed to read file. CSV error: {e_csv} | Excel error: {e_xls}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # Upload handler
 
 
 
 
15
  def on_upload(file):
16
- if not file:
17
- return "No file uploaded", pd.DataFrame()
18
-
19
- df, err = load_csv(file.name)
20
  if err:
21
- return f"Error: {err}", pd.DataFrame()
22
-
23
- return f"Loaded {len(df)} rows, {len(df.columns)} columns", df.head(20)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- # Gradio UI
26
- with gr.Blocks() as demo:
27
- gr.Markdown("## 📂 CSV/Excel File Upload & Preview")
 
 
 
28
 
29
- file_input = gr.File(label="Upload CSV or Excel File", file_types=[".csv", ".xlsx"], type="file")
30
- status_output = gr.Textbox(label="Status")
31
- preview_output = gr.DataFrame(label="Preview (first 20 rows)")
32
 
33
- file_input.change(fn=on_upload, inputs=file_input, outputs=[status_output, preview_output])
34
 
35
- if __name__ == "__main__":
36
- demo.launch()
 
1
+ # Gradio app: CSV -> Preprocessing -> Logistic Regression with hyperparameter tuning
2
+ # Save this file as gradio_logreg_app.py and run: python gradio_logreg_app.py
3
+
4
+ import io
5
  import pandas as pd
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ from sklearn.model_selection import train_test_split, GridSearchCV
9
+ from sklearn.preprocessing import StandardScaler, OneHotEncoder
10
+ from sklearn.impute import SimpleImputer
11
+ from sklearn.compose import ColumnTransformer
12
+ from sklearn.pipeline import Pipeline
13
+ from sklearn.linear_model import LogisticRegression
14
+ from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_auc_score
15
  import gradio as gr
16
 
17
+
18
+ def load_csv(file_obj):
19
  try:
20
+ # Case 1: File path string (Gradio sometimes gives this)
21
+ if isinstance(file_obj, str):
22
+ try:
23
+ return pd.read_csv(file_obj), None
24
+ except Exception as e_csv:
25
+ try:
26
+ return pd.read_excel(file_obj), None
27
+ except Exception as e_xls:
28
+ return None, f"Failed to read file from path. CSV error: {e_csv} / Excel error: {e_xls}"
29
+
30
+ # Case 2: File-like object
31
+ if hasattr(file_obj, "read"):
32
+ file_obj.seek(0)
33
+ try:
34
+ return pd.read_csv(file_obj), None
35
+ except Exception as e_csv:
36
+ file_obj.seek(0)
37
+ try:
38
+ return pd.read_excel(file_obj), None
39
+ except Exception as e_xls:
40
+ return None, f"Failed to read file object. CSV error: {e_csv} / Excel error: {e_xls}"
41
+
42
+ return None, "Unsupported file type."
43
 
44
+ except Exception as e:
45
+ return None, f"Unexpected error: {e}"
46
+
47
+
48
+ # Step 1: upload file -> return column choices
49
  def on_upload(file):
50
+ if file is None:
51
+ return gr.Dropdown.update(choices=[]), "No file uploaded", None
52
+ df, err = load_csv(file)
 
53
  if err:
54
+ return gr.Dropdown.update(choices=[]), f"Error: {err}", None
55
+ cols = df.columns.tolist()
56
+ return gr.Dropdown.update(choices=cols, value=cols[-1] if len(cols)>0 else None), f"Loaded {len(df)} rows, {len(cols)} columns", df
57
+
58
+
59
+ # Helper: build preprocessing + model pipeline
60
+ def build_pipeline(df, target_col, impute_strategy, apply_scaling, encode_categorical):
61
+ X = df.drop(columns=[target_col])
62
+ numeric_cols = X.select_dtypes(include=[np.number]).columns.tolist()
63
+ categorical_cols = X.select_dtypes(exclude=[np.number]).columns.tolist()
64
+
65
+ transformers = []
66
+ if numeric_cols:
67
+ num_transformers = []
68
+ if impute_strategy != 'none':
69
+ num_transformers.append(('imputer', SimpleImputer(strategy=impute_strategy)))
70
+ if apply_scaling:
71
+ num_transformers.append(('scaler', StandardScaler()))
72
+ if num_transformers:
73
+ from sklearn.pipeline import make_pipeline
74
+ transformers.append(('num', make_pipeline(*[t[1] for t in num_transformers]), numeric_cols))
75
+
76
+ if categorical_cols and encode_categorical:
77
+ cat_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='most_frequent')),
78
+ ('ohe', OneHotEncoder(handle_unknown='ignore', sparse=False))])
79
+ transformers.append(('cat', cat_transformer, categorical_cols))
80
+
81
+ if transformers:
82
+ preprocessor = ColumnTransformer(transformers=transformers, remainder='passthrough')
83
+ else:
84
+ preprocessor = 'passthrough'
85
+
86
+ pipe = Pipeline(steps=[('preproc', preprocessor), ('clf', LogisticRegression(max_iter=200))])
87
+ return pipe
88
+
89
+
90
+ # Training function
91
+ def train_model(df, target_col, test_size, random_state, impute_strategy, apply_scaling, encode_categorical,
92
+ use_grid, c_min, c_max, c_steps, penalties, solver, cv_folds, max_iter, n_jobs):
93
+ # Basic checks
94
+ if df is None:
95
+ return "No data loaded", None, None, None
96
+ if target_col not in df.columns:
97
+ return f"Target column '{target_col}' not found", None, None, None
98
+
99
+ # Drop rows where target is missing
100
+ data = df.copy()
101
+ data = data.dropna(subset=[target_col])
102
+
103
+ # If target is not numeric, try to encode it
104
+ y = data[target_col]
105
+ if y.dtype == object or y.dtype.name == 'category' or y.dtype == bool:
106
+ y = pd.factorize(y)[0]
107
+
108
+ X = data.drop(columns=[target_col])
109
+
110
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=random_state, stratify=y if len(np.unique(y))>1 else None)
111
+
112
+ pipe = build_pipeline(pd.concat([X_train, y_train], axis=1), target_col, impute_strategy, apply_scaling, encode_categorical)
113
+ pipe.named_steps['clf'].max_iter = max_iter
114
+
115
+ if use_grid:
116
+ # build param grid for C and penalty
117
+ C_values = np.linspace(c_min, c_max, int(max(1, c_steps)))
118
+ param_grid = {}
119
+ # penalty and solver interaction needs care
120
+ selected_penalties = penalties if len(penalties)>0 else ['l2']
121
+ param_grid['clf__C'] = C_values
122
+ param_grid['clf__penalty'] = selected_penalties
123
+ param_grid['clf__solver'] = [solver]
124
+
125
+ gs = GridSearchCV(pipe, param_grid, cv=cv_folds, n_jobs=n_jobs, scoring='accuracy')
126
+ gs.fit(X_train, y_train)
127
+ best = gs.best_estimator_
128
+ best_params = gs.best_params_
129
+ model = best
130
+ train_pred = model.predict(X_train)
131
+ test_pred = model.predict(X_test)
132
+ acc = accuracy_score(y_test, test_pred)
133
+ report = classification_report(y_test, test_pred)
134
+ cm = confusion_matrix(y_test, test_pred)
135
+ extra = f"Best params: {best_params}"
136
+ else:
137
+ # set hyperparams from UI
138
+ clf = pipe.named_steps['clf']
139
+ try:
140
+ clf.set_params(C=float((c_min+c_max)/2), penalty=penalties[0] if penalties else 'l2', solver=solver)
141
+ except Exception:
142
+ # fallback: set only C
143
+ clf.set_params(C=float((c_min+c_max)/2))
144
+
145
+ pipe.fit(X_train, y_train)
146
+ model = pipe
147
+ train_pred = model.predict(X_train)
148
+ test_pred = model.predict(X_test)
149
+ acc = accuracy_score(y_test, test_pred)
150
+ report = classification_report(y_test, test_pred)
151
+ cm = confusion_matrix(y_test, test_pred)
152
+ extra = "Trained with provided hyperparameters"
153
+
154
+ # Plot confusion matrix
155
+ fig, ax = plt.subplots(figsize=(4,4))
156
+ ax.imshow(cm, interpolation='nearest')
157
+ ax.set_title('Confusion matrix')
158
+ ax.set_xlabel('Predicted')
159
+ ax.set_ylabel('Actual')
160
+ for i in range(cm.shape[0]):
161
+ for j in range(cm.shape[1]):
162
+ ax.text(j, i, str(cm[i, j]), ha='center', va='center', color='white' if cm[i,j]>cm.max()/2 else 'black')
163
+ plt.tight_layout()
164
+
165
+ return f"Accuracy: {acc:.4f}\n{extra}", fig, report, model
166
+
167
+
168
+ # Build Gradio interface
169
+ with gr.Blocks(title="CSV -> Logistic Regression (with tuning)") as demo:
170
+ gr.Markdown("""
171
+ # CSV → Preprocessing → Logistic Regression
172
+ 1. Upload a CSV or Excel file.
173
+ 2. Select the target (label) column.
174
+ 3. Choose preprocessing options and hyperparameters.
175
+ 4. Train model and view accuracy, confusion matrix and classification report.
176
+ """)
177
+
178
+ with gr.Row():
179
+ with gr.Column(scale=1):
180
+ file_input = gr.File(label="Upload CSV/Excel file", file_types=['.csv', '.xls', '.xlsx'])
181
+ load_status = gr.Textbox(label="File status", interactive=False)
182
+ target_dropdown = gr.Dropdown(label="Select target column", choices=[], value=None)
183
+ preview_button = gr.Button("Preview data")
184
+ preview_output = gr.Dataframe(headers=None, interactive=False)
185
+
186
+ with gr.Column(scale=1):
187
+ gr.Markdown("**Preprocessing**")
188
+ impute_radio = gr.Radio(['mean','median','most_frequent','constant','none'], value='mean', label='Numeric imputation (if needed)')
189
+ scaler_checkbox = gr.Checkbox(label='Apply Standard Scaling', value=True)
190
+ encode_checkbox = gr.Checkbox(label='One-Hot Encode categorical', value=True)
191
+
192
+ gr.Markdown("**Train / Test & Randomness**")
193
+ test_size = gr.Slider(0.05, 0.5, value=0.2, step=0.05, label='Test size')
194
+ random_state = gr.Number(value=42, precision=0, label='Random state (int)')
195
+
196
+ gr.Markdown("**Logistic Regression hyperparams**")
197
+ use_grid = gr.Checkbox(label='Use GridSearchCV for hyperparameter tuning', value=True)
198
+ c_min = gr.Number(value=0.01, label='C (min)')
199
+ c_max = gr.Number(value=10.0, label='C (max)')
200
+ c_steps = gr.Slider(1, 20, value=5, step=1, label='C steps (grid size)')
201
+ penalties = gr.CheckboxGroup(['l1','l2','elasticnet','none'], label='Penalties to try (Grid only / or choose first)', value=['l2'])
202
+ solver = gr.Dropdown(['lbfgs','liblinear','saga','sag','newton-cg'], value='lbfgs', label='Solver')
203
+ max_iter = gr.Slider(50,1000,value=200,step=10,label='Max iterations')
204
+ cv_folds = gr.Slider(2,10,value=5,step=1,label='CV folds for GridSearch')
205
+ n_jobs = gr.Slider(1,8,value=1,step=1,label='n_jobs for GridSearch')
206
+
207
+ train_btn = gr.Button("Train model")
208
+
209
+ with gr.Row():
210
+ with gr.Column():
211
+ accuracy_text = gr.Textbox(label='Accuracy & notes', interactive=False)
212
+ conf_plot = gr.Plot(label='Confusion Matrix')
213
+ with gr.Column():
214
+ class_report = gr.Textbox(label='Classification report', interactive=False)
215
+ model_obj = gr.JSON(label='Trained model (sklearn pipeline as repr)')
216
+
217
+ # State to keep dataframe
218
+ df_state = gr.State()
219
+
220
+ # Wire upload -> get columns
221
+ file_input.change(fn=on_upload, inputs=[file_input], outputs=[target_dropdown, load_status, df_state])
222
+
223
+ def preview(df):
224
+ if df is None:
225
+ return pd.DataFrame()
226
+ return df.head(20)
227
+
228
+ preview_button.click(fn=preview, inputs=[df_state], outputs=[preview_output])
229
 
230
+ def do_train(df, target, test_size_val, rand_state, impute_s, scale_flag, encode_flag,
231
+ use_grid_flag, cmin, cmax, csteps, penalties_sel, solver_sel, cv_f, max_it, n_jobs_val):
232
+ msg, fig, report, model = train_model(df, target, test_size_val, int(rand_state), impute_s, scale_flag, encode_flag,
233
+ use_grid_flag, float(cmin), float(cmax), int(csteps), penalties_sel, solver_sel, int(cv_f), int(max_it), int(n_jobs_val))
234
+ model_repr = str(model)
235
+ return msg, fig, report, model_repr
236
 
237
+ train_btn.click(fn=do_train, inputs=[df_state, target_dropdown, test_size, random_state, impute_radio, scaler_checkbox, encode_checkbox,
238
+ use_grid, c_min, c_max, c_steps, penalties, solver, cv_folds, max_iter, n_jobs],
239
+ outputs=[accuracy_text, conf_plot, class_report, model_obj])
240
 
 
241
 
242
+ if __name__ == '__main__':
243
+ demo.launch(server_name='0.0.0.0', share=False)