| 63 | |
| 64 | |
| 65 | class ResNet(nn.Module): |
| 66 | def __init__(self, block, num_blocks, in_dims, out_dims, wide=1): |
| 67 | super(ResNet, self).__init__() |
| 68 | self.wide = wide |
| 69 | self.in_planes = 64 |
| 70 | self.conv1 = nn.Conv2d(in_dims, 64, kernel_size=3, stride=1, padding=1, bias=False) |
| 71 | self.bn1 = nn.BatchNorm2d(64) |
| 72 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) |
| 73 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) |
| 74 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) |
| 75 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) |
| 76 | self.avgpool = nn.AdaptiveAvgPool2d((1,1)) |
| 77 | self.linear = nn.Linear(512*block.expansion, out_dims) |
| 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, self.wide)) |
| 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 = self.avgpool(out) |
| 94 | out = torch.flatten(out, 1) |
| 95 | out = self.linear(out) |
| 96 | return out |
| 97 | |
| 98 | def feature_extract(self, x): |
| 99 | out = F.relu(self.bn1(self.conv1(x))) |
| 100 | out = self.layer1(out) |
| 101 | out = self.layer2(out) |
| 102 | out = self.layer3(out) |
| 103 | out = self.layer4(out) |
| 104 | out = self.avgpool(out) |
| 105 | out = torch.flatten(out, 1) |
| 106 | return out |
| 107 | |
| 108 | |
| 109 | class WRN(nn.Module): |