# PyTorch学习笔记5——卷积神经网络

PS:这里的卷积运算与数学及信号中的不同，神经网络的卷积运算是数学上的互相关运算。

# 5.1 二维卷积层

## 5.1.1 二维互相关运算

``````import torch
from torch import nn
from d2l import torch as d2l

def corr2d(X, K):  #@save
"""计算二维互相关运算。"""
h, w = K.shape
Y = 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
``````

## 5.1.2 二维卷积层

``````class Conv2D(nn.Module):
def __init__(self, kernel_size):
super().__init__()
self.weight = nn.Parameter(torch.rand(kernel_size))
self.bias = nn.Parameter(torch.zeros(1))

def forward(self, x):
return corr2d(x, self.weight) + self.bias
``````

## 5.1.3 图像物体边缘检测

``````X = torch.ones(6, 8)
X[:, 2:6] = 0
X
``````

OUTPUT:

``````tensor([[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.],
[1., 1., 0., 0., 0., 0., 1., 1.]])
``````

``````K = torch.tensor([[1.0, -1.0]])
``````

OUTPUT:

``````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.]])
``````

``````corr2d(X.t(), K)
``````

OUTPUT:

``````tensor([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
``````

## 5.1.4 学习卷积核

``````# 构造一个二维卷积层，它具有1个输出通道和形状为（1，2）的卷积核
conv2d = nn.Conv2d(1, 1, kernel_size=(1, 2), bias=False)

# 这个二维卷积层使用四维输入和输出格式（批量大小、通道、高度、宽度），
# 其中批量大小和通道数都为1
X = X.reshape((1, 1, 6, 8))
Y = Y.reshape((1, 1, 6, 7))

for i in range(10):
Y_hat = conv2d(X)
l = (Y_hat - Y)**2
l.sum().backward()
# 迭代卷积核
if (i + 1) % 2 == 0:
print(f'batch {i+1}, loss {l.sum():.3f}')
``````

OUTPUT:

``````batch 2, loss 3.196
batch 4, loss 0.582
batch 6, loss 0.116
batch 8, loss 0.027
batch 10, loss 0.008
``````