温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

pytorch进行上采样的种类实例

发布时间:2020-10-18 18:02:36 来源:脚本之家 阅读:103 作者:yangdashi888 栏目:开发技术

1、其中再语义分割比较常用的上采样:

其实现方法为:

def upconv2x2(in_channels, out_channels, mode='transpose'):
 if mode == 'transpose':
  # 这个上采用需要设置其输入通道,输出通道.其中kernel_size、stride
  # 大小要跟对应下采样设置的值一样大小。这样才可恢复到相同的wh。这里时反卷积操作。
  return nn.ConvTranspose2d(
   in_channels,
   out_channels,
   kernel_size=2,
   stride=2)
 else:
  # out_channels is always going to be the same
  # as in_channels
  # 这里不会改变通道数,其中scale_factor是上采用的放大因子,其是相对于当前的
  # 输入大小的倍数
  return nn.Sequential(
   nn.Upsample(mode='bilinear', scale_factor=2, align_corners=True))
  # 这里的代码是在这里设置多一个卷积,这样子就起到了可以修改其输出通道的功能了。
  # 相当于功能跟ConvTranspose2d()差不多,只是上采样的方法不同
  conv1x1((in_channels, out_channels))
 
 
def conv1x1(in_channels, out_channels, groups=1):
 return nn.Sequential(nn.Conv2d(
  in_channels,
  out_channels,
  kernel_size=1,
  groups=groups,
  stride=1),
 nn.BatchNorm2d(out_channels))

另一种上采样的方法是,参考代码:segnet_pytorch:

  # Stage 5
  x51 = F.relu(self.bn51(self.conv51(x4p)))
  x52 = F.relu(self.bn52(self.conv52(x51)))
  x53 = F.relu(self.bn53(self.conv53(x52)))
  #这个id5记录的是池化操作时最大值的index,其要设置参数return_indices为True
  x5p, id5 = F.max_pool2d(x53,kernel_size=2, stride=2,return_indices=True)
 
 
  # Stage 5d
  #这个是进行最大值上采样的函数,其是根据id5来把值放到什么位置,其它位置没有值的地方
  补0
  x5d = F.max_unpool2d(x5p, id5, kernel_size=2, stride=2)
  x53d = F.relu(self.bn53d(self.conv53d(x5d)))
  x52d = F.relu(self.bn52d(self.conv52d(x53d)))
  x51d = F.relu(self.bn51d(self.conv51d(x52d)))

测试例子:

#测试上采样
m=nn.MaxPool2d((3,3),stride=(1,1),return_indices=True)
upm=nn.MaxUnpool2d((3,3),stride=(1,1))
data4=torch.randn(1,1,3,3)
output5,indices=m(data4)
output6=upm(output5,indices)
 
print('\ndata4:',data4,
  '\nmaxPool2d',output5,
  '\nindices:',indices,
  '\noutput6:',output6)

其输出为:

data4: tensor([[[[ 2.3151, -1.0391, 0.1074],
   [ 1.9360, 0.2524, 2.3735],
   [-0.1151, 0.4684, -1.8800]]]]) 
maxPool2d tensor([[[[2.3735]]]]) 
indices: tensor([[[[5]]]]) 
output6: tensor([[[[0.0000, 0.0000, 0.0000],
   [0.0000, 0.0000, 2.3735],
   [0.0000, 0.0000, 0.0000]]]])

以上这篇pytorch进行上采样的种类实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI