如何比较 PyTorch 中的两个张量?
为了在PyTorch中按元素比较两个张量,我们使用了该方法。它比较相应的元素,并返回“真” 如果两个元素是相同的,否则返回“假”。我们可以比较两个维度相同或不同的张量,但两个张量的大小必须在非单维上匹配。torch.eq()
脚步
导入所需的库。在以下所有Python示例中,所需的Python库是torch。确保您已经安装了它。
创建一个PyTorch张量并打印它。
计算torch.eq(input1,input2)。它返回一个"True"和/或"False"的张量。它按元素比较张量,如果对应元素相等则返回True,否则返回False。
打印返回的张量。
示例1
以下Python程序展示了如何按元素比较两个一维张量。
# import necessary library
import torch
# Create two tensors
T1 = torch.Tensor([2.4,5.4,-3.44,-5.43,43.5])
T2 = torch.Tensor([2.4,5.5,-3.44,-5.43, 43])
# print above created tensors
print("T1:", T1)
print("T2:", T2)
# Compare tensors T1 and T2 element-wise
print(torch.eq(T1, T2))输出结果T1: tensor([ 2.4000, 5.4000, -3.4400, -5.4300, 43.5000]) T2: tensor([ 2.4000, 5.5000, -3.4400, -5.4300, 43.0000]) tensor([ True, False, True, True, False])
示例2
以下Python程序展示了如何按元素比较两个二维张量。
# import necessary library
import torch
# create two 4x3 2D tensors
T1 = torch.Tensor([[2,3,-32],
[43,4,-53],
[4,37,-4],
[3,75,34]])
T2 = torch.Tensor([[2,3,-32],
[4,4,-53],
[4,37,4],
[3,-75,34]])
# print above created tensors
print("T1:", T1)
print("T2:", T2)
# Conpare tensors T1 and T2 element-wise
print(torch.eq(T1, T2))输出结果T1: tensor([[ 2., 3., -32.],
[ 43., 4., -53.],
[ 4., 37., -4.],
[ 3., 75., 34.]])
T2: tensor([[ 2., 3., -32.],
[ 4., 4., -53.],
[ 4., 37., 4.],
[ 3., -75., 34.]])
tensor([[ True, True, True],
[False, True, True],
[ True, True, False],
[ True, False, True]])示例3
以下Python程序展示了如何按元素比较一维张量和二维张量。
# import necessary library
import torch
# Create two tensors
T1 = torch.Tensor([2.4,5.4,-3.44,-5.43,43.5])
T2 = torch.Tensor([[2.4,5.5,-3.44,-5.43, 7],
[1.0,5.4,3.88,4.0,5.78]])
# Print above created tensors
print("T1:", T1)
print("T2:", T2)
# Compare the tensors T1 and T2 element-wise
print(torch.eq(T1, T2))输出结果T1: tensor([ 2.4000, 5.4000, -3.4400, -5.4300, 43.5000])
T2: tensor([[ 2.4000, 5.5000, -3.4400, -5.4300, 7.0000],
[ 1.0000, 5.4000, 3.8800, 4.0000, 5.7800]])
tensor([[ True, False, True, True, False],
[False, True, False, False, False]])