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