defcorr2d(X,K): #X为输入,K为核矩阵 h,w=K.shape #h得到K的行数,w得到K的列数 Y=torch.zeros((X.shape[0]-h+1,X.shape[1]-w+1)) #用0初始化输出矩阵Y for i inrange(Y.shape[0]): #卷积运算 for j inrange(Y.shape[1]): Y[i,j]=(X[i:i+h,j:j+w]*K).sum() return Y
X = X.reshape((1, 1, 6, 8)) Y = Y.reshape((1, 1, 6, 7))
for i inrange(10): 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}')
>>> batch 2, loss 3.852
batch 4, loss 1.126
batch 6, loss 0.386
batch 8, loss 0.145
batch 10, loss 0.057