Repository navigation
Expand file tree
/
Copy pathworkshop.py
More file actions
92 lines (59 loc) · 2.63 KB
/
Copy pathworkshop.py
File metadata and controls
92 lines (59 loc) · 2.63 KB
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
import torch
import numpy
class HeartFailureDataset(torch.utils.data.Dataset):
def __init__(self, filepath, rows):
self.data = numpy.loadtxt(filepath, skiprows=1, delimiter=',')
self.data = self.data[rows, :]
self.x_data = self.data[:, :-1]
x_min = numpy.min(self.x_data, axis=0)
x_max = numpy.max(self.x_data, axis=0)
self.x_data = (self.x_data - x_min) / (x_max - x_min)
self.x_data = torch.tensor(self.x_data, dtype=torch.float32)
self.y_data = torch.tensor(self.data[:, -1:], dtype=torch.float32)
def __len__(self):
return self.x_data.shape[0]
def __getitem__(self, index):
x = self.x_data[index, :]
y = self.y_data[index]
return x, y
class HeartFailureNetwork(torch.nn.Module):
def __init__(self):
super().__init__()
self.fc1 = torch.nn.Linear(12, 1)
def forward(self, x):
x = self.fc1(x)
return x
#update this
dataset_filepath = r"your_file_path_here"
train_rows = range(0, 200)
val_rows = range(200, 250)
test_rows = range(250, 299)
train_dataset = HeartFailureDataset(dataset_filepath, train_rows)
val_dataset = HeartFailureDataset(dataset_filepath, val_rows)
test_dataset = HeartFailureDataset(dataset_filepath, test_rows)
batch_size = 1
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=len(val_rows), shuffle=False)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=len(test_rows), shuffle=False)
heart_failure_network = HeartFailureNetwork()
print(heart_failure_network)
criterion = torch.nn.BCEWithLogitsLoss()
optimizer = torch.optim.SGD(heart_failure_network.parameters(), lr=0.1)
batches_per_epoch = int(len(train_dataset) / batch_size)
num_epochs = 10
for epoch in range(num_epochs):
heart_failure_network.train()
train_correct = 0
for batch_x, batch_y in train_loader:
batch_y_pred = heart_failure_network(batch_x)
loss = criterion(batch_y_pred, batch_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_correct += numpy.sum(((batch_y_pred.detach() > 0) == batch_y).numpy())
train_accuracy = train_correct / len(train_dataset)
heart_failure_network.eval()
for batch_x, batch_y in val_loader:
batch_y_pred = heart_failure_network(batch_x)
val_accuracy = numpy.sum(((batch_y_pred.detach() > 0) == batch_y).numpy()) / len(batch_y)
print("Epoch " + str(epoch) + " | Train accuracy: " + str(train_accuracy) + " | Val accuracy: " + str(val_accuracy))