ishwarraja commited on
Commit
32f6f96
·
1 Parent(s): 7243f66

Create resnet.py

Browse files
Files changed (1) hide show
  1. resnet.py +75 -0
resnet.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ResNet in PyTorch.
3
+ For Pre-activation ResNet, see 'preact_resnet.py'.
4
+ Reference:
5
+ [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
6
+ Deep Residual Learning for Image Recognition. arXiv:1512.03385
7
+ """
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+
12
+ class BasicBlock(nn.Module):
13
+ expansion = 1
14
+
15
+ def __init__(self, in_planes, planes, stride=1):
16
+ super(BasicBlock, self).__init__()
17
+ self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
20
+ self.bn2 = nn.BatchNorm2d(planes)
21
+
22
+ self.shortcut = nn.Sequential()
23
+ if stride != 1 or in_planes != self.expansion*planes:
24
+ self.shortcut = nn.Sequential(
25
+ nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),
26
+ nn.BatchNorm2d(self.expansion*planes)
27
+ )
28
+
29
+ def forward(self, x):
30
+ out = F.relu(self.bn1(self.conv1(x)))
31
+ out = self.bn2(self.conv2(out))
32
+ out += self.shortcut(x)
33
+ out = F.relu(out)
34
+ return out
35
+
36
+
37
+ class ResNet(nn.Module):
38
+ def __init__(self, block, num_blocks, num_classes=10):
39
+ super(ResNet, self).__init__()
40
+ self.in_planes = 64
41
+
42
+ self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
43
+ self.bn1 = nn.BatchNorm2d(64)
44
+ self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
45
+ self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
46
+ self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
47
+ self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
48
+ self.linear = nn.Linear(512*block.expansion, num_classes)
49
+
50
+ def _make_layer(self, block, planes, num_blocks, stride):
51
+ strides = [stride] + [1]*(num_blocks-1)
52
+ layers = []
53
+ for stride in strides:
54
+ layers.append(block(self.in_planes, planes, stride))
55
+ self.in_planes = planes * block.expansion
56
+ return nn.Sequential(*layers)
57
+
58
+ def forward(self, x):
59
+ out = F.relu(self.bn1(self.conv1(x)))
60
+ out = self.layer1(out)
61
+ out = self.layer2(out)
62
+ out = self.layer3(out)
63
+ out = self.layer4(out)
64
+ out = F.avg_pool2d(out, 4)
65
+ out = out.view(out.size(0), -1)
66
+ out = self.linear(out)
67
+ return out
68
+
69
+
70
+ def ResNet18():
71
+ return ResNet(BasicBlock, [2, 2, 2, 2])
72
+
73
+
74
+ def ResNet34():
75
+ return ResNet(BasicBlock, [3, 4, 6, 3])