当前位置:   article > 正文

深度可分离卷积(计算过程及代码实现)_深度可分离卷积实现

深度可分离卷积实现

一、基本介绍

        深度可分离卷积是对传统卷积的改进,通过拆分空间维度和通道维度的相关性,减少了卷积计算所需要的参数个数。深度可分离卷积计算主要包含两个部分,第一部分是Depthwise Convolution ,将通道拆分,每个通道用一个单独的卷积核卷积。即卷积核的个数等于输入特征的通道数,并且每个卷积核只有一个通道。第二部分是Pointwise Convolution,是为1×1卷积,卷积核通道数和输入的通道数相同。

二、传统卷积计算过程

        在传统的卷积过程中,卷积核的通道数需和输入的通道数相同,每个卷积核的运算包含两部分,第一部分是卷积核相应通道与输入的相应通道进行卷积运算(对应位置相乘再相加),第二部分是将不同通道卷积结果相加得到通道数为1的特征图。n个卷积核最终得到通道数为n的输出。

二、深度可分离卷积计算过程

 

        深度可分离卷积分为两个模块,第一个部分是depthwise convolution,与传统卷积过程不同,depthwise卷积将通道分离,并且卷积核个数和输入特征的通道数相同,每个卷积核的通道数都为1,一个卷积核只对一个通道做运算。最终生成的特征通道数和输入的通道数相同。

第二部分是pointwise convolution,该部分主要有两个功能:

1、自由设置输出的通道数大小,输出通道数等于pointwise convolution中一维卷积核个数。

2、融合通道间信息,depthwise卷积忽略了通道间信息,通过一维卷积可以融合通道间的信息。

三、深度可分离卷积实现

实现深度可分离卷积:

  1. import torch
  2. from torch import nn
  3. from torchsummary import summary
  4. class depth_separable(nn.Module):
  5. def __init__(self, in_channels:int, out_channels:int) -> None:
  6. super(depth_separable,self).__init__()
  7. self.depth_conv = nn.Conv2d( #和常规卷积不同就是设置了groups参数
  8. in_channels,
  9. in_channels,
  10. kernel_size=3,
  11. stride=1,
  12. groups=in_channels, #groups设置为输入通道数,可以使逐通道卷积
  13. )
  14. self.point_conv = nn.Conv2d( #实现点卷积
  15. in_channels,
  16. out_channels,
  17. kernel_size=1,
  18. )
  19. def forward(self, x):
  20. return self.point_conv(self.depth_conv(x))
  21. class mydepth_separable(nn.Module):
  22. def __init__(self) -> None:
  23. super(mydepth_separable,self).__init__()
  24. self.conv2d = depth_separable(3,8)
  25. self.relu = nn.ReLU()
  26. def forward(self, x):
  27. return self.relu(self.conv2d(x))
  28. device = torch.device("cuda" )
  29. model=mydepth_separable().to(device)
  30. summary(model, (3, 5, 5)) #查看参数量(3,5,5)表示输入的尺寸是5×5×3

 参数结果:

 可以看到depthwise卷积后的输出是3×3×3,参数量是30,点卷积的输出是3×3×8,参数量是32,这里的参数量包含了偏置。

普通卷积:

  1. import torch
  2. from torch import nn
  3. from torchsummary import summary
  4. class conv(nn.Module):
  5. def __init__(self, in_channels:int, out_channels:int) -> None:
  6. super(conv,self).__init__()
  7. self.conv = nn.Conv2d(
  8. in_channels,
  9. out_channels,
  10. kernel_size=3,
  11. stride=1,
  12. )
  13. def forward(self,x):
  14. return self.conv(x)
  15. class myconv(nn.Module):
  16. def __init__(self) -> None:
  17. super(myconv,self).__init__()
  18. self.conv2d=conv(3,8)
  19. self.relu=nn.ReLU()
  20. def forward(self,x):
  21. return self.relu(self.conv2d(x))
  22. device = torch.device("cuda" )
  23. model1=myconv().to(device)
  24. summary(model1, (3, 5, 5))

         对比普通卷积和深度可分离卷积,深度可分离卷积一共仅需62个参数,而普通卷积需要224个参数,这就是深度可分离模块的作用,大大地减少了参数量。但是,参数量减少的同时也可能出现模型性能下降的可能,因此如何在降低网络规模的同时保证网络的性能也是轻量型网络的研究热点。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/371506
推荐阅读
相关标签
  

闽ICP备14008679号