PyTorch – 如何檢測張量是否連續?


連續張量是一種元素以連續順序儲存的張量,它們之間不會留有任何空白。最初建立的張量始終是連續張量。張量可以用不同的維度以連續的方式檢視。

轉置張量會建立一個遵循非連續順序的原始張量檢視。張量轉置是非連續的。

語法

Tensor.is_contiguous()

如果張量連續,則返回True;否則返回False

讓我們舉幾個例子來說明如何使用此函式來檢查張量是否連續或不連續。

示例 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

更新日期:2021 年 12 月 6 日

2K+ 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.