MCPcopy Create free account
hub / github.com/AtlasAnalyticsLab/AdaFisher / ResNet

Class ResNet

Image_Classification/src/models/resnet.py:138–235  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

136
137
138class ResNet(nn.Module):
139
140 def __init__(self, block, layers, num_classes=200, zero_init_residual=False,
141 groups=1, width_per_group=64, replace_stride_with_dilation=None,
142 norm_layer=None):
143 super(ResNet, self).__init__()
144 if norm_layer is None:
145 norm_layer = nn.BatchNorm2d
146 self._norm_layer = norm_layer
147
148 self.inplanes = 64
149 self.dilation = 1
150 if replace_stride_with_dilation is None:
151 # each element in the tuple indicates if we should replace
152 # the 2x2 stride with a dilated convolution instead
153 replace_stride_with_dilation = [False, False, False]
154 if len(replace_stride_with_dilation) != 3:
155 raise ValueError("replace_stride_with_dilation should be None "
156 "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
157 self.groups = groups
158 self.base_width = width_per_group
159 self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
160 bias=False)
161 self.bn1 = norm_layer(self.inplanes)
162 self.relu = nn.ReLU(inplace=False)
163 self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
164 self.layer1 = self._make_layer(block, 64, layers[0])
165 self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
166 dilate=replace_stride_with_dilation[0])
167 self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
168 dilate=replace_stride_with_dilation[1])
169 self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
170 dilate=replace_stride_with_dilation[2])
171 self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
172 self.fc = nn.Linear(512 * block.expansion, num_classes)
173
174 for m in self.modules():
175 if isinstance(m, nn.Conv2d):
176 nn.init.kaiming_normal_(
177 m.weight, mode='fan_out', nonlinearity='relu')
178 elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
179 nn.init.constant_(m.weight, 1)
180 nn.init.constant_(m.bias, 0)
181
182 # Zero-initialize the last BN in each residual branch,
183 # so that the residual branch starts with zeros, and each residual block behaves like an identity.
184 # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
185 if zero_init_residual:
186 for m in self.modules():
187 if isinstance(m, Bottleneck):
188 nn.init.constant_(m.bn3.weight, 0)
189 elif isinstance(m, BasicBlock):
190 nn.init.constant_(m.bn2.weight, 0)
191
192 def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
193 norm_layer = self._norm_layer
194 downsample = None
195 previous_dilation = self.dilation

Callers 1

_resnetFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected