Spaces:
Runtime error
Runtime error
add docs + improve ux/ui
Browse files
app.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
|
| 3 |
import gradio as gr
|
| 4 |
import numpy as np
|
| 5 |
import pandas as pd
|
|
@@ -11,49 +9,48 @@ from sklearn.ensemble import GradientBoostingClassifier
|
|
| 11 |
from sklearn.model_selection import train_test_split
|
| 12 |
from sklearn.metrics import accuracy_score, confusion_matrix
|
| 13 |
|
| 14 |
-
# In some remote environments, Matplotlib needs to be set to 'Agg' backend
|
| 15 |
matplotlib.use('Agg')
|
| 16 |
|
| 17 |
################################################################################
|
| 18 |
-
# SUGGESTED_DATASETS:
|
| 19 |
#
|
| 20 |
-
# "scikit-learn/iris" ->
|
| 21 |
-
# "uci/wine" ->
|
|
|
|
| 22 |
################################################################################
|
| 23 |
SUGGESTED_DATASETS = [
|
| 24 |
"scikit-learn/iris",
|
| 25 |
"uci/wine",
|
| 26 |
-
"SKIP/ENTER_CUSTOM"
|
| 27 |
]
|
| 28 |
|
| 29 |
-
|
| 30 |
def update_columns(dataset_id, custom_dataset_id):
|
| 31 |
"""
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
"""
|
| 35 |
-
# If user picked a suggested dataset (not SKIP), use that
|
| 36 |
if dataset_id != "SKIP/ENTER_CUSTOM":
|
| 37 |
final_id = dataset_id
|
| 38 |
else:
|
| 39 |
-
# Use the user-supplied dataset ID
|
| 40 |
final_id = custom_dataset_id.strip()
|
| 41 |
|
| 42 |
try:
|
| 43 |
-
# Load just the "train" split; many HF datasets have train/test/validation
|
| 44 |
ds = load_dataset(final_id, split="train")
|
| 45 |
df = pd.DataFrame(ds)
|
| 46 |
cols = df.columns.tolist()
|
| 47 |
|
| 48 |
-
message =
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
return (
|
| 51 |
gr.update(choices=cols, value=None), # label_col dropdown
|
| 52 |
gr.update(choices=cols, value=[]), # feature_cols checkbox group
|
| 53 |
message
|
| 54 |
)
|
| 55 |
except Exception as e:
|
| 56 |
-
# If load fails or dataset doesn't exist
|
| 57 |
err_msg = f"**Error loading** `{final_id}`: {e}"
|
| 58 |
return (
|
| 59 |
gr.update(choices=[], value=None),
|
|
@@ -61,43 +58,42 @@ def update_columns(dataset_id, custom_dataset_id):
|
|
| 61 |
err_msg
|
| 62 |
)
|
| 63 |
|
| 64 |
-
|
| 65 |
def train_model(dataset_id, custom_dataset_id, label_column, feature_columns,
|
| 66 |
learning_rate, n_estimators, max_depth, test_size):
|
| 67 |
"""
|
| 68 |
-
1.
|
| 69 |
-
2. Load
|
| 70 |
-
3. Train GradientBoostingClassifier.
|
| 71 |
-
4.
|
| 72 |
-
|
| 73 |
-
- Confusion matrix heatmap
|
| 74 |
"""
|
|
|
|
| 75 |
if dataset_id != "SKIP/ENTER_CUSTOM":
|
| 76 |
final_id = dataset_id
|
| 77 |
else:
|
| 78 |
final_id = custom_dataset_id.strip()
|
| 79 |
|
| 80 |
-
# Load dataset
|
| 81 |
ds = load_dataset(final_id, split="train")
|
| 82 |
df = pd.DataFrame(ds)
|
| 83 |
|
| 84 |
-
#
|
| 85 |
if label_column not in df.columns:
|
| 86 |
raise ValueError(f"Label column '{label_column}' not found in dataset columns.")
|
| 87 |
for fc in feature_columns:
|
| 88 |
if fc not in df.columns:
|
| 89 |
raise ValueError(f"Feature column '{fc}' not found in dataset columns.")
|
| 90 |
|
| 91 |
-
#
|
| 92 |
X = df[feature_columns].values
|
| 93 |
y = df[label_column].values
|
| 94 |
|
| 95 |
-
#
|
| 96 |
X_train, X_test, y_train, y_test = train_test_split(
|
| 97 |
X, y, test_size=test_size, random_state=42
|
| 98 |
)
|
| 99 |
|
| 100 |
-
#
|
| 101 |
clf = GradientBoostingClassifier(
|
| 102 |
learning_rate=learning_rate,
|
| 103 |
n_estimators=int(n_estimators),
|
|
@@ -106,14 +102,12 @@ def train_model(dataset_id, custom_dataset_id, label_column, feature_columns,
|
|
| 106 |
)
|
| 107 |
clf.fit(X_train, y_train)
|
| 108 |
|
| 109 |
-
#
|
| 110 |
y_pred = clf.predict(X_test)
|
| 111 |
accuracy = accuracy_score(y_test, y_pred)
|
| 112 |
cm = confusion_matrix(y_test, y_pred)
|
| 113 |
|
| 114 |
-
#
|
| 115 |
-
# 1) Feature importances
|
| 116 |
-
# 2) Confusion matrix heatmap
|
| 117 |
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
|
| 118 |
|
| 119 |
# Subplot 1: Feature Importances
|
|
@@ -131,7 +125,7 @@ def train_model(dataset_id, custom_dataset_id, label_column, feature_columns,
|
|
| 131 |
axs[1].set_xlabel("Predicted")
|
| 132 |
axs[1].set_ylabel("True")
|
| 133 |
|
| 134 |
-
# Optionally annotate each cell with
|
| 135 |
thresh = cm.max() / 2.0
|
| 136 |
for i in range(cm.shape[0]):
|
| 137 |
for j in range(cm.shape[1]):
|
|
@@ -140,7 +134,7 @@ def train_model(dataset_id, custom_dataset_id, label_column, feature_columns,
|
|
| 140 |
|
| 141 |
plt.tight_layout()
|
| 142 |
|
| 143 |
-
#
|
| 144 |
text_summary = (
|
| 145 |
f"**Dataset used**: `{final_id}`\n\n"
|
| 146 |
f"**Label column**: `{label_column}`\n\n"
|
|
@@ -150,44 +144,75 @@ def train_model(dataset_id, custom_dataset_id, label_column, feature_columns,
|
|
| 150 |
|
| 151 |
return text_summary, fig
|
| 152 |
|
| 153 |
-
|
| 154 |
-
#
|
|
|
|
| 155 |
with gr.Blocks() as demo:
|
| 156 |
-
|
|
|
|
| 157 |
gr.Markdown(
|
| 158 |
-
"
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
)
|
| 165 |
|
| 166 |
-
# Row 1: Dataset selection
|
| 167 |
with gr.Row():
|
| 168 |
dataset_dropdown = gr.Dropdown(
|
| 169 |
label="Choose suggested dataset",
|
| 170 |
choices=SUGGESTED_DATASETS,
|
| 171 |
-
value=SUGGESTED_DATASETS[0]
|
| 172 |
)
|
| 173 |
custom_dataset_id = gr.Textbox(
|
| 174 |
label="Or enter a custom dataset ID",
|
| 175 |
-
placeholder="e.g.
|
| 176 |
)
|
| 177 |
|
| 178 |
load_cols_btn = gr.Button("Load Columns")
|
| 179 |
load_cols_info = gr.Markdown()
|
| 180 |
|
| 181 |
-
# Row 2: label & feature columns
|
| 182 |
with gr.Row():
|
| 183 |
label_col = gr.Dropdown(choices=[], label="Label column (choose 1)")
|
| 184 |
feature_cols = gr.CheckboxGroup(choices=[], label="Feature columns (choose 1 or more)")
|
| 185 |
|
| 186 |
-
# Hyperparameters
|
| 187 |
-
learning_rate_slider = gr.Slider(
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
train_button = gr.Button("Train & Evaluate")
|
| 193 |
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
|
|
|
| 9 |
from sklearn.model_selection import train_test_split
|
| 10 |
from sklearn.metrics import accuracy_score, confusion_matrix
|
| 11 |
|
|
|
|
| 12 |
matplotlib.use('Agg')
|
| 13 |
|
| 14 |
################################################################################
|
| 15 |
+
# SUGGESTED_DATASETS: These must actually exist on huggingface.co/datasets
|
| 16 |
#
|
| 17 |
+
# "scikit-learn/iris" -> A small, classic Iris dataset with a "train" split
|
| 18 |
+
# "uci/wine" -> Another small dataset with a "train" split
|
| 19 |
+
# "SKIP/ENTER_CUSTOM" -> Placeholder to let the user enter a custom dataset ID
|
| 20 |
################################################################################
|
| 21 |
SUGGESTED_DATASETS = [
|
| 22 |
"scikit-learn/iris",
|
| 23 |
"uci/wine",
|
| 24 |
+
"SKIP/ENTER_CUSTOM"
|
| 25 |
]
|
| 26 |
|
|
|
|
| 27 |
def update_columns(dataset_id, custom_dataset_id):
|
| 28 |
"""
|
| 29 |
+
After the user chooses a dataset from the dropdown or enters their own,
|
| 30 |
+
this function loads the dataset's "train" split, converts it to a DataFrame,
|
| 31 |
+
and returns the columns. These columns are used to populate the Label and
|
| 32 |
+
Feature selectors in the UI.
|
| 33 |
"""
|
|
|
|
| 34 |
if dataset_id != "SKIP/ENTER_CUSTOM":
|
| 35 |
final_id = dataset_id
|
| 36 |
else:
|
|
|
|
| 37 |
final_id = custom_dataset_id.strip()
|
| 38 |
|
| 39 |
try:
|
|
|
|
| 40 |
ds = load_dataset(final_id, split="train")
|
| 41 |
df = pd.DataFrame(ds)
|
| 42 |
cols = df.columns.tolist()
|
| 43 |
|
| 44 |
+
message = (
|
| 45 |
+
f"**Loaded dataset**: `{final_id}`\n\n"
|
| 46 |
+
f"**Columns found**: {cols}"
|
| 47 |
+
)
|
| 48 |
return (
|
| 49 |
gr.update(choices=cols, value=None), # label_col dropdown
|
| 50 |
gr.update(choices=cols, value=[]), # feature_cols checkbox group
|
| 51 |
message
|
| 52 |
)
|
| 53 |
except Exception as e:
|
|
|
|
| 54 |
err_msg = f"**Error loading** `{final_id}`: {e}"
|
| 55 |
return (
|
| 56 |
gr.update(choices=[], value=None),
|
|
|
|
| 58 |
err_msg
|
| 59 |
)
|
| 60 |
|
|
|
|
| 61 |
def train_model(dataset_id, custom_dataset_id, label_column, feature_columns,
|
| 62 |
learning_rate, n_estimators, max_depth, test_size):
|
| 63 |
"""
|
| 64 |
+
1. Decide which dataset ID to load (from dropdown or custom).
|
| 65 |
+
2. Load that dataset's 'train' split, turn into DataFrame, extract X (features) and y (label).
|
| 66 |
+
3. Train a GradientBoostingClassifier on X_train, y_train.
|
| 67 |
+
4. Compute accuracy and confusion matrix on X_test, y_test.
|
| 68 |
+
5. Plot and return feature importances + confusion matrix heatmap + textual summary.
|
|
|
|
| 69 |
"""
|
| 70 |
+
# Resolve final dataset ID
|
| 71 |
if dataset_id != "SKIP/ENTER_CUSTOM":
|
| 72 |
final_id = dataset_id
|
| 73 |
else:
|
| 74 |
final_id = custom_dataset_id.strip()
|
| 75 |
|
| 76 |
+
# Load dataset -> df
|
| 77 |
ds = load_dataset(final_id, split="train")
|
| 78 |
df = pd.DataFrame(ds)
|
| 79 |
|
| 80 |
+
# Validate columns
|
| 81 |
if label_column not in df.columns:
|
| 82 |
raise ValueError(f"Label column '{label_column}' not found in dataset columns.")
|
| 83 |
for fc in feature_columns:
|
| 84 |
if fc not in df.columns:
|
| 85 |
raise ValueError(f"Feature column '{fc}' not found in dataset columns.")
|
| 86 |
|
| 87 |
+
# Convert to NumPy arrays
|
| 88 |
X = df[feature_columns].values
|
| 89 |
y = df[label_column].values
|
| 90 |
|
| 91 |
+
# Train/test split
|
| 92 |
X_train, X_test, y_train, y_test = train_test_split(
|
| 93 |
X, y, test_size=test_size, random_state=42
|
| 94 |
)
|
| 95 |
|
| 96 |
+
# Instantiate and train GradientBoostingClassifier
|
| 97 |
clf = GradientBoostingClassifier(
|
| 98 |
learning_rate=learning_rate,
|
| 99 |
n_estimators=int(n_estimators),
|
|
|
|
| 102 |
)
|
| 103 |
clf.fit(X_train, y_train)
|
| 104 |
|
| 105 |
+
# Evaluate
|
| 106 |
y_pred = clf.predict(X_test)
|
| 107 |
accuracy = accuracy_score(y_test, y_pred)
|
| 108 |
cm = confusion_matrix(y_test, y_pred)
|
| 109 |
|
| 110 |
+
# Create Matplotlib figure with feature importances + confusion matrix
|
|
|
|
|
|
|
| 111 |
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
|
| 112 |
|
| 113 |
# Subplot 1: Feature Importances
|
|
|
|
| 125 |
axs[1].set_xlabel("Predicted")
|
| 126 |
axs[1].set_ylabel("True")
|
| 127 |
|
| 128 |
+
# Optionally annotate each cell with numeric counts
|
| 129 |
thresh = cm.max() / 2.0
|
| 130 |
for i in range(cm.shape[0]):
|
| 131 |
for j in range(cm.shape[1]):
|
|
|
|
| 134 |
|
| 135 |
plt.tight_layout()
|
| 136 |
|
| 137 |
+
# Textual summary
|
| 138 |
text_summary = (
|
| 139 |
f"**Dataset used**: `{final_id}`\n\n"
|
| 140 |
f"**Label column**: `{label_column}`\n\n"
|
|
|
|
| 144 |
|
| 145 |
return text_summary, fig
|
| 146 |
|
| 147 |
+
###############################################################################
|
| 148 |
+
# Gradio UI
|
| 149 |
+
###############################################################################
|
| 150 |
with gr.Blocks() as demo:
|
| 151 |
+
|
| 152 |
+
# High-level title and description
|
| 153 |
gr.Markdown(
|
| 154 |
+
"""
|
| 155 |
+
# Interactive Gradient Boosting Demo
|
| 156 |
+
|
| 157 |
+
This Space demonstrates how to train a [GradientBoostingClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html#gradientboostingclassifier) from **scikit-learn** on **tabular datasets** hosted on the [Hugging Face Hub](https://huggingface.co/datasets).
|
| 158 |
+
|
| 159 |
+
**Purpose**:
|
| 160 |
+
- Easy explore hyperparameters (_learning_rate, n_estimators, max_depth_) and quickly train an ML model on real data.
|
| 161 |
+
- Visualise model performance via confusion matrix heatmap and a feature importance plot.
|
| 162 |
+
|
| 163 |
+
**How to Use**:
|
| 164 |
+
1. Select one of the suggested datasets from the dropdown _or_ enter any valid dataset from the [Hugging Face Hub](https://huggingface.co/datasets).
|
| 165 |
+
2. Click **Load Columns** to retrieve the column names from the dataset's **train** split.
|
| 166 |
+
3. Choose exactly _one_ **Label column** (the target) and one or more **Feature columns** (the inputs).
|
| 167 |
+
4. Adjust hyperparameters (learning_rate, n_estimators, max_depth, test_size).
|
| 168 |
+
5. Click **Train & Evaluate** to train a Gradient Boosting model and see its accuracy, feature importances, and confusion matrix.
|
| 169 |
+
|
| 170 |
+
---
|
| 171 |
+
**Please Note**:
|
| 172 |
+
- The dataset must have a **"train"** split with tabular columns (i.e., no nested structures).
|
| 173 |
+
- Large datasets may take time to download/train.
|
| 174 |
+
- The confusion matrix helps you see how predictions compare to ground-truth labels. The diagonal cells show correct predictions; off-diagonal cells indicate misclassifications.
|
| 175 |
+
- The feature importance plot shows which features the model relies on the most for its predictions.
|
| 176 |
+
|
| 177 |
+
You are now a machine learning engineer, congratulations π€
|
| 178 |
+
"""
|
| 179 |
)
|
| 180 |
|
|
|
|
| 181 |
with gr.Row():
|
| 182 |
dataset_dropdown = gr.Dropdown(
|
| 183 |
label="Choose suggested dataset",
|
| 184 |
choices=SUGGESTED_DATASETS,
|
| 185 |
+
value=SUGGESTED_DATASETS[0]
|
| 186 |
)
|
| 187 |
custom_dataset_id = gr.Textbox(
|
| 188 |
label="Or enter a custom dataset ID",
|
| 189 |
+
placeholder="e.g. user/my_custom_dataset"
|
| 190 |
)
|
| 191 |
|
| 192 |
load_cols_btn = gr.Button("Load Columns")
|
| 193 |
load_cols_info = gr.Markdown()
|
| 194 |
|
|
|
|
| 195 |
with gr.Row():
|
| 196 |
label_col = gr.Dropdown(choices=[], label="Label column (choose 1)")
|
| 197 |
feature_cols = gr.CheckboxGroup(choices=[], label="Feature columns (choose 1 or more)")
|
| 198 |
|
| 199 |
+
# Model Hyperparameters
|
| 200 |
+
learning_rate_slider = gr.Slider(
|
| 201 |
+
minimum=0.01, maximum=1.0, value=0.1, step=0.01,
|
| 202 |
+
label="learning_rate"
|
| 203 |
+
)
|
| 204 |
+
n_estimators_slider = gr.Slider(
|
| 205 |
+
minimum=50, maximum=300, value=100, step=50,
|
| 206 |
+
label="n_estimators"
|
| 207 |
+
)
|
| 208 |
+
max_depth_slider = gr.Slider(
|
| 209 |
+
minimum=1, maximum=10, value=3, step=1,
|
| 210 |
+
label="max_depth"
|
| 211 |
+
)
|
| 212 |
+
test_size_slider = gr.Slider(
|
| 213 |
+
minimum=0.1, maximum=0.9, value=0.3, step=0.1,
|
| 214 |
+
label="test_size fraction (0.1-0.9)"
|
| 215 |
+
)
|
| 216 |
|
| 217 |
train_button = gr.Button("Train & Evaluate")
|
| 218 |
|