PyTorch torch.Tensor.contiguous() 用法与理解

中文文档:

contiguous() → Tensor
        返回一个内存连续的有相同数据的 tensor,如果原 tensor 内存连续则返回原 tensor

英文文档:

contiguous() → Tensor
        Returns a contiguous tensor containing the same data as self tensor. If self tensor is contiguous, this function returns the self tensor.

常见用法:

contiguous 一般用于 transpose/permute 后和 view 前,即使用 transpose 或 permute 进行维度变换后,调用 contiguous,然后方可使用 view 对维度进行变形(如:tensor_var.contiguous().view() ),示例如下:

x = torch.Tensor(2,3)
y = x.permute(1,0)         # permute:二维tensor的维度变换,此处功能相当于转置transpose
y.view(-1)                 # 报错,view使用前需调用contiguous()函数
y = x.permute(1,0).contiguous()
y.view(-1)                 # OK
两个可能原因
  1. view 函数只能用于 contiguous 后的 tensor 上,也就是只能用于内存中连续存储的 tensor。如果对 tensor 调用过 transpose, permute 等操作的话会使该 tensor 在内存中变得不再连续,此时就不能再调用 view 函数。因此,需要先使用 contiguous 来返回一个 contiguous copy。
  2. 维度变换后的变量是之前变量的浅拷贝,指向同一区域,即 view 操作会连带原来的变量一同变形,这是不合法的,所以也会报错。(这个解释有部分道理,也即 contiguous 返回了 tensor 的深拷贝 contiguous copy 数据)
参考文章
  1. https://zhuanlan.zhihu.com/p/64376950
  2. https://blog.csdn.net/qq_37385726/article/details/81738518
  • 12
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值