首页 文章资讯内容详情

如何检查对象是否是 PyTorch 张量?

2026-06-02 1 花语

要检查对象是否为张量,我们可以使用该方法。如果输入是张量,则返回True;否则为torch.is_tensor()

语法

torch.is_tensor(input)

参数

input–要检查的对象,如果它是张量或不是。

输出结果

如果输入是张量,则返回True;否则为

脚步

导入所需的库。所需的库是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 ("输入对象是一个张量。") else: print ("输入对象不是张量。")输出结果输入对象不是张量。

在示例2中,返回False,因此输入对象不是张量。torch.is_tensor(x)