在深度学习中,卷积时很重要的一个环节,它能够提取出图片或序列中的模式。卷积可以分为很多种类型,如:卷积,反卷积,深度可分离卷积等等,这篇文章主要介绍几种常用的卷积方式以及其在pytorch中对应的实现。
卷积
首先我们定义两种类型的张量,一种是图片,一种是序列。图片的张量的size为[batch, channel, height, width]
,序列的张量的size为[batch, channel, length]
。
图像
对于图像,pytorch
中提供的函数为torch.nn.Conv2d
,其函数签名如下:
1
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, padding_mode='zeros', dilation=1, groups=1, bias=True)
其中kernel_size, stride, padding, dilation
可以为int,tuple
,当为tuple
时可以分别控制宽高方向。
对于卷积的输出大小可用下面的公式计算
序列
对于序列,pytorch
中提供的函数为torch.nn.Conv1d
,其签名同Conv2d
,只是不能使用tuple
,以为其是一维的。
反卷积
图像
1 | torch.nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, padding_mode='zeros') |
其中大部分参数和Conv2d
一样,多出来的output_padding
指的是对输出进行pad。
其输出大小的计算公式如下: