Pytorch笔记--卷积操作

一、卷积操作

以conv2d为例

常用参数: 

input: 输入图像

weight: 卷积核

stride: 步长

padding: 填充大小

input和weight的尺寸要求均为4个参数

相关参数的一些理解:

1.步长(stride)

滑动卷积核时,我们会先从输入的左上角开始,每次往左滑动一列或者往下滑动一行逐一计算输出,我们将每次滑动的行数和列数称为stride。

当stride=1时 

当stride=2时

stride就是缩小的具体倍数,比如步幅为2,输出就是输入的1/2;步幅为3,输出就是输入的1/3。

2.填充(padding)

在矩阵的边界上填充一些值,以增加矩阵的大小(通常填充0),填充的圈数就是padding的值。

为什么要进行填充?

在卷积核移动的时候中间位置都被计算了,而输入图像二维矩阵的边缘却只计算了一次,可能会导致计算的结果不准确,所以为了让每个方块都能作为卷积窗口的中心,从而提高准确度就进行了padding。

二、实例

import torch
import torch.nn.functional as F

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]])

input = torch.reshape(input, (1, 1, 5, 5)) # 转换为符合要求的尺寸
kernel = torch.reshape(kernel, (1, 1, 3, 3))

print(input.shape)
print(kernel.shape)

output = F.conv2d(input, kernel, stride=1) # 步长为1
print(output)

output2 = F.conv2d(input, kernel, stride=2) # 步长为2
print(output2)

output3 = F.conv2d(input, kernel, stride=1, padding=1) # 步长为1 填充1圈
print(output3)

运行结果: 

实际应用

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

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


class Mikko(nn.Module): 
    def __init__(self):
        super(Mikko, 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


mikko = Mikko()
writer = SummaryWriter("../log3")

step = 0
for data in dataloader:
    imgs, target = data
    output = mikko(imgs)
    # print(imgs.shape)
    # print(output.shape)
    writer.add_images("input", imgs, step)
    output = torch.reshape(output, (-1, 3, 30, 30))
    writer.add_images("output", output, step)
    step = step + 1
writer.close()

 

 

参考:

 卷积神经网络(CNN)详细介绍及其原理详解-CSDN博客

CNN基础知识——卷积(Convolution)、填充(Padding)、步长(Stride) - 知乎 (zhihu.com)

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mikko_6214

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值