forked from x4nth055/pythoncode-tutorials
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdarknet.py
More file actions
Latest commit
463 lines (410 loc) · 18.2 KB
/
Copy pathdarknet.py
File metadata and controls
463 lines (410 loc) · 18.2 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
importtorch
importtorch.nnasnn
importnumpyasnp
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
iftorch.cuda.is_available():
x=torch.randn(1)
device=torch.device("cuda") # a CUDA device object
y=torch.ones_like(x, device=device) # directly create a tensor on GPU
x=x.to(device) # or just use strings ``.to("cuda")``
z=x+y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
classYoloLayer(nn.Module):
def__init__(self, anchor_mask=[], num_classes=0, anchors=[], num_anchors=1):
super(YoloLayer, self).__init__()
self.anchor_mask=anchor_mask
self.num_classes=num_classes
self.anchors=anchors
self.num_anchors=num_anchors
self.anchor_step=len(anchors)/num_anchors
self.coord_scale=1
self.noobject_scale=1
self.object_scale=5
self.class_scale=1
self.thresh=0.6
self.stride=32
self.seen=0
defforward(self, output, nms_thresh):
self.thresh=nms_thresh
masked_anchors= []
forminself.anchor_mask:
masked_anchors+=self.anchors[m*self.anchor_step:(m+1)*self.anchor_step]
masked_anchors= [anchor/self.strideforanchorinmasked_anchors]
boxes=get_region_boxes(output.data, self.thresh, self.num_classes, masked_anchors, len(self.anchor_mask))
returnboxes
classUpsample(nn.Module):
def__init__(self, stride=2):
super(Upsample, self).__init__()
self.stride=stride
defforward(self, x):
stride=self.stride
assert(x.data.dim() ==4)
B=x.data.size(0)
C=x.data.size(1)
H=x.data.size(2)
W=x.data.size(3)
ws=stride
hs=stride
x=x.view(B, C, H, 1, W, 1).expand(B, C, H, stride, W, stride).contiguous().view(B, C, H*stride, W*stride)
returnx
#for route and shortcut
classEmptyModule(nn.Module):
def__init__(self):
super(EmptyModule, self).__init__()
defforward(self, x):
returnx
# support route shortcut
classDarknet(nn.Module):
def__init__(self, cfgfile):
super(Darknet, self).__init__()
self.blocks=parse_cfg(cfgfile)
self.models=self.create_network(self.blocks) # merge conv, bn,leaky
self.loss=self.models[len(self.models)-1]
self.width=int(self.blocks[0]['width'])
self.height=int(self.blocks[0]['height'])
self.header=torch.IntTensor([0,0,0,0])
self.seen=0
defforward(self, x, nms_thresh):
ind=-2
self.loss=None
outputs=dict()
out_boxes= []
forblockinself.blocks:
ind=ind+1
ifblock['type'] =='net':
continue
elifblock['type'] in ['convolutional', 'upsample']:
x=self.models[ind](x)
outputs[ind] =x
elifblock['type'] =='route':
layers=block['layers'].split(',')
layers= [int(i) ifint(i) >0elseint(i)+indforiinlayers]
iflen(layers) ==1:
x=outputs[layers[0]]
outputs[ind] =x
eliflen(layers) ==2:
x1=outputs[layers[0]]
x2=outputs[layers[1]]
x=torch.cat((x1,x2),1)
outputs[ind] =x
elifblock['type'] =='shortcut':
from_layer=int(block['from'])
activation=block['activation']
from_layer=from_layeriffrom_layer>0elsefrom_layer+ind
x1=outputs[from_layer]
x2=outputs[ind-1]
x=x1+x2
outputs[ind] =x
elifblock['type'] =='yolo':
boxes=self.models[ind](x, nms_thresh)
out_boxes.append(boxes)
else:
print('unknown type %s'% (block['type']))
returnout_boxes
defprint_network(self):
print_cfg(self.blocks)
defcreate_network(self, blocks):
models=nn.ModuleList()
prev_filters=3
out_filters=[]
prev_stride=1
out_strides= []
conv_id=0
forblockinblocks:
ifblock['type'] =='net':
prev_filters=int(block['channels'])
continue
elifblock['type'] =='convolutional':
conv_id=conv_id+1
batch_normalize=int(block['batch_normalize'])
filters=int(block['filters'])
kernel_size=int(block['size'])
stride=int(block['stride'])
is_pad=int(block['pad'])
pad= (kernel_size-1)//2ifis_padelse0
activation=block['activation']
model=nn.Sequential()
ifbatch_normalize:
model.add_module('conv{0}'.format(conv_id), nn.Conv2d(prev_filters, filters, kernel_size, stride, pad, bias=False))
model.add_module('bn{0}'.format(conv_id), nn.BatchNorm2d(filters))
else:
model.add_module('conv{0}'.format(conv_id), nn.Conv2d(prev_filters, filters, kernel_size, stride, pad))
ifactivation=='leaky':
model.add_module('leaky{0}'.format(conv_id), nn.LeakyReLU(0.1, inplace=True))
prev_filters=filters
out_filters.append(prev_filters)
prev_stride=stride*prev_stride
out_strides.append(prev_stride)
models.append(model)
elifblock['type'] =='upsample':
stride=int(block['stride'])
out_filters.append(prev_filters)
prev_stride=prev_stride//stride
out_strides.append(prev_stride)
models.append(Upsample(stride))
elifblock['type'] =='route':
layers=block['layers'].split(',')
ind=len(models)
layers= [int(i) ifint(i) >0elseint(i)+indforiinlayers]
iflen(layers) ==1:
prev_filters=out_filters[layers[0]]
prev_stride=out_strides[layers[0]]
eliflen(layers) ==2:
assert(layers[0] ==ind-1)
prev_filters=out_filters[layers[0]] +out_filters[layers[1]]
prev_stride=out_strides[layers[0]]
out_filters.append(prev_filters)
out_strides.append(prev_stride)
models.append(EmptyModule())
elifblock['type'] =='shortcut':
ind=len(models)
prev_filters=out_filters[ind-1]
out_filters.append(prev_filters)
prev_stride=out_strides[ind-1]
out_strides.append(prev_stride)
models.append(EmptyModule())
elifblock['type'] =='yolo':
yolo_layer=YoloLayer()
anchors=block['anchors'].split(',')
anchor_mask=block['mask'].split(',')
yolo_layer.anchor_mask= [int(i) foriinanchor_mask]
yolo_layer.anchors= [float(i) foriinanchors]
yolo_layer.num_classes=int(block['classes'])
yolo_layer.num_anchors=int(block['num'])
yolo_layer.anchor_step=len(yolo_layer.anchors)//yolo_layer.num_anchors
yolo_layer.stride=prev_stride
out_filters.append(prev_filters)
out_strides.append(prev_stride)
models.append(yolo_layer)
else:
print('unknown type %s'% (block['type']))
returnmodels
defload_weights(self, weightfile):
print()
fp=open(weightfile, 'rb')
header=np.fromfile(fp, count=5, dtype=np.int32)
self.header=torch.from_numpy(header)
self.seen=self.header[3]
buf=np.fromfile(fp, dtype=np.float32)
fp.close()
start=0
ind=-2
counter=3
forblockinself.blocks:
ifstart>=buf.size:
break
ind=ind+1
ifblock['type'] =='net':
continue
elifblock['type'] =='convolutional':
model=self.models[ind]
batch_normalize=int(block['batch_normalize'])
ifbatch_normalize:
start=load_conv_bn(buf, start, model[0], model[1])
else:
start=load_conv(buf, start, model[0])
elifblock['type'] =='upsample':
pass
elifblock['type'] =='route':
pass
elifblock['type'] =='shortcut':
pass
elifblock['type'] =='yolo':
pass
else:
print('unknown type %s'% (block['type']))
percent_comp= (counter/len(self.blocks)) *100
print('Loading weights. Please Wait...{:.2f}% Complete'.format(percent_comp), end='\r', flush=True)
counter+=1
defconvert2cpu(gpu_matrix):
returntorch.FloatTensor(gpu_matrix.size()).copy_(gpu_matrix)
defconvert2cpu_long(gpu_matrix):
returntorch.LongTensor(gpu_matrix.size()).copy_(gpu_matrix)
defget_region_boxes(output, conf_thresh, num_classes, anchors, num_anchors, only_objectness=1, validation=False):
anchor_step=len(anchors)//num_anchors
ifoutput.dim() ==3:
output=output.unsqueeze(0)
batch=output.size(0)
assert(output.size(1) == (5+num_classes)*num_anchors)
h=output.size(2)
w=output.size(3)
all_boxes= []
output=output.view(batch*num_anchors, 5+num_classes, h*w).transpose(0,1).contiguous().view(5+num_classes, batch*num_anchors*h*w)
grid_x=torch.linspace(0, w-1, w).repeat(h,1).repeat(batch*num_anchors, 1, 1).view(batch*num_anchors*h*w).type_as(output) #cuda()
grid_y=torch.linspace(0, h-1, h).repeat(w,1).t().repeat(batch*num_anchors, 1, 1).view(batch*num_anchors*h*w).type_as(output) #cuda()
xs=torch.sigmoid(output[0]) +grid_x
ys=torch.sigmoid(output[1]) +grid_y
anchor_w=torch.Tensor(anchors).view(num_anchors, anchor_step).index_select(1, torch.LongTensor([0]))
anchor_h=torch.Tensor(anchors).view(num_anchors, anchor_step).index_select(1, torch.LongTensor([1]))
anchor_w=anchor_w.repeat(batch, 1).repeat(1, 1, h*w).view(batch*num_anchors*h*w).type_as(output) #cuda()
anchor_h=anchor_h.repeat(batch, 1).repeat(1, 1, h*w).view(batch*num_anchors*h*w).type_as(output) #cuda()
ws=torch.exp(output[2]) *anchor_w
hs=torch.exp(output[3]) *anchor_h
det_confs=torch.sigmoid(output[4])
cls_confs=torch.nn.Softmax(dim=1)(output[5:5+num_classes].transpose(0,1)).detach()
cls_max_confs, cls_max_ids=torch.max(cls_confs, 1)
cls_max_confs=cls_max_confs.view(-1)
cls_max_ids=cls_max_ids.view(-1)
sz_hw=h*w
sz_hwa=sz_hw*num_anchors
det_confs=convert2cpu(det_confs)
cls_max_confs=convert2cpu(cls_max_confs)
cls_max_ids=convert2cpu_long(cls_max_ids)
xs=convert2cpu(xs)
ys=convert2cpu(ys)
ws=convert2cpu(ws)
hs=convert2cpu(hs)
ifvalidation:
cls_confs=convert2cpu(cls_confs.view(-1, num_classes))
forbinrange(batch):
boxes= []
forcyinrange(h):
forcxinrange(w):
foriinrange(num_anchors):
ind=b*sz_hwa+i*sz_hw+cy*w+cx
det_conf=det_confs[ind]
ifonly_objectness:
conf=det_confs[ind]
else:
conf=det_confs[ind] *cls_max_confs[ind]
ifconf>conf_thresh:
bcx=xs[ind]
bcy=ys[ind]
bw=ws[ind]
bh=hs[ind]
cls_max_conf=cls_max_confs[ind]
cls_max_id=cls_max_ids[ind]
box= [bcx/w, bcy/h, bw/w, bh/h, det_conf, cls_max_conf, cls_max_id]
if (notonly_objectness) andvalidation:
forcinrange(num_classes):
tmp_conf=cls_confs[ind][c]
ifc!=cls_max_idanddet_confs[ind]*tmp_conf>conf_thresh:
box.append(tmp_conf)
box.append(c)
boxes.append(box)
all_boxes.append(boxes)
returnall_boxes
defparse_cfg(cfgfile):
blocks= []
fp=open(cfgfile, 'r')
block=None
line=fp.readline()
whileline!='':
line=line.rstrip()
ifline==''orline[0] =='#':
line=fp.readline()
continue
elifline[0] =='[':
ifblock:
blocks.append(block)
block=dict()
block['type'] =line.lstrip('[').rstrip(']')
# set default value
ifblock['type'] =='convolutional':
block['batch_normalize'] =0
else:
key,value=line.split('=')
key=key.strip()
ifkey=='type':
key='_type'
value=value.strip()
block[key] =value
line=fp.readline()
ifblock:
blocks.append(block)
fp.close()
returnblocks
defprint_cfg(blocks):
print('layer filters size input output')
prev_width=416
prev_height=416
prev_filters=3
out_filters=[]
out_widths=[]
out_heights=[]
ind=-2
forblockinblocks:
ind=ind+1
ifblock['type'] =='net':
prev_width=int(block['width'])
prev_height=int(block['height'])
continue
elifblock['type'] =='convolutional':
filters=int(block['filters'])
kernel_size=int(block['size'])
stride=int(block['stride'])
is_pad=int(block['pad'])
pad= (kernel_size-1)//2ifis_padelse0
width= (prev_width+2*pad-kernel_size)//stride+1
height= (prev_height+2*pad-kernel_size)//stride+1
print('%5d %-6s %4d %d x %d / %d %3d x %3d x%4d -> %3d x %3d x%4d'% (ind, 'conv', filters, kernel_size, kernel_size, stride, prev_width, prev_height, prev_filters, width, height, filters))
prev_width=width
prev_height=height
prev_filters=filters
out_widths.append(prev_width)
out_heights.append(prev_height)
out_filters.append(prev_filters)
elifblock['type'] =='upsample':
stride=int(block['stride'])
filters=prev_filters
width=prev_width*stride
height=prev_height*stride
print('%5d %-6s * %d %3d x %3d x%4d -> %3d x %3d x%4d'% (ind, 'upsample', stride, prev_width, prev_height, prev_filters, width, height, filters))
prev_width=width
prev_height=height
prev_filters=filters
out_widths.append(prev_width)
out_heights.append(prev_height)
out_filters.append(prev_filters)
elifblock['type'] =='route':
layers=block['layers'].split(',')
layers= [int(i) ifint(i) >0elseint(i)+indforiinlayers]
iflen(layers) ==1:
print('%5d %-6s %d'% (ind, 'route', layers[0]))
prev_width=out_widths[layers[0]]
prev_height=out_heights[layers[0]]
prev_filters=out_filters[layers[0]]
eliflen(layers) ==2:
print('%5d %-6s %d %d'% (ind, 'route', layers[0], layers[1]))
prev_width=out_widths[layers[0]]
prev_height=out_heights[layers[0]]
assert(prev_width==out_widths[layers[1]])
assert(prev_height==out_heights[layers[1]])
prev_filters=out_filters[layers[0]] +out_filters[layers[1]]
out_widths.append(prev_width)
out_heights.append(prev_height)
out_filters.append(prev_filters)
elifblock['type'] in ['region', 'yolo']:
print('%5d %-6s'% (ind, 'detection'))
out_widths.append(prev_width)
out_heights.append(prev_height)
out_filters.append(prev_filters)
elifblock['type'] =='shortcut':
from_id=int(block['from'])
from_id=from_idiffrom_id>0elsefrom_id+ind
print('%5d %-6s %d'% (ind, 'shortcut', from_id))
prev_width=out_widths[from_id]
prev_height=out_heights[from_id]
prev_filters=out_filters[from_id]
out_widths.append(prev_width)
out_heights.append(prev_height)
out_filters.append(prev_filters)
else:
print('unknown type %s'% (block['type']))
defload_conv(buf, start, conv_model):
num_w=conv_model.weight.numel()
num_b=conv_model.bias.numel()
conv_model.bias.data.copy_(torch.from_numpy(buf[start:start+num_b])); start=start+num_b
conv_model.weight.data.copy_(torch.from_numpy(buf[start:start+num_w]).view_as(conv_model.weight.data)); start=start+num_w
returnstart
defload_conv_bn(buf, start, conv_model, bn_model):
num_w=conv_model.weight.numel()
num_b=bn_model.bias.numel()
bn_model.bias.data.copy_(torch.from_numpy(buf[start:start+num_b])); start=start+num_b
bn_model.weight.data.copy_(torch.from_numpy(buf[start:start+num_b])); start=start+num_b
bn_model.running_mean.copy_(torch.from_numpy(buf[start:start+num_b])); start=start+num_b
bn_model.running_var.copy_(torch.from_numpy(buf[start:start+num_b])); start=start+num_b
conv_model.weight.data.copy_(torch.from_numpy(buf[start:start+num_w]).view_as(conv_model.weight.data)); start=start+num_w
returnstart