KNN_Classifier / app.py
saramneena's picture
Upload 3 files
b016c22 verified
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification, make_circles, make_blobs, make_moons
from sklearn.model_selection import train_test_split, learning_curve
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, f1_score
from mlxtend.plotting import plot_decision_regions
# 🌟 Display image (Logo)
st.image("innomatics_logo.png", width=600)
# πŸ† Streamlit App Title
st.title("πŸ” KNN Classifier: Decision Boundaries & Learning Curve")
# πŸ“Œ Select dataset
st.sidebar.header("πŸ“Š Select Dataset")
data = st.sidebar.selectbox("Choose a dataset type:", ("Classification", "Circles", "Blobs", "Moons"))
if data == "Classification":
X, y = make_classification(n_samples=100, n_features=2, n_redundant=0, random_state=42)
elif data == "Circles":
X, y = make_circles(n_samples=100, factor=0.5, noise=0.05)
elif data == "Blobs":
X, y = make_blobs(n_samples=250, centers=2, n_features=2, cluster_std=1.0, random_state=42)
elif data == "Moons":
X, y = make_moons(n_samples=250, noise=0.1, random_state=42)
# πŸ”€ Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# πŸ“Œ Function to plot decision boundary
def plot_decision_surface(X, y, model, title):
plt.figure(figsize=(6, 4))
plot_decision_regions(X, y, clf=model, colors="red,blue,green")
plt.title(title, fontsize=12, color="purple")
plt.xlabel("Feature 1", fontsize=10, color="blue")
plt.ylabel("Feature 2", fontsize=10, color="blue")
st.pyplot(plt.gcf(), clear_figure=True)
# πŸ”§ KNN Classifier Parameters
st.sidebar.header("βš™οΈ KNN Parameters")
n_neighbors = st.sidebar.slider("πŸ”’ Number of Neighbors (k)", 1, 15, 3)
weights = st.sidebar.radio("βš–οΈ Weight Function", ("uniform", "distance"))
algorithm = st.sidebar.selectbox("πŸ“Œ Algorithm", ("auto", "ball_tree", "kd_tree", "brute"))
# 🎯 Initialize and Train Model
model = KNeighborsClassifier(n_neighbors=n_neighbors, weights=weights, algorithm=algorithm)
model.fit(X_train, y_train)
# πŸ“Œ Make Predictions
y_pred = model.predict(X_test)
# πŸ“Š Compute Accuracy & F1-score
accuracy = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
# 🎯 Model Performance Metrics
st.subheader("πŸ“ˆ Model Performance")
st.markdown(f"βœ… **Accuracy:** `{accuracy:.2f}` 🎯")
st.markdown(f"πŸ† **F1-score:** `{f1:.2f}` πŸ”₯")
# 🎨 Plot Decision Boundary
st.subheader("πŸ–ΌοΈ Decision Boundary")
plot_decision_surface(X, y, model, "🌍 KNN Decision Surface")
# πŸ“‰ Plot Learning Curve
def plot_learning_curve(model, X, y):
train_sizes, train_scores, test_scores = learning_curve(
model, X, y, cv=5, scoring="accuracy", train_sizes=np.linspace(0.1, 1.0, 10)
)
train_mean = np.mean(train_scores, axis=1)
test_mean = np.mean(test_scores, axis=1)
plt.figure(figsize=(6, 4))
plt.plot(train_sizes, train_mean, "o-", label="πŸ‹οΈ Training Accuracy", color="green")
plt.plot(train_sizes, test_mean, "o-", label="πŸ§ͺ Validation Accuracy", color="red")
plt.xlabel("Training Samples", fontsize=10, color="blue")
plt.ylabel("Accuracy", fontsize=10, color="blue")
plt.title("πŸ“Š Learning Curve: KNN", fontsize=12, color="purple")
plt.legend()
st.pyplot(plt.gcf(), clear_figure=True)
# πŸ“Š Display Learning Curve
st.subheader("πŸ“š Learning Curve")
plot_learning_curve(model, X, y)