PyTorch .logical_or()
The .logical_or() function performs an element-wise logical OR operation between two tensors. Each input value is converted to a Boolean value (zero → False, non-zero → True) before the operation. The output is a Boolean tensor where each element is True if at least one of the corresponding input elements is True.
Syntax
torch.logical_or(input, other, out)
Parameters:
input: A tensor whose elements are treated as Boolean.other: A tensor broadcastable with input.out(optional): A tensor to store the result.
Return value:
Returns a Boolean tensor where each element is True if at least one of the corresponding input elements is True.
Example 1
In this example, .logical_or() evaluates pairs of values from two 2-D tensors and returns a Boolean matrix showing which positions satisfy the OR condition:
import torcha = torch.tensor([[0, 1], [2, 0]])b = torch.tensor([[3, 0], [0, 5]])result = torch.logical_or(a, b)print("Tensor A:\n", a)print("\nTensor B:\n", b)print("\nA OR B:\n", result)
The output of this code is:
Tensor A:tensor([[0, 1],[2, 0]])Tensor B:tensor([[3, 0],[0, 5]])A OR B:tensor([[True, True],[True, True]])
Example 2
In this example, a 1-D tensor is combined with a scalar using broadcasting to show how .logical_or() can apply a Boolean condition efficiently across all elements:
import torchx = torch.tensor([0, 4, 0, 7])y = torch.tensor(1) # scalarresult = torch.logical_or(x, y)print(result)
The output of this code is:
tensor([True, True, True, True])
Frequently Asked Questions
1. What are the tensor operations in PyTorch?
Tensor operations in PyTorch include arithmetic, logical operations, reductions, reshaping, indexing, broadcasting, and matrix operations. These operations run efficiently on CPU or GPU and form the core building blocks of neural network workflows.
2. Why use tensor instead of NumPy?
Tensors support automatic differentiation and execute seamlessly on GPUs, which makes them suited for deep learning workloads. They also integrate tightly with PyTorch’s computation graph, while NumPy arrays operate only on the CPU and lack gradient support.
3. What does cpu() do in PyTorch?
The .cpu() method moves a tensor or model from a GPU device to the system’s CPU. This is useful for running operations on hardware without CUDA support or preparing data for libraries that operate only on CPU-based arrays.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours