forked from dbstjswo505/DSDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeploy.py
executable file
·214 lines (157 loc) · 7.01 KB
/
deploy.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
214
import time
import torch
import torch.nn.functional as F
import numpy as np
import pdb
from torch import nn
from torch.autograd import Variable
from utils import print_results, save_checkpoint
def confusion_matrix(l, o):
matrix = np.zeros((5,5))
L = len(l)
for i in range(L):
label = int(l[i])
pred = int(o[i])
matrix[label][pred] = matrix[label][pred] + 1
return matrix
def test(net, dataloaders, model_name, optimizer, criterion, phases=["test"], max_epochs=1, classlabels=None):
results = []
for epoch in range(max_epochs):
results.append(dict())
# Each epoch has a training and validation phase
for phase in phases:
since = time.time()
net.eval()
running_loss = 0.
num_correct = 0.
total_samples = 0.
correct = []
o = np.zeros((0,))
l = np.zeros((0,))
results[-1][phase] = dict(loss=[], time=[], acc=[])
if classlabels is not None:
for label in classlabels:
results[-1][phase][label] = []
# Iterate over data.
for idx, data in enumerate(dataloaders[phase]):
inputs, labels = data
if phase != 'train':
with torch.no_grad():
inputs = Variable(inputs.cuda())
labels = Variable(labels.cuda())
else:
inputs = Variable(inputs.cuda())
labels = Variable(labels.cuda())
# zero the parameter gradients
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
if phase == "train":
z=1
#loss.backward()
#optimizer.step()
# statistics
running_loss += loss.item()
num_correct += outputs[:labels.size(0)].max(1)[1].eq(labels).sum().item()
correct = correct + outputs[:labels.size(0)].max(1)[1].eq(labels).tolist()
total_samples += len(outputs)
o = np.concatenate((o, outputs[:labels.size(0)].max(1)[1].cpu().data.numpy()))
l = np.concatenate((l, labels.cpu().data.numpy()))
del inputs, outputs, labels, loss
results[-1][phase]["loss"].append(running_loss / (idx + 1))
results[-1][phase]["acc"].append(1 - num_correct / total_samples)
results[-1][phase]["time"].append(time.time() - since)
if classlabels is not None:
for label in classlabels:
idx = classlabels.index(label)
if np.sum(l == idx) > 0:
results[-1][phase][label].append(1. - float(np.sum(l[o == idx] == idx)) / np.sum(l == idx))
else:
results[-1][phase][label].append(1.0)
best_valid_loss, best_test_loss = print_results(results)
#if best_valid_loss and epoch>30:
# matrix = confusion_matrix(l,o)
print(epoch+1,
results[epoch]['train']['loss'][-1],
results[epoch]['valid']['loss'][-1],
results[epoch]['valid']['acc'][-1],
results[epoch]['test']['loss'][-1] if 'test' in phases else "",
results[epoch]['test']['acc'][-1] if 'test' in phases else "" )
pdb.set_trace()
tmp = np.array(correct)
np.save('test_result_a', tmp)
z=1
def train(net, dataloaders, model_name, optimizer, criterion, phases=["train", "valid", "test"], max_epochs=1000, classlabels=None):
assert "train" in phases
results = []
for epoch in range(max_epochs):
results.append(dict())
# Each epoch has a training and validation phase
for phase in phases:
since = time.time()
if phase == 'train':
net.train(True)
else:
net.eval()
running_loss = 0.
num_correct = 0.
total_samples = 0.
o = np.zeros((0,))
l = np.zeros((0,))
results[-1][phase] = dict(loss=[], time=[], acc=[])
if classlabels is not None:
for label in classlabels:
results[-1][phase][label] = []
# Iterate over data.
for idx, data in enumerate(dataloaders[phase]):
inputs, labels = data
if phase != 'train':
with torch.no_grad():
inputs = Variable(inputs.cuda())
labels = Variable(labels.cuda())
else:
inputs = Variable(inputs.cuda())
labels = Variable(labels.cuda())
# zero the parameter gradients
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
if phase == "train":
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item()
num_correct += outputs[:labels.size(0)].max(1)[1].eq(labels).sum().item()
total_samples += len(outputs)
o = np.concatenate((o, outputs[:labels.size(0)].max(1)[1].cpu().data.numpy()))
l = np.concatenate((l, labels.cpu().data.numpy()))
del inputs, outputs, labels, loss
results[-1][phase]["loss"].append(running_loss / (idx + 1))
results[-1][phase]["acc"].append(1 - num_correct / total_samples)
results[-1][phase]["time"].append(time.time() - since)
if classlabels is not None:
for label in classlabels:
idx = classlabels.index(label)
if np.sum(l == idx) > 0:
results[-1][phase][label].append(1. - float(np.sum(l[o == idx] == idx)) / np.sum(l == idx))
else:
results[-1][phase][label].append(1.0)
best_valid_loss, best_test_loss = print_results(results)
#if best_valid_loss and epoch>30:
# matrix = confusion_matrix(l,o)
print()
save_checkpoint({
'epoch': epoch + 1,
# 'arch': args.arch,
'state_dict': net.state_dict(),
#'best_loss': results["valid"]["loss"][-1],
'optimizer': optimizer.state_dict(),
}, best_valid_loss, best_test_loss, model_name)
print()
epoch = np.argmin([results[i]["valid"]["loss"][-1] for i in range(len(results))])
print(epoch+1,
results[epoch]['train']['loss'][-1],
results[epoch]['valid']['loss'][-1],
results[epoch]['valid']['acc'][-1],
results[epoch]['test']['loss'][-1] if 'test' in phases else "",
results[epoch]['test']['acc'][-1] if 'test' in phases else "" )