什么是nn.seqential?
nn.Sequential是一个有序的容器,神经网络模块将按照在传入构造器的顺序依次被添加到计算图中执行,同时以神经网络模块为元素的有序字典也可以作为传入参数。
查看sequential的官方文档,有如下示例:
以下面CIFAR10 mode structure为例,写一个简单的神经网络分类模型:
"""
以cifar10 model structure为例
"""
import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.tensorboard import SummaryWriter
class Tudui(nn.Module):
def __init__(self):
super(Tudui,self).__init__()
#创建一个卷积层
self.conv1=Conv2d(in_channels=3,out_channels=32,kernel_size=5,padding=2)
#最大池化层
"""
1、从图中可知,池化层的输入是32*32,输出是16*16,说明步长为2,说明每两个格输入变成一个输出,不存在ceil_mode问题
2、这里步长,使用默认值,stride=kernel_size
"""
self.maxpool1=MaxPool2d(kernel_size=2)
self.conv2=Conv2d(in_channels=32,out_channels=32,kernel_size=5,padding=2)
self.maxpool2=MaxPool2d(kernel_size=2)
self.conv3=Conv2d(in_channels=32,out_channels=64,kernel_size=5,padding=2)
self.maxpool3=MaxPool2d(kernel_size=2)
self.flatten=Flatten() #变成一列为 64*4*4=1024个数据
self.linear1=Linear(in_features=1024,out_features=64)
self.linear2=Linear(in_features=64,out_features=10) #最后是10,就是CIFAR10数据集经过这个网络预测到的类别为10
)
def forward(self,x):
x=self.conv1(x)
x=self.maxpool1(x)
x=self.conv2(x)
x=self.maxpool2(x)
x=self.conv3(x)
x=self.maxpool3(x)
x=self.linear1(x)
x=self.linear2(x)
return x
tudui=Tudui()
print(tudui)
#如何验证上面创建的网络正确性
input=torch.ones((64,3,32,32))
output=tudui(input)
print(output.shape) #torch.Size([64, 10])
writer=SummaryWriter("./logs_sequential")
writer.add_graph(tudui,input)
writer.close()
【插曲】 如何计算padding?
使用上面公式计算。
使用Sequential去简化上面代码,如下:
"""
以cifar10 model structure为例
"""
import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.tensorboard import SummaryWriter
class Tudui(nn.Module):
def __init__(self):
super(Tudui,self).__init__()
self.model1=Sequential(
Conv2d(in_channels=3,out_channels=32,kernel_size=5,padding=2),
MaxPool2d(kernel_size=2),
Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
MaxPool2d(kernel_size=2),
Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
MaxPool2d(kernel_size=2),
Flatten(),
Linear(in_features=1024, out_features=64),
Linear(in_features=64, out_features=10)
)
def forward(self,x):
x=self.model1(x) #简化代码
return x
tudui=Tudui()
print(tudui)
#如何验证上面创建的网络正确性
input=torch.ones((64,3,32,32))
output=tudui(input)
print(output.shape) #torch.Size([64, 10])
writer=SummaryWriter("./logs_sequential")
writer.add_graph(tudui,input)
writer.close()
通过tensorboard --logdir=logs_sequential命令,打开tensorboard本地服务器,看到如下: