/
yolov3.go
498 lines (441 loc) · 13.5 KB
/
yolov3.go
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package yologo
import (
"fmt"
"strconv"
"strings"
"github.com/chewxy/math32"
"github.com/pkg/errors"
"gorgonia.org/gorgonia"
"gorgonia.org/tensor"
)
// YOLOv3 YOLOv3 architecture
type YOLOv3 struct {
g *gorgonia.ExprGraph
classesNum, boxesPerCell, netSize int
out []*gorgonia.Node
layersInfo []string
LearningNodes []*gorgonia.Node
training []YoloTrainer
}
// Print Print architecture of network
func (net *YOLOv3) Print() {
for i := range net.layersInfo {
fmt.Println(net.layersInfo[i])
}
}
// GetOutput Get out YOLO layers (can be multiple of them)
func (net *YOLOv3) GetOutput() []*gorgonia.Node {
return net.out
}
// NewYoloV3 Create new YOLO v3
func NewYoloV3(g *gorgonia.ExprGraph, input *gorgonia.Node, classesNumber, boxesPerCell int, leakyCoef float64, cfgFile, weightsFile string) (*YOLOv3, error) {
shp := input.Shape()
if len(shp) < 4 {
return nil, fmt.Errorf("Input for tiny-YOLOv3 must contain 4 dimensions, but recieved %d)", len(shp))
}
buildingBlocks, err := ParseConfiguration(cfgFile)
if err != nil {
return nil, errors.Wrap(err, "Can't read darknet configuration")
}
netParams := buildingBlocks[0]
netWidthStr := netParams["width"]
netWidth, err := strconv.Atoi(netWidthStr)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("Network's width must be integer, got value: '%s'", netWidthStr))
}
weightsData, err := ParseWeights(weightsFile)
if err != nil {
return nil, errors.Wrap(err, "Can't read darknet weights")
}
fmt.Println("Loading network...")
layers := []*layerN{}
outputFilters := []int{}
prevFilters := 3
networkNodes := []*gorgonia.Node{}
blocks := buildingBlocks[1:]
lastIdx := 5 // Skip first 5 values (header of weights file)
epsilon := float32(0.000001)
yoloNodes := []*gorgonia.Node{}
learningNodes := []*gorgonia.Node{}
yoloTrainers := []YoloTrainer{}
for i := range blocks {
block := blocks[i]
filtersIdx := 0
layerType, ok := block["type"]
if ok {
switch layerType {
case "convolutional":
filters := 0
padding := 0
kernelSize := 0
stride := 0
batchNormalize := 0
bias := false
activation := "activation"
activation, ok := block["activation"]
if !ok {
fmt.Printf("No field 'activation' for convolution layer")
continue
}
batchNormalizeStr, ok := block["batch_normalize"]
batchNormalize, err := strconv.Atoi(batchNormalizeStr)
if !ok || err != nil {
batchNormalize = 0
bias = true
}
filtersStr, ok := block["filters"]
filters, err = strconv.Atoi(filtersStr)
if !ok || err != nil {
fmt.Printf("Wrong or empty 'filters' parameter for convolution layer: %s\n", err.Error())
continue
}
paddingStr, ok := block["pad"]
padding, err = strconv.Atoi(paddingStr)
if !ok || err != nil {
fmt.Printf("Wrong or empty 'pad' parameter for convolution layer: %s\n", err.Error())
continue
}
kernelSizeStr, ok := block["size"]
kernelSize, err = strconv.Atoi(kernelSizeStr)
if !ok || err != nil {
fmt.Printf("Wrong or empty 'size' parameter for convolution layer: %s\n", err.Error())
continue
}
pad := 0
if padding != 0 {
pad = (kernelSize - 1) / 2
}
strideStr, ok := block["stride"]
stride, err = strconv.Atoi(strideStr)
if !ok || err != nil {
fmt.Printf("Wrong or empty 'stride' parameter for convolution layer: %s\n", err.Error())
continue
}
ll := &convLayer{
filters: filters,
padding: pad,
kernelSize: kernelSize,
stride: stride,
activation: activation,
activationReLUCoef: leakyCoef,
batchNormalize: batchNormalize,
bias: bias,
}
shp := tensor.Shape{filters, prevFilters, kernelSize, kernelSize}
kernels := []float32{}
biases := []float32{}
if ll.batchNormalize > 0 {
nb := shp[0]
nk := shp.TotalSize()
biases = weightsData[lastIdx : lastIdx+nb]
lastIdx += nb
gammas := weightsData[lastIdx : lastIdx+nb]
lastIdx += nb
means := weightsData[lastIdx : lastIdx+nb]
lastIdx += nb
vars := weightsData[lastIdx : lastIdx+nb]
lastIdx += nb
kernels = weightsData[lastIdx : lastIdx+nk]
lastIdx += nk
// Denormalize weights
for s := 0; s < shp[0]; s++ {
scale := gammas[s] / math32.Sqrt(vars[s]+epsilon)
biases[s] = biases[s] - means[s]*scale
isize := shp[1] * shp[2] * shp[3]
for j := 0; j < isize; j++ {
kernels[isize*s+j] *= scale
}
}
} else {
if ll.bias {
nb := shp[0]
nk := shp.TotalSize()
biases = weightsData[lastIdx : lastIdx+nb]
lastIdx += nb
kernels = weightsData[lastIdx : lastIdx+nk]
lastIdx += nk
}
}
convTensor := tensor.New(tensor.WithBacking(kernels), tensor.WithShape(shp...))
convNode := gorgonia.NewTensor(g, tensor.Float32, 4, gorgonia.WithShape(shp...), gorgonia.WithName(fmt.Sprintf("conv_%d", i)), gorgonia.WithValue(convTensor))
ll.convNode = convNode
ll.biases = biases
ll.layerIndex = i
var l layerN = ll
convBlock, err := l.ToNode(g, input)
if err != nil {
fmt.Printf("\tError preparing Convolutional block: %s\n", err.Error())
}
networkNodes = append(networkNodes, convBlock)
input = convBlock
layers = append(layers, &l)
learningNodes = append(learningNodes, ll.convNode)
filtersIdx = filters
break
case "upsample":
scale := 0
scaleStr, ok := block["stride"]
scale, err = strconv.Atoi(scaleStr)
if !ok || err != nil {
fmt.Printf("Wrong or empty 'stride' parameter for upsampling layer: %s\n", err.Error())
continue
}
var l layerN = &upsampleLayer{
scale: scale,
}
upsampleBlock, err := l.ToNode(g, input)
if err != nil {
fmt.Printf("\tError preparing Upsample block: %s\n", err.Error())
}
networkNodes = append(networkNodes, upsampleBlock)
input = upsampleBlock
layers = append(layers, &l)
filtersIdx = prevFilters
break
case "route":
routeLayersStr, ok := block["layers"]
if !ok {
fmt.Printf("No field 'layers' for route layer")
continue
}
layersSplit := strings.Split(routeLayersStr, ",")
if len(layersSplit) < 1 {
fmt.Printf("Something wrong with route layer. Check if it has one array item atleast")
continue
}
for l := range layersSplit {
layersSplit[l] = strings.TrimSpace(layersSplit[l])
}
start := 0
end := 0
start, err := strconv.Atoi(layersSplit[0])
if err != nil {
fmt.Printf("Each first element of 'layers' parameter for route layer should be an integer: %s\n", err.Error())
continue
}
if len(layersSplit) > 1 {
end, err = strconv.Atoi(layersSplit[1])
if err != nil {
fmt.Printf("Each second element of 'layers' parameter for route layer should be an integer: %s\n", err.Error())
continue
}
}
if start > 0 {
start = start - i
}
if end > 0 {
end = end - i
}
l := routeLayer{
firstLayerIdx: i + start,
secondLayerIdx: -1,
}
if end < 0 {
l.secondLayerIdx = i + end
filtersIdx = outputFilters[i+start] + outputFilters[i+end]
} else {
filtersIdx = outputFilters[i+start]
}
var ll layerN = &l
routeBlock, err := l.ToNode(g, networkNodes...)
if err != nil {
fmt.Printf("\tError preparing Route block: %s\n", err.Error())
}
networkNodes = append(networkNodes, routeBlock)
input = routeBlock
layers = append(layers, &ll)
break
case "yolo":
maskStr, ok := block["mask"]
if !ok {
fmt.Printf("No field 'mask' for YOLO layer")
continue
}
maskSplit := strings.Split(maskStr, ",")
if len(maskSplit) < 1 {
fmt.Printf("Something wrong with yolo layer. Check if it has one item in 'mask' array atleast")
continue
}
masks := make([]int, len(maskSplit))
for l := range maskSplit {
maskSplit[l] = strings.TrimSpace(maskSplit[l])
masks[l], err = strconv.Atoi(maskSplit[l])
if err != nil {
fmt.Printf("Each element of 'mask' parameter for yolo layer should be an integer: %s\n", err.Error())
}
}
anchorsStr, ok := block["anchors"]
if !ok {
fmt.Printf("No field 'anchors' for YOLO layer")
continue
}
anchorsSplit := strings.Split(anchorsStr, ",")
if len(anchorsSplit) < 1 {
fmt.Printf("Something wrong with yolo layer. Check if it has one item in 'anchors' array atleast")
continue
}
if len(anchorsSplit)%2 != 0 {
fmt.Printf("Number of elemnts in 'anchors' parameter for yolo layer should be divided exactly by 2 (even number)")
continue
}
anchors := make([]int, len(anchorsSplit))
for l := range anchorsSplit {
anchorsSplit[l] = strings.TrimSpace(anchorsSplit[l])
anchors[l], err = strconv.Atoi(anchorsSplit[l])
if err != nil {
fmt.Printf("Each element of 'anchors' parameter for yolo layer should be an integer: %s\n", err.Error())
}
}
anchorsPairs := [][2]int{}
for a := 0; a < len(anchors); a += 2 {
anchorsPairs = append(anchorsPairs, [2]int{anchors[a], anchors[a+1]})
}
selectedAnchors := [][2]int{}
for m := range masks {
selectedAnchors = append(selectedAnchors, anchorsPairs[masks[m]])
}
flatten := []int{}
for a := range selectedAnchors {
flatten = append(flatten, selectedAnchors[a][0])
flatten = append(flatten, selectedAnchors[a][1])
}
ignoreThreshStr, ok := block["ignore_thresh"]
if !ok {
fmt.Printf("Warning: no field 'ignore_thresh' for YOLO layer")
}
ignoreThresh64, err := strconv.ParseFloat(ignoreThreshStr, 32)
if !ok {
fmt.Printf("Warning: can't cast 'ignore_thresh' to float32 for YOLO layer")
}
yoloL := yoloLayer{
masks: masks,
anchors: selectedAnchors,
flattenAnchors: flatten,
inputSize: shp[2],
classesNum: classesNumber,
ignoreThresh: float32(ignoreThresh64),
}
var l layerN = &yoloL
yoloBlock, err := l.ToNode(g, input)
if err != nil {
fmt.Printf("\tError preparing YOLO block: %s\n", err.Error())
}
networkNodes = append(networkNodes, yoloBlock)
input = yoloBlock
layers = append(layers, &l)
yoloNodes = append(yoloNodes, yoloBlock)
yoloTrainers = append(yoloTrainers, yoloL.yoloTrainer)
filtersIdx = prevFilters
break
case "maxpool":
sizeStr, ok := block["size"]
if !ok {
fmt.Printf("No field 'size' for maxpooling layer")
continue
}
size, err := strconv.Atoi(sizeStr)
if err != nil {
fmt.Printf("'size' parameter for maxpooling layer should be an integer: %s\n", err.Error())
continue
}
strideStr, ok := block["stride"]
if !ok {
fmt.Printf("No field 'stride' for maxpooling layer")
continue
}
stride, err := strconv.Atoi(strideStr)
if err != nil {
fmt.Printf("'size' parameter for maxpooling layer should be an integer: %s\n", err.Error())
continue
}
var l layerN = &maxPoolingLayer{
size: size,
stride: stride,
}
maxpoolingBlock, err := l.ToNode(g, input)
if err != nil {
fmt.Printf("\tError preparing Max-Pooling block: %s\n", err.Error())
}
networkNodes = append(networkNodes, maxpoolingBlock)
input = maxpoolingBlock
layers = append(layers, &l)
filtersIdx = prevFilters
break
case "shortcut":
fromStr, ok := block["from"]
if !ok {
fmt.Printf("No field 'from' for route layer")
continue
}
from, err := strconv.Atoi(fromStr)
if err != nil {
fmt.Printf("Field 'from' should be of type int (value='%s')\n", fromStr)
continue
}
l := shortcutLayer{
layerFromIdx: i + from,
layerToIdx: i - 1,
}
var ll layerN = &l
shortcutBlock, err := l.ToNode(g, networkNodes[i-1], networkNodes[i+from])
if err != nil {
fmt.Printf("\tError preparing Shortcut block: %s\n", err.Error())
}
networkNodes = append(networkNodes, shortcutBlock)
input = shortcutBlock
layers = append(layers, &ll)
filtersIdx = prevFilters
default:
fmt.Printf("Impossible layer: '%s'\n", layerType)
break
}
}
prevFilters = filtersIdx
outputFilters = append(outputFilters, filtersIdx)
}
// Pretty print
linfo := []string{}
for i := range layers {
linfo = append(linfo, fmt.Sprintf("%v", *layers[i]))
}
model := &YOLOv3{
classesNum: classesNumber,
boxesPerCell: boxesPerCell,
netSize: netWidth,
out: yoloNodes,
layersInfo: linfo,
LearningNodes: learningNodes,
training: yoloTrainers,
}
return model, nil
}
// ActivateTrainingMode Activates training mode for unexported yoloOP
func (net *YOLOv3) ActivateTrainingMode() error {
if len(net.training) == 0 {
return fmt.Errorf("Model doesn't contain any YOLO layer to activate training mode")
}
for i := range net.training {
net.training[i].ActivateTrainingMode()
}
return nil
}
// DisableTrainingMode Disables training mode for unexported yoloOP
func (net *YOLOv3) DisableTrainingMode() error {
if len(net.training) == 0 {
return fmt.Errorf("Model doesn't contain any YOLO layer to disable training mode")
}
for i := range net.training {
net.training[i].DisableTrainingMode()
}
return nil
}
// SetTarget Set desired target for net's output (for training mode)
func (net *YOLOv3) SetTarget(target []float32) error {
if len(net.training) == 0 {
return fmt.Errorf("Model has not any YOLO layers")
}
for i := range net.training {
net.training[i].SetTarget(target)
}
return nil
}