15.1 搭建CIFAR10 model
15.1.1 直观理解
15.1.2 代码实现
from torch import nn, Tensor
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear
class Avlon(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = Conv2d(3, 32, 5, padding=2)
self.maxpool1 = MaxPool2d(2) # kernel_size=2
self.conv2 = Conv2d(32, 32, 5, padding=2)
self.maxpool2 = MaxPool2d(2)
self.conv3 = Conv2d(32, 64, 5, padding=2)
self.maxpool3 = MaxPool2d(2)
self.flatten = Flatten()
self.linear1 = Linear(1024, 64)
self.linear2 = Linear(64, 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.flatten(x)
x = self.linear1(x)
x = self.linear2(x)
return x
avlon = Avlon()
print(avlon)
运行后
神经网络搭建完毕。
# Conv2d 中的 padding 参数根据帮助文档中的公式计算得出
将第15行 Linear() 中 in_features 改成10240,代码照样可以正常运行,故需要用别的方法测试神经网络的正确性。
15.1.3 代码测试
加入以下代码进行测试
input = torch.ones((64, 3, 32, 32))
output = avlon(input)
print(output.shape)
运行后,返回结果 torch.Size([64, 10]) ;
此时将第15行 Linear() 中 in_features 改成10240,再次运行则会报错。
15.2 Sequential的使用
15.2.1 代码修改
import torch
from torch import nn, Tensor
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
class Avlon(nn.Module):
def __init__(self):
super().__init__()
self.model1 = Sequential(
Conv2d(3, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 64, 5, padding=2),
MaxPool2d(2),
Flatten(),
Linear(1024, 64),
Linear(64, 10)
)
def forward(self, x):
x = self.model1(x)
return x
avlon = Avlon()
print(avlon)
input = torch.ones((64, 3, 32, 32))
output = avlon(input)
print(output.shape)
运行后
15.2.2 使用TensorBoard进行展示
加入以下代码
writer = SummaryWriter("../logs_seq")
writer.add_graph(avlon, input) # 生成模型结构图
writer.close()
通过双击进行查看