如何檢查物件是否是 PyTorch 張量?
要檢查物件是否為張量,我們可以使用torch.is_tensor()方法。如果輸入是張量則返回 **True**;否則返回** False**。
語法
torch.is_tensor(input)
引數
input – 要檢查的物件,即它是否是一個張量。
輸出
如果輸入是張量則返回 True;否則返回 False。
步驟
匯入所需的庫。所需的庫是torch。
定義一個張量或其他物件。
使用 torch.is_tensor(input) 檢查建立的物件是否是張量。
顯示結果。
示例 1
# import the required library import torch # create an object x x = torch.rand(4) print(x) # check if the above created object is a tensor print(torch.is_tensor(x))
輸出
tensor([0.9270, 0.2194, 0.2078, 0.5716]) True
示例 2
# import the required library import torch # define an object x x = 4 # check if the above created object is a tensor if torch.is_tensor(x): print ("The input object is a Tensor.") else: print ("The input object is not a Tensor.")
輸出
The input object is not a Tensor.
在示例 2 中,torch.is_tensor(x) 返回 False,因此輸入物件不是張量。
廣告