当前位置:网站首页>【pytorch】2.4 卷积函数 nn.conv2d
【pytorch】2.4 卷积函数 nn.conv2d
2022-07-01 09:03:00 【Enzo 想砸电脑】
二维卷积应该是最常用的卷积方式了,在Pytorch的nn模块中,封装了nn.Conv2d()类作为二维卷积的实现。使用方法和普通的类一样,先实例化再使用。下面是一个只有一层二维卷积的神经网络,作为nn.Conv2d()方法的使用简介:
class Net(nn.Module):
def __init__(self):
nn.Module.__init__(self)
self.conv2d = nn.Conv2d(in_channels=3,out_channels=64,kernel_size=4,stride=2,padding=1)
def forward(self, x):
print(x.requires_grad)
x = self.conv2d(x)
return x
print(net.conv2d.weight)
print(net.conv2d.bias)
它的形参由Pytorch手册可以查得,前三个参数是必须手动提供的,后面的有默认值。接下来将一一介绍:
- in_channels
这个很好理解,就是输入的四维张量[N, C, H, W]中的C了,即输入张量的channels数。这个形参是确定权重等可学习参数的shape所必需的。
- out_channels
也很好理解,即期望的四维输出张量的channels数,不再多说。
- kernel_size
卷积核的大小,一般我们会使用5x5、3x3这种左右两个数相同的卷积核,因此这种情况只需要写kernel_size = 5这样的就行了。如果左右两个数不同,比如3x5的卷积核,那么写作kernel_size = (3, 5),注意需要写一个tuple,而不能写一个列表(list)。
- stride = 1
卷积核在图像窗口上每次平移的间隔,即所谓的步长。这个概念和Tensorflow等其他框架没什么区别,不再多言。
- padding = 0
Pytorch与Tensorflow在卷积层实现上最大的差别就在于padding上。
Padding即所谓的图像填充,后面的int型常数代表填充的多少(行数、列数),默认为0。需要注意的是这里的填充包括图像的上下左右,以padding = 1为例,若原始图像大小为32x32,那么padding后的图像大小就变成了34x34,而不是33x33。
Pytorch不同于Tensorflow的地方在于,Tensorflow提供的是padding的模式,比如same、valid,且不同模式对应了不同的输出图像尺寸计算公式。而Pytorch则需要手动输入padding的数量,当然,Pytorch这种实现好处就在于输出图像尺寸计算公式是唯一的,即
- dilation = 1
这个参数决定了是否采用空洞卷积,啥是空洞卷积,放两张图你就懂了。默认为1(不采用)。
- groups = 1
控制输入和输出之间的连接。group=1,输出是所有的输入的卷积;group=2,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。
- bias = True
即是否要添加偏置参数作为可学习参数,默认为True。
- padding_mode = ‘zeros’
即padding的模式,默认采用零填充。
边栏推荐
猜你喜欢
随机推荐
Redis source code learning (29), compressed list learning, ziplist C (II)
Shell script -for loop and for int loop
Shell脚本-read命令:读取从键盘输入的数据
Public network cluster intercom +gps visual tracking | help the logistics industry with intelligent management and scheduling
Jetson nano installs tensorflow GPU and problem solving
Do you know how data is stored? (C integer and floating point)
电视机尺寸与观看距离
LogBack
Redis -- lattice connects to redis cluster
pcl_viewer命令
Screenshot tips
【ESP 保姆级教程】疯狂毕设篇 —— 案例:基于阿里云、小程序、Arduino的WS2812灯控系统
Pain points and solutions of equipment management in large factories
The jar package embedded with SQLite database is deployed by changing directories on the same machine, and the newly added database records are gone
Shell script echo command escape character
C language student information management system
ARM v7的体系结构A、R、M区别,分别应用在什么领域?
jeecg 重启报40001
Football and basketball game score live broadcast platform source code /app development and construction project
Imitation of Baidu search results top navigation bar effect