神经网络搭建实战&Sequential使用

145 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情

利用Sequential简化神经网络搭建代码

CIFAR 10模型结构如下 image.png

根据模型结构和下列公式计算padding和stirde,dilation为默认值1

image.png

得出padding=2 stride=1,由此可以编写以下代码(使用Sequential简化搭建代码):

import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.tensorboard import SummaryWriter

class Anke(nn.Module):
    def __init__(self):
        super(Anke, self).__init__()
        # self.conv1=Conv2d(in_channels=3,out_channels=32,kernel_size=5,padding=2)
        # self.maxpool1=MaxPool2d(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)
        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.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)
        x=self.model1(x)
        return x

anke=Anke()
print(anke)
input=torch.ones(64,3,32,32)
output=anke(input)
print(output.shape)

writer=SummaryWriter("logs")
writer.add_graph(anke,input)
writer.close();

运行代码时遇到问题:

Please note and check the following:

  * The Python version is: Python3.6 from ...
  * The NumPy version is: "1.19.15"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: DLL load failed: 找不到指定的模块。

原因是在Anaconda的环境下有支持 import torch 的 dll,而在PyCharm中使用的是自己创建的新环境,缺少相应支持的dll,所以需在PyCharm中配置环境变量

image.png

image.png

运行结果:

image.png

在tensorboard中可以对模型结构可视化,查看每一层的输入输出。