| 64 | |
| 65 | |
| 66 | class ResNet(nn.Module): |
| 67 | def __init__(self, block, num_blocks, num_classes=10): |
| 68 | super(ResNet, self).__init__() |
| 69 | self.in_planes = 64 |
| 70 | |
| 71 | self.conv1 = conv3x3(3,64) |
| 72 | self.bn1 = nn.BatchNorm2d(64) |
| 73 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) |
| 74 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) |
| 75 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) |
| 76 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) |
| 77 | self.linear = nn.Linear(512*block.expansion, num_classes) |
| 78 | |
| 79 | def _make_layer(self, block, planes, num_blocks, stride): |
| 80 | strides = [stride] + [1]*(num_blocks-1) |
| 81 | layers = [] |
| 82 | for stride in strides: |
| 83 | layers.append(block(self.in_planes, planes, stride)) |
| 84 | self.in_planes = planes * block.expansion |
| 85 | return nn.Sequential(*layers) |
| 86 | |
| 87 | def forward(self, x): |
| 88 | out = F.relu(self.bn1(self.conv1(x))) |
| 89 | out = self.layer1(out) |
| 90 | out = self.layer2(out) |
| 91 | out = self.layer3(out) |
| 92 | out = self.layer4(out) |
| 93 | out = F.avg_pool2d(out, 4) |
| 94 | out = out.view(out.size(0), -1) |
| 95 | out = self.linear(out) |
| 96 | return out |
| 97 | |
| 98 | |
| 99 | def ResNet18(num_classes=10): |