-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
141 lines (109 loc) · 4.78 KB
/
trainer.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
import torch
import numpy as np
from sklearn.metrics import r2_score
def train_classification(model, loader, criterion, optimizer, epochs):
train_losses = []
train_accuracies = []
val_losses = []
val_accuracies = []
for epoch in range(epochs):
train_running_loss = 0
train_running_correct = 0
val_running_loss = 0
val_running_correct = 0
for data in loader['train']:
model.train()
dt = data
image = dt['image'].to()
bin = dt['bin']
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = model(image[None, ...].float())
expected = torch.Tensor([bin]).type(torch.LongTensor)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, expected)
loss.backward()
optimizer.step()
# print statistics
train_running_loss += loss.item()
train_running_correct += torch.sum(preds == bin)
if len(train_losses) > 1 and abs(train_running_loss - train_losses[-1]) <= 0.1:
# early stopping
return train_losses, train_accuracies, val_losses, val_accuracies
train_losses.append(train_running_loss)
train_accuracies.append(train_running_correct / len(loader['train']))
limit = int(len(loader['val']) / 2)
for i, data in enumerate(loader['val'], 0):
if i >= limit: break
model.eval()
dt = data
image = dt['image'].to()
bin = dt['bin']
outputs = model(image[None, ...].float())
expected = torch.Tensor([bin]).type(torch.LongTensor)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, expected)
# print statistics
val_running_loss += loss.item()
val_running_correct += torch.sum(preds == bin)
val_losses.append(val_running_loss)
val_accuracies.append(2 * val_running_correct / len(loader['val']))
print('Epoch: {}, training loss: {}, training acc: {}'.format(epoch, train_losses[-1], train_accuracies[-1]))
print('\t validation loss: {}, validation acc: {}'.format(val_losses[-1], val_accuracies[-1]))
return train_losses, train_accuracies, val_losses, val_accuracies
def train(model, loader, criterion, optimizer, epochs):
train_losses = []
train_r2 = []
val_losses = []
val_r2 = []
for epoch in range(epochs):
train_running_loss = 0
train_running_expected = []
train_running_predicted = []
val_running_loss = 0
val_running_expected = []
val_running_predicted = []
for data in loader['train']:
model.train()
dt = data
image = dt['image'].to()
den = dt['den']
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = model(image[None, ...].float())
loss = criterion(outputs, torch.from_numpy(den[None, ...]))
loss.backward()
optimizer.step()
# print statistics
train_running_loss += loss.item()
prediction = outputs.squeeze().data.cpu().numpy()
count = np.sum(prediction) / 100
train_running_predicted.append(count)
train_running_expected.append(len(dt['gt']))
if len(train_losses) > 1 and abs(train_running_loss - train_losses[-1]) <= 0.001:
# early stopping
return train_losses, train_r2, val_losses, val_r2
train_losses.append(train_running_loss)
train_r2.append(r2_score(train_running_expected, train_running_predicted))
limit = int(len(loader['val']) / 2)
for i, data in enumerate(loader['val'], 0):
if i >= limit: break
model.eval()
dt = data
image = dt['image'].to()
den = dt['den']
outputs = model(image[None, ...].float())
loss = criterion(outputs, torch.from_numpy(den[None, ...]))
# print statistics
val_running_loss += loss.item()
prediction = outputs.squeeze().data.cpu().numpy()
count = np.sum(prediction) / 100
val_running_predicted.append(count)
val_running_expected.append(len(dt['gt']))
val_losses.append(val_running_loss)
val_r2.append(r2_score(val_running_expected, val_running_predicted))
print('Epoch: {}, training loss: {}, training r2: {}'.format(epoch, train_losses[-1], train_r2[-1]))
print('\t validation loss: {}, validation r2: {}'.format(val_losses[-1], val_r2[-1]))
return train_losses, train_r2, val_losses, val_r2