|
import gradio as gr |
|
import numpy as np |
|
from sklearn.datasets import load_iris |
|
from sklearn.ensemble import GradientBoostingClassifier |
|
from sklearn.model_selection import train_test_split |
|
from sklearn.metrics import accuracy_score, confusion_matrix |
|
|
|
|
|
iris = load_iris() |
|
X, y = iris.data, iris.target |
|
feature_names = iris.feature_names |
|
class_names = iris.target_names |
|
|
|
|
|
X_train, X_test, y_train, y_test = train_test_split( |
|
X, y, test_size=0.3, random_state=42 |
|
) |
|
|
|
|
|
def train_and_evaluate(learning_rate, n_estimators, max_depth): |
|
|
|
clf = GradientBoostingClassifier( |
|
learning_rate=learning_rate, |
|
n_estimators=n_estimators, |
|
max_depth=int(max_depth), |
|
random_state=42 |
|
) |
|
clf.fit(X_train, y_train) |
|
|
|
|
|
y_pred = clf.predict(X_test) |
|
|
|
|
|
accuracy = accuracy_score(y_test, y_pred) |
|
cm = confusion_matrix(y_test, y_pred) |
|
|
|
|
|
cm_display = "" |
|
for row in cm: |
|
cm_display += str(row) + "\n" |
|
|
|
return f"Accuracy: {accuracy:.3f}\nConfusion Matrix:\n{cm_display}" |
|
|
|
|
|
def predict_species(sepal_length, sepal_width, petal_length, petal_width, |
|
learning_rate, n_estimators, max_depth): |
|
|
|
clf = GradientBoostingClassifier( |
|
learning_rate=learning_rate, |
|
n_estimators=n_estimators, |
|
max_depth=int(max_depth), |
|
random_state=42 |
|
) |
|
clf.fit(X_train, y_train) |
|
|
|
|
|
user_sample = np.array([[sepal_length, sepal_width, petal_length, petal_width]]) |
|
prediction = clf.predict(user_sample)[0] |
|
return f"Predicted species: {class_names[prediction]}" |
|
|
|
|
|
|
|
|
|
hyperparam_inputs = [ |
|
gr.inputs.Slider(0.01, 1.0, step=0.01, default=0.1, label="learning_rate"), |
|
gr.inputs.Slider(50, 300, step=50, default=100, label="n_estimators"), |
|
gr.inputs.Slider(1, 10, step=1, default=3, label="max_depth") |
|
] |
|
|
|
|
|
training_interface = gr.Interface( |
|
fn=train_and_evaluate, |
|
inputs=hyperparam_inputs, |
|
outputs="text", |
|
title="Gradient Boosting Training and Evaluation", |
|
description="Train a GradientBoostingClassifier on the Iris dataset with different hyperparameters." |
|
) |
|
|
|
|
|
feature_inputs = [ |
|
gr.inputs.Number(default=5.1, label=feature_names[0]), |
|
gr.inputs.Number(default=3.5, label=feature_names[1]), |
|
gr.inputs.Number(default=1.4, label=feature_names[2]), |
|
gr.inputs.Number(default=0.2, label=feature_names[3]) |
|
] + hyperparam_inputs |
|
|
|
prediction_interface = gr.Interface( |
|
fn=predict_species, |
|
inputs=feature_inputs, |
|
outputs="text", |
|
title="Iris Species Prediction", |
|
description="Use a GradientBoostingClassifier to predict Iris species from user input." |
|
) |
|
|
|
demo = gr.TabbedInterface([training_interface, prediction_interface], |
|
["Train & Evaluate", "Predict"]) |
|
|
|
|
|
demo.launch() |
|
|