RuntimeError: Input type (torch.cuda.HalfTensor) and weight type (torch.FloatTensor)

将卷积运算放到初始化中,与模型初始化一块加载到cuda
原来代码:

class layer(nn.Module):
    '''
    x: input features with shape [N,C,H,W]
    gamma, b: parameters of mapping function
    '''
    def __init__(self):
        super(layer, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x, gamma=2, b=1):
        n,channel,h,w = x.size()
        t = int(abs((math.log(channel, 2) + b) / gamma))
        k = t if t % 2 else t + 1
        conv = nn.Conv1d(1, 1, kernel_size=k, padding=int(k/2), bias=False)

        y = self.avg_pool(x)
        y = conv(y.squeeze(-1).transpose(-1, -2))
        y = y.transpose(-1, -2).unsqueeze(-1)
        y = self.sigmoid(y)
        return x * y.expand_as(x)

修改后:

class layer(nn.Module):
    '''
    x: input features with shape [N,C,H,W]
    gamma, b: parameters of mapping function
    '''
    def __init__(self, channel, gamma=2, b=1):
        super(layer, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        t = int(abs((math.log(channel, 2) + b) / gamma))
        k = t if t % 2 else t + 1
        self.conv = nn.Conv1d(1, 1, kernel_size=k, padding=int(k/2), bias=False)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):

        y = self.avg_pool(x)
        y = self.conv(y.squeeze(-1).transpose(-1, -2))
        y = y.transpose(-1, -2).unsqueeze(-1)
        y = self.sigmoid(y)
        return x * y.expand_as(x)
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值