shufflenet v2的block的pytorch实现代码

shufflenet v2的block的pytorch实现代码

def channel_shuffle(x, groups):
    # type: (torch.Tensor, int) -> torch.Tensor
    batchsize, num_channels, height, width = x.data.size()
    channels_per_group = num_channels // groups

    # reshape
    x = x.view(batchsize, groups,
               channels_per_group, height, width)
 
    x = torch.transpose(x, 1, 2).contiguous()
 
    # flatten
    x = x.view(batchsize, -1, height, width)
 
    return x


class ShuffleV2Block(nn.Module):
    def __init__(self, inp, oup, stride, activation='ReLU'):
        super(ShuffleV2Block, self).__init__()
 
    if not (1 <= stride <= 3):
        raise ValueError('illegal stride value')
    self.stride = stride

    branch_features = oup // 2
    assert (self.stride != 1) or (inp == branch_features << 1)

    if self.stride > 1:
        self.branch1 = nn.Sequential(
            self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1),
            nn.BatchNorm2d(inp),
            nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
            nn.BatchNorm2d(branch_features),
            act_layers(activation),
        )
    else:
        self.branch1 = nn.Sequential()

    self.branch2 = nn.Sequential(
        nn.Conv2d(inp if (self.stride > 1) else branch_features,
                  branch_features, kernel_size=1, stride=1, padding=0, bias=False),
        nn.BatchNorm2d(branch_features),
        act_layers(activation),
        self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1),
        nn.BatchNorm2d(branch_features),
        nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
        nn.BatchNorm2d(branch_features),
        act_layers(activation),
    )

    @staticmethod
    def depthwise_conv(i, o, kernel_size, stride=1, padding=0, bias=False):
        return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i)
 
    def forward(self, x):
        if self.stride == 1:
            x1, x2 = x.chunk(2, dim=1)
            out = torch.cat((x1, self.branch2(x2)), dim=1)
        else:
            out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)
 
        out = channel_shuffle(out, 2)
 
        return out
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lindsayshuo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值