torch.nn.functional.conv2d
在官方文档可以查看参数
其中 input表示输入的图像,weight表示卷积核,图像和卷积核都有固定的shape,所以在卷积之前要用reshape()将两个矩阵的shape转换为固定的格式,stride表示每次移动的步数,padding是对原来输入图像的填充,默认为0,如果为1,将原来矩阵填充一圈
代码示例:
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("padding = 0:")
output = F.conv2d(input, kernel, stride=1)
print(output)
print("padding = 1:")
output1 = F.conv2d(input, kernel, stride=1, padding=1)
print(output1)
输出: