卷积(Convolution)操作比较常见,是通过一个卷积核在特征图上的滑动,得到另一个特征图
卷积操作通常被理解为提取局部特征
以二维卷积为例,通常有以下三种模式:
- Full Mode:以卷积层最下角对齐输入的最上角,最后会导致输入维度 < 输出维度,其中浅色的地方一般是补0
- Valid Mode:从输入的最上角开始,最后输入维度 > 输出维度
- Same Mode:自适应匹配位置,使最终的输入维度 = 输出维度
在pytorch里直接指定输入输出,而不需要指定模式
一维卷积
import torch
import torch.nn as nn
input_x = torch.randn(50, 3, 33) # batch size, channel 通道数, 任意维度
conv1d = nn.Conv1d(3, 20, kernel_size=10) # Conv1d(in_channels 输入的通道数, out_channels 输出的通道数, kernel_size 卷积核大小,)
print(conv1d(input_x).shape) # torch.Size([50, 20, 24])
最后输出的维度是torch.Size([50, 20, 24])
,其中:
- 50:batch的大小
- 20:初始化
nn.Conv1d
时指定的输出通道数 - 24:卷积后的维度,值等于
input_x最后的维度 - kernel_size + 1
二维卷积
import torch
import torch.nn as nn
input_x = torch.randn(50, 3, 44, 33) # batch size, channel 通道数, 特征图长, 特征图宽
conv2d = nn.Conv2d(3, 20, kernel_size=10) # Conv1d(in_channels 输入的通道数, out_channels 输出的通道数, kernel_size 卷积核大小,)
print(conv2d(input_x).shape) # torch.Size([50, 20, 35, 24])
最后的输出中torch.Size([50, 20, 35, 24])
,其中:
- 50:batch的大小
- 20:初始化
nn.Conv2d
时指定的输出通道数 - 35:卷积后的特征图长,值等于
input_x特征图长 - kernel_size + 1
- 24:卷积后的特征图宽,值等于
input_x特征图宽 - kernel_size + 1