PyTorch .is_nonzero()

raghavtandulkar's avatar
Published Feb 13, 2025
Contribute to Docs

In PyTorch, the .is_nonzero() function is used to check if a scalar tensor contains a non-zero element. It returns True if the tensor’s element is non-zero and False if it is zero. This method is particularly useful for conditional checks or validation in tensor operations.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
    • Intermediate.
      3 hours

Syntax

torch.is_nonzero(input)
  • input: Tensor with a single element.

Example

This code demonstrates how PyTorch’s .is_nonzero() function checks whether a tensor contains a non-zero value:

import torch
# Define a tensor with a non-zero element
tensor1 = torch.tensor(5.0)
# Check if the tensor contains a non-zero element
result1 = torch.is_nonzero(tensor1)
print(result1)
# Define a tensor with a zero element
tensor2 = torch.tensor(0.0)
# Check if the tensor contains a non-zero element
result2 = torch.is_nonzero(tensor2)
print(result2)

The above code produces the following output:

True
False

All contributors

Contribute to Docs

Learn PyTorch on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
    • Intermediate.
      3 hours