PyTorch – 如何检查张量是否连续?

连续张量是一种张量,其元素以连续的顺序存储,它们之间不留任何空白。最初创建的张量始终是连续的张量。可以以连续的方式查看具有不同维度的张量。

张量的转置创建遵循非连续顺序的原始张量的视图。张量的转置是不连续的。

语法

Tensor.is_contiguous()

如果张量是连续的,则返回True;否则为

让我们举几个例子来演示如何使用这个函数来检查张量是连续的还是不连续的。

示例 1

# import torch library
import torch

# define a torch tensor
A = torch.tensor([1. ,2. ,3. ,4. ,5. ,6.])
print(A)

# find a view of the above tensor
B = A.view(-1,3)
print(B)

print("id(A):", id(A))
print("id(A.view):", id(A.view(-1,3)))
# check if A or A.view() are contiguous or not
print(A.is_contiguous()) # True
print(A.view(-1,3).is_contiguous()) # True
print(B.is_contiguous()) # True
输出结果
tensor([1., 2., 3., 4., 5., 6.])
tensor([[1., 2., 3.],
   [4., 5., 6.]])
id(A): 80673600
id(A.view): 63219712
True
True
True

示例 2

# import torch library
import torch

# create a torch tensor
A = torch.tensor([[1.,2.],[3.,4.],[5.,6.]])
print(A)

# take transpose of the above tensor
B = A.transpose(0,1)
print(B)
print("id(A):", id(A))
print("id(A.transpose):", id(A.transpose(0,1)))

# check if A or A transpose are contiguous or not
print(A.is_contiguous()) # True
print(A.transpose(0,1).is_contiguous()) # False
print(B.is_contiguous()) # False
输出结果
tensor([[1., 2.],
   [3., 4.],
   [5., 6.]])
tensor([[1., 3., 5.],
   [2., 4., 6.]])
id(A): 63218368
id(A.transpose): 99215808
True
False
False