resnet.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/python
  2. # -*- encoding: utf-8 -*-
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. import torch.utils.model_zoo as modelzoo
  7. # from modules.bn import InPlaceABNSync as BatchNorm2d
  8. resnet18_url = 'https://download.pytorch.org/models/resnet18-5c106cde.pth'
  9. def conv3x3(in_planes, out_planes, stride=1):
  10. """3x3 convolution with padding"""
  11. return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
  12. padding=1, bias=False)
  13. class BasicBlock(nn.Module):
  14. def __init__(self, in_chan, out_chan, stride=1):
  15. super(BasicBlock, self).__init__()
  16. self.conv1 = conv3x3(in_chan, out_chan, stride)
  17. self.bn1 = nn.BatchNorm2d(out_chan)
  18. self.conv2 = conv3x3(out_chan, out_chan)
  19. self.bn2 = nn.BatchNorm2d(out_chan)
  20. self.relu = nn.ReLU(inplace=True)
  21. self.downsample = None
  22. if in_chan != out_chan or stride != 1:
  23. self.downsample = nn.Sequential(
  24. nn.Conv2d(in_chan, out_chan,
  25. kernel_size=1, stride=stride, bias=False),
  26. nn.BatchNorm2d(out_chan),
  27. )
  28. def forward(self, x):
  29. residual = self.conv1(x)
  30. residual = F.relu(self.bn1(residual))
  31. residual = self.conv2(residual)
  32. residual = self.bn2(residual)
  33. shortcut = x
  34. if self.downsample is not None:
  35. shortcut = self.downsample(x)
  36. out = shortcut + residual
  37. out = self.relu(out)
  38. return out
  39. def create_layer_basic(in_chan, out_chan, bnum, stride=1):
  40. layers = [BasicBlock(in_chan, out_chan, stride=stride)]
  41. for i in range(bnum-1):
  42. layers.append(BasicBlock(out_chan, out_chan, stride=1))
  43. return nn.Sequential(*layers)
  44. class Resnet18(nn.Module):
  45. def __init__(self):
  46. super(Resnet18, self).__init__()
  47. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
  48. bias=False)
  49. self.bn1 = nn.BatchNorm2d(64)
  50. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  51. self.layer1 = create_layer_basic(64, 64, bnum=2, stride=1)
  52. self.layer2 = create_layer_basic(64, 128, bnum=2, stride=2)
  53. self.layer3 = create_layer_basic(128, 256, bnum=2, stride=2)
  54. self.layer4 = create_layer_basic(256, 512, bnum=2, stride=2)
  55. self.init_weight()
  56. def forward(self, x):
  57. x = self.conv1(x)
  58. x = F.relu(self.bn1(x))
  59. x = self.maxpool(x)
  60. x = self.layer1(x)
  61. feat8 = self.layer2(x) # 1/8
  62. feat16 = self.layer3(feat8) # 1/16
  63. feat32 = self.layer4(feat16) # 1/32
  64. return feat8, feat16, feat32
  65. def init_weight(self):
  66. state_dict = modelzoo.load_url(resnet18_url)
  67. self_state_dict = self.state_dict()
  68. for k, v in state_dict.items():
  69. if 'fc' in k: continue
  70. self_state_dict.update({k: v})
  71. self.load_state_dict(self_state_dict)
  72. def get_params(self):
  73. wd_params, nowd_params = [], []
  74. for name, module in self.named_modules():
  75. if isinstance(module, (nn.Linear, nn.Conv2d)):
  76. wd_params.append(module.weight)
  77. if not module.bias is None:
  78. nowd_params.append(module.bias)
  79. elif isinstance(module, nn.BatchNorm2d):
  80. nowd_params += list(module.parameters())
  81. return wd_params, nowd_params
  82. if __name__ == "__main__":
  83. net = Resnet18()
  84. x = torch.randn(16, 3, 224, 224)
  85. out = net(x)
  86. print(out[0].size())
  87. print(out[1].size())
  88. print(out[2].size())
  89. net.get_params()