.is_nonzero()
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.
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 elementtensor1 = torch.tensor(5.0)# Check if the tensor contains a non-zero elementresult1 = torch.is_nonzero(tensor1)print(result1)# Define a tensor with a zero elementtensor2 = torch.tensor(0.0)# Check if the tensor contains a non-zero elementresult2 = torch.is_nonzero(tensor2)print(result2)
The above code produces the following output:
TrueFalse
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
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Intro to PyTorch and Neural Networks
Learn how to use PyTorch to build, train, and test artificial neural networks in this course.Intermediate3 hours