WanjohiK's picture
Update app.py
60280c3 verified
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier
from sklearn.svm import SVC
import pandas as pd
import gradio as gr
# Load dataset
df1 = pd.read_csv("iris_dataset.csv")
# Preprocessing
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(df1["species"])
# Split the dataset
X = df1[["sepal_length", "sepal_width", "petal_length", "petal_width"]]
y = y_encoded
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Base models
rf = RandomForestClassifier(n_estimators=100, random_state=42)
gb = GradientBoostingClassifier(random_state=42)
svm = SVC(probability=True, kernel='rbf', random_state=42)
# Voting Classifier (Hard voting)
voting_model = VotingClassifier(
estimators=[('rf', rf), ('gb', gb), ('svm', svm)],
voting='hard'
)
# Train model
voting_model.fit(X_train, y_train)
# Predict & Evaluate
y_pred_test = voting_model.predict(X_test)
y_pred_train = voting_model.predict(X_train)
print("Voting Ensemble Train Accuracy:", accuracy_score(y_train, y_pred_train))
print("Voting Ensemble Test Accuracy:", accuracy_score(y_test, y_pred_test))
print("\nClassification Report (Test Data):\n", classification_report(y_test, y_pred_test))
# ===============================
# GRADIO APP
# ===============================
def predict_iris_species(sepal_length, sepal_width, petal_length, petal_width):
# Create DataFrame for model input
user_input = pd.DataFrame(
[[sepal_length, sepal_width, petal_length, petal_width]],
columns=['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
)
# Predict encoded label
pred_encoded = voting_model.predict(user_input)[0]
# Convert back to species name
pred_label = label_encoder.inverse_transform([pred_encoded])[0]
return f"Predicted Iris Species: {pred_label}"
# Build Gradio interface
interface = gr.Interface(
fn=predict_iris_species,
inputs=[
gr.Number(label="Sepal Length"),
gr.Number(label="Sepal Width"),
gr.Number(label="Petal Length"),
gr.Number(label="Petal Width")
],
outputs=gr.Textbox(label="Prediction"),
title="Iris Species Prediction",
description="Enter iris measurements to predict the species using a Voting Ensemble model."
)
interface.launch(share=True)