UmaKumpatla/Support_Vector_Machine-SVM
0
1import streamlit as st2import pandas as pd3import numpy as np4from sklearn.datasets import load_breast_cancer5from sklearn.model_selection import train_test_split6from sklearn.preprocessing import StandardScaler7from sklearn.svm import SVC8from sklearn.metrics import accuracy_score, classification_report9import matplotlib.pyplot as plt10import seaborn as sns11 12# Streamlit Page Config13st.set_page_config(page_title="SVM Classifier", layout="wide")14st.title("๐ฌ SVM Classifier")15 16# Intro Section17st.markdown("""18## ๐ค What is a Support Vector Machine (SVM)?19Support Vector Machine is a powerful classification algorithm that works by finding the optimal decision boundary (hyperplane) that best separates different classes.20 21### Key Features:22- Maximizes the margin between classes23- Uses support vectors โ data points closest to the margin24- Can handle linear and non-linear data using **kernels**25 26---27 28## ๐ Dataset: Breast Cancer Diagnosis29Weโll classify tumors as **Malignant (1)** or **Benign (0)** based on features from cell nuclei in digitized images.30""")31 32# Load Dataset33@st.cache_data34def load_data():35 data = load_breast_cancer()36 df = pd.DataFrame(data.data, columns=data.feature_names)37 df["target"] = data.target38 return df, data39 40df, data_info = load_data()41 42# Show Data43st.subheader("๐ Data Preview")44st.dataframe(df.head(), use_container_width=True)45 46# Sidebar Settings47st.sidebar.header("โ๏ธ SVM Settings")48kernel = st.sidebar.selectbox("Kernel Type", ["linear", "rbf", "poly"])49C = st.sidebar.slider("Regularization (C)", min_value=0.01, max_value=10.0, value=1.0)50 51# Preprocess52X = df.drop("target", axis=1)53y = df["target"]54 55scaler = StandardScaler()56X_scaled = scaler.fit_transform(X)57 58X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)59 60# Model Training61model = SVC(kernel=kernel, C=C, probability=True, random_state=42)62model.fit(X_train, y_train)63y_pred = model.predict(X_test)64 65# Results66acc = accuracy_score(y_test, y_pred)67st.success(f"โ
Accuracy: {acc * 100:.2f}%")68 69st.markdown("### ๐ Classification Report")70st.text(classification_report(y_test, y_pred, target_names=data_info.target_names))71 72# Feature Visualization73st.subheader("๐ Visualizing with 2 Features")74feature_x = st.selectbox("X-axis Feature", df.columns[:-1], index=0)75feature_y = st.selectbox("Y-axis Feature", df.columns[:-1], index=1)76 77X_vis = df[[feature_x, feature_y]]78X_vis_scaled = scaler.fit_transform(X_vis)79X_train_vis, X_test_vis, y_train_vis, y_test_vis = train_test_split(X_vis_scaled, y, test_size=0.2, random_state=42)80 81model_vis = SVC(kernel=kernel, C=C)82model_vis.fit(X_train_vis, y_train_vis)83 84# Decision Boundary85h = 0.0286x_min, x_max = X_vis_scaled[:, 0].min() - 1, X_vis_scaled[:, 0].max() + 187y_min, y_max = X_vis_scaled[:, 1].min() - 1, X_vis_scaled[:, 1].max() + 188xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))89Z = model_vis.predict(np.c_[xx.ravel(), yy.ravel()])90Z = Z.reshape(xx.shape)91 92fig, ax = plt.subplots(figsize=(8, 6))93plt.contourf(xx, yy, Z, alpha=0.3, cmap="coolwarm")94sns.scatterplot(x=X_vis_scaled[:, 0], y=X_vis_scaled[:, 1], hue=df["target"], palette="coolwarm", ax=ax)95plt.xlabel(feature_x)96plt.ylabel(feature_y)97plt.title("SVM Decision Boundary")98st.pyplot(fig)99 100# Summary101st.markdown("""102---103## ๐ก Summary104- SVM creates a hyperplane that separates classes.105- Works well for small and high-dimensional datasets.106- The `C` parameter controls the trade-off between margin and misclassification.107 108### Tips:109- Use **RBF kernel** for non-linear data.110- Try adjusting C to see how the margin changes.111""")112 113 114 