如何在 PyTorch 中比较两个张量?
要逐元素地比较 PyTorch 中的两个张量,我们使用 torch.eq() 方法。它比较对应的元素并返回 “True” 如果两个元素相同,则返回 “False” 。我们可以比较具有相同或不同维度的两个张量,但是两个张量的大小必须在非单例维度上匹配。
步骤
-
创建 PyTorch 张量并打印它。
-
计算 torch.eq(input1,input2) 。它返回一个 “True” 和/或 “False” 的张量。它逐元素地比较张量,并在对应元素相等时返回True,否则返回False。
-
打印返回的张量。
示例1
下面的 Python 程序演示了如何逐元素地比较两个1-D张量。
# 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 程序演示了如何逐元素地比较一个1-D张量与一个2-D张量。
# 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]])