如何比较 PyTorch 中的两个张量?
在本文中,我们将了解如何在 Pytorch 中比较两个张量。
我们可以使用 torch.eq() 方法比较两个张量。该方法比较张量的对应元素。它必须在两个张量具有相等值的每个位置返回 rue,否则它将返回 false。
torch.eq()函数:
Syntax: torch.eq( First_tensor, Second_tensor, out=None )
Parameters: torch.eq() accept tensors that are we want to compare as parameters.
Return: It return a boolean value. true if tensors are equals else it will return false.
示例 1:
在此示例中,我们使用Python编程语言中的 torch.eq()函数比较两个一维张量。
Python3
# import library
import torch
# Create first tensor
first = torch.Tensor([4.4, 2.4, -9.1,
-5.31, 5.3])
# Create second tensor
second = torch.Tensor([4.4, 5.5, -9.1,
-5.31, 43])
# print first tensors
print("First Tensor:", first)
# print first tensors
print("Second Tensor:", second)
# Compare element wise tensors
# first and second
print(torch.eq(first, second))
Python3
# import library
import torch
# create two 2D tensors
first = torch.Tensor([[7, -2, 3],
[29, 9, -5],
[2, -8, 34],
[24, 62, 98]])
second = torch.Tensor([[7, -5, 3],
[26, 9, -4],
[3, -8, 43],
[23, -62, 98]])
# print first tensors
print("First Tensor:", first)
# print second tensors
print("Second Tensor:\n", second)
print("After Comparing Both Tensors")
# Compare element wise tensors first
# and second
print(torch.eq(first, second))
输出:
示例 2:
在这个例子中,我们使用 torch.eq()函数比较 2D 张量 PyTorch。
Python3
# import library
import torch
# create two 2D tensors
first = torch.Tensor([[7, -2, 3],
[29, 9, -5],
[2, -8, 34],
[24, 62, 98]])
second = torch.Tensor([[7, -5, 3],
[26, 9, -4],
[3, -8, 43],
[23, -62, 98]])
# print first tensors
print("First Tensor:", first)
# print second tensors
print("Second Tensor:\n", second)
print("After Comparing Both Tensors")
# Compare element wise tensors first
# and second
print(torch.eq(first, second))
输出: