akshaymudmal/SupervisedUnsupervisedLearning
0
1import streamlit as st2import numpy as np3import matplotlib.pyplot as plt4from sklearn.datasets import make_classification, make_blobs5from sklearn.linear_model import LogisticRegression6from sklearn.cluster import KMeans7 8# Disable Streamlit style elements to hide branding9hide_streamlit_style = """10 <style>11 #MainMenu {visibility: hidden;}12 footer {visibility: hidden;}13 header {visibility: hidden;}14 </style>15 """16st.markdown(hide_streamlit_style, unsafe_allow_html=True)17 18st.title("๐ Interactive Learning: Supervised vs Unsupervised Learning")19st.markdown("Adjust the sliders below to explore how supervised and unsupervised learning works!")20 21tab1, tab2 = st.tabs(["Supervised Learning", "Unsupervised Learning"])22 23with tab1:24 st.header("Supervised Learning: Classification")25 samples = st.slider("Number of Samples", 50, 500, 100, step=10)26 class_sep = st.slider("Class Separation", 0.5, 3.0, 1.0, step=0.1)27 28 # Generate classification data29 X, y = make_classification(30 n_samples=samples, n_features=2, n_classes=2,31 n_redundant=0, n_informative=2, class_sep=class_sep, random_state=4232 )33 clf = LogisticRegression().fit(X, y)34 35 fig, ax = plt.subplots(figsize=(6, 6))36 ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bwr", edgecolors="k")37 38 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 139 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 140 xx, yy = np.meshgrid(np.linspace(x_min, x_max, 200), np.linspace(y_min, y_max, 200))41 Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)42 ax.contourf(xx, yy, Z, alpha=0.2, cmap="bwr")43 44 ax.set_title("Supervised Learning: Classification")45 st.pyplot(fig)46 47with tab2:48 st.header("Unsupervised Learning: Clustering")49 samples_unsup = st.slider("Number of Samples", 50, 500, 100, step=10, key="unsup_samples")50 clusters = st.slider("Number of Clusters", 2, 6, 3, step=1)51 cluster_std = st.slider("Cluster Spread (Std)", 0.2, 2.0, 1.0, step=0.1)52 53 X_unsup, _ = make_blobs(54 n_samples=samples_unsup, centers=clusters, n_features=2,55 cluster_std=cluster_std, random_state=4256 )57 kmeans = KMeans(n_clusters=clusters, random_state=42).fit(X_unsup)58 y_kmeans = kmeans.predict(X_unsup)59 60 fig_unsup, ax_unsup = plt.subplots(figsize=(6, 6))61 scatter = ax_unsup.scatter(X_unsup[:, 0], X_unsup[:, 1], c=y_kmeans, cmap="viridis", edgecolors="k")62 ax_unsup.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1],63 s=200, c="red", marker="X", label="Cluster Centers")64 ax_unsup.set_title("Unsupervised Learning: Clustering")65 ax_unsup.legend()66 st.pyplot(fig_unsup)67 