forked from sirreajohn/Lumin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassification_POC.py
More file actions
222 lines (149 loc) · 8.98 KB
/
classification_POC.py
File metadata and controls
222 lines (149 loc) · 8.98 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
220
221
222
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 1 15:03:14 2021
@author: mahesh
"""
#------------------basic_Libs-----------------
import pandas as pd
import random
#-----------------------preprocessing-----------------
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
#--------------------------algorithms-----------------------
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
#------------------------------metrics------------------------
from sklearn.metrics import accuracy_score,confusion_matrix,f1_score,precision_score,recall_score,roc_curve,auc
from tqdm import tqdm
#---------------------STREAMLIT AND PLOTLY-------------------------
import streamlit as st
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
#-----------------------------Start here-------------------------------
st.set_option('deprecation.showfileUploaderEncoding', False)
st.title("Project Lumin -- Classification report")
st.markdown("this is a automated report generated by Project Lumin, an Unified Machine Learning Framework.")
#------------User defined-------------------
data_path = st.file_uploader("drop the data set here: ", type = ["csv"])
if data_path:
data = pd.read_csv(data_path)
tar_var = st.selectbox("choose Y var(prediction)",list(data.columns))
if st.button("press here"):
target = data[tar_var]
#--------------------------------------preprocessing-------------------------------
drop_str = [col for col in data.columns if type(data[col][0]) == str]
data_head = data.copy(deep = True) #is used in presentation
data = data.drop(drop_str,axis = 1)
data = data.drop(target.name, axis = 1) #dropping y from data
corr_mat = data_head.corr() # for later use in presentation
pca = False # FIX THIS!
if len(data.columns) > 2:
pca = True
#------------------------------scaling------------------------
sc_1 = StandardScaler()
x_scaled = sc_1.fit_transform(data)
#----------------------------splits---------------------
x_train,x_test,y_train,y_test = train_test_split(x_scaled,target ,test_size = 0.2, random_state = 177013)
#-----------------------PCA only if >2 cols---------------
if pca == True:
pca = PCA(n_components = 2)
x_train = pd.DataFrame(data = pca.fit_transform(x_train),columns = ['pc1',"pc2"]).iloc[:,:].values
x_test = pca.transform(x_test)
#----------------------------algorithms-----------------------------NB is disqualified
# (has some reservations about neg values)
classification_models = {"LR":LogisticRegression(),"SVC":SVC(kernel = "rbf"),
"DTC":DecisionTreeClassifier(),
"RFC":RandomForestClassifier(n_estimators = 500),
"XGBC":XGBClassifier(n_estimators = 500)}
metric_dict = {}
accu_dict = {}
for name,algorithm in tqdm(classification_models.items()):
model = algorithm
model.fit(x_train,y_train)
y_pred = model.predict(x_test)
metric_dict[name] = {"precision":round(precision_score(y_test,y_pred,pos_label=y_pred[0]),2),
"recall":round(recall_score(y_test,y_pred,pos_label=y_pred[0]),2),
"f1_score":round(f1_score(y_test,y_pred,average = 'micro'),2),
"accuracy":accuracy_score(y_test,y_pred),
"confusion":confusion_matrix(y_test,y_pred),
"ROC_Vals" :roc_curve(y_test,y_pred,pos_label=y_pred[0])}
accu_dict[name] = accuracy_score(y_test,y_pred)
#-------------------------helper FUNCTIONS---------------------
def list_maker(metric_dict,keyword = "accuracy"):
key_list = list(metric_dict.keys())
return [metric_dict[key][keyword] for key in key_list]
def random_color(metric_dict):
return ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(len(metric_dict))]
metric_df = pd.DataFrame(metric_dict).drop(["confusion","ROC_Vals"],axis = 0)
metric_df.reset_index(inplace = True)
#--------------------------------------------- presentation and graphs -----------------------------------0
#-------------------------------------view data --------------------------
st.header("Lets look at what we are dealing with ")
st.dataframe(data_head.head())
#-----------------------------corelation_plot----------------------------------
st.header("Corelation Plot")
st.markdown("zoom if intelligible")
corr_val = data.corr()
corr = ff.create_annotated_heatmap(y = corr_val.index.tolist(),
x = corr_val.columns.tolist(),z = corr_val.values)
for i in range(len(corr.layout.annotations)):
corr.layout.annotations[i].font.size = 8
corr.layout.annotations[i].text = str(round(float(corr.layout.annotations[i].text),4))
corr.update_layout(width = 800,height = 800)
st.plotly_chart(corr)
st.header("METRICS FOR CLASSIFICATION ALGORITHMS")
#------------------------metric_table-----------------
table = ff.create_table(metric_df)
table.update_layout(width = 1350)
st.plotly_chart(table)
#--------------heatmaps------------------------------
st.markdown("### CONFUSION MATRICES")
fig = make_subplots(rows = 1,cols =len(metric_df.columns[1:].values),
shared_yaxes=True,horizontal_spacing=0.05,
subplot_titles= metric_df.columns[1:].values)
annot_var = []
axis_count = 0
row_col = []
for row in range(1,2):
for col in range(1,6):
row_col.append([row,col])
row_col_pos = 0
for al in metric_df.columns[1:].values:
heatmap2 = ff.create_annotated_heatmap(z = metric_dict[al]["confusion"],x = ["1_pred","0_pred"],
y = ["1_true","0_true"],
annotation_text= metric_dict[al]["confusion"])
fig.add_trace(heatmap2.data[0],row_col[row_col_pos][0],row_col[row_col_pos][1])
annot_temp = list(heatmap2.layout.annotations)
axis_count = axis_count + 1
row_col_pos = row_col_pos+1
for k in range(len(annot_temp)):
annot_temp[k]['xref'] = "x"+str(axis_count)
annot_temp[k]['yref'] = 'y'+str(axis_count)
annot_var= annot_var + annot_temp
lo = list(fig['layout']["annotations"]) + annot_var
fig.update_layout(annotations = lo,autosize = True,width = 1350)
st.plotly_chart(fig)
#------------scatter plots----------------
fpr, tpr,thres = roc_curve(y_test,y_pred,pos_label=y_pred[0])
scatter_plot = go.Figure(go.Scatter(x = [0,1], y = [0,1], mode = "lines", name = "ref"))
for al in metric_df.columns[1:].values:
AUC_val = auc(metric_dict[al]["ROC_Vals"][0].tolist(),metric_dict[al]["ROC_Vals"][1].tolist())
scat = go.Scatter(x = metric_dict[al]["ROC_Vals"][0].tolist(),
y = metric_dict[al]["ROC_Vals"][1].tolist(),
name = f"{al} - AUC val - {AUC_val:.2f}")
scatter_plot.add_trace(scat)
scatter_plot.update_layout(width = 1300,height = 500)
st.header("ROC_curves")
st.plotly_chart(scatter_plot)
#-------------funnel-chart-----------------
st.header("Recommendations")
st.markdown("the percent below classifier represents recommended probability for classifier")
accu_dict = dict(sorted(accu_dict.items(), key=lambda item: item[1],reverse=True))
funnel = go.Figure(go.Funnelarea(values = list(accu_dict.values()),text = list(accu_dict.keys())))
funnel.update_layout(showlegend = False)
st.plotly_chart(funnel)