侧边栏壁纸
  • 累计撰写 49 篇文章
  • 累计创建 5 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

卷积

Administrator
2024-08-23 / 0 评论 / 0 点赞 / 8 阅读 / 2708 字
温馨提示:
本文最后更新于 2024-08-23,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

卷积

定义输入张量和卷积核张量

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

评论区