卷积层(Conbolution Layers)
- 卷积和:每个卷积核的数组中的值与图像对应位置的值形成并相加再输出
Conv2d
- 查询官网https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d
- API
torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) → [Tensor]
- 参数
1. input – 形状 (minibatch,in_channels,𝑖𝐻,𝑖𝑊)(minibatch,in_channels,iH,iW) 的输入张量
2. weight – 形状 (out_channels,in_channelsgroups,𝑘𝐻,𝑘𝑊)(out_channels,groupsin_channels,kH,kW) 过滤器,权重/卷积和
3. bias – 形状 (out_channels)(out_channels) 的可选偏置张量。默认值: `None`
4. stride – 卷积内核的步幅。可以是单个数字或元组 (sH, sW),元组就是会有横向移动和纵向移动。默认值:1,每次计算完之后移动多少
5. padding - 输入两侧的隐式填充。可以是字符串 {'valid', 'same'}、单个数字或元组 (padH, padW)。默认值:0,`padding='valid'` 与无填充相同。 `padding='same'` 填充输入,使输出具有与输入相同的形状。但是,此模式不支持除 1 以外的任何步幅值。
- 代码示例
'''
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)
- padding的使用
- 作用:在数组周围全部填充一个数字,默认为0
- 代码示例
'''
tensor([[[[ 1, 3, 4, 10, 8],
[ 5, 10, 12, 12, 6],
[ 7, 18, 16, 16, 8],
[11, 13, 9, 3, 4],
[14, 13, 9, 7, 4]]]])
'''
output_pd = F.conv2d(input,kernel,stride=1,padding=1)
print(output_pd)