MCPcopy Create free account
hub / github.com/Sirwenhao/Deep-Learning-Notes / ResNet

Class ResNet

CV/Pytorch_classification/ResNet/model.py:85–156  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

83 return out
84
85class ResNet(nn.Module):
86 def __init__(self,
87 block,
88 blocks_num,
89 num_classes=1000,
90 include_top=True,
91 groups=1,
92 width_per_group=64):
93 super(ResNet, self).__init__()
94 self.include_top = include_top
95 self.in_channel = 64
96
97 self.groups = groups
98 self.width_per_group = width_per_group
99
100 self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=7, stride=2,
101 padding=3, bias=False)
102 self.bn1 = nn.BatchNorm2d(self.in_channel)
103 self.relu = nn.ReLU(inplace=True)
104 self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
105 self.layer1 = self._make_layer(block, 64, blocks_num[0])
106 self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
107 self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
108 self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
109 if self.include_top:
110 self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
111 self.fc = nn.Linear(512 * block.expansion, num_classes)
112
113 for m in self.modules():
114 if isinstance(m, nn.Conv2d):
115 nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') # pytorch新版本已经更新nn.init.kaiming_nomal为nn.kaiming_normal_
116
117 def _make_layer(self, block, channel, block_num, stride=1):
118 downsample = None
119 if stride != 1 or self.in_channel != channel * block.expansion:
120 downsample = nn.Sequential(
121 nn.Conv2d(self.in_channel, channel*block.expansion, kernel_size=1, stride=stride, bias=False),
122 nn.BatchNorm2d(channel * block.expansion))
123 layers = []
124 layers.append(block(self.in_channel,
125 channel,
126 downsample = downsample,
127 stride = stride,
128 groups = self.groups,
129 width_per_group = self.width_per_group))
130 self.in_channel = channel * block.expansion
131
132 for _ in range(1, block_num):
133 layers.append(block(self.in_channel,
134 channel,
135 groups=self.groups,
136 width_per_group=self.width_per_group))
137
138 return nn.Sequential(*layers)
139
140 def forward(self, x):
141 x = self.conv1(x)
142 x = self.bn1(x)

Callers 5

resnet34Function · 0.85
resnet50Function · 0.85
resnet101Function · 0.85
resnext50_32x4dFunction · 0.85
resnext101_32x8dFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected