File size: 5,184 Bytes
6f65fff
 
 
 
 
 
 
 
07998e0
6f65fff
 
 
 
 
 
 
 
 
 
07998e0
 
6f65fff
 
 
 
 
 
 
07998e0
6f65fff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07998e0
6f65fff
07998e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f65fff
 
 
 
 
 
07998e0
 
 
 
6f65fff
 
 
 
 
07998e0
6f65fff
 
07998e0
6f65fff
 
 
 
 
 
 
 
07998e0
6f65fff
 
 
 
07998e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f65fff
 
07998e0
 
6f65fff
07998e0
6f65fff
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import gradio as gr
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler

from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

import mlflow
import mlflow.sklearn

sns.set(style="whitegrid")

# ----------------------------
# Load Iris Data
# ----------------------------
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["target"] = iris.target

# Scale
scaler = StandardScaler()
x_scaled = scaler.fit_transform(iris.data)
y = iris.target

# Split
x_train, x_test, y_train, y_test = train_test_split(
    x_scaled, y, test_size=0.2, random_state=42
)

# ----------------------------
# MLflow Setup
# ----------------------------
mlflow.set_experiment("iris-Experiment")

models = {
    "Logistic Regression": LogisticRegression(),
    "KNN (k=3)": KNeighborsClassifier(n_neighbors=3),
    "Decision Tree": DecisionTreeClassifier(),
    "Linear SVM": SVC(kernel="linear"),
}

trained_models = {}

def train_and_log(model, name):
    with mlflow.start_run(run_name=name):
        model.fit(x_train, y_train)
        y_pred = model.predict(x_test)
        acc = accuracy_score(y_test, y_pred)

        mlflow.log_param("model_name", name)
        mlflow.log_metric("accuracy", acc)
        mlflow.sklearn.log_model(model, name)

        trained_models[name] = model

for name, model in models.items():
    train_and_log(model, name)

# ----------------------------
# Visualization Functions
# ----------------------------
def create_plot(func_name):
    plt.figure(figsize=(7,5))

    if func_name == "Pairplot":
        sns.pairplot(df, hue="target")
        plt.savefig("pairplot.png")
        return "pairplot.png"

    elif func_name == "Correlation Heatmap":
        plt.figure(figsize=(8,6))
        sns.heatmap(df.iloc[:, :-1].corr(), annot=True, cmap="viridis")
        plt.title("Feature Correlation Heatmap")
        plt.savefig("heatmap.png")
        return "heatmap.png"

    elif func_name == "Boxplot":
        plt.figure(figsize=(8,6))
        df_melt = df.melt(id_vars="target", var_name="feature", value_name="value")
        sns.boxplot(x="feature", y="value", hue="target", data=df_melt)
        plt.xticks(rotation=45)
        plt.title("Boxplot of Features")
        plt.tight_layout()
        plt.savefig("boxplot.png")
        return "boxplot.png"

    elif func_name == "Violin Plot":
        plt.figure(figsize=(8,6))
        sns.violinplot(x="feature", y="value", hue="target", data=df_melt, split=True)
        plt.xticks(rotation=45)
        plt.title("Violin Plot of Features")
        plt.tight_layout()
        plt.savefig("violin.png")
        return "violin.png"

    elif func_name == "Countplot":
        sns.countplot(x=df["target"])
        plt.title("Class Distribution")
        plt.savefig("countplot.png")
        return "countplot.png"

    elif func_name == "Scatterplot (Petal Length vs Width)":
        sns.scatterplot(
            x=df["petal length (cm)"],
            y=df["petal width (cm)"],
            hue=df["target"],
            palette="deep",
            s=70
        )
        plt.title("Petal Length vs Petal Width")
        plt.savefig("scatter.png")
        return "scatter.png"


# ----------------------------
# Prediction Function
# ----------------------------
def predict(model_name, sepal_length, sepal_width, petal_length, petal_width):
    model = trained_models[model_name]
    x = np.array([[sepal_length, sepal_width, petal_length, petal_width]])
    x_scaled = scaler.transform(x)
    pred = model.predict(x_scaled)[0]
    return f"Predicted Class: {iris.target_names[pred]}"

# ----------------------------
# Build Gradio UI
# ----------------------------
with gr.Blocks() as demo:
    gr.Markdown("## 🌸 Iris Classification with MLflow + Rich Visualizations")

    with gr.Row():
        model_choice = gr.Dropdown(list(trained_models.keys()), label="Select ML Model")

    with gr.Row():
        sepal_length = gr.Number(label="Sepal Length")
        sepal_width = gr.Number(label="Sepal Width")
        petal_length = gr.Number(label="Petal Length")
        petal_width = gr.Number(label="Petal Width")

    predict_btn = gr.Button("Predict")
    output = gr.Textbox(label="Prediction")

    predict_btn.click(
        predict,
        inputs=[model_choice, sepal_length, sepal_width, petal_length, petal_width],
        outputs=output
    )

    gr.Markdown("### 📊 Choose Visualization")

    graph_choice = gr.Dropdown(
        [
            "Pairplot",
            "Correlation Heatmap",
            "Boxplot",
            "Violin Plot",
            "Countplot",
            "Scatterplot (Petal Length vs Width)",
        ],
        label="Select Graph"
    )

    plot_btn = gr.Button("Show Graph")
    graph_output = gr.Image()

    plot_btn.click(create_plot, inputs=graph_choice, outputs=graph_output)

demo.launch()