-
Notifications
You must be signed in to change notification settings - Fork 8
/
cli.py
366 lines (184 loc) · 8.28 KB
/
cli.py
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# Librerías estándar de análisis de datos
import pandas as pd
import numpy as np
# Librerías de visualización
import warnings
warnings.filterwarnings("ignore")
# Una variable para la ruta, buenas prácticas
path_to_data = "./stroke_dataset.csv"
# variables data usuario
#Mensaje de bienvenida
#Mensaje de bienvenida
print("¡Hola! Introduce los datos del nuevo paciente")
#Escribimos genero
gender = input("Por favor ingrese el genero del paciente (Male/Female): ")
#Escribimos work_type
work_type = input("\nPor favor ingrese el tipo de trabajo(Private/Self-employed/Govt_job/children): \n")
##Leemos Residence_type
residence_type = input("\nPor favor ingrese el tipo de residencia(Urban/Rural): \n")
##Leemos smoking_status
smoking_status = input("\nPor favor ingrese el tipo de fumador(formerly smoked/never smoked/smokes/Unknown): \n")
##Leemos age
age = input("\nPor favor ingrese la edad del pàciente: \n")
##Leemos hypertension
hypertension = input("\nPor favor ingrese la hipertension(1 or 0): \n")
##Leemos heart_disease
heart_disease = input("\nPor favor ingrese si esta enfermo del corazón(1 or 0): \n")
##Leemos avg_glucose_level
avg_glucose_level = input("\nPor favor ingrese nivel medio de glucosa: \n")
##Leemos avg_glucose_level
bmi = input("\nPor favor ingrese el BMI (Base Muscle Index): \n")
#Age será un entero o binario (0 ó 1)
age = int(age)
#BMI, avg_glucose_level será un real, así que usamos float()
bmi = float(bmi)
avg_glucose_level = float(avg_glucose_level)
#Bool
heart_disease = int(heart_disease)
hypertension = int(hypertension)
list_variables_predictoras = [[gender, age, hypertension, heart_disease, work_type, residence_type, avg_glucose_level, bmi, smoking_status]]
list_variables_predictoras
#Llamo a mi funcion predictora
#predict(variables_predictoras)
list_variables_predictoras
columns = ['gender', 'age', 'hypertension', 'heart_disease', 'work_type', 'Residence_type', 'avg_glucose_level', 'bmi', 'smoking_status']
# dataframe del usuario
df_usuario_test = []
df_usuario_test = pd.DataFrame(list_variables_predictoras, columns = columns)
# df en crudo
print( df_usuario_test.head() )
#print(f"columnas", df_usuario_test.columns )
print()
print()
# df One Hot Encoding
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
df_usuario_test = pd.get_dummies(df_usuario_test)
print(f"\n----------------dummies---------------\n", df_usuario_test.head() )
df_usuario_test = pd.DataFrame(scaler.fit_transform(df_usuario_test))
print(f"\n-----------------test-----------------\n", df_usuario_test.head() )
# Importamos el dataset
df = pd.read_csv(path_to_data)
df["hypertension"] = df["hypertension"].astype(bool)
df["heart_disease"] = df["heart_disease"].astype(bool)
df["stroke"] = df["stroke"].astype(bool)
df["stroke"].value_counts()
df.isnull().sum(axis = 0)
df_duplicadas = df[df.duplicated()]
len(df_duplicadas)
df.describe()
categoricas = ["gender", "ever_married", "work_type", "Residence_type", "smoking_status", "hypertension", "heart_disease", "stroke"]
numericas = ["age", "avg_glucose_level", "bmi"]
df.corr()
## se elimina variable objetivo, por que es la que queremos predecir
X = df.drop("stroke", axis=1)
y = df["stroke"]
#print("X:\n",X)
#print("y:\n",y)
X.head()
y.head()
#XX.head()
#yy.head()
categoricas = ["gender", "ever_married", "work_type", "Residence_type", "smoking_status", "hypertension", "heart_disease"]
from imblearn.under_sampling import RandomUnderSampler
rus = RandomUnderSampler(sampling_strategy=1) # Float
X, y = rus.fit_resample(X,y)
#from imblearn import under_sampling
#balanced = under_sampling.NearMiss()
#X, y = balanced.fit_resample(X, y)
#//who to connect a sqlite3?
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
transformer_numerico = ("transformer_numerico", MinMaxScaler(), numericas)
transformer_categorico = ("transformer_categorico", OneHotEncoder(), categoricas)
transformer = ColumnTransformer([transformer_numerico, transformer_categorico], remainder="passthrough")
X = transformer.fit_transform(X)
print(X)
pd.DataFrame(X, columns = transformer.get_feature_names_out())
#pd.DataFrame(XX, columns = transformer.get_feature_names_out())
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, random_state=1)
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score
from sklearn.metrics import r2_score
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import confusion_matrix
import pickle
def train_evaluate(nombre_modelo, modelo):
#LogisticRegression si algo no funciona puede ser los hiperparamentros
mod = modelo(fit_intercept=True, penalty='l2', tol=1e-5, C=0.8, solver='lbfgs', max_iter=75,warm_start=True)
# csv(mod)
# json(mod)
# return carga(X_test, y_test)
mod.fit(X_train, y_train)
y_predict = mod.predict(X_test)
mod.fit(X_train, y_train)
user = mod.predict(df_usuario_test)
print("acuracy user", accuracy_score(y_test, y_predict) )
accuracy = accuracy_score(y_test, y_predict)
auc = roc_auc_score(y_test, y_predict)
recall = recall_score(y_test, y_predict)
precision = precision_score(y_test, y_predict)
confusionmatrix = confusion_matrix(y_test, y_predict)
y_pred_train = mod.predict(X_train)
# yy_pred_train = mod.predict(XX_train)
accuracy_train = accuracy_score(y_train, y_pred_train)
# accuracy_train_y = accuracy_score(yy_train, yy_pred_train)
auc_train = roc_auc_score(y_train, y_pred_train)
recall_train = recall_score(y_train, y_pred_train)
precision_train = precision_score(y_train, y_pred_train)
confusionmatrix_train = confusion_matrix(y_train, y_pred_train)
print(nombre_modelo)
print()
print(f"Accuracy: {accuracy}")
# print(f"Accuracy: {accuracy_y}")
print(f"RocAUC: {auc}")
print(f"Recall: {recall}")
print(f"Precision: {precision}")
print(f"ConfusionMatrix: {confusionmatrix}")
print(nombre_modelo)
print()
print(f"Accuracy_train: {accuracy_train}")
# print(f"Accuracy_train: {accuracy_train_y}")
print(f"RocAUC_train: {auc_train}")
print(f"Recall_train: {recall_train}")
print(f"Precision_train: {precision_train}")
print(f"ConfusionMatrix_train: {confusionmatrix_train}")
print(f"\nError: ", accuracy - accuracy_train)
#guardar(mod)
print()
y_pred_train = mod.predict(X_train)
print(user )
train_evaluate("LogisticRegression", LogisticRegression)
######## ESTO O SE EJECUTA #############
def guardar(datos):
print('Guardado !!!')
file = open('modelo_entrenado.pkl', 'wb')
pickle.dump(datos, file)
file.close()
print('\n')
def carga(X_test, y_test):
loaded_model = pickle.load(open('modelo_entrenado.pkl', 'rb'))
print(" Cargado !!!")
result = loaded_model.score(X_test, y_test)
print(result)
def json(mod):
df.to_json('api.json', orient='index')
def csv(mod):
df_new_test = df.drop(columns =["gender", "ever_married", "work_type", "Residence_type", "smoking_status", "hypertension", "heart_disease"],axis = 1)
print( df_new_test.head() )
# One Hot Encoding
df_new_test = pd.get_dummies(df_new_test,columns=["gender", "ever_married", "work_type", "Residence_type", "smoking_status", "hypertension", "heart_disease"])
print( df_new_test.head() )
df_new_test[["gender", "ever_married", "work_type", "Residence_type", "smoking_status", "hypertension", "heart_disease"]] = pd.DataFrame(scaler.fit_transform(df_new_test[["gender", "ever_married", "work_type", "Residence_type", "smoking_status", "hypertension", "heart_disease"]]))
print( df_new_test.head() )
#predicion para Transported para el test de datos
# ADB es la variable del modelo Ada Boost Classifier/ rfc randon fores
df_new_test['stroke'] = mod.predict(df_new_test)
print( df_new_test.head() )
# Creamos el fichero submission.csv
pres = pd.DataFrame({'PassengerId':df['PassengerId'],'Transported': df_new_test['Transported']})
pres.to_csv('submission.csv', index=False)
print( pres.head() )