当前位置: 代码迷 >> 综合 >> 神经网络-简单的搭建实战
  详细解决方案

神经网络-简单的搭建实战

热度:116   发布时间:2023-11-22 21:16:08.0

在这里插入图片描述
搭建上图神经网络并测试

import torch
import torchvision
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear
from torch.utils.data import DataLoaderdataset = torchvision.datasets.CIFAR10("dataset2",train=False,transform=torchvision.transforms.ToTensor())
dataloader = DataLoader(dataset,batch_size=64)class Test(nn.Module):def __init__(self):super(Test, self).__init__()self.conv1 = Conv2d(3,32,5,padding=2)self.maxpool1 = MaxPool2d(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(kernel_size=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;
test = Test()
print(test)
input = torch.ones(64,3,32,32)
output = test(input)
print(output.shape)

其中,paddingstride的值需要自己计算,打开官网
在这里插入图片描述
通过这个公式来求出需要的值
输出:

Test((conv1): Conv2d(3, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(maxpool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(conv2): Conv2d(32, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(maxpool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(conv3): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(maxpool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(flatten): Flatten(start_dim=1, end_dim=-1)(linear1): Linear(in_features=1024, out_features=64, bias=True)(linear2): Linear(in_features=64, out_features=10, bias=True)
)
torch.Size([64, 10])

利用tensoard展示计算图
在这里插入图片描述

  相关解决方案