-
Notifications
You must be signed in to change notification settings - Fork 0
/
comp258_final_project.py
212 lines (144 loc) · 5.35 KB
/
comp258_final_project.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
# -*- coding: utf-8 -*-
"""COMP258_FINAL_PROJECT.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/14Dx68Awh_lO-9wDCkCjw5U5SSPrvjbAJ
"""
#from google.colab import drive
#drive.mount('/content/drive')
import os
import pickle
import joblib as jb
#!ls '/content/drive/My Drive/dataset'
# Commented out IPython magic to ensure Python compatibility.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.style as style; style.use('fivethirtyeight')
# %matplotlib inline
# Metrics and preprocessing
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix, precision_score, recall_score, f1_score, precision_recall_curve, auc
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
# TF and Keras
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization
from tensorflow.keras.layers import Activation, Dense
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras import optimizers
import tensorflow as tf
from keras.models import load_model
dataset = pd.read_csv('Heart_failure_clinical_records_dataset.csv')
dataset.shape
dataset.head()
dataset.isnull().sum()
"""# Feature Selection
"""
plt.rcParams['figure.figsize']=15,6
sns.set_style("darkgrid")
dataset[dataset['ejection_fraction']>=70]
dataset = dataset.drop(dataset[dataset['platelets']>420000].index)
dataset = dataset.drop(dataset[dataset['serum_creatinine']>2.5].index)
dataset = dataset.drop(dataset[dataset['creatinine_phosphokinase']>1500].index)
x = dataset.iloc[:,:12].values
y = dataset.iloc[:,-1].values
print(x)
# Splitting the dataset into training set and test set
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state =0)
pickle.dump(y_test, open('y_test.pkl', 'wb'))
print(x_train)
print(y_test)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
"""LOGISTIC REGRESSION
"""
# Applying logistic regression on the training set
"""ANN"""
np.random.seed(0)
import tensorflow as tf
# Initialising the ANN
ann = tf.keras.models.Sequential()
# Adding the input layer and the first hidden layer
ann.add(tf.keras.layers.Dense(units = 7, activation = 'relu'))
# Adding the second hidden layer
ann.add(tf.keras.layers.Dense(units = 7, activation = 'relu'))
# Adding the third hidden layer
ann.add(tf.keras.layers.Dense(units = 7, activation = 'relu'))
# Adding the fourth hidden layer
ann.add(tf.keras.layers.Dense(units = 7, activation = 'relu'))
# Adding the output layer
ann.add(tf.keras.layers.Dense(units = 1, activation = 'sigmoid'))
# Compiling the ANN
ann.compile(optimizer = 'adam', loss = 'binary_crossentropy' , metrics = ['accuracy'] )
# Training the ANN on the training set
ann.fit(x_train, y_train, batch_size = 32, epochs = 100)
pickle.dump(ann, open('ann_model.pkl', 'wb'))
ann.save('ann_model.h5')
# Predicting the test set results
y_pred = ann.predict(x_test)
y_pred = (y_pred > 0.5)
np.set_printoptions()
print(np.concatenate( (y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))
# Making the confusion matrix, calculating accuracy_score
from sklearn.metrics import confusion_matrix, accuracy_score
# confusion matrix
cm = confusion_matrix(y_test,y_pred)
print("Confusion Matrix")
print(cm)
print()
# accuracy
ac = accuracy_score(y_test,y_pred)
print("Accuracy")
print(ac)
#mylist.append(ac)
#from scikeras.wrappers import KerasClassifier
#from sklearn.model_selection import GridSearchCV
#model = KerasClassifier(model=ann, verbose=0)
# define the grid search parameters
#batch_size = [10, 20, 40, 60, 80, 100]
#epochs = [10, 50, 100]
#optimizer = ['SGD','adam']
#param_grid = dict(batch_size=batch_size, epochs=epochs)
#grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3, estimator = )
#grid.compile(loss = 'binary_crossentropy' , metrics = ['accuracy'] )
#grid_result = grid.fit(x_train, y_train)
from xgboost import XGBClassifier
from sklearn.metrics import confusion_matrix, accuracy_score
list1 = []
for estimators in range(10,30,1):
classifier = XGBClassifier(n_estimators = estimators, max_depth=12, subsample=0.7)
classifier.fit(x_train, y_train)
y_pred = classifier.predict(x_test)
list1.append(accuracy_score(y_test,y_pred))
#print(mylist)
plt.plot(list(range(10,30,1)), list1)
plt.show()
from xgboost import XGBClassifier
classifier = XGBClassifier(n_estimators = 10, max_depth=12, subsample=0.7)
classifier.fit(x_train,y_train)
y_pred = classifier.predict(x_test)
print(y_pred)
# Making the confusion matrix and calculating the accuracy score
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
ac = accuracy_score(y_test, y_pred)
#mylist.append(ac)
print(cm)
print(ac)
from catboost import CatBoostClassifier
classifier = CatBoostClassifier()
classifier.fit(x_train, y_train)
y_pred = classifier.predict(x_test)
print(y_pred)
# Making the confusion matrix and calculating the accuracy score
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
ac = accuracy_score(y_test, y_pred)
#mylist.append(ac)
print(cm)
print(ac)