resnet.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from torch import nn
  2. from torchvision.models.resnet import ResNet, Bottleneck
  3. class ResNetEncoder(ResNet):
  4. """
  5. ResNetEncoder inherits from torchvision's official ResNet. It is modified to
  6. use dilation on the last block to maintain output stride 16, and deleted the
  7. global average pooling layer and the fully connected layer that was originally
  8. used for classification. The forward method additionally returns the feature
  9. maps at all resolutions for decoder's use.
  10. """
  11. layers = {
  12. 'resnet50': [3, 4, 6, 3],
  13. 'resnet101': [3, 4, 23, 3],
  14. }
  15. def __init__(self, in_channels, variant='resnet101', norm_layer=None):
  16. super().__init__(
  17. block=Bottleneck,
  18. layers=self.layers[variant],
  19. replace_stride_with_dilation=[False, False, True],
  20. norm_layer=norm_layer)
  21. # Replace first conv layer if in_channels doesn't match.
  22. if in_channels != 3:
  23. self.conv1 = nn.Conv2d(in_channels, 64, 7, 2, 3, bias=False)
  24. # Delete fully-connected layer
  25. del self.avgpool
  26. del self.fc
  27. def forward(self, x):
  28. x0 = x # 1/1
  29. x = self.conv1(x)
  30. x = self.bn1(x)
  31. x = self.relu(x)
  32. x1 = x # 1/2
  33. x = self.maxpool(x)
  34. x = self.layer1(x)
  35. x2 = x # 1/4
  36. x = self.layer2(x)
  37. x3 = x # 1/8
  38. x = self.layer3(x)
  39. x = self.layer4(x)
  40. x4 = x # 1/16
  41. return x4, x3, x2, x1, x0