动手学深度学习v2-卷积层

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

# 互相关运算
def corr2d(X, K): # X表示样本输入,K表示核矩阵 h,w 分别表示长和高
  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

# 验证上述二维互相关运算的输出
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)

# 实现二维卷积层----Module的应用
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 生成 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(10): # 自定义训练逻辑
  Y_hat = conv2d(X):
  l = (Y_hat - Y)**2 # 均方误差 作为loss
  conv2d.zero_grad()
  l.sum().backward()
  conv2d.weight,data[:] -= 3e-2 * conv2d.weight.grad # 3e-2表示为学习率,后面接着是梯度
  if (i + 1) % 2 == 0:
    print(f'batch{i+1}, loss{l.sum():.3f}')

conv2d.weight.data.reshape((1, 2)) # 所学到的卷积核的权重张量
#---------------------------------------------------------------------

你可能感兴趣的:(pytorch,深度学习,神经网络)