| 73 | |
| 74 | |
| 75 | class ResNet(nn.Module): |
| 76 | def __init__(self, block, num_blocks, num_classes=10): |
| 77 | super(ResNet, self).__init__() |
| 78 | self.in_planes = 64 |
| 79 | |
| 80 | self.conv1 = nn.Conv2d(3, self.in_planes, kernel_size=3, |
| 81 | stride=1, padding=1, bias=False) |
| 82 | self.bn1 = nn.BatchNorm2d(self.in_planes) |
| 83 | self.layer1 = self._make_layer(block, self.in_planes, num_blocks[0], stride=1) |
| 84 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) |
| 85 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) |
| 86 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) |
| 87 | self.linear = nn.Linear(512*block.expansion, num_classes) |
| 88 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) |
| 89 | self.relu = nn.ReLU(inplace=False) |
| 90 | |
| 91 | def _make_layer(self, block, planes, num_blocks, stride): |
| 92 | strides = [stride] + [1]*(num_blocks-1) |
| 93 | layers = [] |
| 94 | for stride in strides: |
| 95 | layers.append(block(self.in_planes, planes, stride)) |
| 96 | self.in_planes = planes * block.expansion |
| 97 | return nn.Sequential(*layers) |
| 98 | |
| 99 | def forward(self, x): |
| 100 | out = self.relu(self.bn1(self.conv1(x))) |
| 101 | out = self.layer1(out) |
| 102 | out = self.layer2(out) |
| 103 | out = self.layer3(out) |
| 104 | out = self.layer4(out) |
| 105 | out = self.avgpool(out) |
| 106 | out = out.view(out.size(0), -1) |
| 107 | out = self.linear(out) |
| 108 | return out |
| 109 | |
| 110 | |
| 111 | def ResNet18(num_classes: int = 10): |