pytorch中tensor常用is_contiguous含义

is_contiguous

根据名字就可以知道判断是否连续相邻, pytorch中不管任意维度的张量底层都是一维tensor,只是取决于你怎么读,因此每个tensor中标量都是连续的。如果我们将矩阵进行转置操作,则会导致tensor标量都不连续了,调用is_contiguous就会False,而False则无法调用view来改变tensor维度, 只能使用reshape。

代码演示

import torch

a = [[1,2,3], [4,5,6], [7,8,9]]
a = torch.tensor(a)

'''
tensor([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])
'''
a = a.t()
'''
tensor([[1, 4, 7],
        [2, 5, 8],
        [3, 6, 9]])
'''


print(a.is_contiguous())
# False
a = a.contiguous()
print(a.is_contiguous())
# True

猜你喜欢

转载自blog.csdn.net/weixin_45074568/article/details/126748659