__all__ = ["ResNet45"] def conv1x1(in_planes, out_planes, stride=1): return nn.Conv2D( in_planes, out_planes, kernel_size=1, stride=1, weight_attr=ParamAttr(initializer=KaimingNormal()), bias_attr=Fals
时间: 2024-04-03 20:36:40 浏览: 136
e() def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): return nn.Conv2D( in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, dilation=dilation, weight_attr=ParamAttr(initializer=KaimingNormal()), bias_attr=False) class BasicBlock(nn.Layer): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2D(planes) self.relu = nn.ReLU() self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2D(planes) self.downsample = downsample self.stride = stride def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out class ResNet45(nn.Layer): def __init__(self, block=BasicBlock, layers=[2, 2, 2, 2], num_classes=1000): super(ResNet45, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2D( 3, 64, kernel_size=7, stride=2, padding=3, weight_attr=ParamAttr(initializer=KaimingNormal()), bias_attr=False) self.bn1 = nn.BatchNorm2D(64) self.relu = nn.ReLU() self.maxpool = nn.MaxPool2D(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AdaptiveAvgPool2D((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2D( self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, weight_attr=ParamAttr(initializer=KaimingNormal()), bias_attr=False), nn.BatchNorm2D(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = paddle.flatten(x, 1) x = self.fc(x) return x
这是一个 ResNet45 的实现,是一个卷积神经网络用于图像分类。其中包含了 BasicBlock 和 ResNet45 两个类,ResNet45 是整个网络的主体部分,由多个 BasicBlock 组成。BasicBlock 由两个卷积层和一个残差连接组成。网络的输入是一张 3 通道的图片,输出是对应的分类结果。
阅读全文