resnet python代码
时间: 2024-05-31 09:06:07 浏览: 120
ResNet是一种深度神经网络架构,主要解决深度网络训练过程中梯度消失的问题。它的核心是残差学习,通过跨层连接将输入直接传递到输出,避免了梯度在深层网络中消失的问题。
以下是ResNet的Python代码实现示例:
```python
import torch.nn as nn
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels)
)
def forward(self, x):
out = nn.functional.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
out += self.shortcut(x)
out = nn.functional.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=10):
super(ResNet, self).__init__()
self.in_channels = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self.make_layer(block, 64, layers, stride=1)
self.layer2 = self.make_layer(block, 128, layers, stride=2)
self.layer3 = self.make_layer(block, 256, layers, stride=2)
self.layer4 = self.make_layer(block, 512, layers, stride=2)
self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512, num_classes)
def make_layer(self, block, out_channels, blocks, stride):
layers = []
layers.append(block(self.in_channels, out_channels, stride))
self.in_channels = out_channels
for i in range(blocks-1):
layers.append(block(out_channels, out_channels))
return nn.Sequential(*layers)
def forward(self, x):
out = nn.functional.relu(self.bn1(self.conv1(x)))
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = self.avg_pool(out)
out = out.view(out.size(0), -1)
out = self.fc(out)
return out
def ResNet18(num_classes=10):
return ResNet(ResidualBlock, [2, 2, 2, 2], num_classes=num_classes)
def ResNet34(num_classes=10):
return ResNet(ResidualBlock, [3, 4, 6, 3], num_classes=num_classes)
def ResNet50(num_classes=10):
return ResNet(BottleneckBlock, [3, 4, 6, 3], num_classes=num_classes)
def ResNet101(num_classes=10):
return ResNet(BottleneckBlock, [3, 4, 23, 3], num_classes=num_classes)
def ResNet152(num_classes=10):
return ResNet(BottleneckBlock, [3, 8, 36, 3], num_classes=num_classes)
```
以上代码实现了ResNet的基本结构,并提供了ResNet18、ResNet34、ResNet50、ResNet101、ResNet152等不同深度的模型供选择。通过调用不同的函数即可构建不同深度的ResNet模型。
阅读全文