-
Notifications
You must be signed in to change notification settings - Fork 1
/
Model_Building_and_Tuning.py
140 lines (97 loc) · 4.06 KB
/
Model_Building_and_Tuning.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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, mean_squared_error, confusion_matrix
# read data set
diabetes_data = pd.read_csv("Data set/diabetes_data_cleaned.csv", encoding= 'unicode_escape')
# define x, y
X = diabetes_data.drop(['class'], axis = 1)
y = diabetes_data['class']
# split into train test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 7)
# ****************************************** Training Models *******************************************
# Logistic Regression
lr = LogisticRegression(max_iter = 2000)
cv = cross_val_score(lr, X_train, y_train,cv=5)
print(cv)
print(cv.mean())
# Decision Tree
dt = tree.DecisionTreeClassifier(random_state = 1)
cv = cross_val_score(dt, X_train, y_train, cv=5)
print(cv)
print(cv.mean())
# Random Forest
rf = RandomForestClassifier(random_state = 1)
cv = cross_val_score(rf, X_train, y_train,cv=5)
print(cv)
print(cv.mean())
# ****************************************** Hyperparameter Tuning *******************************************
# Logistic Regression
lr = LogisticRegression()
param_grid = {'max_iter' : [2000],
'penalty' : ['l1', 'l2'],
'C' : np.logspace(-4, 4, 20),
'solver' : ['liblinear']}
clf_lr = GridSearchCV(lr, param_grid = param_grid, cv = 5, verbose = True, n_jobs = -1)
best_clf_lr = clf_lr.fit(X_train, y_train)
print('Best Score: ' + str(best_clf_lr.best_score_))
print('Best Parameters: ' + str(best_clf_lr.best_params_))
# calculate accuracy
y_predict = best_clf_lr.predict(X_test)
print("Confusion Matrix:\n", confusion_matrix(y_test, y_predict))
print("Accuracy:", accuracy_score(y_test, y_predict))
# Decision Tree
gini_acc_scores = []
entropy_acc_scores = []
criterions = ["gini", "entropy"]
for criterion in criterions:
for depth in range(25):
dt = tree.DecisionTreeClassifier(criterion=criterion, max_depth = depth+1, random_state=depth)
model = dt.fit(X_train,y_train)
y_predict = dt.predict(X_test)
if criterion == "gini":
gini_acc_scores.append(accuracy_score(y_test, y_predict))
else:
entropy_acc_scores.append(accuracy_score(y_test, y_predict))
# plot the accuracy scores by depths and criterion
figuresize = plt.figure(figsize=(12,8))
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
EntropyAcc = plt.plot(np.arange(25)+1, entropy_acc_scores, '--bo')
GiniAcc = plt.plot(np.arange(25)+1, gini_acc_scores, '--ro')
legend = plt.legend(['Entropy', 'Gini'], loc ='lower right', fontsize=15)
title = plt.title('(Decision Tree) Accuracy Score for Multiple Depths', fontsize=25)
xlab = plt.xlabel('Depth of Tree', fontsize=20)
ylab = plt.ylabel('Accuracy Score', fontsize=20)
plt.show()
print("Gini max accuracy:", max(gini_acc_scores))
print("Entropy max accuracy:", max(entropy_acc_scores))
# use best depth for prediction
dt = tree.DecisionTreeClassifier(max_depth = 1, random_state = 1)
dt = dt.fit(X_train, y_train)
y_predict = dt.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_predict))
# RandomForest
acc_scores = []
depth = np.arange(1, 30)
for i in depth:
rf = RandomForestClassifier(n_estimators=25, max_depth=i, random_state=1)
rf.fit(X_train,y_train)
y_predict = rf.predict(X_test)
acc_scores.append(accuracy_score(y_test, y_predict))
figsize = plt.figure(figsize = (12,8))
plot = plt.plot(depth, acc_scores, 'r')
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
xlab = plt.xlabel('Depth of the trees', fontsize = 20)
ylab = plt.ylabel('Accuracy', fontsize = 20)
title = plt.title('(Random Forest) Accuracy vs Depth of Trees', fontsize = 25)
plt.show()
rf = RandomForestClassifier(n_estimators=25, max_depth=acc_scores.index(max(acc_scores))+1, random_state=1)
rf.fit(X_train,y_train)
y_predict = rf.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_predict))