-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
219 lines (181 loc) · 7.23 KB
/
app.py
File metadata and controls
219 lines (181 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import streamlit as st
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.cluster import DBSCAN, MeanShift, SpectralClustering, AffinityPropagation
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
silhouette_score,
roc_curve,
roc_auc_score,
normalized_mutual_info_score,
)
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import numpy as np
# Set layout to wide in order to make the columns fill the whole page
st.set_page_config(layout="wide")
def run_supervised(algorithm, df, label_col, st_col):
# Split dataframe to features and labels
x = df.drop(label_col, axis=1)
# Normalize dataset
x = StandardScaler().fit_transform(x)
y = df[label_col]
# Split to train and test
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
# Pick model
if algorithm == "KNN":
n_neighbors = st_col.number_input(
label="Select minimum number of neighbors", min_value=1, value=5
)
model = KNeighborsClassifier(n_neighbors=n_neighbors)
elif algorithm == "LR":
model = LogisticRegression()
elif algorithm == "DT":
model = DecisionTreeClassifier(random_state=0)
elif algorithm == "RF":
max_depth = st_col.number_input(
label="Select minimum number of neighbors", min_value=1, value=2
)
model = RandomForestClassifier(max_depth=max_depth, random_state=0)
# Train and get test results
model.fit(x_train, y_train)
y_pred = model.predict(x_test)
# Calulcate metrics
y_scores = model.predict_proba(x)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average="weighted")
recall = recall_score(y_test, y_pred, average="weighted")
results_dict = {
"Metric": ["Accuracy", "Precision", "Recall"],
"Score": [accuracy, precision, recall],
}
st_col.table(results_dict)
y_onehot = pd.get_dummies(y, columns=model.classes_)
# Draw AUC curve
fig = go.Figure()
fig.add_shape(type="line", line=dict(dash="dash"), x0=0, x1=1, y0=0, y1=1)
for i in range(y_scores.shape[1]):
y_true = y_onehot.iloc[:, i]
y_score = y_scores[:, i]
fpr, tpr, _ = roc_curve(y_true, y_score)
auc_score = roc_auc_score(y_true, y_score)
name = f"{y_onehot.columns[i]} (AUC={auc_score:.2f})"
fig.add_trace(go.Scatter(x=fpr, y=tpr, name=name, mode="lines"))
fig.update_layout(
xaxis_title="False Positive Rate",
yaxis_title="True Positive Rate",
yaxis=dict(scaleanchor="x", scaleratio=1),
xaxis=dict(constrain="domain"),
width=700,
height=500,
)
st_col.plotly_chart(fig, use_container_width=True)
def run_unsupervised(algorithm, df, label_col, st_col):
# Split dataframe to features and labels
x = df.drop(label_col, axis=1)
y = df[label_col]
# Normalize dataset
x = StandardScaler().fit_transform(x)
# Pick model
if algorithm == "DBS":
eps = st_col.slider(
label="Select maximum distance for neighbors",
min_value=0.1,
max_value=2.0,
step=0.1,
value=0.5,
)
min_samples = st_col.number_input(
label="Select minimum number of neighbors", min_value=3, value=5
)
model = DBSCAN(eps=eps, min_samples=min_samples)
elif algorithm == "MS":
bandwidth = st_col.slider(
label="Select maximum distance for neighbors",
min_value=0.5,
max_value=10.0,
step=0.5,
value=2.0)
model = MeanShift(bandwidth=bandwidth)
elif algorithm == "SC":
n_clusters = st_col.number_input(
label="Select the number of clusters", min_value=1, value=2
)
model = SpectralClustering(
n_clusters=n_clusters, assign_labels="discretize", random_state=0
)
elif algorithm == "AP":
model = AffinityPropagation(random_state=5)
# Fit the model to the data
clustering_labels = model.fit_predict(x)
graph_df = df.drop(label_col, axis=1)
graph_df["labels"] = clustering_labels.astype("str")
clusters_labeled = np.concatenate(
[clustering_labels[:, np.newaxis], y[:, np.newaxis]], axis=1
)
silhouette = silhouette_score(graph_df, graph_df["labels"])
nmis = normalized_mutual_info_score(y, clustering_labels)
results_dict = {
"Metric": ["Silhouette Score", "Normalized Mutual Information Score"],
"Score": [silhouette, nmis],
}
st_col.table(results_dict)
st_col.write(f"Number of Clusters Found: {len(set(clustering_labels))}")
# Plot the clusters
with st_col.expander("Show Cluster Plot"):
fig = px.scatter(
x=graph_df[graph_df.keys()[0]],
y=graph_df[graph_df.keys()[1]],
color=clusters_labeled[:, 0],
color_discrete_sequence=["orange", "red", "green", "blue", "purple"],
)
fig.update_layout(plot_bgcolor="rgb(47,47,47)")
fig.update_layout(showlegend=False)
fig.update_layout(height=400, width=550)
st_col.plotly_chart(fig)
if __name__ == "__main__":
file = st.sidebar.file_uploader("Insert CSV file...")
if file is not None:
sep = st.sidebar.text_input("Seperator: ", value=",")
if st.sidebar.checkbox("File contains headers"):
df = pd.read_csv(file, sep=sep)
else:
df = pd.read_csv(file, sep=sep, index_col=False)
# Remove possible id column
for key in df:
if "id" in str.lower(key):
df = df.drop(key, axis=1)
if st.sidebar.checkbox("Show dataframe"):
st.sidebar.write(df.head())
label_col = st.sidebar.selectbox(
"Select Labels Column", df.keys(), index=len(df.keys()) - 1
)
col1, col2 = st.columns((10, 10), gap="large")
supervised_map = {
"K Nearest Neighbors": "KNN",
"Logistic Regression": "LR",
"Decision Tree Classifier": "DT",
"Random Forest Classifier": "RF",
}
supervised_classifier = col1.selectbox(
"Pick a supervised algorithm to use", supervised_map.keys()
)
run_supervised(supervised_map[supervised_classifier], df, label_col, col1)
unsupervised_map = {
"Mean Shift": "MS",
"DBSCAN": "DBS",
"Spectral Clustering": "SC",
"Affinity Propagation": "AP",
}
unsupervised_classifier = col2.selectbox(
"Pick an unsupervised algorithm to use", unsupervised_map.keys()
)
run_unsupervised(unsupervised_map[unsupervised_classifier], df, label_col, col2)