卷积
定义输入张量和卷积核张量
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)) #将input张量调整为(batch_size, in_channels, height, width)
kernel = torch.reshape(kernel, (1, 1, 3, 3)) #将kernel张量调整为(out_channels, in_channels, kernel_height, kernel_width)
卷积操作
output1 = F.conv2d(input, kernel, stride=1)
output2 = F.conv2d(input, kernel, stride=2)
output3 = F.conv2d(input, kernel, stride=1, padding=1)
output4 = F.conv2d(input, kernel, stride=1, padding=0)
完整代码
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:", input.shape)
print("kernel.shape:", kernel.shape)
#使用torch.nn.functional.conv2d这个函数需要将输入和卷积核的形状调整为合适的格式
input = torch.reshape(input, (1, 1, 5, 5)) #将input张量调整为(batch_size, in_channels, height, width)
kernel = torch.reshape(kernel, (1, 1, 3, 3)) #将kernel张量调整为(out_channels, in_channels, kernel_height, kernel_width)
print("input.shape:", input.shape)
print("kernel.shape:", kernel.shape)
#进行2D卷积操作,不同的参数设置会得到不同的输出
output1 = F.conv2d(input, kernel, stride=1)
print("output with stride=1:\n", output)
output2 = F.conv2d(input, kernel, stride=2)
print("output with stride=2:\n", output2)
output3 = F.conv2d(input, kernel, stride=1, padding=1)
print("output with stride=1 and padding=1:\n", output3)
output4 = F.conv2d(input, kernel, stride=1, padding=0)
print("output with stride=1 and padding=0:\n", output4)
评论区