-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-Logistic_Regression.py
293 lines (202 loc) · 7.76 KB
/
2-Logistic_Regression.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
######################################################
# Diabetes Prediction with Logistic Regression
######################################################
# İş Problemi:
# Özellikleri belirtildiğinde kişilerin diyabet hastası olup
# olmadıklarını tahmin edebilecek bir makine öğrenmesi
# modeli geliştirebilir misiniz?
# Veri seti ABD'deki Ulusal Diyabet-Sindirim-Böbrek Hastalıkları Enstitüleri'nde tutulan büyük veri setinin
# parçasıdır. ABD'deki Arizona Eyaleti'nin en büyük 5. şehri olan Phoenix şehrinde yaşayan 21 yaş ve üzerinde olan
# Pima Indian kadınları üzerinde yapılan diyabet araştırması için kullanılan verilerdir. 768 gözlem ve 8 sayısal
# bağımsız değişkenden oluşmaktadır. Hedef değişken "outcome" olarak belirtilmiş olup; 1 diyabet test sonucunun
# pozitif oluşunu, 0 ise negatif oluşunu belirtmektedir.
# Değişkenler
# Pregnancies: Hamilelik sayısı
# Glucose: Glikoz.
# BloodPressure: Kan basıncı.
# SkinThickness: Cilt Kalınlığı
# Insulin: İnsülin.
# BMI: Beden kitle indeksi.
# DiabetesPedigreeFunction: Soyumuzdaki kişilere göre diyabet olma ihtimalimizi hesaplayan bir fonksiyon.
# Age: Yaş (yıl)
# Outcome: Kişinin diyabet olup olmadığı bilgisi. Hastalığa sahip (1) ya da değil (0)
# 1. Exploratory Data Analysis
# 2. Data Preprocessing
# 3. Model & Prediction
# 4. Model Evaluation
# 5. Model Validation: Holdout
# 6. Model Validation: 10-Fold Cross Validation
# 7. Prediction for A New Observation
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.preprocessing import RobustScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score, confusion_matrix, classification_report, RocCurveDisplay # plot_roc_curve
from sklearn.model_selection import train_test_split, cross_validate
def outlier_thresholds(dataframe, col_name, q1=0.05, q3=0.95):
quartile1 = dataframe[col_name].quantile(q1)
quartile3 = dataframe[col_name].quantile(q3)
interquantile_range = quartile3 - quartile1
up_limit = quartile3 + 1.5 * interquantile_range
low_limit = quartile1 - 1.5 * interquantile_range
return low_limit, up_limit
def check_outlier(dataframe, col_name):
low_limit, up_limit = outlier_thresholds(dataframe, col_name)
if dataframe[(dataframe[col_name] > up_limit) | (dataframe[col_name] < low_limit)].any(axis=None):
return True
else:
return False
def replace_with_thresholds(dataframe, variable):
low_limit, up_limit = outlier_thresholds(dataframe, variable)
dataframe.loc[(dataframe[variable] < low_limit), variable] = low_limit
dataframe.loc[(dataframe[variable] > up_limit), variable] = up_limit
pd.set_option('display.max_columns', None)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
pd.set_option('display.width', 500)
######################################################
# Exploratory Data Analysis
######################################################
df = pd.read_csv("datasets/diabetes.csv")
##########################
# Target'ın Analizi
##########################
df["Outcome"].value_counts()
sns.countplot(x="Outcome", data=df)
plt.show()
100 * df["Outcome"].value_counts() / len(df) # sınıfların oranlarını öğreniyoruz burada
##########################
# Feature'ların Analizi
##########################
df.describe().T
df["BloodPressure"].hist(bins=20)
plt.xlabel("BloodPressure")
plt.show()
def plot_numerical_col(dataframe, numerical_col):
dataframe[numerical_col].hist(bins=20)
plt.xlabel(numerical_col)
plt.show(block=True) # block=True sebebi peş peşe gösteereceğimiz argümanların birbiri üstüne gelmemesi
for col in df.columns:
plot_numerical_col(df, col)
cols = [col for col in df.columns if "Outcome" not in col] # outcome değişkenini dışarıda bırakıyoruz
# for col in cols:
# plot_numerical_col(df, col)
df.describe().T
##########################
# Target vs Features
##########################
df.groupby("Outcome").agg({"Pregnancies": "mean"})
# bu outcome ın bağımsız bir değişkene nasıl etki ettiğini değerlendirmek istedik
def target_summary_with_num(dataframe, target, numerical_col):
print(dataframe.groupby(target).agg({numerical_col: "mean"}), end="\n\n\n")
for col in cols:
target_summary_with_num(df, "Outcome", col)
######################################################
# Data Preprocessing (Veri Ön İşleme)
######################################################
df.shape
df.head()
df.isnull().sum()
df.describe().T
for col in cols:
print(col, check_outlier(df, col))
replace_with_thresholds(df, "Insulin")
# standartlaşma işlemi yapıyoruz:
for col in cols:
df[col] = RobustScaler().fit_transform(df[[col]])
# robust aykırı değerlere dayanıklı olduğu iin bunun tercih ettik
df.head()
######################################################
# Model & Prediction
######################################################
y = df["Outcome"]
X = df.drop(["Outcome"], axis=1)
log_model = LogisticRegression().fit(X, y)
log_model.intercept_ # sabit
log_model.coef_ # ağırlıklar (katsayıları)
y_pred = log_model.predict(X)
y_pred[0:10]
y[0:10].T
######################################################
# Model Evaluation
######################################################
def plot_confusion_matrix(y, y_pred):
acc = round(accuracy_score(y, y_pred), 2)
cm = confusion_matrix(y, y_pred)
sns.heatmap(cm, annot=True, fmt=".0f")
plt.xlabel('y_pred')
plt.ylabel('y')
plt.title('Accuracy Score: {0}'.format(acc), size=10)
plt.show()
plot_confusion_matrix(y, y_pred)
print(classification_report(y, y_pred))
# Accuracy: 0.78
# Precision: 0.74
# Recall: 0.58
# F1-score: 0.65
# ROC AUC
y_prob = log_model.predict_proba(X)[:, 1]
roc_auc_score(y, y_prob)
# 0.83939
######################################################
# Model Validation: Holdout
######################################################
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.20, random_state=17)
log_model = LogisticRegression().fit(X_train, y_train)
y_pred = log_model.predict(X_test)
y_prob = log_model.predict_proba(X_test)[:, 1]
print(classification_report(y_test, y_pred))
# Accuracy: 0.78
# Precision: 0.74
# Recall: 0.58
# F1-score: 0.65
# ----------------
# Accuracy: 0.77
# Precision: 0.79
# Recall: 0.53
# F1-score: 0.63
# plot_roc_curve(log_model, X_test, y_test)
RocCurveDisplay(log_model, X_test, y_test) # burada plot u halledemedim
plt.title('ROC Curve')
plt.plot([0, 1], [0, 1], 'r--')
plt.show()
# AUC
roc_auc_score(y_test, y_prob)
######################################################
# Model Validation: 5-Fold Cross Validation
######################################################
y = df["Outcome"]
X = df.drop(["Outcome"], axis=1)
log_model = LogisticRegression().fit(X, y)
cv_results = cross_validate(log_model,
X, y,
cv=5,
scoring=["accuracy", "precision", "recall", "f1", "roc_auc"])
# Accuracy: 0.78
# Precision: 0.74
# Recall: 0.58
# F1-score: 0.65
# ----------------
# Accuracy: 0.77
# Precision: 0.79
# Recall: 0.53
# F1-score: 0.63
cv_results['test_accuracy'].mean()
# Accuracy: 0.7721
cv_results['test_precision'].mean()
# Precision: 0.7192
cv_results['test_recall'].mean()
# Recall: 0.5747
cv_results['test_f1'].mean()
# F1-score: 0.6371
cv_results['test_roc_auc'].mean()
# AUC: 0.8327
######################################################
# Prediction for A New Observation
######################################################
X.columns
random_user = X.sample(1, random_state=45)
log_model.predict(random_user)