selva1909's picture
Update app.py
2e5d1c7 verified
raw
history blame
6.46 kB
import gradio as gr
import numpy as np
import plotly.graph_objects as go
import pandas as pd
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, accuracy_score
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
# ------------------------------------------------
# DATA GENERATORS
# ------------------------------------------------
def generate_3d_regression(n_points, noise):
n_points = int(n_points)
x1 = np.linspace(0, 10, n_points)
x2 = np.linspace(0, 10, n_points)
X1, X2 = np.meshgrid(x1, x2)
Z = 3 * X1 + 2 * X2 + 10 + np.random.randn(*X1.shape) * noise
X_flat = np.column_stack((X1.ravel(), X2.ravel()))
Z_flat = Z.ravel()
return X1, X2, X_flat, Z_flat
def generate_classification(n_points, noise):
X = np.random.randn(n_points, 2)
y = (X[:, 0]**2 + X[:, 1] > 0.5).astype(int)
X += np.random.randn(*X.shape) * noise * 0.1
return X, y
# ------------------------------------------------
# TRUE INTERACTIVE 3D USING PLOTLY
# ------------------------------------------------
def interactive_3d(n_points, noise, n_estimators, max_depth):
X1, X2, X_flat, Z_flat = generate_3d_regression(n_points, noise)
rf = RandomForestRegressor(n_estimators=n_estimators, max_depth=max_depth, random_state=42)
rf.fit(X_flat, Z_flat)
Z_pred = rf.predict(X_flat).reshape(X1.shape)
mse = mean_squared_error(Z_flat, Z_pred.ravel())
fig = go.Figure()
fig.add_surface(x=X1, y=X2, z=Z_pred, colorscale="Blues", opacity=0.9)
fig.update_layout(
title="Interactive 3D Random Forest Surface",
scene=dict(
xaxis_title="X1",
yaxis_title="X2",
zaxis_title="Z",
bgcolor="#0b1e3d"
),
paper_bgcolor="#0b1e3d",
font=dict(color="white")
)
return fig, f"MSE: {mse:.4f}", rf
# ------------------------------------------------
# SINGLE TREE VISUALIZATION
# ------------------------------------------------
def show_tree(rf_model):
if rf_model is None:
return None
tree = rf_model.estimators_[0]
fig, ax = plt.subplots(figsize=(10, 6))
plot_tree(tree, ax=ax, filled=True)
ax.set_title("Single Decision Tree from Random Forest")
return fig
# ------------------------------------------------
# CLASSIFICATION VIEW
# ------------------------------------------------
def classification_view(n_points, noise, n_estimators, max_depth):
X, y = generate_classification(n_points, noise)
rf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, random_state=42)
rf.fit(X, y)
y_pred = rf.predict(X)
acc = accuracy_score(y, y_pred)
fig = go.Figure()
fig.add_trace(go.Scatter(
x=X[:, 0],
y=X[:, 1],
mode="markers",
marker=dict(color=y_pred, colorscale="Blues"),
))
fig.update_layout(
title="Random Forest Classification",
paper_bgcolor="#0b1e3d",
plot_bgcolor="#0b1e3d",
font=dict(color="white")
)
return fig, f"Accuracy: {acc:.4f}"
# ------------------------------------------------
# LINEAR VS RANDOM FOREST COMPARISON
# ------------------------------------------------
def compare_models(n_points, noise):
x = np.linspace(0, 10, n_points).reshape(-1, 1)
y = 2.5 * x.flatten() + 5 + np.random.randn(n_points) * noise
lr = LinearRegression().fit(x, y)
rf = RandomForestRegressor().fit(x, y)
y_lr = lr.predict(x)
y_rf = rf.predict(x)
fig = go.Figure()
fig.add_scatter(x=x.flatten(), y=y, mode="markers", name="Data")
fig.add_scatter(x=x.flatten(), y=y_lr, mode="lines", name="Linear")
fig.add_scatter(x=x.flatten(), y=y_rf, mode="lines", name="Random Forest")
fig.update_layout(
title="Linear vs Random Forest",
paper_bgcolor="#0b1e3d",
plot_bgcolor="#0b1e3d",
font=dict(color="white")
)
return fig
# ------------------------------------------------
# DATASET UPLOAD
# ------------------------------------------------
def train_uploaded(file, target, n_estimators, max_depth):
if file is None:
return None, "Upload CSV to train"
df = pd.read_csv(file.name)
if target not in df.columns:
return None, "Invalid target column"
X = df.drop(columns=[target])
y = df[target]
rf = RandomForestRegressor(n_estimators=n_estimators, max_depth=max_depth)
rf.fit(X, y)
preds = rf.predict(X)
mse = mean_squared_error(y, preds)
return None, f"Uploaded Data MSE: {mse:.4f}"
# ------------------------------------------------
# GRADIO DASHBOARD UI (BLUE THEME)
# ------------------------------------------------
with gr.Blocks() as demo:
gr.Markdown("# 🎓 Full Machine Learning Teaching Dashboard")
with gr.Tab("🌐 Interactive 3D"):
n_points = gr.Slider(20, 100, 40, label="Points")
noise = gr.Slider(0.0, 3.0, 1.0, label="Noise")
n_estimators = gr.Slider(10, 100, 50, label="Trees")
max_depth = gr.Slider(2, 15, 8, label="Depth")
plot3d = gr.Plot()
mse_text = gr.Markdown()
tree_plot = gr.Plot()
def run_3d(n_points, noise, n_estimators, max_depth):
fig, text, rf = interactive_3d(n_points, noise, n_estimators, max_depth)
tree_fig = show_tree(rf)
return fig, text, tree_fig
gr.Button("Run 3D").click(run_3d, [n_points, noise, n_estimators, max_depth], [plot3d, mse_text, tree_plot])
with gr.Tab("🧩 Classification"):
cls_plot = gr.Plot()
cls_text = gr.Markdown()
gr.Button("Run Classification").click(
classification_view,
[n_points, noise, n_estimators, max_depth],
[cls_plot, cls_text],
)
with gr.Tab("🧪 Compare Models"):
cmp_plot = gr.Plot()
gr.Button("Compare").click(compare_models, [n_points, noise], cmp_plot)
with gr.Tab("📂 Upload Dataset"):
file = gr.File(file_types=[".csv"])
target = gr.Textbox(label="Target Column")
upload_text = gr.Markdown()
gr.Button("Train Uploaded Data").click(
train_uploaded,
[file, target, n_estimators, max_depth],
[gr.Plot(visible=False), upload_text],
)
demo.launch(theme=gr.themes.Soft(primary_hue="blue"))