要检查对象是否为张量,我们可以使用该方法。如果输入是张量,则返回True;否则为假。 torch.is_tensor()
torch.is_tensor(input)
input – 要检查的对象,如果它是张量或不是。
输出结果
如果输入是张量,则返回True;否则为假。
导入所需的库。所需的库是torch。
定义张量或其他对象。
检查创建的对象是否是张量或不使用.torch.is_tensor(input)
显示结果。
# 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
# 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 ("输入对象是一个张量。") else: print ("输入对象不是张量。")输出结果
输入对象不是张量。
在示例 2 中,返回 False,因此输入对象不是张量。torch.is_tensor(x)