目录
torch.nn — PyTorch 1.13 documentation
代码中引入torch.nn.functional,起别名为F
import torch.nn.functional as F
什么是二维卷积?
二维卷积
nn.Conv2d用于图像数据,对宽度和高度都进行卷积。

torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0,
dilation=1, groups=1) → Tensor
方法中对input和weight要求的shape都需要是4维的。
1. input的shape要求: ![]()
2. weight的shape要求:
![]()
(29条消息) 如何理解卷积神经网络中的通道(channel)_Medlen的博客-CSDN博客_卷积神经网络通道数
正常定义的tensor型shape均为二维,即只有长和宽,
因此需要使用reshape方法进行尺寸重定义。
代码将完成以下操作:

输入的input大小为5*5,输入的kernel大小为3*3,均不符合conv2d方法中要求的shape大小,因此使用reshape方法进行tensor的尺寸重定义操作。
torch.reshape方法输入的第一个参数为需要改变大小的tensor,第二个参数为需要改变的大小,使用括号括起来的4个数字,前两个数字均为1,后两个数字为tensor的长和宽。
- 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]])
-
- print(input.shape)
- print(kernel.shape)
-
- # 重新定义尺寸,把尺寸改成四个数,1个batchsize,1个通道,长和宽和之前一样
- input = torch.reshape(input,(1,1,5,5))
- kernel = torch.reshape(kernel,(1,1,3,3))
-
- print(input.shape)
- print(kernel.shape)
输出:

可见两个tensor的大小都已经成功被改变,可以输入conv2d中进行下一步操作。
- output = F.conv2d(input,kernel)
- print(output)
输出:

可见已成功进行卷积操作。
步长(stride):
卷积核是在图片上移动后遍历每一个像素,每次移动的大小就是步长stride
- #stride=1或2时的输出
- output1 = F.conv2d(input,kernel,stride=1)
- print(output1)
- output2 = F.conv2d(input,kernel,stride=2)
- print(output2)
输出:

可以看到stride=1时输出的tensor大小为3*3,stride=2时为2*2。
padding(填充):
习惯上,我们可以使用0来对图像进行填充。规定p( padding )代表填充的层数。
是为了满足输出的图像的维度要求,最终图像的输出宽度会=原来输出宽度+2padding,因为是周围填充
- # padding=1或2时的
- output3 = F.conv2d(input,kernel,stride=1,padding=1)
- print(output3)
- output4 = F.conv2d(input,kernel,stride=1,padding=2)
- print(output4)
输出:

可以看到不同的padding输出的tensor大小不同。
- import torch
- #引入F
- 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]])
-
- print(input.shape)
- print(kernel.shape)
-
- # 重新定义尺寸,把尺寸改成四个数,1个batchsize,1个通道,长和宽和之前一样
- input = torch.reshape(input,(1,1,5,5))
- kernel = torch.reshape(kernel,(1,1,3,3))
-
- print(input.shape)
- print(kernel.shape)
-
- #stride=1或2时的输出
- output1 = F.conv2d(input,kernel,stride=1)
- print(output1)
- output2 = F.conv2d(input,kernel,stride=2)
- print(output2)
-
- # padding=1或2时的
- output3 = F.conv2d(input,kernel,stride=1,padding=1)
- print(output3)
- output4 = F.conv2d(input,kernel,stride=1,padding=2)
- print(output4)