Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,22 +3,18 @@ import pandas as pd
|
|
| 3 |
import numpy as np
|
| 4 |
from sklearn.model_selection import train_test_split
|
| 5 |
from sklearn.ensemble import RandomForestClassifier
|
| 6 |
-
from sklearn.preprocessing import LabelEncoder
|
| 7 |
from sklearn.metrics import classification_report
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
def load_data(file):
|
| 12 |
try:
|
|
|
|
| 13 |
if file.name.endswith(".csv"):
|
| 14 |
-
df = pd.read_csv(file
|
| 15 |
else:
|
| 16 |
-
df = pd.read_excel(file
|
| 17 |
|
| 18 |
-
# Show first 5 rows of the uploaded file
|
| 19 |
preview = df.head(5)
|
| 20 |
-
|
| 21 |
-
# Create a short summary with column types and missing values
|
| 22 |
summary = pd.DataFrame({
|
| 23 |
"Column": df.columns,
|
| 24 |
"Data Type": [df[col].dtype for col in df.columns],
|
|
@@ -29,151 +25,99 @@ def load_data(file):
|
|
| 29 |
except Exception as e:
|
| 30 |
return None, [], pd.DataFrame(), "", f"β Error loading file: {e}"
|
| 31 |
|
|
|
|
| 32 |
def preprocess_dataframe(df, quantile_binning=False, count_words=False):
|
| 33 |
-
# Copy the original DataFrame to avoid overwriting
|
| 34 |
df = df.copy()
|
| 35 |
|
| 36 |
-
#
|
| 37 |
if quantile_binning:
|
| 38 |
-
numeric_cols = df.select_dtypes(include=
|
| 39 |
for col in numeric_cols:
|
| 40 |
try:
|
| 41 |
-
df[col + "_qbin"] = pd.qcut(df[col], q=4, labels=
|
| 42 |
-
except
|
| 43 |
-
|
| 44 |
|
| 45 |
-
#
|
| 46 |
if count_words:
|
| 47 |
-
text_cols = df.select_dtypes(include=
|
| 48 |
for col in text_cols:
|
| 49 |
-
|
| 50 |
-
df[col + "_wordcount"] = df[col].astype(str).apply(lambda x: len(x.split()))
|
| 51 |
-
except Exception as e:
|
| 52 |
-
print(f"Warning (wordcount failed for {col}):", e)
|
| 53 |
|
| 54 |
return df
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
df =
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
if y.dtype == "O":
|
| 76 |
-
y = LabelEncoder().fit_transform(y)
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
report = classification_report(y_test, y_pred)
|
| 88 |
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
|
|
|
| 98 |
|
| 99 |
-
# Upload section
|
| 100 |
with gr.Row():
|
| 101 |
-
file_input = gr.File(label="π Upload CSV or Excel
|
|
|
|
|
|
|
| 102 |
|
| 103 |
with gr.Row():
|
| 104 |
-
|
| 105 |
-
|
| 106 |
|
| 107 |
with gr.Row():
|
| 108 |
-
|
| 109 |
-
feature_cols = gr.CheckboxGroup(label="π§Ύ Feature Columns (Used to predict target)", choices=[])
|
| 110 |
|
| 111 |
-
# Buttons
|
| 112 |
with gr.Row():
|
| 113 |
-
|
| 114 |
-
|
| 115 |
|
| 116 |
-
|
| 117 |
-
with gr.Row():
|
| 118 |
-
output = gr.Textbox(label="π Model Output (Classification Report)", lines=10)
|
| 119 |
|
| 120 |
with gr.Row():
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
# Data Previews
|
| 125 |
-
with gr.Row():
|
| 126 |
-
table_preview = gr.DataFrame(label="π Original Data Preview")
|
| 127 |
-
processed_preview = gr.DataFrame(label="π§ͺ Processed Data Preview (with new columns)")
|
| 128 |
-
|
| 129 |
-
# ----------- Define App Logic -----------
|
| 130 |
-
|
| 131 |
-
# Handle file upload and update column options
|
| 132 |
-
def on_file_change(file, quantile_binning, count_words):
|
| 133 |
-
df, _, preview, summary_md, error = load_data(file)
|
| 134 |
-
if df is None:
|
| 135 |
-
return None, gr.update(choices=[], value=None), gr.update(choices=[], value=[]), pd.DataFrame(), "", "", "", error
|
| 136 |
-
|
| 137 |
-
# Apply preprocessing
|
| 138 |
-
df_processed = preprocess_dataframe(df, quantile_binning, count_words)
|
| 139 |
-
|
| 140 |
-
# Update selectors with new columns from the processed DataFrame
|
| 141 |
-
columns = list(df_processed.columns)
|
| 142 |
-
|
| 143 |
-
return (
|
| 144 |
-
df_processed, # Store processed df in state
|
| 145 |
-
gr.update(choices=columns, value=None),
|
| 146 |
-
gr.update(choices=columns, value=[]),
|
| 147 |
-
preview,
|
| 148 |
-
summary_md,
|
| 149 |
-
df_processed.head(100), # Show processed preview
|
| 150 |
-
"", # Clear model output
|
| 151 |
-
"" # Clear help
|
| 152 |
-
)
|
| 153 |
-
|
| 154 |
-
# Handle training the model
|
| 155 |
-
def on_train(df, target, features):
|
| 156 |
-
if df is None:
|
| 157 |
-
return "β οΈ Please upload a file first."
|
| 158 |
-
if target is None or not features:
|
| 159 |
-
return "β οΈ Please select target and feature columns."
|
| 160 |
-
return train_model(df, target, features)
|
| 161 |
-
|
| 162 |
-
# Clear all interface elements
|
| 163 |
-
def on_clear():
|
| 164 |
-
return (
|
| 165 |
-
None, # df_state
|
| 166 |
-
None, # target_col
|
| 167 |
-
[], # feature_cols
|
| 168 |
-
pd.DataFrame(),
|
| 169 |
-
"",
|
| 170 |
-
pd.DataFrame(),
|
| 171 |
-
"",
|
| 172 |
-
"βοΈ Upload a dataset, choose preprocessing options, then train."
|
| 173 |
-
)
|
| 174 |
-
|
| 175 |
-
# ----------- Connect Actions to Widgets -----------
|
| 176 |
|
|
|
|
| 177 |
file_input.change(
|
| 178 |
fn=on_file_change,
|
| 179 |
inputs=[file_input, quantile_option, wordcount_option],
|
|
@@ -185,32 +129,15 @@ with gr.Blocks() as demo:
|
|
| 185 |
data_summary,
|
| 186 |
processed_preview,
|
| 187 |
output,
|
| 188 |
-
help_box
|
| 189 |
-
]
|
| 190 |
)
|
| 191 |
|
| 192 |
train_button.click(
|
| 193 |
-
fn=
|
| 194 |
inputs=[df_state, target_col, feature_cols],
|
| 195 |
-
outputs=output
|
| 196 |
)
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
inputs=[],
|
| 201 |
-
outputs=[
|
| 202 |
-
df_state,
|
| 203 |
-
target_col,
|
| 204 |
-
feature_cols,
|
| 205 |
-
table_preview,
|
| 206 |
-
data_summary,
|
| 207 |
-
processed_preview,
|
| 208 |
-
output,
|
| 209 |
-
help_box
|
| 210 |
-
]
|
| 211 |
-
)
|
| 212 |
-
|
| 213 |
-
# ----------- Launch the App -----------
|
| 214 |
-
|
| 215 |
-
if __name__ == "__main__":
|
| 216 |
-
demo.launch(share=True)
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
from sklearn.model_selection import train_test_split
|
| 5 |
from sklearn.ensemble import RandomForestClassifier
|
|
|
|
| 6 |
from sklearn.metrics import classification_report
|
| 7 |
|
| 8 |
+
# β
Load data from CSV or Excel
|
|
|
|
| 9 |
def load_data(file):
|
| 10 |
try:
|
| 11 |
+
# π Use file object directly to avoid FileNotFoundError
|
| 12 |
if file.name.endswith(".csv"):
|
| 13 |
+
df = pd.read_csv(file)
|
| 14 |
else:
|
| 15 |
+
df = pd.read_excel(file)
|
| 16 |
|
|
|
|
| 17 |
preview = df.head(5)
|
|
|
|
|
|
|
| 18 |
summary = pd.DataFrame({
|
| 19 |
"Column": df.columns,
|
| 20 |
"Data Type": [df[col].dtype for col in df.columns],
|
|
|
|
| 25 |
except Exception as e:
|
| 26 |
return None, [], pd.DataFrame(), "", f"β Error loading file: {e}"
|
| 27 |
|
| 28 |
+
# β
Preprocess DataFrame
|
| 29 |
def preprocess_dataframe(df, quantile_binning=False, count_words=False):
|
|
|
|
| 30 |
df = df.copy()
|
| 31 |
|
| 32 |
+
# β Add _qbin columns for numeric columns
|
| 33 |
if quantile_binning:
|
| 34 |
+
numeric_cols = df.select_dtypes(include=np.number).columns
|
| 35 |
for col in numeric_cols:
|
| 36 |
try:
|
| 37 |
+
df[col + "_qbin"] = pd.qcut(df[col], q=4, labels=False, duplicates='drop')
|
| 38 |
+
except:
|
| 39 |
+
pass # Some columns can't be binned (e.g., constant values)
|
| 40 |
|
| 41 |
+
# β Add _wordcount columns for text columns
|
| 42 |
if count_words:
|
| 43 |
+
text_cols = df.select_dtypes(include="object").columns
|
| 44 |
for col in text_cols:
|
| 45 |
+
df[col + "_wordcount"] = df[col].astype(str).apply(lambda x: len(x.split()))
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
return df
|
| 48 |
|
| 49 |
+
# β
Handle file input and update UI
|
| 50 |
+
def on_file_change(file, quantile_binning, count_words):
|
| 51 |
+
df, _, preview, summary_md, error = load_data(file)
|
| 52 |
+
if df is None:
|
| 53 |
+
return None, gr.update(choices=[], value=None), gr.update(choices=[], value=[]), pd.DataFrame(), "", "", "", error
|
| 54 |
+
|
| 55 |
+
# π Preprocess data and get new columns
|
| 56 |
+
df_processed = preprocess_dataframe(df, quantile_binning, count_words)
|
| 57 |
+
columns = list(df_processed.columns)
|
| 58 |
+
|
| 59 |
+
return (
|
| 60 |
+
df_processed, # Save in state
|
| 61 |
+
gr.update(choices=columns, value=None), # Update target dropdown
|
| 62 |
+
gr.update(choices=columns, value=[]), # Update feature selector
|
| 63 |
+
preview, # Show original preview
|
| 64 |
+
summary_md, # Show summary table
|
| 65 |
+
df_processed.head(100), # Show processed data
|
| 66 |
+
"", "", # Clear output and help box
|
| 67 |
+
)
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
# β
Train model
|
| 70 |
+
def train_model(df, target, features):
|
| 71 |
+
if df is None or target is None or not features:
|
| 72 |
+
return "β οΈ Please upload data, select a target column and features.", ""
|
| 73 |
|
| 74 |
+
try:
|
| 75 |
+
X = df[features]
|
| 76 |
+
y = df[target]
|
| 77 |
|
| 78 |
+
# Handle categorical features
|
| 79 |
+
X = pd.get_dummies(X)
|
|
|
|
| 80 |
|
| 81 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 82 |
+
clf = RandomForestClassifier()
|
| 83 |
+
clf.fit(X_train, y_train)
|
| 84 |
+
y_pred = clf.predict(X_test)
|
| 85 |
|
| 86 |
+
report = classification_report(y_test, y_pred)
|
| 87 |
+
help_text = "β
Model trained successfully. You can review the metrics below."
|
| 88 |
+
return report, help_text
|
| 89 |
|
| 90 |
+
except Exception as e:
|
| 91 |
+
return f"β Error training model: {e}", ""
|
| 92 |
|
| 93 |
+
# β
Gradio App Interface
|
| 94 |
+
with gr.Blocks(title="π ML Model Trainer with Quartiles and Word Counts") as app:
|
| 95 |
+
gr.Markdown("## π§ Train a Machine Learning Model on Your Dataset")
|
| 96 |
|
|
|
|
| 97 |
with gr.Row():
|
| 98 |
+
file_input = gr.File(label="π Upload CSV or Excel", file_types=[".csv", ".xls", ".xlsx"])
|
| 99 |
+
quantile_option = gr.Checkbox(label="Discretize into Quartiles", value=True)
|
| 100 |
+
wordcount_option = gr.Checkbox(label="Count Words in Text Columns", value=True)
|
| 101 |
|
| 102 |
with gr.Row():
|
| 103 |
+
target_col = gr.Dropdown(label="π― Select Target Column")
|
| 104 |
+
feature_cols = gr.CheckboxGroup(label="π§ Select Feature Columns")
|
| 105 |
|
| 106 |
with gr.Row():
|
| 107 |
+
df_state = gr.State()
|
|
|
|
| 108 |
|
|
|
|
| 109 |
with gr.Row():
|
| 110 |
+
table_preview = gr.DataFrame(label="π Data Preview")
|
| 111 |
+
processed_preview = gr.DataFrame(label="π Processed Data (100 rows)")
|
| 112 |
|
| 113 |
+
data_summary = gr.Markdown()
|
|
|
|
|
|
|
| 114 |
|
| 115 |
with gr.Row():
|
| 116 |
+
train_button = gr.Button("π Train Model")
|
| 117 |
+
output = gr.Textbox(label="π Classification Report", lines=10)
|
| 118 |
+
help_box = gr.Textbox(label="βΉοΈ Status", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
# π Events
|
| 121 |
file_input.change(
|
| 122 |
fn=on_file_change,
|
| 123 |
inputs=[file_input, quantile_option, wordcount_option],
|
|
|
|
| 129 |
data_summary,
|
| 130 |
processed_preview,
|
| 131 |
output,
|
| 132 |
+
help_box,
|
| 133 |
+
],
|
| 134 |
)
|
| 135 |
|
| 136 |
train_button.click(
|
| 137 |
+
fn=train_model,
|
| 138 |
inputs=[df_state, target_col, feature_cols],
|
| 139 |
+
outputs=[output, help_box],
|
| 140 |
)
|
| 141 |
|
| 142 |
+
# π Launch the app
|
| 143 |
+
app.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|