Skip to content

Commit 913853b

Browse files
[Term Entry] PyTorch Tensor Operations: .nonzero()
1 parent 0bf782d commit 913853b

File tree

1 file changed

+55
-0
lines changed
  • content/pytorch/concepts/tensor-operations/terms/nonzero

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
---
2+
Title: '.nonzero()'
3+
Description: 'Returns a tensor containing the indices of non-zero elements in the input tensor.'
4+
Subjects:
5+
- 'AI'
6+
- 'Data Science'
7+
Tags:
8+
- 'AI'
9+
- 'Data Types'
10+
- 'Deep Learning'
11+
- 'Functions'
12+
CatalogContent:
13+
- 'intro-to-py-torch-and-neural-networks'
14+
- 'paths/data-science'
15+
---
16+
17+
In PyTorch, the **`.nonzero()`** function returns a tensor of indices of all non-zero elements in the input [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors). This function is useful for identifying the locations of non-zero values in sparse tensors or when performing operations based on the positions of non-zero elements.
18+
19+
## Syntax
20+
21+
```pseudo
22+
torch.nonzero(input, *, out=None, as_tuple=False)
23+
```
24+
25+
- `input`: The input tensor for which the indices of non-zero elements are to be found.
26+
- `out` (Optional): A tensor to store the result. It must have the appropriate shape to accommodate the output. If not provided, a new tensor will be allocated to store the result.
27+
- `as_tuple` (Optional): If set to `True`, the result will be a tuple of 1-D tensors, each containing the indices for a specific dimension of the input tensor. If set to `False` (default), the result will be a 2-D tensor where each row represents the index of a non-zero element in the input tensor.
28+
29+
## Example
30+
31+
The following example demonstrates the usage of the `.nonzero()` function:
32+
33+
```py
34+
import torch
35+
36+
# Create a tensor
37+
ten = torch.tensor([[1, 0, 3], [0, 5, 6]])
38+
39+
# Get the indices of non-zero elements
40+
indices = torch.nonzero(ten)
41+
42+
# Print the result
43+
print(indices)
44+
```
45+
46+
The above code produces the following output:
47+
48+
```shell
49+
tensor([[0, 0],
50+
[0, 2],
51+
[1, 1],
52+
[1, 2]])
53+
```
54+
55+
In this example, the tensor's non-zero elements are located at indices _(0,0)_, _(0,2)_, _(1,1)_, and _(1,2)_.

0 commit comments

Comments
 (0)