1.二维卷积计算
import torch
from torch import nn
from d2l import torch as d2l
定义二维卷积函数
def corr2d(X, K):'''计算二维互相关运算'''h, w = K.shapeY = torch.zeros((X.shape[0]) - h + 1, X.shape[1] - w + 1)# 测试数据z = X[0:2, 0:2]*Kprint(z)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.0, 1.0, 2.0], [3.0, 4.0, 5.0],[6.0, 7.0, 8.0]])
K = torch.tensor([[0.0, 1.0], [2.0, 3.0]])
corr2d(X, K)
tensor([[ 0., 1.],[ 6., 12.]])tensor([[19., 25.],[37., 43.]])
2.卷积层
创建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
创建目标边缘检测数据
X = torch.ones((6, 8)) # 创建 6x8 的数据为全1
X[:, 2:6] = 0 # 将二维数据中的第2列到第6列为0
X
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.]])
# 创建卷积核 高为1 宽为2
K = torch.tensor([[1.0, -1.0]])
# 参数x(输入) 和 k(卷积核)执行互相关运算
# 输出1:白色到黑色的边缘
# 输出-1: 黑色到白色的边缘
# 其他情况输出为0
Y = corr2d(X, K)
Y
tensor([[ 1., -1.],[ 1., -1.]])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)
tensor([[ 1., -1.],[ 1., -1.]])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.]])
3.学习卷积核
# 创造一个二维卷积层,它具有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))
lr = 3e-2 # 学习率for i in range(10):Y_hat = conv2d(X)l = (Y_hat - Y)**2conv2d.zero_grad()l.sum().backward()# 迭代卷积核conv2d.weight.data[:] -= lr * conv2d.weight.gradif (i+1)%2 == 0:print(f'epoch {i+1}, loss{l.sum():.3f}')
epoch 2, loss1.817
epoch 4, loss0.311
epoch 6, loss0.055
epoch 8, loss0.010
epoch 10, loss0.002