Compute element-wise logical AND, OR and NOT of tensors in PyTorch

Compute element-wise logical AND, OR and NOT of tensors in PyTorch

In PyTorch, you can perform element-wise logical operations such as AND, OR, and NOT on tensors. These operations are useful when working with boolean tensors. Let's see how to perform each of these operations:

Step 1: Import PyTorch

First, make sure you have PyTorch installed. If not, you can install it via pip:

pip install torch 

Then, import PyTorch in your Python script:

import torch 

Step 2: Create Sample Tensors

Let's create two boolean tensors for demonstrating the AND and OR operations, and one tensor for the NOT operation:

tensor1 = torch.tensor([True, False, True, False], dtype=torch.bool) tensor2 = torch.tensor([True, True, False, False], dtype=torch.bool) 

Step 3: Perform Logical Operations

Element-wise Logical AND

result_and = tensor1 & tensor2 print("AND:", result_and) 

Element-wise Logical OR

result_or = tensor1 | tensor2 print("OR:", result_or) 

Element-wise Logical NOT

result_not = ~tensor1 print("NOT:", result_not) 

Example

Here's a complete example with the operations:

import torch # Create boolean tensors tensor1 = torch.tensor([True, False, True, False], dtype=torch.bool) tensor2 = torch.tensor([True, True, False, False], dtype=torch.bool) # Element-wise logical AND result_and = tensor1 & tensor2 print("AND:", result_and) # Element-wise logical OR result_or = tensor1 | tensor2 print("OR:", result_or) # Element-wise logical NOT result_not = ~tensor1 print("NOT:", result_not) 

When you run this script, it will output the results of the AND, OR, and NOT operations performed element-wise on the given tensors.

Notes

  • PyTorch performs these logical operations element-wise, which means that it compares corresponding elements in the input tensors.
  • The tensors you perform these operations on should be of boolean type (torch.bool).
  • These operations are useful in a variety of contexts, especially in conditional operations and masking within neural networks.

More Tags

jar http-status-code-400 ts-node sqlanywhere bloburls websphere-7 jquery-callback country dropzone.js trendline

More Programming Guides

Other Guides

More Programming Examples