(pytorch-深度学习系列)CNN二维卷积层-学习笔记
二維卷積層
在二維互相關運算中,卷積窗口從輸入數組的最左上方開始,按從左往右、從上往下的順序,依次在輸入數組上滑動。當卷積窗口滑動到某一位置時,窗口中的輸入子數組與核數組按元素相乘并求和,得到輸出數組中相應位置的元素。
例如:
輸入為:input:
[012345678]\begin{bmatrix} 0 & 1 & 2 \\ 3 & 4 &5 \\ 6 & 7 & 8 \end{bmatrix}???036?147?258????
核為:kernel:
[0123]\begin{bmatrix} 0 & 1 \\ 2 & 3 \end{bmatrix}[02?13?]
則輸出為:output
output=input?kernel=[012345678]?[0123]=[19253743]output = input * kernel = \begin{bmatrix} 0 & 1 & 2 \\ 3 & 4 &5 \\ 6 & 7 & 8 \end{bmatrix} * \begin{bmatrix} 0 & 1 \\ 2 & 3 \end{bmatrix} = \begin{bmatrix} 19 & 25 \\ 37 & 43 \end{bmatrix}output=input?kernel=???036?147?258?????[02?13?]=[1937?2543?]
輸出數組高和寬分別為2,其中的4個元素由二維互相關運算得出:
0×0+1×1+3×2+4×3=19,1×0+2×1+4×2+5×3=25,3×0+4×1+6×2+7×3=37,4×0+5×1+7×2+8×3=43.0\times0+1\times1+3\times2+4\times3=19,\\ 1\times0+2\times1+4\times2+5\times3=25,\\ 3\times0+4\times1+6\times2+7\times3=37,\\ 4\times0+5\times1+7\times2+8\times3=43. 0×0+1×1+3×2+4×3=19,1×0+2×1+4×2+5×3=25,3×0+4×1+6×2+7×3=37,4×0+5×1+7×2+8×3=43.
設計函數實現卷積層的計算:
import torch from torch import nndef corr2d(X, K): h, w = K.shapeY = torch.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))for i in range(Y.shape[0]):for j in range(Y.shape[1]):Y[i, j] = (X[i: i + h, j: j + w] * K).sum()return Y構造輸入數據以及卷積核驗證上述計算:
X = torch.tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) K = torch.tensor([[0, 1], [2, 3]]) corr2d(X, K)輸出:
tensor([[19., 25.],[37., 43.]])自定義二維卷積層
class conv2d(nn.Module):def __init(self, kernel_size):super(conv2d, self).__init__()self.weight = nn.Parameter(torch.randn(kernel_size))self.bias = nn.Parameter(torch.randn(1))def forward(self, x):return corr2d(x, self.weight) + self.bias這里我們使用了corr2d函數來實現一個自定義的二維卷積層,這個網絡層有weight、bias兩個參數,前向計算函數是直接調用corr2d函數再加上偏差。
使用卷積層做圖像中物體邊緣的檢測
檢測圖像中物體的邊緣,即找到像素變化的位置。首先我們構造一張6×86\times 86×8的圖像(即高和寬分別為6像素和8像素的圖像)。它中間4列為黑(0),其余為白(1)。
X = torch.ones(6, 8) X[:, 2:6] = 0構造一個高和寬分別為1和2的卷積核K。當它與輸入做互相關運算時,如果橫向相鄰元素相同,輸出為0;否則輸出為非0。
K = torch.tensor([[1, -1]])將輸入X和我們設計的卷積核K做互相關運算。計算 將從白到黑的邊緣和從黑到白的邊緣分別檢測成了1和-1。其余部分的輸出全是0。
Y = corr2d(X, K) print(Y) tensor([[ 0., 1., 0., 0., 0., -1., 0.],[ 0., 1., 0., 0., 0., -1., 0.],[ 0., 1., 0., 0., 0., -1., 0.],[ 0., 1., 0., 0., 0., -1., 0.],[ 0., 1., 0., 0., 0., -1., 0.],[ 0., 1., 0., 0., 0., -1., 0.]])通過這個例子我們能看出,卷積層可以通過重復使用卷積核有效的表示局部空間。
通過數據學習出卷積核
使用物體邊緣檢測中的輸入數據X和輸出數據Y來學習我們構造的核數組K。
我們首先構造一個卷積層,其卷積核將被初始化成隨機數組。接下來在每一次迭代中,我們使用平方誤差來比較Y和卷積層的輸出,然后計算梯度來更新權重。
總結
以上是生活随笔為你收集整理的(pytorch-深度学习系列)CNN二维卷积层-学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 贝加尔湖,冰雪奇缘之旅
- 下一篇: 科研这条路:一位数学博士给本科生的建议