badrih21 commited on
Commit
d057ea9
·
1 Parent(s): d8f3298

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +258 -0
app.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+
4
+ df=pd.read_csv('D:/downloads/drug200.csv')
5
+
6
+ # -*- coding: utf-8 -*-
7
+ """pred_drugs_addict.ipynb
8
+
9
+ Automatically generated by Colaboratory.
10
+
11
+ Original file is located at
12
+ https://colab.research.google.com/drive/1miD2NyrOv7i41irDQgUrNs410_vZ-oy9
13
+
14
+ Programme permetttant de detecter sous quelle drogue se trouve un patient.
15
+ """
16
+
17
+ from numpy.core.fromnumeric import shape
18
+ import pandas as pd
19
+ import numpy as np
20
+ from scipy import stats
21
+ import matplotlib.pyplot as plt
22
+ import seaborn as sns
23
+
24
+
25
+ df=pd.read_csv('D:/downloads/drug200.csv')
26
+
27
+ print(df.shape)
28
+ print(df.dtypes)
29
+ print(df.describe)
30
+
31
+ # Extraction des différentes classes de la colonne 'classe'
32
+ classes = df['Drug'].unique()
33
+
34
+ # Affichage des différentes classes
35
+ print(classes)
36
+
37
+ """Nous observons dans notre dataset, plusieurs colonnes qui sont: Age , Sexe, Pression sanguine, taux de cholesterol, ration de sodium a potassium et la colone cible, Type de drogue."""
38
+
39
+ #print(df['Drug'].value_counts(normalize=True))
40
+ #Nous alons commencer par encoder les variables qualitatives afin de pouvoir continuer notre traitement
41
+
42
+ from sklearn.model_selection import train_test_split
43
+ #nous allons encoder les diferentes variables
44
+
45
+ from sklearn.preprocessing import LabelEncoder
46
+
47
+ # Créer un objet LabelEncoder
48
+ label_encoder = LabelEncoder()
49
+
50
+ # Définir la variable de catégorie à encoder
51
+ # Encoder les catégories en entiers
52
+
53
+ Drug_encoded = label_encoder.fit_transform(df['Drug'])
54
+
55
+ Sex_encoded = label_encoder.fit_transform(df['Sex'])
56
+
57
+ BP_encoded = label_encoder.fit_transform(df['BP'])
58
+
59
+ Cholesterol_encoded = label_encoder.fit_transform(df['Cholesterol'])
60
+
61
+ #df.Drug=Drug_encoded
62
+
63
+
64
+ #df.Sex=Sex_encoded
65
+
66
+ #df.BP=BP_encoded
67
+
68
+ #df.Cholesterol= Cholesterol_encoded
69
+
70
+ #print(df['Drug'])
71
+ df
72
+ df.drop("Drug", axis=1, inplace=True)
73
+ df.drop("Sex", axis=1, inplace=True)
74
+ df.drop("BP", axis=1, inplace=True)
75
+ df.drop("Cholesterol", axis=1, inplace=True)
76
+
77
+ # Appending the array to our dataFrame
78
+ # with column name 'Purchased'
79
+ df["Drug"] = Drug_encoded
80
+ df['Sex'] = Sex_encoded
81
+ df['BP'] = BP_encoded
82
+ df['Cholesterol'] = Cholesterol_encoded
83
+ df
84
+
85
+ x = df[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']]
86
+ y = df['Drug']
87
+
88
+
89
+ #nous allons maintenant creer les instances de test et d'entrainement pour x et y
90
+
91
+ from sklearn.model_selection import train_test_split
92
+ X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.5, random_state=0)
93
+
94
+ y
95
+ # choix du model d'entrainement
96
+
97
+
98
+ #Premier : Knn
99
+
100
+
101
+ classifier.fit(X_train, y_train)
102
+
103
+ y_pred = classifier.predict(X_test)
104
+ classifier.score(X_train,y_train)
105
+ #classifier.score(X_test,y_test)
106
+ #Evaluation des performances du modele de KNN
107
+
108
+ #importons les metriques de perf
109
+ from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
110
+
111
+ #accuracy
112
+ acc= round(accuracy_score(y_test,y_pred),6)
113
+
114
+ #precision
115
+ prec=round(precision_score(y_test,y_pred,average='macro'),6)
116
+
117
+ #
118
+ rec=round(recall_score(y_test,y_pred,average='macro'),6)
119
+
120
+ #
121
+ f1= round(f1_score(y_test,y_pred,average='macro'),6)
122
+
123
+ print("Acc=",acc," prec=",prec," rec=",rec," f1=",f1)
124
+
125
+ #recherche des meilleurs parametres
126
+
127
+ for p in [0.1, 0.2, 0.3, 0.4, 0.5]:
128
+ X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=p, random_state=0)
129
+ classifier = KNeighborsClassifier(n_neighbors=6)
130
+ classifier.fit(X_train, y_train)
131
+ y_pred = classifier.predict(X_test)
132
+ acc=round(accuracy_score(y_test,y_pred),6)
133
+ prec=round(precision_score(y_test,y_pred,average='macro'),6)
134
+
135
+ print(acc, prec)
136
+
137
+ score = []
138
+ for i in range(1,5):
139
+ Xtrain, Xtest, ytrain, ytest = train_test_split(x, y, test_size=i/10, random_state=0)
140
+ classifier = KNeighborsClassifier(n_neighbors=6)
141
+ classifier.fit(Xtrain, ytrain)
142
+ ypred = classifier.predict(Xtest)
143
+ acc=round(accuracy_score(ytest,ypred),6)
144
+ prec=round(precision_score(ytest,ypred,average='macro'),6)
145
+ score.append(acc)
146
+
147
+ score_rate = pd.DataFrame(data = score, columns = ['Acc'])
148
+ score_rate.insert(loc=0, column = 'test_size', value=range(1,5))
149
+
150
+ X = score_rate['test_size']
151
+ Y = score_rate['Acc']
152
+ fig = px.bar(X,Y)
153
+ fig.show()
154
+
155
+
156
+ score = []
157
+ for i in range(1,51):
158
+ clf = RandomForestClassifier(criterion = 'entropy', n_estimators = i)
159
+ clf.fit(X_train,y_train)
160
+ scores = clf.score(X_test,y_test)
161
+ score.append(scores)
162
+
163
+ score_rate = pd.DataFrame(data = score, columns = ['Score'])
164
+ score_rate.insert(loc=0, column = 'n_estimators', value=range(1,51))
165
+
166
+ X = score_rate['n_estimators']
167
+ Y = score_rate['Score']
168
+ fig = px.bar(X,Y)
169
+ fig.show()
170
+ print("dd")
171
+ print(clf.score(X_test,y_test))
172
+
173
+ #Essayons la svm
174
+ from sklearn import svm
175
+
176
+ # Entraîner le SVM
177
+ clf = svm.SVC(kernel='linear')
178
+ clf.fit(X_train, y_train)
179
+
180
+ #testons la svm
181
+
182
+ y_pred = clf.predict(X_test)
183
+ accuracy = accuracy_score(y_test, y_pred)
184
+ prec=round(precision_score(y_test,y_pred,average='macro'),6)
185
+ print("Accuracy:", accuracy)
186
+ print(prec)
187
+
188
+ """Meilleure accuracy"""
189
+
190
+ #Normaliser les données
191
+ X_train_norm = (X_train - X_train.min()) / (X_train.max() - X_train.min())
192
+ X_test_norm = (X_test - X_train.min()) / (X_train.max() - X_train.min())
193
+
194
+ clf.fit(X_train_norm, y_train)
195
+
196
+ # Tester le modèle
197
+
198
+
199
+
200
+ y_pred = clf.predict(X_test_norm)
201
+ accuracy = accuracy_score(y_test, y_pred)
202
+ prec=round(precision_score(y_test,y_pred,average='macro'),6)
203
+ print("Accuracy:", accuracy)
204
+ print(prec)
205
+ i=Y.max()
206
+ print("Accuracy:::",i)
207
+
208
+ """Prefere la version non normalise."""
209
+
210
+ clf = RandomForestClassifier(criterion = 'entropy', n_estimators = 4)
211
+ clf.fit(X_train,y_train)
212
+ score = clf.score(X_test,y_test)
213
+ print(score)
214
+
215
+ def start(Age,Sex,BP,Cholesterol,Na_to_K):
216
+ if (Sex =='male'):
217
+ sex = "1"
218
+ if (Sex =='female'):
219
+ sex = "0"
220
+ if (BP =='LOW'):
221
+ bp = "1"
222
+ if (BP =='NORMAL'):
223
+ bp = "2"
224
+ if (BP =='HIGH'):
225
+ bp = "0"
226
+ if (Cholesterol =='LOW'):
227
+ ch = "1"
228
+ if (Cholesterol =='NORMAL'):
229
+ ch = "2"
230
+ if (Cholesterol =='HIGH'):
231
+ ch = "0"
232
+ cels = Na_to_K
233
+ data = []
234
+ data = [[Age,sex,bp,ch,cels]]
235
+ pred = pd.DataFrame(data, columns=['Age','Sex','BP','Cholesterol','Na_to_K'])
236
+ y_pred = clf.predict(pred)
237
+ if (y_pred ==0):
238
+ ch = "Drug: Y"
239
+ if (y_pred ==4):
240
+ ch = "Drug: X"
241
+ if (y_pred ==3):
242
+ ch = "Drug: C"
243
+ if (y_pred ==1):
244
+ ch = "Drug: A"
245
+ if (y_pred ==2):
246
+ ch = "Drug: B"
247
+ return ch
248
+
249
+
250
+ def is_number(x):
251
+ return bool(re.match("^[0-9]+$", x))
252
+
253
+ input_text = gr.inputs.Textbox(label="Na_to_K")
254
+ sex = gr.inputs.Radio(['female', 'male'], label="Sex")
255
+ BP = gr.inputs.Radio(['LOW','NORMAL','HIGH'], label="BP")
256
+ Cholesterol = gr.inputs.Radio(['LOW','NORMAL','HIGH'], label="Cholesterol")
257
+ face = gr.Interface(fn=start, inputs=[gr.inputs.Slider(1, 130),sex,BP,Cholesterol,input_text],examples = [[51,"male","HIGH","LOW",5],[60,"male","HIGH","NORMAL",8.61],[69,"female","NORMAL","HIGH",10.05],[64,"female","LOW","NORMAL",25.61],[22,"male","LOW","HIGH",8.11]],cache_examples = True ,outputs=["text"])
258
+ face.launch()