forked from VitjanZ/DRAEM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_DRAEM.py
185 lines (144 loc) · 7.65 KB
/
train_DRAEM.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
import torch
from data_loader import MVTecDRAEMTrainDataset
from torch.utils.data import DataLoader
from torch import optim
from tensorboard_visualizer import TensorboardVisualizer
from model_unet import ReconstructiveSubNetwork, DiscriminativeSubNetwork
from loss import FocalLoss, SSIM
import os
from skimage.filters import edges
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
def train_on_device(obj_names, args):
if not os.path.exists(args.checkpoint_path):
os.makedirs(args.checkpoint_path)
if not os.path.exists(args.log_path):
os.makedirs(args.log_path)
pretrained_base_model_name = "DRAEM_seg_large_ae_large_0.0001_800_bs8"
pretrained_base_model_name = "DRAEM_checkpoints/" + pretrained_base_model_name
for obj_name in obj_names:
pretrained_model = os.path.join(args.checkpoint_path, pretrained_base_model_name+"_"+obj_name+"_.pckl")
pretrained_model_seg = os.path.join(args.checkpoint_path, pretrained_base_model_name+"_"+obj_name+"__seg.pckl")
run_name = 'DRAEM_test_'+str(args.lr)+'_'+str(args.epochs)+'_bs'+str(args.bs)+"_"+obj_name+'_'
visualizer = TensorboardVisualizer(log_dir=os.path.join(args.log_path, run_name+"/"))
model = ReconstructiveSubNetwork(in_channels=3, out_channels=3)
model.cuda()
model_seg = DiscriminativeSubNetwork(in_channels=6, out_channels=2)
model_seg.cuda()
if args.pretrained:
model.load_state_dict(torch.load(pretrained_model, map_location='cuda:0'))
model_seg.load_state_dict(torch.load(pretrained_model_seg, map_location='cuda:0'))
else:
model.apply(weights_init)
model_seg.apply(weights_init)
# optimizer获取所有parameters的引用,每个parameter都包含梯度(gradient),optimizer可以把根据梯度更新parameter。
optimizer = torch.optim.Adam([
{"params": model.parameters(), "lr": args.lr},
{"params": model_seg.parameters(), "lr": args.lr}])
scheduler = optim.lr_scheduler.MultiStepLR(optimizer,[args.epochs*0.8,args.epochs*0.9],gamma=0.2, last_epoch=-1)
loss_l2 = torch.nn.modules.loss.MSELoss()
loss_ssim = SSIM()
loss_focal = FocalLoss()
dataset = MVTecDRAEMTrainDataset(args.data_path + obj_name + "/train/good/", args.anomaly_source_path, resize_shape=[256, 256])
dataloader = DataLoader(dataset, batch_size=args.bs,
shuffle=True, num_workers=0)
n_iter = 0
for epoch in range(args.epochs):
print("Epoch: "+str(epoch))
for i_batch, sample_batched in enumerate(dataloader):
gray_batch = sample_batched["image"].cuda()
aug_gray_batch = sample_batched["augmented_image"].cuda()
anomaly_mask = sample_batched["anomaly_mask"].cuda()
gray_rec = model(aug_gray_batch)
joined_in = torch.cat((gray_rec, aug_gray_batch), dim=1)
out_mask = model_seg(joined_in)
out_mask_sm = torch.softmax(out_mask, dim=1)
l2_loss = loss_l2(gray_rec,gray_batch)
ssim_loss = loss_ssim(gray_rec, gray_batch)
segment_loss = loss_focal(out_mask_sm, anomaly_mask)
# 对prediction和y之间进行比对(熵或者其他loss function),产生最初的梯度
loss = l2_loss + ssim_loss + segment_loss
# 清除之前的梯度,需要在loss.backward()之前调用
optimizer.zero_grad()
# loss.backward(),将梯度反向传播到整个网络的所有链路和节点,获得model的所有parameter的gradient
loss.backward()
# optimizer存了这些parameter的指针,step()根据这些parameter的gradient对parameter的值进行更新。
optimizer.step()
# loss 和 optimizer 之间是通过parameter建立的关系
if args.visualize and n_iter % 8 == 0:
visualizer.plot_loss(l2_loss, n_iter, loss_name='l2_loss')
visualizer.plot_loss(ssim_loss, n_iter, loss_name='ssim_loss')
visualizer.plot_loss(segment_loss, n_iter, loss_name='segment_loss')
if args.visualize and n_iter % 8 == 0:
t_mask = out_mask_sm[:, 1:, :, :]
visualizer.visualize_image_batch(aug_gray_batch, n_iter, image_name='batch_augmented')
visualizer.visualize_image_batch(gray_batch, n_iter, image_name='batch_recon_target')
visualizer.visualize_image_batch(gray_rec, n_iter, image_name='batch_recon_out')
visualizer.visualize_image_batch(anomaly_mask, n_iter, image_name='mask_target')
visualizer.visualize_image_batch(t_mask, n_iter, image_name='mask_out')
n_iter +=1
# 对lr进行调整
scheduler.step()
torch.save(model.state_dict(), os.path.join(args.checkpoint_path, run_name+".pckl"))
torch.save(model_seg.state_dict(), os.path.join(args.checkpoint_path, run_name+"_seg.pckl"))
if __name__=="__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--obj_id', action='store', type=int, required=True)
parser.add_argument('--bs', action='store', type=int, required=True)
parser.add_argument('--lr', action='store', type=float, required=True)
parser.add_argument('--epochs', action='store', type=int, required=True)
parser.add_argument('--gpu_id', action='store', type=int, default=0, required=False)
parser.add_argument('--data_path', action='store', type=str, required=True)
parser.add_argument('--anomaly_source_path', action='store', type=str, required=True)
parser.add_argument('--checkpoint_path', action='store', type=str, required=True)
parser.add_argument('--log_path', action='store', type=str, required=True)
parser.add_argument('--visualize', action='store_true')
parser.add_argument('--pretrained', action='store_true')
args = parser.parse_args()
obj_batch = [['capsule'],
['bottle'],
['carpet'],
['leather'],
['pill'],
['transistor'],
['tile'],
['cable'],
['zipper'],
['toothbrush'],
['metal_nut'],
['hazelnut'],
['screw'],
['grid'],
['wood']
]
if int(args.obj_id) == -1:
obj_list = ['capsule',
'bottle',
'carpet',
'leather',
'pill',
'transistor',
'tile',
'cable',
'zipper',
'toothbrush',
'metal_nut',
'hazelnut',
'screw',
'grid',
'wood'
]
picked_classes = obj_list
else:
picked_classes = obj_batch[int(args.obj_id)]
with torch.cuda.device(args.gpu_id):
train_on_device(picked_classes, args)