pytorch框架--网络方面--自建模型示例

自己搭建模型、检查网络是否错误

import torch
from torch import nn
# 导入记好了,2维卷积,2维最大池化,展成1维,全连接层,构建网络结构辅助工具
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.tensorboard import SummaryWriter


class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.model1 = Sequential(
            # 输入, 输出, 卷积核、补几圈零
            Conv2d(3, 32, (5, 5), padding=2),
            # Conv2d(in_channels=3, out_channels=32, kernel_size=(5, 5), stride=1, padding=2),
            # 池化核
            MaxPool2d(2),
            # MaxPool2d(kernel_size=2, stride=2, padding=0),
            
            Conv2d(32, 32, (5, 5), padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, (5, 5), padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )

    def forward(self, x):
        x = self.model1(x)
        return x


if __name__ == '__main__':
    tudui = Tudui()
    # 验证网络 须知输入图像,设定全1矩阵测试
    input = torch.ones((64, 3, 32, 32))
    output = tudui(input)
    print(output.shape)
    # 绘制网络结构图
    writer = SummaryWriter("log")
    # 参数:网络结构对象、输入图像矩阵
    writer.add_graph(tudui, input)
    writer.close()

正向计算输出图像大小:

例如:conv2d(64,64,3,1,1) 、(输入,输出,卷积核,步长,补零)、
输出:64 = (64 + 2 * 1 - 3) / 1 + 1、输出大小 =(输入大小 + 2 * 补零 - 卷积核大小)步长 + 1

反向计算补零(padding)
例如:conv2d(64,64,3,1,1) 、(输入,输出,卷积核,步长,补零)、
补零 = ((64 - 1) * 1 + 3 - 64) / 2、((输出 - 1)* 1 + 卷积核 - 输入)/ 2

你可能感兴趣的:(Pytorch框架,ubuntu,pytorch,python)