目标搭建模型:
设置卷积层等的参数时,除了in_channels、out_channels、kernel_size等,还需要设置padding等参数,可以根据官方给出的公式计算需要的参数是多少
带入已知数据,其中dilation没说空洞卷积,要用她的默认值1
里面只有padding和stride是未知数,求解方程,得padding=2, stride=1
from torch import nn
class Test(nn.Module):
def __init__(self):
super(Test,self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2)
self.maxpool1 = nn.MaxPool2d(kernel_size=2)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2) # 计算同上
self.maxpool2 = nn.MaxPool2d(kernel_size=2)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2)
self.maxpool3 = nn.MaxPool2d(kernel_size=2)
self.flatten = nn.Flatten()
# 64@4*4 到 64那里其实省略了步骤
# 上一步是64*4*4, 这一步就是将其展开成一行,就是1024
# 之后1024再到64 这就是一个线性层
self.linear1 = nn.Linear(1024, 64)
# 64到10 这也是一个线性层
self.linear2 = nn.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
# 这样网络就写完了
net = Test()
print(net)
这就可以看到网路的结构:
关注数据经过网络后是否是想要的输出
torch提供了一些创建数据的方法 可以进行测试
net = Test()
input = torch.ones((64,3,32,32)) # 64张图片,3个通道,32*32大小,全是1
output = net(input)
print(output.shape)
class Test(nn.Module):
def __init__(self):
super(Test,self).__init__()
self.model1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2), # 计算同上
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Flatten() ,
nn.Linear(1024, 64),
nn.Linear(64, 10),
)
def forward(self, x):
x = self.model1(x)
return x
# 这就不需要像之前那种一样一个一个调用了
# 这样网络就写完了
除了用print可视化,tensorboard也可以
from torch import nn
import torch
from torch.utils.tensorboard import SummaryWriter
class Test(nn.Module):
def __init__(self):
super(Test,self).__init__()
self.model1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2), # 计算同上
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
nn.Flatten() ,
nn.Linear(1024, 64),
nn.Linear(64, 10),
)
def forward(self, x):
x = self.model1(x)
return x
# 这就不需要像之前那种一样一个一个调用了
# 这样网络就写完了
net = Test()
print(net)
input = torch.ones((64,3,32,32)) # 64张图片,3个通道,32*32大小
output = net(input)
print(output.shape)
writer = SummaryWriter('logs')
writer.add_graph(net, input)
writer.close()
效果图
双击可以逐层打开