clementBE commited on
Commit
e2cdf36
Β·
verified Β·
1 Parent(s): fc30ed8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -28
app.py CHANGED
@@ -6,7 +6,7 @@ import matplotlib.pyplot as plt
6
  from io import BytesIO
7
  from sklearn.model_selection import train_test_split
8
  from sklearn.ensemble import RandomForestClassifier
9
- from sklearn.metrics import classification_report
10
  from PIL import Image
11
 
12
  original_df = None
@@ -22,8 +22,9 @@ def load_data(file):
22
  else:
23
  original_df = pd.read_excel(file)
24
  help_text = (
25
- "Step 1: Data loaded successfully! Here you see a preview of the first 10 rows.\n"
26
- "Next, click 'Process Data' to discretize numeric columns and add word counts."
 
27
  )
28
  return original_df.head(10), "βœ… File loaded successfully.", help_text
29
  except Exception as e:
@@ -34,19 +35,19 @@ def process_data():
34
  if original_df is None:
35
  return pd.DataFrame(), gr.update(choices=[]), gr.update(choices=[]), "⚠️ Please load a dataset first.", ""
36
  df = original_df.copy()
37
- # Quartiles
38
  for col in df.select_dtypes(include=np.number).columns:
39
  try:
40
  df[col + "_qbin"] = pd.qcut(df[col], 4, labels=False, duplicates='drop')
41
  except Exception:
42
  pass
43
- # Deciles
44
  for col in df.select_dtypes(include=np.number).columns:
45
  try:
46
  df[col + "_decil"] = pd.qcut(df[col], 10, labels=False, duplicates='drop')
47
  except Exception:
48
  pass
49
- # Word counts
50
  for col in df.select_dtypes(include='object').columns:
51
  df[col + "_wordcount"] = df[col].astype(str).apply(lambda x: len(x.split()))
52
  processed_df = df.copy()
@@ -55,35 +56,44 @@ def process_data():
55
  "Step 2: Data processed!\n"
56
  "- Numeric columns discretized into quartiles and deciles.\n"
57
  "- Word counts added for text columns.\n"
58
- "You can now select your target and feature columns."
59
  )
60
  return df.head(10), gr.update(choices=all_columns), gr.update(choices=all_columns), "βœ… Data processed.", help_text
61
 
62
  def train_model(target_col, feature_cols):
63
  global processed_df, trained_model, processed_X_columns
64
  if processed_df is None:
65
- return "⚠️ Please process your data first.", None, "Load and process your data before training."
66
  if not target_col or not feature_cols:
67
- return "⚠️ Please select a target and at least one feature.", None, "Select a target variable and features to train the model."
68
 
69
  try:
70
  X = processed_df[feature_cols]
71
  y = processed_df[target_col]
 
 
72
  X = pd.get_dummies(X)
73
  processed_X_columns = X.columns.tolist()
 
 
74
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
 
75
  clf = RandomForestClassifier(random_state=42)
76
  clf.fit(X_train, y_train)
77
  trained_model = clf
 
 
78
  y_pred = clf.predict(X_test)
 
79
  report = classification_report(y_test, y_pred)
80
 
81
- # Prepare feature importance heatmap
82
  fi = clf.feature_importances_
83
  fi_df = pd.DataFrame({'Feature': processed_X_columns, 'Importance': fi})
84
  fi_df = fi_df.sort_values(by='Importance', ascending=False).head(20)
85
 
86
- plt.figure(figsize=(8,6))
87
  sns.heatmap(fi_df.set_index('Feature').T, annot=True, cmap="YlGnBu", cbar_kws={'label': 'Feature Importance'})
88
  plt.title("Feature Importances Heatmap (Top 20)")
89
  plt.tight_layout()
@@ -94,16 +104,20 @@ def train_model(target_col, feature_cols):
94
  buf.seek(0)
95
  img = Image.open(buf)
96
 
97
- # Dynamic explanatory help text
98
  help_text = (
99
- "πŸ“‹ **Classification Report Help:**\n"
100
- "- Precision: Of all predicted positive cases, how many are actually positive?\n"
101
- "- Recall: Of all actual positive cases, how many did the model identify?\n"
102
- "- F1-Score: Balance between precision and recall.\n\n"
103
- "🌟 **Heatmap Help:**\n"
104
- "- Shows top 20 features by importance.\n"
105
- "- Darker color = more influence on model's decisions.\n"
106
- "- Use this to understand which variables drive predictions most."
 
 
 
 
107
  )
108
 
109
  return report, img, help_text
@@ -111,7 +125,6 @@ def train_model(target_col, feature_cols):
111
  except Exception as e:
112
  return f"❌ Model training failed: {e}", None, ""
113
 
114
-
115
  with gr.Blocks(title="Step-by-Step Model Trainer with Help and Heatmap") as app:
116
  gr.Markdown("## 🧠 Step-by-Step Model Trainer\nUpload your data, process it, train a model, and get help at each step!")
117
 
@@ -131,11 +144,9 @@ with gr.Blocks(title="Step-by-Step Model Trainer with Help and Heatmap") as app:
131
  feature_selector = gr.CheckboxGroup(label="πŸ“Š Select Feature Columns", choices=[])
132
 
133
  train_button = gr.Button("πŸš€ Train Model")
134
- train_output = gr.Textbox(label="πŸ“ˆ Classification Report", lines=10)
135
  heatmap_output = gr.Image(label="🌑️ Feature Importance Heatmap")
136
- train_help = gr.Textbox(label="πŸ“ Help to read results", interactive=False, lines=10)
137
- train_help = gr.Textbox(label="πŸ“– Step 3 Help", interactive=False)
138
- heatmap_img = gr.Image(label="πŸ”₯ Feature Importances Heatmap")
139
 
140
  # Callbacks
141
  file_input.change(
@@ -151,9 +162,9 @@ with gr.Blocks(title="Step-by-Step Model Trainer with Help and Heatmap") as app:
151
  )
152
 
153
  train_button.click(
154
- fn=train_model,
155
- inputs=[target_selector, feature_selector],
156
- outputs=[train_output, heatmap_output, train_help]
157
  )
158
 
159
  app.launch()
 
6
  from io import BytesIO
7
  from sklearn.model_selection import train_test_split
8
  from sklearn.ensemble import RandomForestClassifier
9
+ from sklearn.metrics import classification_report, accuracy_score
10
  from PIL import Image
11
 
12
  original_df = None
 
22
  else:
23
  original_df = pd.read_excel(file)
24
  help_text = (
25
+ "Step 1: Data loaded successfully!\n"
26
+ "- Preview shows first 10 rows.\n"
27
+ "- Next: Click 'Process Data' to discretize numeric columns and add word counts for text."
28
  )
29
  return original_df.head(10), "βœ… File loaded successfully.", help_text
30
  except Exception as e:
 
35
  if original_df is None:
36
  return pd.DataFrame(), gr.update(choices=[]), gr.update(choices=[]), "⚠️ Please load a dataset first.", ""
37
  df = original_df.copy()
38
+ # Quartiles discretization
39
  for col in df.select_dtypes(include=np.number).columns:
40
  try:
41
  df[col + "_qbin"] = pd.qcut(df[col], 4, labels=False, duplicates='drop')
42
  except Exception:
43
  pass
44
+ # Deciles discretization
45
  for col in df.select_dtypes(include=np.number).columns:
46
  try:
47
  df[col + "_decil"] = pd.qcut(df[col], 10, labels=False, duplicates='drop')
48
  except Exception:
49
  pass
50
+ # Word counts for text columns
51
  for col in df.select_dtypes(include='object').columns:
52
  df[col + "_wordcount"] = df[col].astype(str).apply(lambda x: len(x.split()))
53
  processed_df = df.copy()
 
56
  "Step 2: Data processed!\n"
57
  "- Numeric columns discretized into quartiles and deciles.\n"
58
  "- Word counts added for text columns.\n"
59
+ "- You can now select your target and feature columns."
60
  )
61
  return df.head(10), gr.update(choices=all_columns), gr.update(choices=all_columns), "βœ… Data processed.", help_text
62
 
63
  def train_model(target_col, feature_cols):
64
  global processed_df, trained_model, processed_X_columns
65
  if processed_df is None:
66
+ return "⚠️ Please process your data first.", None, ""
67
  if not target_col or not feature_cols:
68
+ return "⚠️ Please select a target and at least one feature.", None, ""
69
 
70
  try:
71
  X = processed_df[feature_cols]
72
  y = processed_df[target_col]
73
+
74
+ # One-hot encoding categorical features if any
75
  X = pd.get_dummies(X)
76
  processed_X_columns = X.columns.tolist()
77
+
78
+ # Train/test split
79
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
80
+
81
+ # Train Random Forest Classifier
82
  clf = RandomForestClassifier(random_state=42)
83
  clf.fit(X_train, y_train)
84
  trained_model = clf
85
+
86
+ # Predict & evaluate
87
  y_pred = clf.predict(X_test)
88
+ accuracy = accuracy_score(y_test, y_pred)
89
  report = classification_report(y_test, y_pred)
90
 
91
+ # Feature importances
92
  fi = clf.feature_importances_
93
  fi_df = pd.DataFrame({'Feature': processed_X_columns, 'Importance': fi})
94
  fi_df = fi_df.sort_values(by='Importance', ascending=False).head(20)
95
 
96
+ plt.figure(figsize=(10, 6))
97
  sns.heatmap(fi_df.set_index('Feature').T, annot=True, cmap="YlGnBu", cbar_kws={'label': 'Feature Importance'})
98
  plt.title("Feature Importances Heatmap (Top 20)")
99
  plt.tight_layout()
 
104
  buf.seek(0)
105
  img = Image.open(buf)
106
 
107
+ # Detailed help text
108
  help_text = (
109
+ f"πŸ“Š Model type: Random Forest Classifier\n"
110
+ f"🎯 Target: '{target_col}'\n"
111
+ f"οΏ½οΏ½οΏ½οΏ½ Features used: {len(feature_cols)}\n"
112
+ f"βœ… Accuracy on test set: {accuracy:.2%}\n\n"
113
+ "πŸ“‹ Classification Report Explanation:\n"
114
+ "- Precision: Of predicted positives, how many are correct?\n"
115
+ "- Recall: Of actual positives, how many were found?\n"
116
+ "- F1-Score: Harmonic mean of precision & recall.\n\n"
117
+ "🌑️ Heatmap Explanation:\n"
118
+ "- Shows top 20 most important features by model.\n"
119
+ "- Darker cells = higher influence on predictions.\n"
120
+ "- Use this to understand which variables drive decisions."
121
  )
122
 
123
  return report, img, help_text
 
125
  except Exception as e:
126
  return f"❌ Model training failed: {e}", None, ""
127
 
 
128
  with gr.Blocks(title="Step-by-Step Model Trainer with Help and Heatmap") as app:
129
  gr.Markdown("## 🧠 Step-by-Step Model Trainer\nUpload your data, process it, train a model, and get help at each step!")
130
 
 
144
  feature_selector = gr.CheckboxGroup(label="πŸ“Š Select Feature Columns", choices=[])
145
 
146
  train_button = gr.Button("πŸš€ Train Model")
147
+ train_output = gr.Textbox(label="πŸ“ˆ Classification Report", lines=15)
148
  heatmap_output = gr.Image(label="🌑️ Feature Importance Heatmap")
149
+ train_help = gr.Textbox(label="πŸ“ Help to read results", interactive=False, lines=12)
 
 
150
 
151
  # Callbacks
152
  file_input.change(
 
162
  )
163
 
164
  train_button.click(
165
+ fn=train_model,
166
+ inputs=[target_selector, feature_selector],
167
+ outputs=[train_output, heatmap_output, train_help]
168
  )
169
 
170
  app.launch()