01.10 pytorch学习(神经网络-搭建小实战和Sequential的使用)

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

要实现的网络结构:
01.10 pytorch学习(神经网络-搭建小实战和Sequential的使用)_第1张图片

代码:

import torch
import torch.nn as nn
import torchvision
from torch.utils.data import DataLoader
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential

dataset = torchvision.datasets.CIFAR10("./dataset2", train=True, transform=torchvision.transforms.ToTensor(), download=True)
dataloader = DataLoader(dataset,batch_size=64)

#生成一个(64,3,32,32)格式的全1矩阵
input = torch.ones((64,3,32,32))

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        #如果我们直接像注释这样写,沉余过大
        # super(Tudui, 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)
        #Sequential能将这些层接起来,类似前面的Compose()组合transform
        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.model1(x)
        return x

tudui = Tudui()
#测试代码正确性
print(input.shape)
output=tudui(input)
print(output.shape)
# for data in dataloader:
#     img,target = data
#     tudui(img)

Sequential
能将这些层接起来,类似前面的Compose()组合transform

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