如何在pytorch中使用可分离卷积 depth-wise Separable convolution

针对深度级别/可分离的卷积,可以使用卷积组参数,如果groups = nInputPlane,就是Depthwise;如果groups = nInputPlane,kernel=(K, 1)(针对二维卷积,前面加上,groups=1 and kernel=(1, K)),就是可分离的。
以下将torch的官方手册搬过来介绍使用方法(https://pytorch.org/docs/master/nn.html#conv2d):
如何在pytorch中使用可分离卷积 depth-wise Separable convolution
以上维最简单、普适的卷积。
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode=‘zeros’)
这里重点介绍相关的变量groups:
—groups控制输入、输出之间的连接,通过groups,in_channels 和out_channels都必须是可分离的,比如说:
—groups=1,所有的输入被卷积成所有的输出;
—groups=2,卷积操作就被等效为有两个卷积层并排,每一个对应输入通道的一半,产生输出通道的一半,然后将它们contate在一起;
----groups= in_channels,每一个输入通道跟自己的一组filter卷积(卷积核的个数为:out_channels/in_channels
----值得注意的是:
当groups= in_channels,out_channels == K * in_channels(K为一个正整数),那么这就是depthwise convolution,换句话说,输入是,如何在pytorch中使用可分离卷积 depth-wise Separable convolution,depthwise convolution with a depthwise multiplier K,可以构建如下操作:
如何在pytorch中使用可分离卷积 depth-wise Separable convolution,这相当于深度无关卷积,一个有in_channels个group,每一个group有K个卷积核,能产生K张特征图,所以最后的输出是Cin*K.

depth-wise卷积就是把每个输入通道分开,每个卷积核通道也分开,分别卷积。(把depth-wise卷积称为深度无关卷积更贴切)
那什么是depthwise_separabel卷积呢?
如下图所示:
self.depthwise是执行空间维度的卷积(一共nin个卷积核,每个通道spatial conv一下,这个是depth-wise卷积,深度无关卷积),self.pointwise是执行深度通道的融合(一共nout个卷积核,每个卷积核的大小nin11)。总共的参数量是,kernel_size_hkernel_size_wnin+ninnout,普通卷积的参数两是ninnoutkernel_size_hkernel_size_w(不考虑bias),由此可见,参数量大大下降。
如何在pytorch中使用可分离卷积 depth-wise Separable convolution
贴一个文字版本的方便大家拷贝:

class depthwise_separable_conv(nn.Module):
def init(self, nin, nout):
super(depthwise_separable_conv, self).init()
self.depthwise = nn.Conv2d(nin, nin, kernel_size=3, padding=1, groups=nin)
self.pointwise = nn.Conv2d(nin, nout, kernel_size=1)
def forward(self, x):
out = self.depthwise(x)
out = self.pointwise(out)
return out