自定义神经网络
pytorch自定义神经网络的方法是重写nn.Module函数,来自于from torch import nn。下面是具体实践。
class CNN(nn.Module):
def __init__(self,num_classes):
super(CNN, self).__init__() # 3 64 64
self.layer1=nn.Sequential(
torch.nn.Conv2d(
in_channels=3,
out_channels=16,
kernel_size=5,
stride=2,
padding=2
),
# nn.Conv2d(3, 16, 3),
nn.BatchNorm2d(16),
nn.Sigmoid(),
nn.MaxPool2d(kernel_size=2,stride=2) #16 32 32\\
)
self.layer2=nn.Sequential(
torch.nn.Conv2d(
in_channels=16,
out_channels=32,
kernel_size=5,
stride=2,
padding=2
),
# nn.Conv2d(16, 32, 3, 2),
nn.BatchNorm2d(32),
nn.Sigmoid(),
nn.MaxPool2d(kernel_size=2,stride=2) #32 16 16
)
# self.layer3=nn.Sequential(
# nn.Conv2d(
# in_channels=32,
# out_channels=32,
# kernel_size=3,
# stride=2,
# padding=2
# ),
# # nn.Conv2d(32,32,3,2),
# nn.BatchNorm2d(32),
# nn.Sigmoid(),
# nn.MaxPool2d(kernel_size=2,stride=2) #32 8 8
# )
self.fc1=nn.Sequential(
nn.Linear(32*14*14,120),
nn.Sigmoid()
)
self.fc2=nn.Sequential(
nn.Linear(120,84),
nn.Sigmoid(),
nn.Linear(84,num_classes)
)
# 前向传播
def forward(self,x):
# print('1 output shape:\t', x.shape)
x=self.layer1(x)
# print('2 output shape:\t', x.shape)
x=self.layer2(x)
# print('3 output shape:\t', x.shape)
# x=self.layer3(x)
# print('4 output shape:\t', x.shape)
x=x.view(x.size(0),-1)
# print('5 output shape:\t', x.shape)
x=self.fc1(x)
# print('6 output shape:\t', x.shape)
x=self.fc2(x)
# print('7 output shape:\t', x.shape)
return
#实例化模型
models = CNN(config.num_classes)
需要注意前向传播的输入输出通道需要一致
卷积神神经网络通道变化的计算方法: