| 92 | |
| 93 | |
| 94 | class ResNet(nn.Module): |
| 95 | |
| 96 | def __init__(self, block, layers, num_classes=1000): |
| 97 | self.inplanes = 64 |
| 98 | super(ResNet, self).__init__() |
| 99 | self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, |
| 100 | bias=False) |
| 101 | self.bn1 = NN.BatchNorm2d(64) #NN.BatchNorm2d |
| 102 | self.relu = nn.ReLU(inplace=True) |
| 103 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) |
| 104 | self.layer1 = self._make_layer(block, 64, layers[0]) |
| 105 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2) |
| 106 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2) |
| 107 | self.layer4 = self._make_layer(block, 512, layers[3], stride=2) |
| 108 | #self.avgpool = nn.AvgPool2d(7, stride=1) |
| 109 | #self.fc = nn.Linear(512 * block.expansion, num_classes) |
| 110 | |
| 111 | for m in self.modules(): |
| 112 | if isinstance(m, nn.Conv2d): |
| 113 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') |
| 114 | elif isinstance(m, nn.BatchNorm2d): |
| 115 | nn.init.constant_(m.weight, 1) |
| 116 | nn.init.constant_(m.bias, 0) |
| 117 | |
| 118 | def _make_layer(self, block, planes, blocks, stride=1): |
| 119 | downsample = None |
| 120 | if stride != 1 or self.inplanes != planes * block.expansion: |
| 121 | downsample = nn.Sequential( |
| 122 | nn.Conv2d(self.inplanes, planes * block.expansion, |
| 123 | kernel_size=1, stride=stride, bias=False), |
| 124 | NN.BatchNorm2d(planes * block.expansion), #NN.BatchNorm2d |
| 125 | ) |
| 126 | |
| 127 | layers = [] |
| 128 | layers.append(block(self.inplanes, planes, stride, downsample)) |
| 129 | self.inplanes = planes * block.expansion |
| 130 | for i in range(1, blocks): |
| 131 | layers.append(block(self.inplanes, planes)) |
| 132 | |
| 133 | return nn.Sequential(*layers) |
| 134 | |
| 135 | def forward(self, x): |
| 136 | features = [] |
| 137 | |
| 138 | x = self.conv1(x) |
| 139 | x = self.bn1(x) |
| 140 | x = self.relu(x) |
| 141 | x = self.maxpool(x) |
| 142 | |
| 143 | x = self.layer1(x) |
| 144 | features.append(x) |
| 145 | x = self.layer2(x) |
| 146 | features.append(x) |
| 147 | x = self.layer3(x) |
| 148 | features.append(x) |
| 149 | x = self.layer4(x) |
| 150 | features.append(x) |
| 151 | |