-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdetector.py
84 lines (65 loc) · 2.49 KB
/
detector.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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: liuyaqi
"""
import torch
import torch.nn as nn
import math
affine_par = True
class Detector(nn.Module):
def __init__(self,pool_stride):
super(Detector, self).__init__()
'The pooling of images needs to be researched.'
self.img_pool = nn.AvgPool2d(pool_stride,stride=pool_stride)
self.input_dim = 3
'Feature extraction blocks.'
self.conv = nn.Sequential(
nn.Conv2d(self.input_dim, 16, 3, 1, 1),
nn.BatchNorm2d(16,affine = affine_par),
nn.ReLU(inplace=True),
nn.Conv2d(16, 32, 3, 1, 1),
nn.BatchNorm2d(32,affine = affine_par),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
nn.Conv2d(32, 64, 3, 1, 1),
nn.BatchNorm2d(64,affine = affine_par),
nn.ReLU(inplace=True),
nn.Conv2d(64, 128, 3, 1, 1),
nn.BatchNorm2d(128,affine = affine_par),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
)
'Detection branch.'
self.classifier_det = nn.Sequential(
nn.Linear(128*8*8,1024),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(1024,2),
)
self._initialize_weights()
def forward(self,x1,x2,m1,m2):
x1 = self.img_pool(x1)
x2 = self.img_pool(x2)
x1 = torch.mul(x1,m1)
x2 = torch.mul(x2,m2)
x1 = self.conv(x1)
x2 = self.conv(x2)
x1 = x1.view(x1.size(0),-1)
x2 = x2.view(x2.size(0),-1)
x12_abs = torch.abs(x1-x2)
x_det = self.classifier_det(x12_abs)
return x_det
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()