一、卷积pytorch
在pytorch中有两种方式,一种是torch.nn.Conv2d()
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
参数 | 解释 |
---|---|
in_channels | 输入图像通道数 |
out_channels | 卷积产生的通道数 |
kernel_size | 卷积核尺寸 |
stride | 卷积步长,默认为1 |
padding | 填充操作,控制padding_mode的数目 |
padding_mode | padding模式,默认为Zero-padding |
dilation | 扩张操作:控制kernel点(卷积核点)的间距,默认值:1 |
groups | group参数的作用是控制分组卷积,默认不分组,为1组 |
bias | 添加一个可学习的偏差。默认:True |
一种是torch.nn.functional.conv2d()
torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)
weight权重 也就是卷积核
二、卷积pytorch代码实现
在这里我使用的是第二种 torch.nn.functional.conv2d()
1、定义输入,和卷积核
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]])
2、reshape输入和卷积核
# [ batch_size, channels, height, width ]
input = torch.reshape(input,(1,1,5,5))
kernel = torch.reshape(kernel,(1,1,3,3))
3、conv2d卷积
output = F.conv2d(input,kernel,stride=1)
4、输出
print(output)
# tensor([[[[10, 12, 12],
# [18, 16, 16],
# [13, 9, 3]]]])
代码:
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))
output = F.conv2d(input,kernel,stride=1)
print(output)