import torch
from torch import nn
from d2l import torch as d2l
# 互相关运算
def corr2d(X, K):
"""计算二维互相关运算"""
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
# 实现二维卷积层
class Conv2D(nn.Module):
def __init__(self, kernel_size):
super().__init__()
self.weight = nn.Parameter(torch.rand(kernel_size)) # 卷积核和bias都是可学的
self.bias = nn.Parameter(torch.zeros(1))
def forward(self, x):
return corr2d(x, self.weight) + self.bias
# 图像中目标的边缘检测
X = torch.ones((6, 8))
X[:, 2:6] = 0
print(X)
K = torch.tensor([[1.0, -1.0]])
Y = corr2d(X, K)
print(Y)
# 这个卷积核K只可以检测垂直边缘
print(corr2d(X.t(), K))
# 学习由X生成Y的卷积核
conv2d = nn.Conv2d(1, 1, kernel_size=(1, 2), bias=False)
X = X.reshape((1, 1, 6, 8))
Y = Y.reshape((1, 1, 6, 7))
for i in range(50):
Y_hat = conv2d(X)
l = (Y_hat - Y)**2
conv2d.zero_grad()
l.sum().backward()
conv2d.weight.data[:] -= 3e-2 * conv2d.weight.grad
if(i + 1) % 2 == 0:
print(f'batch {i + 1}, loss {l.sum():.3f}')
print(conv2d.weight.data.reshape((1, 2)))