1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| import torch import torch.nn as nn
class ResidualBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride =4, padding = 1, bias=False): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(out_channels) if in_channels != out_channels: self.shortcut = nn.Sequential( nn.Conv2d(in_channels,out_channels, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(out_channels), ) else: self.shortcut = nn.Identity() def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out += self.shortcut(residual) out = self.relu(out) return out
class SimpleResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(SimpleResNet, self).__init__()
self.in_channels = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self.make_layer(block, 64, num_blocks[0], strife=1) self.avgpool = nn.AvgPool2d(kernel_size=4) self.fc= nn.Linear(512, num_classes) def make_layer(self, block, out_channels, num_blacks, stride): strides = [stride] + [1] * (num_blacks -1) layers =[] for stride in strides: layers.append(block(self.in_channels, out_channels, stride)) self.in_channels = out_channels return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.layer1(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x model = SimpleResNet(ResidualBlock, [2, 2,2,2])
|