Logical XOR in PyTorch
PyTorch is an open-source framework available with a Python programming language. We can process the data in PyTorch in the form of a Tensor.
A tensor is a multidimensional array that is used to store the data. So for using a Tensor, we have to import the torch module.
To create a tensor, the method used is tensor()”
Syntax:
Where data is a multi-dimensional array.
torch.logical_xor()
torch.logical_xor() in PyTorch is performed on two tensor objects. It will perform element-wise comparison and return True if both the elements are different and return False if both the elements are the same. It takes two tensors as parameters.
Syntax:
Parameters:
1. tensor_object1 is the first tensor
2. tensor_object2 is the second tensor
Example 1
In this example, we will create two one-dimensional tensors – data1 and data2 with 5 boolean values each and perform logical_xor().
import torch
#create a 1D tensor - data1 with 5 boolean values
data1 = torch.tensor([False,True, True, True,False])
#create a 1D tensor - data2 with 5 boolean values
data2 = torch.tensor([False,False, True, False,True])
#display
print("First Tensor: ",data1)
print("Second Tensor: ",data2)
#logical_xor on data1 and data2
print("Logical XOR on above two tensors: ",torch.logical_xor(data1,data2))
Output:
Second Tensor: tensor([False, False, True, False, True])
Logical XOR on above two tensors: tensor([False, True, False, True, True])
Working:
1. logical_xor(False ,False) – False
2. logical_xor(True , False) – True
3. logical_xor(True , True) – False
4. logical_xor(True , False) – True
5. logical_xor(False , True) – True
Example 2
In this example, we will create two-dimensional tensors – data1 and data2 with 5 boolean values each in a row and perform logical_xor().
import torch
#create a 2D tensor - data1 with 5 boolean values in each row
data1 = torch.tensor([[False,True, True, True,False],[False,True, True, True,False]])
#create a 2D tensor - data2 with 5 boolean values in each row
data2 = torch.tensor([[False,False, True, False,True],[False,False, True, False,True]])
#display
print("First Tensor: ",data1)
print("Second Tensor: ",data2)
#logical_xor on data1 and data2
print("Logical XOR on above two tensors: ",torch.logical_xor(data1,data2))
Output:
[False, True, True, True, False]])
Second Tensor: tensor([[False, False, True, False, True],
[False, False, True, False, True]])
Logical XOR on above two tensors: tensor([[False, True, False, True, True],[False, True, False, True, True]])
Conclusion
In this PyTorch lesson, we discussed how to perform logical XOR operation with a torch.logical_xor() method. It will perform an element-wise comparison and return True if both the elements are different and return False if both the elements are the same
Source: linuxhint.com