欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > 22、PyTorch nn.Conv2d卷积网络使用教程

22、PyTorch nn.Conv2d卷积网络使用教程

2025/2/25 7:39:42 来源:https://blog.csdn.net/scar2016/article/details/145114096  浏览:    关键词:22、PyTorch nn.Conv2d卷积网络使用教程

文章目录

  • 1. 卷积
  • 2. python 代码
  • 3. notes

1. 卷积

  • 输入A张量为:
    A = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ] \begin{equation} A=\begin{bmatrix} 0&1&2&3\\\\ 4&5&6&7\\\\ 8&9&10&11\\\\ 12&13&14&15 \end{bmatrix} \end{equation} A= 0481215913261014371115
  • 卷积核矩阵
    w e i g h t = [ 0 1 2 3 4 5 6 7 8 ] , b i a s = 10 \begin{equation} weight=\begin{bmatrix} 0&1&2\\\\ 3&4&5\\\\ 6&7&8 \end{bmatrix},bias = 10 \end{equation} weight= 036147258 ,bias=10
    在这里插入图片描述

2. python 代码

  • pytorch
import torch
import torch.nn as nn
import torch.nn.functional as Ftorch.set_printoptions(precision=3, sci_mode=False)if __name__ == "__main__":run_code = 0batch_size = 1in_channels = 1out_channels = 1kernel_size = 4input_h = 4input_w = 4input_total = input_h * input_winput_matrix = torch.arange(input_total).reshape(batch_size, in_channels, input_h, input_w).to(torch.float)my_conv2d = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, bias=True,stride=1)print(f"my_conv2d={my_conv2d}")my_conv2d_weight = torch.arange(9).reshape((1, 1, 3, 3)).to(torch.float)my_conv2d_bias = torch.tensor([10.0])my_conv2d.weight = nn.Parameter(my_conv2d_weight)my_conv2d.bias = nn.Parameter(my_conv2d_bias)print(f"my_conv2d_weight=\n{my_conv2d_weight}")print(f"my_conv2d_bias=\n{my_conv2d_bias}")output_matrix = my_conv2d(input_matrix)print(f"input_matrix=\n{input_matrix}")print(f"output_matrix=\n{output_matrix}")output_matrix_F = F.conv2d(input=input_matrix, weight=my_conv2d_weight, bias=my_conv2d_bias)print(f"output_matrix_F=\n{output_matrix_F}")
  • 结果:
my_conv2d=Conv2d(1, 1, kernel_size=(4, 4), stride=(1, 1))
my_conv2d_weight=
tensor([[[[0., 1., 2.],[3., 4., 5.],[6., 7., 8.]]]])
my_conv2d_bias=
tensor([10.])
input_matrix=
tensor([[[[ 0.,  1.,  2.,  3.],[ 4.,  5.,  6.,  7.],[ 8.,  9., 10., 11.],[12., 13., 14., 15.]]]])
output_matrix=
tensor([[[[268., 304.],[412., 448.]]]], grad_fn=<ConvolutionBackward0>)
output_matrix_F=
tensor([[[[268., 304.],[412., 448.]]]])

3. notes

在这里插入图片描述

版权声明:

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

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

热搜词