-
Notifications
You must be signed in to change notification settings - Fork 1
/
semi_train.py
215 lines (172 loc) · 8.25 KB
/
semi_train.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
215
import datetime
import os
import torch
from torch import nn
from torch import optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
import joint_transforms
from config import train_data
from datasets_semi import ImageFolder
from misc import AvgMeter, check_mkdir
from Res2_DTEN import Res2_DTEN
from student_res2net import student_net
from torch.backends import cudnn
import torch.nn.functional as functional
import numpy as np
import cv2
import torch.nn.functional as F
cudnn.benchmark = True
torch.manual_seed(2018)
torch.cuda.set_device(0)
def visualize_prediction1(pred):
for kk in range(pred.shape[0]):
pred_edge_kk = pred[kk, :, :, :]
pred_edge_kk = pred_edge_kk.detach().cpu().numpy().squeeze()
pred_edge_kk = (pred_edge_kk - pred_edge_kk.min()) / (pred_edge_kk.max() - pred_edge_kk.min() + 1e-8)
pred_edge_kk *= 255.0
pred_edge_kk = pred_edge_kk.astype(np.uint8)
save_path = './semi/'
if not os.path.exists(save_path):
os.makedirs(save_path)
name = '{:02d}_out.png'.format(kk)
cv2.imwrite(save_path+name, pred_edge_kk)
def visualize_prediction2(pred):
for kk in range(pred.shape[0]):
pred_edge_kk = pred[kk, :, :, :]
pred_edge_kk = pred_edge_kk.detach().cpu().numpy().squeeze()
#pred_edge_kk = pred_edge_kk.cpu().numpy().squeeze()
pred_edge_kk = (pred_edge_kk - pred_edge_kk.min()) / (pred_edge_kk.max() - pred_edge_kk.min() + 1e-8)
pred_edge_kk *= 255.0
pred_edge_kk = pred_edge_kk.astype(np.uint8)
save_path = './semi/'
if not os.path.exists(save_path):
os.makedirs(save_path)
name = '{:02d}_pseudo.png'.format(kk)
cv2.imwrite(save_path+name, pred_edge_kk)
def visualize_prediction3(pred):
for kk in range(pred.shape[0]):
pred_edge_kk = pred[kk, :, :, :]
pred_edge_kk = pred_edge_kk.detach().cpu().numpy().squeeze()
pred_edge_kk = (pred_edge_kk - pred_edge_kk.min()) / (pred_edge_kk.max() - pred_edge_kk.min() + 1e-8)
pred_edge_kk *= 255.0
pred_edge_kk = pred_edge_kk.astype(np.uint8)
save_path = './semi/'
if not os.path.exists(save_path):
os.makedirs(save_path)
name = '{:02d}_gt.png'.format(kk)
cv2.imwrite(save_path+name, pred_edge_kk)
##########################hyperparameters###############################
ckpt_path = './model'
exp_name = 'res2net_detr_weakly_semi'
args = {
'iter_num':20000,
'train_batch_size': 4,
'last_iter': 0,
'lr': 1e-4,
'lr_decay': 0.9,
'weight_decay': 0.0005,
'momentum': 0.9,
'snapshot': ''
}
##########################data augmentation###############################
joint_transform = joint_transforms.Compose([
joint_transforms.RandomCrop(352,352),
joint_transforms.RandomHorizontallyFlip(),
joint_transforms.RandomRotate(10)
])
img_transform = transforms.Compose([
transforms.ColorJitter(0.1, 0.1, 0.1),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
target_transform = transforms.ToTensor()
##########################################################################
train_set = ImageFolder(train_data, joint_transform, img_transform, target_transform,352)
train_loader = DataLoader(train_set, batch_size=args['train_batch_size'], num_workers=12, shuffle=True)
criterion = nn.BCEWithLogitsLoss().cuda()
criterion_BCE = nn.BCELoss().cuda()
criterion_MAE = nn.L1Loss().cuda()
criterion_MSE = nn.MSELoss().cuda()
log_path = os.path.join(ckpt_path, exp_name, str(datetime.datetime.now()) + '.txt')
def main():
model_student = student_net().cuda()
model_teacher = Res2_DTEN().cuda()
model_teacher.load_state_dict(torch.load('./model/20000.pth'))
net = model_student.train()
optimizer = optim.SGD([
{'params': [param for name, param in net.named_parameters() if name[-4:] == 'bias'],
'lr': 2 * args['lr']},
{'params': [param for name, param in net.named_parameters() if name[-4:] != 'bias'],
'lr': args['lr'], 'weight_decay': args['weight_decay']}
], momentum=args['momentum'])
if len(args['snapshot']) > 0:
print ('training resumes from ' + args['snapshot'])
net.load_state_dict(torch.load(os.path.join(ckpt_path, exp_name, args['snapshot'] + '.pth')))
optimizer.load_state_dict(torch.load(os.path.join(ckpt_path, exp_name, args['snapshot'] + '_optim.pth')))
optimizer.param_groups[0]['lr'] = 2 * args['lr']
optimizer.param_groups[1]['lr'] = args['lr']
check_mkdir(ckpt_path)
check_mkdir(os.path.join(ckpt_path, exp_name))
open(log_path, 'w').write(str(args) + '\n\n')
train(net, optimizer,model_teacher)
def train(net, optimizer,model_teacher):
curr_iter = args['last_iter']
while True:
total_loss_record, loss1_record, loss2_record,loss3_record,loss4_record,loss5_record,loss6_record,loss7_record,loss8_record = AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(),AvgMeter(),AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter()
for i, data in enumerate(train_loader):
optimizer.param_groups[0]['lr'] = 2 * args['lr'] * (1 - float(curr_iter) / args['iter_num']
) ** args['lr_decay']
optimizer.param_groups[1]['lr'] = args['lr'] * (1 - float(curr_iter) / args['iter_num']
) ** args['lr_decay']
inputs, masks, gts,padding_mask= data
gts[gts>0.5] = 1
gts[gts!=1] = 0
masks[masks>0.5] = 1
masks[masks!=1] = 0
batch_size = inputs.size(0)
inputs = Variable(inputs).cuda()
masks = Variable(masks).cuda()
gts = Variable(gts).cuda()
padding_mask = Variable(padding_mask).cuda()
padding_mask = padding_mask.squeeze(1)
pseudo1,pseudo_label = model_teacher(inputs,padding_mask)
outputs,dten_out = net(inputs,padding_mask)
##########loss#############
optimizer.zero_grad()
labeled_num = len(torch.nonzero(gts))
if labeled_num!=0:
sal1_prob = torch.sigmoid(outputs)
sal1_prob = sal1_prob * masks
loss1 = ratio*criterion_BCE(sal1_prob, gts*masks)+0.1*criterion_MAE(outputs,pseudo_label.detach())
sal2_prob = torch.sigmoid(dten_out)
sal2_prob = sal2_prob * masks
loss2 = ratio*criterion_BCE(sal2_prob, gts*masks)+0.1*criterion_MAE(detr_out,pseudo_label.detach())
total_loss = loss1 + loss2
else:
loss1 =0.5*criterion_MAE(outputs,pseudo_label.detach())
loss2 =0.5*criterion_MAE(outputs,pseudo_label.detach())
total_loss = loss1 + loss2
visualize_prediction2(torch.sigmoid(pseudo_label))
visualize_prediction1(torch.sigmoid(dten_out))
visualize_prediction3(torch.sigmoid(gts))
total_loss.backward()
optimizer.step()
total_loss_record.update(total_loss.item(), batch_size)
loss1_record.update(loss1.item(), batch_size)
loss2_record.update(loss2.item(), batch_size)
curr_iter += 1
#############log###############
if curr_iter %10000==0:
torch.save(net.state_dict(), os.path.join(ckpt_path, exp_name, '%d.pth' % curr_iter))
log = '[iter %d], [total loss %.5f],[loss1 %.5f],[loss2 %.5f],[lr %.13f] ' % \
(curr_iter, total_loss_record.avg,loss1_record.avg,loss2_record.avg, optimizer.param_groups[1]['lr'])
print(log)
open(log_path, 'a').write(log + '\n')
if curr_iter == args['iter_num']:
torch.save(net.state_dict(), os.path.join(ckpt_path, exp_name, '%d.pth' % curr_iter))
return
#############end###############
if __name__ == '__main__':
main()