以一個例子展示一維卷積過程:
原理
假設輸入數據為 6 個維度的數據,有 4 個通道,即[6,4]的數據。
設置核大小(kernel_size)為 2,卷積的步長(stride)為 2,核數量(也就是out_channels)為 1 的卷積。
其中卷積核的通道數和輸入的通道數相同,即同樣是 4 。
卷積過程及結果如下圖所示:
得到一個[1,3]得輸出。
第一維結果1:由於核維度默認和輸入通道數相同,所以當只有一個卷積核時,第一維輸出就為1。有多少個卷積核,輸出第一維就是多少。
第二維結果3:可通過公式計算:\(N=\frac{W-F+2P}{S}+1\)。其中:\(W\)為輸入大小,\(F\)為核大小,\(P\)為填充大小,\(S\)為步長。
代碼
通過pytorch的實現:
pytorch的一維卷積nn.Conv1d()
參數:
- in_channels (int) – Number of channels in the input image
- out_channels (int) – Number of channels produced by the convolution
- kernel_size (int or tuple) – Size of the convolving kernel
- stride (int or tuple, optional) – Stride of the convolution. Default: 1
- padding (int, tuple or str, optional) – Padding added to both sides of the input. Default: 0
- padding_mode (string, optional) – 'zeros', 'reflect', 'replicate' or 'circular'. Default: 'zeros'
- dilation (int or tuple, optional) – Spacing between kernel elements. Default: 1
- groups (int, optional) – Number of blocked connections from input channels to output channels. Default: 1
- bias (bool, optional) – If True, adds a learnable bias to the output. Default: True
例程:
import torch
import torch.nn as nn
torch.manual_seed(2021)
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
inp = torch.Tensor([a, b, a, b, a, b])
# 擴充一維,作為batch_size
inp = inp.unsqueeze(0)
print(inp.shape)
# 調換位置
inp = inp.permute(0, 2, 1)
model = nn.Conv1d(in_channels=4, out_channels=1, kernel_size=2, stride=2, padding=0)
# 顯示權重
for name, parameters in model.named_parameters():
print(name, ':', parameters)
out = model(inp)
print(out.shape)
print(out)
結果:
NOTE:
- 例子里只使用1個數據,即batch_size=1。所以構造了[1, 6, 4]的Tensor,如果一個batch的輸入數據,即
[batch_size, 6, 4]
nn.Conv1d()
計算時,它的輸入格式是[batch_size, in_channels, in_size]
,所以要使用permute()
函數,把后面兩個維度的順序調換一下!- 一維卷積默認的輸入數據其實是2維的。如果是1維的輸入數據,應該通過
unsqueeze()
函數,擴充1維。將[batch_size, 6]
變為[batch_size, 6, 1]
。卷積過程也如下圖所示:
