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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP