报错:RuntimeError: view size is not compatible with input tensor‘s size and stride

报错:RuntimeError: view size is not compatible with input tensor‘s size and stride

def attention_net(self, lstm_output, final_state):
        batch_size = lstm_output.size(0)
        hidden = final_state.view(batch_size, -1, 1)
        
        attn_weights = torch.bmm(lstm_output, hidden).squeeze(2)
        soft_attn_weights = F.softmax(attn_weights, 1)
        context = torch.bmm(lstm_output.transpose(1, 2), soft_attn_weights.unsqueeze(2)).squeeze(2)
        print(context.shape)
        print(soft_attn_weights.shape)
        return context, soft_attn_weights 

python报错:RuntimeError: view size is not compatible with input tensor‘s size and stride

这是因为view()需要Tensor中的元素地址是连续的,但可能出现Tensor不连续的情况,所以先用 .contiguous() 将其在内存中变成连续分布,改为:

hidden = final_state.contiguous().view(batch_size, -1, 1)

这样就能成功运行了;

关于连续性的解释:
多维张量在内存中存储是线性数组,而怎么去解读它,就需要自己定义shape,比如对于a[6]数组,可以解释为两行三列(2,3)或者三行两列(3,2)。而这里的索引和在内存中的线性数组的一一对应关系要符合一定的规则,符合就是连续的,不符合就不是,就得需要调用contiguous。而在训练网络中,并不需要理解背后的机理,这属于张量计算框架的内容,想要进一步了解的可以参考Github上的miniTorch教程。

参考文章:https://blog.csdn.net/tiao_god/article/details/108189879

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值