JayPatwardhan / ResNet-PyTorch

Basic implementation of ResNet 50, 101, 152 in PyTorch
95 stars 28 forks source link

ResNet18 #3

Open HansaemIanOh opened 5 months ago

HansaemIanOh commented 5 months ago
class ResNet(nn.Module):
    def __init__(self, ResBlock, layer_list, num_classes, num_channels=3, stride=2): #<- fixed
        super(ResNet, self).__init__()
        self.in_channels = 64
        self.stride = stride #<- fixed

        self.conv1 = nn.Conv2d(num_channels, 64, kernel_size=7, stride=2, padding=3, bias=False)
        self.batch_norm1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU()
        self.max_pool = nn.MaxPool2d(kernel_size = 3, stride=2, padding=1)

        self.layer1 = self._make_layer(ResBlock, layer_list[0], planes=64)
        self.layer2 = self._make_layer(ResBlock, layer_list[1], planes=128, stride=self.stride) #<- fixed
        self.layer3 = self._make_layer(ResBlock, layer_list[2], planes=256, stride=self.stride) #<- fixed
        self.layer4 = self._make_layer(ResBlock, layer_list[3], planes=512, stride=self.stride) #<- fixed

        self.avgpool = nn.AdaptiveAvgPool2d((1,1))
        self.fc = nn.Linear(512*ResBlock.expansion, num_classes)

    def forward(self, x):
        x = self.relu(self.batch_norm1(self.conv1(x)))
        x = self.max_pool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = x.reshape(x.shape[0], -1)
        x = self.fc(x)

        return x

    def _make_layer(self, ResBlock, blocks, planes, stride=1):
        ii_downsample = None
        layers = []

        if stride != 1 or self.in_channels != planes*ResBlock.expansion:
            ii_downsample = nn.Sequential(
                nn.Conv2d(self.in_channels, planes*ResBlock.expansion, kernel_size=1, stride=stride),
                nn.BatchNorm2d(planes*ResBlock.expansion)
            )
        layers.append(ResBlock(self.in_channels, planes, i_downsample=ii_downsample, stride=stride))
        self.in_channels = planes*ResBlock.expansion

        for i in range(blocks-1):
            layers.append(ResBlock(self.in_channels, planes))

        return nn.Sequential(*layers)

def ResNet18(num_classes, channels=3):
    return ResNet(Block, [2,2,2,2], num_classes, channels, stride=1)

If you fix the code like that, it would work.

Nikhil-Rao20 commented 2 months ago

Thanks for your contribution