(九)神经网络-搭建小实战和Sequential的使用

【声明】来源b站视频小土堆PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】_哔哩哔哩_bilibili

(九)神经网络-搭建小实战和Sequential的使用_第1张图片 CIFAR10 model结构

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


class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()

        self.conv1 = Conv2d(3, 32, 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)

    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

mymodel = MyModel()
print(mymodel)
#检验
input = torch.ones(64,3,32,32)
ouput = mymodel(input)
print(ouput.shape)

(九)神经网络-搭建小实战和Sequential的使用_第2张图片

 

Sequential

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


class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()

        # self.conv1 = Conv2d(3, 32, 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.sequntial = 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.sequntial(x)#自动按顺序经过以上步骤
        return x

mymodel = MyModel()
print(mymodel)
#检验
input = torch.ones(64,3,32,32)
ouput = mymodel(input)
print(ouput.shape)

(九)神经网络-搭建小实战和Sequential的使用_第3张图片

 可视化

(九)神经网络-搭建小实战和Sequential的使用_第4张图片

 

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