0
点赞
收藏
分享

微信扫一扫

【Pytorch】6.torch.nn.functional.conv2d的使用

阅读之前应该先了解基础的CNN网络的逻辑

是PyTorch中用于执行二维卷积操作的函数。它的作用是对输入数据进行二维卷积操作,通常用于图像处理和深度学习中的卷积神经网络(CNN)模型。

我们先查看一下官方文档
在这里插入图片描述

  • input用于存放输入
  • weight用于存放卷积核
  • bias为偏置
  • stride用于记录步长,默认为1,代表每次卷积计算后移动的步数
  • padding用于对外边框进行填充,默认为0

首先导入包

import torch            # 用于创建tensor形式的input与kernel
import torch.nn.functional as F     # 用于完成卷积操作

然后创建torch类型的inputkernel

# 输入
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]])

但是我们这样创建的inputkernel只是shape为2的,而我们的conv2d需要使用shape=4的类型,我们需要通过torch.reshape()

input = torch.reshape(input,[1, 1, 5, 5])       # 将原本维度为2的转化为维度为4的,分别代表数量,通道(RGB),长,宽
kernel = torch.reshape(kernel,[1, 1, 3, 3])

然后通过

output = F.conv2d(input, kernel, stride=1, padding=0)

来进行卷积运算
在这里插入图片描述

举报

相关推荐

0 条评论