-
Notifications
You must be signed in to change notification settings - Fork 2
/
4_cardiovascular_disease_pytorch.py
213 lines (145 loc) · 6.04 KB
/
4_cardiovascular_disease_pytorch.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
# -*- coding: utf-8 -*-
"""
İU Data Klubu - Yapay Sinir Aglari Sunumu
07.04.2021
Author: Dr. Zeki Ozen
Dataset kaynagi: Cardiovascular Disease dataset @ Kaggle
Link: https://www.kaggle.com/sulianova/cardiovascular-disease-dataset
PyTorch yeni baslayanlar icin guzel bir anlatim ve uygulama linki:
https://www.freecodecamp.org/news/how-to-build-a-neural-network-with-pytorch/
Faydalanilan PyTorch Kod Kaynaklari:
https://curiousily.com/posts/build-your-first-neural-network-with-pytorch/
https://www.kaggle.com/kanncaa1/pytorch-tutorial-for-deep-learning-lovers
"""
# standart kutuphanelerimiz
import numpy as np
import pandas as pd
# veri seti yukleyelim
data = pd.read_csv('cardio.csv', sep=';')
data.head()
#id sutunu kaldiriliyor
data.drop('id',axis=1,inplace=True)
#yas sutunu
#data.age = np.round(data.age/365.25,decimals=1)
#gender sutununda 2 ile temsil edilen veriyi 0 yapiyoruz
data.gender = data.gender.replace(2,0)
#cinsiyet degerleri kacar tane var
data.gender.value_counts()
# vucut kutle indeksini hesaplayip veri setimize ekliyoruz
data['bmi'] = data.weight / (data.height / 100) ** 2
# height ve weight kolonlarina artik gere kalmadigi icin kaldiriyoruz
data.drop('height', axis=1,inplace=True)
data.drop('weight', axis=1,inplace=True)
#bagimli ve bagimsiz degiskenelr ayarlaniyor
X = data[data.columns.difference(['cardio'])]
y = pd.DataFrame(data['cardio'])
# Egitim ve test veri setlerini 80-20 oraninda ayarliyoruz
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=42)
print(X_train.info())
print(y_train.info())
#bagimli numerik degiskenler normalize ediliyor
#from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
#numerik degiskenler
to_be_scaled_feat = ['age', 'ap_hi', 'ap_lo','bmi']
scaler=StandardScaler()
scaler.fit(X_train[to_be_scaled_feat])
X_train[to_be_scaled_feat] = scaler.transform(X_train[to_be_scaled_feat])
X_test[to_be_scaled_feat] = scaler.transform(X_test[to_be_scaled_feat])
#bagimli kategorik degiskenler one-hot-encoding yontemi ile kategorik formata donusturuluyor
X_train = pd.get_dummies( X_train, columns= ["gender", 'cholesterol', 'gluc', 'smoke', 'alco', 'active'], drop_first=True)
X_test = pd.get_dummies( X_test, columns= ["gender", 'cholesterol', 'gluc', 'smoke', 'alco', 'active'], drop_first=True)
# pytorch kutuphanesini calisma alanimiza dahil ediyoruz
import torch
from torch import nn, optim
import torch.nn.functional as F
# egitim ve test veri setlerimizin
# bagimli ve bagimsiz degiskenlerini torch yapisina donusturuyoruz
X_train = torch.from_numpy(X_train.to_numpy()).float()
y_train = torch.squeeze(torch.from_numpy(y_train.to_numpy()).float())
X_test = torch.from_numpy(X_test.to_numpy()).float()
y_test = torch.squeeze(torch.from_numpy(y_test.to_numpy()).float())
print(X_train.shape, y_train.shape)
print(X_test.shape, y_test.shape)
# modelin dogrulugunu hesaplayacak fonksiyon
def calculate_accuracy(y_true, y_pred):
predicted = y_pred.ge(.5).view(-1)
return (y_true == predicted).sum().float() / len(y_true)
# sonuclari yuvarlayacak fonksiyon
def round_tensor(t, decimal_places=3):
return round(t.item(), decimal_places)
# Yapay sinir mimarisi bu sinif ile olusturuluyor
class Net(nn.Module):
def __init__(self, n_features):
super(Net, self).__init__()
self.fc1 = nn.Linear(n_features, 5)
self.fc2 = nn.Linear(5, 3)
self.fc3 = nn.Linear(3, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return torch.sigmoid(self.fc3(x))
# Yapilandirdigimiz modelin girdi katmani boyutu, hata fonk, optimizasyon fonk. gibi
# parametrelerini veriyoruz
net = Net(X_train.shape[1])
# hata hesaplama metriklerimiz
#criterion = nn.BCELoss()
criterion = nn.MSELoss()
# ogrenme fonksiyonumuz ve ogrenme orani
optimizer = optim.Adam(net.parameters(), lr=0.001)
# hesaplamada kullanilacak degiskenlerimiz
count = 0
loss_list = []
iteration_list = []
accuracy_list = []
# modelin egitimi yapiliyor
for epoch in range(1000):
#egitim verisiyle model kuruluyor ve cikti tahmin ediliyor
y_pred = net(X_train)
y_pred = torch.squeeze(y_pred)
#egitim verisindeki tahmin hatasi hesaplaniyor
train_loss = criterion(y_pred, y_train)
# her 100 iterasyonda bir hata hesapliyoruz
if epoch % 100 == 0:
train_acc = calculate_accuracy(y_train, y_pred)
y_test_pred = net(X_test)
y_test_pred = torch.squeeze(y_test_pred)
test_loss = criterion(y_test_pred, y_test)
test_acc = calculate_accuracy(y_test, y_test_pred)
loss_list.append(test_loss.data)
iteration_list.append(count)
accuracy_list.append(train_acc)
print(
f'''epoch {epoch}
Train set - loss: {round_tensor(train_loss)}, accuracy: {round_tensor(train_acc)}
Test set - loss: {round_tensor(test_loss)}, accuracy: {round_tensor(test_acc)}
''')
# Clear gradients
optimizer.zero_grad()
# Calculating gradients
train_loss.backward()
# Update parameters
optimizer.step()
count += 1
# performans degerlendirme icin gerekli standart kutuphaneler
from sklearn.metrics import classification_report, accuracy_score
y_pred = net(X_test)
y_pred = y_pred.ge(.5).view(-1).cpu()
y_test = y_test.cpu()
print(classification_report(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
# her bir iterasyonda kayip (hata) grafigi
import matplotlib.pyplot as plt
# visualization loss
plt.plot(iteration_list,loss_list)
plt.xlabel("Number of iteration")
plt.ylabel("Loss")
plt.title("ANN: Loss vs Number of iteration")
plt.show()
# her bir iterasyonda modelin dogruluk grafigi
plt.plot(iteration_list,accuracy_list,color = "red")
plt.xlabel("Number of iteration")
plt.ylabel("Accuracy")
plt.title("ANN: Accuracy vs Number of iteration")
plt.show()