pytorch之torch.nn.Conv2d()函数详解

一、官方文档介绍

官网
在这里插入图片描述
nn.Conv2d:对由多个输入平面组成的输入信号进行二维卷积
在这里插入图片描述
在这里插入图片描述

二、torch.nn.Conv2d()函数详解

参数详解

torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

参数 参数类型
in_channels int Number of channels in the input image 输入图像通道数
out_channels int Number of channels produced by the convolution 卷积产生的通道数
kernel_size (int or tuple) Size of the convolving kernel 卷积核尺寸,可以设为1个int型数或者一个(int, int)型的元组。例如(2,3)是高2宽3卷积核
stride (int or tuple, optional) Stride of the convolution. Default: 1 卷积步长,默认为1。可以设为1个int型数或者一个(int, int)型的元组。
padding (int or tuple, optional) Zero-padding added to both sides of the input. Default: 0 填充操作,控制padding_mode的数目。
padding_mode (string, optional) ‘zeros’, ‘reflect’, ‘replicate’ or ‘circular’. Default: ‘zeros’ padding模式,默认为Zero-padding 。
dilation (int or tuple, optional) Spacing between kernel elements. Default: 1 扩张操作:控制kernel点(卷积核点)的间距,默认值:1。
groups (int, optional) Number of blocked connections from input channels to output channels. Default: 1 group参数的作用是控制分组卷积,默认不分组,为1组。
bias (bool, optional) If True, adds a learnable bias to the output. Default: True 为真,则在输出中添加一个可学习的偏差。默认:True。

参数dilation——扩张卷积(也叫空洞卷积)

dilation操作动图演示如下:
Dilated Convolution with a 3 x 3 kernel and dilation rate 2
扩张卷积核为3×3,扩张率为2
在这里插入图片描述

参数groups——分组卷积

Group Convolution顾名思义,则是对输入feature map进行分组,然后每组分别卷积。
假设输入feature map的尺寸仍为

### 查找 `torch.nn.Conv2d` 的源代码 在 PyTorch 中,`Conv2d` 类位于模块 `torch.nn.modules.conv` 下面。具体来说,类定义如下: ```python import torch.nn as nn class Conv2d(_ConvNd): def __init__( self, in_channels: int, out_channels: int, kernel_size: _size_2_t, stride: _size_2_t = 1, padding: Union[_size_2_t, str] = 0, dilation: _size_2_t = 1, groups: int = 1, bias: bool = True, padding_mode: str = 'zeros' ): ... ``` 该类继承自 `_ConvNd` 并实现了二维卷积层的功能[^4]。 当创建一个 `Conv2d` 对象并调用它时(即执行前向传播),实际发生的操作是由底层 C++ 扩展通过 Python 绑定来完成的。对于具体的卷积计算部分,则是在 `torch._C` 库内部处理,这部分通常是编译后的高效实现而不是纯 Python 代码[^5]。 为了查看更详细的源码逻辑,在 GitHub 上可以找到完整的文件路径以及更多细节说明。通常情况下,用户并不需要直接修改或深入理解这些底层实现,除非是为了贡献代码给项目本身或是出于学习目的深入了解框架的工作机制[^3]。 #### 关于 `torch.nn.functional.conv2d` 值得注意的是,除了 `torch.nn.Conv2d` 外还有一个函数版本叫做 `torch.nn.functional.conv2d()` 。这两个接口提供了相似的功能但是应用场景有所不同:前者用于构建可训练模型的一部分;后者则更适合一次性使用的场景或者是作为其他组件的基础构件。 ```python # 使用 torch.nn.Conv2d 构建网络层 conv_layer = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=(2, 3)) # 或者使用 functional API 进行单次运算 output = F.conv2d(input_tensor, weights, ... ) ```
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏普通

谢谢打赏~普通在此谢过

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值