import torch
import torch.nn as nn
# 定义一个Residual模块
class Residual(nn.Module):
def __init__(self,in_channels,out_channels,stride=1):
super(Residual, self).__init__()
self.stride = stride
self.conv1 = nn.Conv2d(in_channels,out_channels,kernel_size=3,stride=stride,padding=1)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_channels,out_channels,kernel_size=3,padding=1)
self.bn2 = nn.BatchNorm2d(out_channels)
# 核心内容,残差块,x卷积后shape发生变化,
if in_channels != out_channels: # 如果输入的通道和输出的通道数不一样,则使用1×1的卷积残差块,也就是shortcut
self.conv1x1 = nn.Conv2d(in_channels,out_channels,kernel_size=1,stride=stride)
self.bn = nn.BatchNorm2d(out_channels)
else:
self.conv1x1 = None
def forward(self,x):
o1 = self.relu(self.bn1(self.conv1(x)))
o2 = self.bn2(self.conv2(o1))
if self.conv1x1:
x = self.bn(self.conv1x1(x))
out = self.relu(o2 + x)
return out
# 自己定义一个resnet18网络
class ResNet18(nn.Module):
def __init__(self,in_channels,num_classes):
super(ResNet18, self).__init__()
self.layer0 = nn.Sequential(
nn.Conv2d(in_channels,64,kernel_size=7,stride=2,padding=3,bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3,stride=2,padding=1)
)
self.layer1 = nn.Sequential(
Residual(64,64),
Residual(64,64)
)
self.layer2 = nn.Sequential(
Residual(64,128,stride=2),
Residual(128,128)
)
self.layer3 = nn.Sequential(
Residual(128,256,stride=2),
Residual(256,256)
)
self.layer4 = nn.Sequential(
Residual(256,512,stride=2),
Residual(512,512)
)
self.avgpool = nn.AdaptiveAvgPool2d(output_size=(1,1))
self.fc = nn.Linear(512,1000)
self.classifier = nn.Sequential(
nn.Linear(1000,64),
nn.ReLU(True),
nn.Dropout(p=0.5,inplace=False),
nn.Linear(64,num_classes)
)
def forward(self,x):
out0 = self.layer0(x)
out1 = self.layer1(out0)
out2 = self.layer2(out1)
out3 = self.layer3(out2)
out4 = self.layer4(out3)
out = self.avgpool(out4)
out = out.view((x.shape[0],-1))
out = self.fc(out)
out = self.classifier(out)
return out
resnet18 = ResNet18(3,10)
print(resnet18)
自己实现resnet18网络结构
最新推荐文章于 2024-07-14 13:36:04 发布