如何检查对象是否是 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,因此输入对象不是张量。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP