Pytorch实现各种2d卷积示例

yipeiwu_com6年前Python基础

普通卷积

使用nn.Conv2d(),一般还会接上BN和ReLu

参数量NNCin*Cout+Cout(如果有bias,相对来说表示对参数量影响很小,所以后面不考虑)

class ConvBNReLU(nn.Module):

 def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):
  super(ConvBNReLU, self).__init__()
  self.op = nn.Sequential(
   nn.Conv2d(C_in, C_out, kernel_size, stride=stride, padding=padding, bias=False),
   nn.BatchNorm2d(C_out, eps=1e-3, affine=affine),
   nn.ReLU(inplace=False)
  )

 def forward(self, x):
  return self.op(x)

深度可分离卷积depthwise separable convolution

卷积操作可以分为NN 的Depthwise卷积(不改变通道数)和11的Pointwise卷积(改变为输出通道数),同样后接BN,ReLU。参数量明显减少

参数量:

NNCin+Cin11*Cout

class SepConv(nn.Module):
 
 def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True):
  super(SepConv, self).__init__()
  self.op = nn.Sequential(
   nn.ReLU(inplace=False),
   nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, groups=C_in, bias=False),
   nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),
   nn.BatchNorm2d(C_out, eps=1e-3, affine=affine)
   )
 def forward(self, x):
  return self.op(x)

空洞卷积dilated convolution

空洞卷积(dilated convolution)是针对图像语义分割问题中下采样会降低图像分辨率、丢失信息而提出的一种卷积思路。利用添加空洞扩大感受野。

参数量不变,但感受野增大(可结合深度可分离卷积实现)

class DilConv(nn.Module):
  
 def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation, affine=True):
  super(DilConv, self).__init__()
  self.op = nn.Sequential(
   nn.ReLU(inplace=False),
   nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=C_in, bias=False),
   nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False),
   nn.BatchNorm2d(C_out, eps=1e-3, affine=affine),
   )

 def forward(self, x):
  return self.op(x)

Identity

这个其实不算卷积操作,但是在实现跨层传递捷径

class Identity(nn.Module):

 def __init__(self):
  super(Identity, self).__init__()

 def forward(self, x):
  return x

以上这篇Pytorch实现各种2d卷积示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用coverage统计python web项目代码覆盖率的方法详解

使用coverage统计python web项目代码覆盖率的方法详解

本文实例讲述了使用coverage统计python web项目代码覆盖率的方法。分享给大家供大家参考,具体如下: 在使用python+selenium过程中,有时候考虑代码覆盖率,所以专...

pandas的排序和排名的具体使用

有的时候我们可以要根据索引的大小或者值的大小对Series和DataFrame进行排名和排序。 一、排序 pandas提供了sort_index方法可以根据行或列的索引按照字典的顺序进...

Python设计模式之职责链模式原理与用法实例分析

Python设计模式之职责链模式原理与用法实例分析

本文实例讲述了Python设计模式之职责链模式原理与用法。分享给大家供大家参考,具体如下: 职责链模式(Chain Of Responsibility):使多个对象都有机会处理请求,从而...

python中使用enumerate函数遍历元素实例

这个是python的一个内建函数,看书的时候发现了他,mark一下当我们既需要遍历索引同时需要遍历元素的时候,可以考虑使用enumerate函数,enumerate函数接受一个可遍历的对...

python OpenCV GrabCut使用实例解析

python OpenCV GrabCut使用实例解析

这篇文章主要介绍了python OpenCV GrabCut使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 先上一个效果图...