forked from AceCoooool/DSS-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
166 lines (156 loc) · 8.25 KB
/
solver.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
import torch
from collections import OrderedDict
from torch.nn import utils, functional as F
from torch.optim import Adam
from torch.autograd import Variable
from torch.backends import cudnn
from dssnet import build_model, weights_init
from loss import Loss
from tools.visual import Viz_visdom
class Solver(object):
def __init__(self, train_loader, val_loader, test_loader, config):
self.train_loader = train_loader
self.val_loader = val_loader
self.test_loader = test_loader
self.config = config
self.beta = 0.3 # for max F_beta metric
self.mean = torch.Tensor([123.68, 116.779, 103.939]).view(3, 1, 1) / 255
# inference: choose the side map (see paper)
self.select = [1, 2, 3, 6]
if config.visdom:
self.visual = Viz_visdom("DSS", 1)
self.build_model()
if self.config.pre_trained: self.net.load_state_dict(torch.load(self.config.pre_trained))
if config.mode == 'train':
self.log_output = open("%s/logs/log.txt" % config.save_fold, 'w')
else:
self.net.load_state_dict(torch.load(self.config.model))
self.net.eval()
self.test_output = open("%s/test.txt" % config.test_fold, 'w')
# print the network information and parameter numbers
def print_network(self, model, name):
num_params = 0
for p in model.parameters():
num_params += p.numel()
print(name)
print(model)
print("The number of parameters: {}".format(num_params))
# build the network
def build_model(self):
self.net = build_model()
if self.config.mode == 'train': self.loss = Loss()
if self.config.cuda: self.net = self.net.cuda()
if self.config.cuda and self.config.mode == 'train': self.loss = self.loss.cuda()
self.net.train()
self.net.apply(weights_init)
if self.config.load == '': self.net.base.load_state_dict(torch.load(self.config.vgg))
if self.config.load != '': self.net.load_state_dict(torch.load(self.config.load))
self.optimizer = Adam(self.net.parameters(), self.config.lr)
self.print_network(self.net, 'DSS')
# update the learning rate
def update_lr(self, lr):
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr
# evaluate MAE (for test or validation phase)
def eval_mae(self, y_pred, y):
return torch.abs(y_pred - y).mean()
# TODO: write a more efficient version
# get precisions and recalls: threshold---divided [0, 1] to num values
def eval_pr(self, y_pred, y, num):
prec, recall = torch.zeros(num), torch.zeros(num)
thlist = torch.linspace(0, 1 - 1e-10, num)
for i in range(num):
y_temp = (y_pred >= thlist[i]).float()
tp = (y_temp * y).sum()
prec[i], recall[i] = tp / (y_temp.sum() + 1e-20), tp / y.sum()
return prec, recall
# validation: using resize image, and only evaluate the MAE metric
def validation(self):
avg_mae = 0.0
self.net.eval()
for i, data_batch in enumerate(self.val_loader):
images, labels = data_batch
images, labels = Variable(images, volatile=True), Variable(labels, volatile=True)
if self.config.cuda:
images, labels = images.cuda(), labels.cuda()
prob_pred = self.net(images)
prob_pred = torch.mean(torch.cat([prob_pred[i] for i in self.select], dim=1), dim=1, keepdim=True)
avg_mae += self.eval_mae(prob_pred, labels).cpu().data[0]
self.net.train()
return avg_mae / len(self.val_loader)
# test phase: using origin image size, evaluate MAE and max F_beta metrics
def test(self, num):
avg_mae, img_num = 0.0, len(self.test_loader)
avg_prec, avg_recall = torch.zeros(num), torch.zeros(num)
for i, data_batch in enumerate(self.test_loader):
images, labels = data_batch
shape = labels.size()[2:]
images = Variable(images, volatile=True)
if self.config.cuda:
images = images.cuda()
prob_pred = self.net(images)
prob_pred = torch.mean(torch.cat([prob_pred[i] for i in self.select], dim=1), dim=1, keepdim=True)
prob_pred = F.upsample(prob_pred, size=shape, mode='bilinear').cpu().data
mae = self.eval_mae(prob_pred, labels)
prec, recall = self.eval_pr(prob_pred, labels, num)
print("[%d] mae: %.4f" % (i, mae))
print("[%d] mae: %.4f" % (i, mae), file=self.test_output)
avg_mae += mae
avg_prec, avg_recall = avg_prec + prec, avg_recall + recall
avg_mae, avg_prec, avg_recall = avg_mae / img_num, avg_prec / img_num, avg_recall / img_num
score = (1 + self.beta ** 2) * avg_prec * avg_recall / (self.beta ** 2 * avg_prec + avg_recall)
score[score != score] = 0 # delete the nan
print('average mae: %.4f, max fmeasure: %.4f' % (avg_mae, score.max()))
print('average mae: %.4f, max fmeasure: %.4f' % (avg_mae, score.max()), file=self.test_output)
# training phase
def train(self):
x = torch.FloatTensor(self.config.batch_size, self.config.n_color, self.config.img_size, self.config.img_size)
y = torch.FloatTensor(self.config.batch_size, self.config.n_color, self.config.img_size, self.config.img_size)
if self.config.cuda:
cudnn.benchmark = True
x, y = x.cuda(), y.cuda()
x, y = Variable(x), Variable(y)
iter_num = len(self.train_loader.dataset) // self.config.batch_size
best_mae = 1.0 if self.config.val else None
for epoch in range(self.config.epoch):
loss_epoch = 0
for i, data_batch in enumerate(self.train_loader):
if (i + 1) > iter_num: break
self.net.zero_grad()
images, labels = data_batch
if self.config.cuda:
images, labels = images.cuda(), labels.cuda()
x.data.resize_as_(images).copy_(images)
y.data.resize_as_(labels).copy_(labels)
y_pred = self.net(x)
loss = self.loss(y_pred, y)
loss.backward()
utils.clip_grad_norm(self.net.parameters(), self.config.clip_gradient)
# utils.clip_grad_norm(self.loss.parameters(), self.config.clip_gradient)
self.optimizer.step()
loss_epoch += loss.cpu().data[0]
print('epoch: [%d/%d], iter: [%d/%d], loss: [%.4f]' % (
epoch, self.config.epoch, i, iter_num, loss.cpu().data[0]))
if self.config.visdom:
error = OrderedDict([('loss:', loss.cpu().data[0])])
self.visual.plot_current_errors(epoch, i / iter_num, error)
if (epoch + 1) % self.config.epoch_show == 0:
print('epoch: [%d/%d], epoch_loss: [%.4f]' % (epoch, self.config.epoch, loss_epoch / iter_num),
file=self.log_output)
if self.config.visdom:
avg_err = OrderedDict([('avg_loss', loss_epoch / iter_num)])
self.visual.plot_current_errors(epoch, i / iter_num, avg_err, 1)
y_show = torch.mean(torch.cat([y_pred[i] for i in self.select], dim=1), dim=1, keepdim=True)
img = OrderedDict([('origin', self.mean + images.cpu()[0]), ('label', labels.cpu()[0][0]),
('pred_label', y_show.cpu().data[0][0])])
self.visual.plot_current_img(img)
if self.config.val and (epoch + 1) % self.config.epoch_val == 0:
mae = self.validation()
print('--- Best MAE: %.2f, Curr MAE: %.2f ---' % (best_mae, mae))
print('--- Best MAE: %.2f, Curr MAE: %.2f ---' % (best_mae, mae), file=self.log_output)
if best_mae > mae:
best_mae = mae
torch.save(self.net.state_dict(), '%s/models/best.pth' % self.config.save_fold)
if (epoch + 1) % self.config.epoch_save == 0:
torch.save(self.net.state_dict(), '%s/models/epoch_%d.pth' % (self.config.save_fold, epoch + 1))
torch.save(self.net.state_dict(), '%s/models/final.pth' % self.config.save_fold)