神经网络之搭建小实战和Sequential的使用

SWQUENTIAL:使代码更加简洁

目标:搭建一个对CIFAR-10分类的简单神经网络
神经网络之搭建小实战和Sequential的使用_第1张图片
神经网络之搭建小实战和Sequential的使用_第2张图片

import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear


class Peipei(nn.Module):
    def __init__(self) -> None:
        super(Peipei, self).__init__()
        self.conv1 = Conv2d(3, 32, 5, padding=2, stride=1)
        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.lin1 = Linear(1024, 64)
        self.lin2 = 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.lin1(x)
        x = self.lin2(x)
        return x


peipei = Peipei()
print(peipei)
input = torch.ones(64, 3, 32, 32)
output = peipei(input)
print(output.shape)

输出:
神经网络之搭建小实战和Sequential的使用_第3张图片
使用了Sequential

import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential


class Peipei(nn.Module):
    def __init__(self) -> None:
        self.model1 = Sequential(
            Conv2d(3, 32, 5, padding=2, stride=1),
            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
        
peipei = Peipei()
print(peipei)
input = torch.ones(64, 3, 32, 32)
output = peipei(input)
print(output.shape)
writer = SummaryWriter("logs_seq")
writer.add_graph(peipei,input)
writer.close()

结果:
神经网络之搭建小实战和Sequential的使用_第4张图片

你可能感兴趣的:(pytorch,深度学习,神经网络)