05 神经网络的基本骨架 —— module 及 卷积层

Pytorch关于神经网络的包都在torch.nn里

forward是前向传播(backward是反向传播)

 

 

1 卷积基础

# 学习卷积层基础 —— 卷积
input = torch.tensor([[1, 2, 0, 3, 1],
                      [0, 1, 2, 3, 1],
                      [1, 2, 1, 0, 0],
                      [5, 2, 3, 1, 1],
                      [2, 1, 0, 1, 1]])

kernel = torch.tensor([[1, 2, 1],
                       [0, 1, 0],
                       [2, 1, 0]])

# 由于TORCH.NN.FUNCTIONAL.CONV2D 要求参数input和weight是四维的,所以这里做个升维
input = torch.reshape(input, (1, 1, 5, 5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))
print(input.shape)
print(kernel.shape)


# 开始卷积
# 指定stride卷积
output = F.conv2d(input, kernel, stride=1)
print(output)
# 指定padding卷积
output = F.conv2d(input, kernel, stride=1, padding=1)
print(output)

 

2 卷积层

 

2.1 卷积层使用案例

import torch
import torchvision
from torch.utils.data import DataLoader
from torch import nn
from torch.nn import Conv2d
from torch.utils.tensorboard import SummaryWriter

dataset = torchvision.datasets.CIFAR10(root="D:/Learn/dataSet/Pytorch", train=False, transform=torchvision.transforms.ToTensor(), download=False)

dataloader = DataLoader(dataset, batch_size=64)

# 创建卷积层
class Test_NN(nn.Module):
    def __init__(self):
        super(Test_NN, self).__init__()
        self.conv1 = Conv2d(in_channels=3, out_channels=6, kernel_size=3, stride=1, padding=0)

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


# 实例化
testNN = Test_NN()
print(testNN)

writer = SummaryWriter("logs")

step = 0
# 看结果
for data in dataloader:
    imgs, targets = data
    output = testNN(imgs)
    # 输入图像
    print(imgs.shape)   # torch.Size([64, 3, 32, 32])
    writer.add_images("input", imgs, step)

    # 输出图像
    print(output.shape)     # torch.Size([64, 6, 30, 30])
    # 这里输出为6通道,tensorboard不知道怎么显示,需要reshape尺寸变换再显示
    # torch.Size([64, 6, 30, 30]) ->  torch.Size([xxx, 3, 30, 30])
    output = torch.reshape(output, (-1, 3, 30, 30))   # 第一个参数不知道写多少,就写-1
    writer.add_images("output", output, step)

    step += 1

writer.close()

得到结果

 

 

根据下面公司进行计算输入输出shape

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章