TimRoith / BregmanLearning

Optimizing neural networks via an inverse scale space flow.
MIT License
15 stars 5 forks source link

ResNet mean handling #5

Closed TimRoith closed 1 year ago

TimRoith commented 1 year ago

The ResNet class is missing the mean, std option

bellhello commented 1 year ago

I revised the file that defines the model ResNet /model/resnet.py:

class ResNet(nn.Module):
    def __init__(self, block, num_blocks, num_classes=10, mean=0,std=1):
        super(ResNet, self).__init__()
        self.in_planes = 64
        self.mean = mean
        self.std = std

        self.conv1 = nn.Conv2d(3, 64, kernel_size=3,
                               stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
        self.linear = nn.Linear(512*block.expansion, num_classes)

    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return nn.Sequential(*layers)

    def forward(self, x):
        out = (x - self.mean)/self.std
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = F.avg_pool2d(out, 4)
        out = out.view(out.size(0), -1)
        out = self.linear(out)
        return out

def ResNet18(mean,std):
    return ResNet(BasicBlock, [2, 2, 2, 2],10,mean,std)

It works!

TimRoith commented 1 year ago

Thank you very much. I updated the code accordingly 👍🏻