当前位置: 首页> 科技> 名企 > 动手学深度学习(Pytorch版)代码实践 -卷积神经网络-19图像卷积

动手学深度学习(Pytorch版)代码实践 -卷积神经网络-19图像卷积

时间:2025/9/2 6:22:42来源:https://blog.csdn.net/weixin_46560570/article/details/139884072 浏览次数:0次

19图像卷积

#互相关运算
#在卷积层中,输入张量和核张量通过互相关运算产生输出张量。
import torch
from torch import nn
from d2l import torch as d2ldef corr2d(X, K):"""计算二维互相关运算"""h, w = K.shapeY = 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 YX = 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]])
print(corr2d(X, K))
"""
tensor([[19., 25.],[37., 43.]])
"""#卷积层
#卷积层对输入和卷积核权重进行互相关运算,并在添加标量偏置之后产生输出。
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))
X[:, 2:6] = 0
print(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.]])
"""#检测垂直边缘
K = torch.tensor([[1.0, -1.0]])
Y = corr2d(X, K)
print(Y)
"""
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.]])
"""#检测水平边缘
Z = torch.tensor([[1.0],[-1.0]])
print(corr2d(X.t(), Z))#学习卷积核
#学习由X生成Y的卷积核#构造一个二维卷积层,它具有输入和输出通道数均为1和形状为(1,2)的卷积核
#在创建 nn.Conv2d 层时,卷积核的权重参数会随机初始化。
#这些权重参数会在训练过程中通过反向传播进行调整。
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)#计算输出 Y_hat 和目标 Y 之间的平方误差l = (Y_hat - Y) ** 2conv2d.zero_grad() #将卷积层的梯度清零。l.sum().backward() #对损失求梯度。# 迭代卷积核,根据梯度和学习率 lr 更新权重。conv2d.weight.data[:] -= lr * conv2d.weight.grad if (i + 1) % 2 == 0:print(f'epoch {i+1}, loss {l.sum():.3f}')#查看卷积核的权重张量
print(conv2d.weight.data.reshape(1,2))
"""
epoch 2, loss 3.004
epoch 4, loss 0.793
epoch 6, loss 0.251
epoch 8, loss 0.091
epoch 10, loss 0.035
tensor([[ 1.0120, -0.9741]])
"""
#学习到的卷积核权重非常接近我们之前定义的卷积核K
#K = torch.tensor([[1.0, -1.0]])
关键字:动手学深度学习(Pytorch版)代码实践 -卷积神经网络-19图像卷积

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: