-
Notifications
You must be signed in to change notification settings - Fork 0
/
baseline.py
203 lines (152 loc) · 7.05 KB
/
baseline.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
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
"""# Import Libraries"""
import numpy as np
import torch
import os
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from utils.model import select_model
from utils.options import parse_args_function
from utils.dataset import Dataset
def calculate_f_score(error_list, threshold):
binary_results = [0 if error >= threshold else 1 for error in error_list]
true_positives = sum(binary_results)
false_positives = len(binary_results) - true_positives
false_negatives = binary_results.count(0)
precision = true_positives / (true_positives + false_positives)
recall = true_positives / (true_positives + false_negatives)
f_score = 2 * (precision * recall) / (precision + recall)
return f_score
args = parse_args_function()
"""# Load Dataset"""
root = args.input_file
#mean = np.array([120.46480086, 107.89070987, 103.00262132])
#std = np.array([5.9113948 , 5.22646725, 5.47829601])
transform = transforms.Compose([transforms.Resize((224, 224)),
transforms.ToTensor()])
if args.train:
trainset = Dataset(root=root, load_set='train', transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True, num_workers=16)
print('Train files loaded')
if args.val:
valset = Dataset(root=root, load_set='val', transform=transform)
valloader = torch.utils.data.DataLoader(valset, batch_size=args.batch_size, shuffle=False, num_workers=8)
print('Validation files loaded')
if args.test:
testset = Dataset(root=root, load_set='test', transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=args.batch_size, shuffle=False, num_workers=8)
print('Test files loaded')
"""# Model"""
use_cuda = False
if args.gpu:
use_cuda = True
model = select_model(args.model_def)
if use_cuda and torch.cuda.is_available():
model = model.cuda()
model = nn.DataParallel(model, device_ids=args.gpu_number)
"""# Load Snapshot"""
if args.pretrained_model != '':
model.load_state_dict(torch.load(args.pretrained_model))
losses = np.load(args.pretrained_model[:-4] + '-losses.npy').tolist()
start = len(losses)
else:
losses = []
start = 0
"""# Optimizer"""
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.lr_step, gamma=args.lr_step_gamma)
scheduler.last_epoch = start
lambda_1 = 0.01
lambda_2 = 1
best_epoch = 0
"""# Train"""
if args.train:
print('Begin training the network...')
for epoch in range(start, args.num_iterations): # loop over the dataset multiple times
running_loss = 0.0
train_loss = 0.0
for i, tr_data in enumerate(trainloader):
# get the inputs
inputs, labels2d, labels3d = tr_data
# wrap them in Variable
inputs = Variable(inputs)
labels2d = Variable(labels2d)
labels3d = Variable(labels3d)
if use_cuda and torch.cuda.is_available():
inputs = inputs.float().cuda(device=args.gpu_number[0])
labels2d = labels2d.float().cuda(device=args.gpu_number[0])
labels3d = labels3d.float().cuda(device=args.gpu_number[0])
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs2d_init, outputs2d, outputs3d = model(inputs)
loss2d_init = criterion(outputs2d_init[0, -1], labels2d)
loss2d = criterion(outputs2d[0, -1], labels2d)
loss3d = criterion(outputs3d[0, -1], labels3d)
loss = (lambda_1) * loss2d_init + (lambda_1) * loss2d + (lambda_2) * loss3d
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.data
train_loss += loss.data
if (i+1) % args.log_batch == 0: # print every log_iter mini-batches
print('[%d, %5d] loss: %.5f' % (epoch + 1, i + 1, running_loss / args.log_batch))
running_loss = 0.0
if args.val and (epoch+1) % args.val_epoch == 0:
val_loss = 0.0
for v, val_data in enumerate(valloader):
# get the inputs
inputs, labels2d, labels3d = val_data
# wrap them in Variable
inputs = Variable(inputs)
labels2d = Variable(labels2d)
labels3d = Variable(labels3d)
if use_cuda and torch.cuda.is_available():
inputs = inputs.float().cuda(device=args.gpu_number[0])
labels2d = labels2d.float().cuda(device=args.gpu_number[0])
labels3d = labels3d.float().cuda(device=args.gpu_number[0])
outputs2d_init, outputs2d, outputs3d = model(inputs)
loss2d_init = criterion(outputs2d_init[0, -1], labels2d)
loss2d = criterion(outputs2d[0, -1], labels2d)
loss3d = criterion(outputs3d[0, -1], labels3d)
loss = (lambda_1) * loss2d_init + (lambda_1) * loss2d + (lambda_2) * loss3d
val_loss += loss.data
print('val error: %.5f' % (val_loss / (v+1)))
losses.append((train_loss / (i+1)).cpu().numpy())
if (epoch+1) % args.snapshot_epoch == 0:
torch.save(model.state_dict(), args.output_file+str(epoch+1)+'.pkl')
np.save(args.output_file+str(epoch+1)+'-losses.npy', np.array(losses))
# Decay Learning Rate
scheduler.step()
print('Finished Training')
"""# Test"""
if args.test:
print('Begin testing the network...')
error = []
error_2d = []
for i, ts_data in enumerate(testloader):
# get the inputs
inputs, labels2d, labels3d = ts_data
# wrap them in Variable
inputs = Variable(inputs)
labels2d = Variable(labels2d)
labels3d = Variable(labels3d)
if use_cuda and torch.cuda.is_available():
inputs = inputs.float().cuda(device=args.gpu_number[0])
labels2d = labels2d.float().cuda(device=args.gpu_number[0])
labels3d = labels3d.float().cuda(device=args.gpu_number[0])
outputs2d_init, outputs2d, outputs3d = model(inputs)
loss = torch.sqrt(criterion(torch.mean(outputs3d[0][25:], dim=0), labels3d))
error.append(loss.item())
loss_2d = torch.sqrt(criterion(outputs2d[0, -1], labels2d))
error_2d.append(loss_2d.item())
print('test error: %.5f ± %.5f, f@50: %.5f, f@100: %.5f' % (np.mean(error), np.std(error), calculate_f_score(error, 50), calculate_f_score(error, 100)))
np.save('baseline3d.npy', error)
print('test error (2d): %.5f ± %.5f' % (np.mean(error_2d), np.std(error_2d)))
np.save('baseline2d.npy', error_2d)