|
| 1 | +# Video link: https://www.youtube.com/watch?v=Klqn--Mu2pE&ab_channel=PythonEngineer |
| 2 | +import numpy as np |
| 3 | +import streamlit as st |
| 4 | +from sklearn import datasets |
| 5 | +from sklearn.ensemble import RandomForestClassifier |
| 6 | +from sklearn.metrics import accuracy_score, f1_score |
| 7 | +from sklearn.model_selection import train_test_split |
| 8 | +from sklearn.neighbors import KNeighborsClassifier |
| 9 | +from sklearn.svm import SVC |
| 10 | + |
| 11 | +st.title("Beginner ML WebApp") |
| 12 | +st.write( |
| 13 | + "_You can change the dataset and the classifier from the left sidebar._\n\n---" |
| 14 | +) |
| 15 | + |
| 16 | +dataset = st.sidebar.selectbox( |
| 17 | + "Choose a dataset:", ("Iris", "Breast cancer", "Wine dataset") |
| 18 | +) |
| 19 | +clf = st.sidebar.selectbox("Choose a classifier:", ("KNN", "SVM", "Random Forest")) |
| 20 | + |
| 21 | +_dataset = { |
| 22 | + "Iris": datasets.load_iris(), |
| 23 | + "Breast cancer": datasets.load_breast_cancer(), |
| 24 | + "Wine dataset": datasets.load_wine(), |
| 25 | +} |
| 26 | + |
| 27 | + |
| 28 | +def get_dataset(dataset_name): |
| 29 | + _data = _dataset[dataset_name] |
| 30 | + return _data.data, _data.target |
| 31 | + |
| 32 | + |
| 33 | +def get_clf(clf_name): |
| 34 | + if clf_name == "KNN": |
| 35 | + k = st.sidebar.slider("Nearest neighbours to consider:", 1, 15) |
| 36 | + clf = KNeighborsClassifier(n_neighbors=k) |
| 37 | + elif clf_name == "SVM": |
| 38 | + c = st.sidebar.slider("Regularization value:", 0.01, 10.0) |
| 39 | + clf = SVC(C=c) |
| 40 | + elif clf_name == "Random Forest": |
| 41 | + max_depth = st.sidebar.slider("Maximum depth:", 2, 15) |
| 42 | + n_estimators = st.sidebar.slider("Number of estimators:", 1, 100) |
| 43 | + clf = RandomForestClassifier( |
| 44 | + max_depth=max_depth, n_estimators=n_estimators, random_state=42 |
| 45 | + ) |
| 46 | + |
| 47 | + return clf |
| 48 | + |
| 49 | + |
| 50 | +clf = get_clf(clf) |
| 51 | +X, y = get_dataset(dataset) |
| 52 | +X_train, X_test, y_train, y_test = train_test_split( |
| 53 | + X, y, test_size=0.25, random_state=42 |
| 54 | +) |
| 55 | +clf.fit(X_train, y_train) |
| 56 | +preds = clf.predict(X_test) |
| 57 | + |
| 58 | +acc = accuracy_score(y_test, preds) |
| 59 | +f1_macro = f1_score(y_test, preds, average="macro") |
| 60 | +f1_micro = f1_score(y_test, preds, average="micro") |
| 61 | + |
| 62 | +st.write( |
| 63 | + f"Dataset:\n" |
| 64 | + f"#### **{dataset}**\n" |
| 65 | + f"- Shape: **{X.shape}**\n" |
| 66 | + f"- Number of classes: **{len(np.unique(y))}**\n---" |
| 67 | +) |
| 68 | +st.write("Classifier (*with params*):\n" "#### **{}**\n---".format(clf)) |
| 69 | +st.write( |
| 70 | + f"Performance:\n\n" |
| 71 | + f"Accuracy: **{acc}**\n\n" |
| 72 | + f"F1 Score:\n" |
| 73 | + f"- Macro: **{f1_macro}**\n" |
| 74 | + f"- Micro: **{f1_micro}**" |
| 75 | +) |
0 commit comments