torch.Tensor.Tensor.nonzero
Returns indices of all non-zero elements.
Finds all indices where tensor values are non-zero and returns them as a tensor. Output shape is (num_nonzero, ndim) where num_nonzero is the count of non-zero elements. Useful for sparse tensor operations and conditional indexing.
Use Cases:
- Extracting sparse tensor coordinates
- Finding active elements in feature maps
- Conditional indexing and masking
- Sparse matrix operations
- Data validation and cleanup
- Output shape: Always (num_nonzero, ndim) regardless of input shape
- Sparse format: Result can be used as sparse tensor coordinates
- Row-major order: Indices follow row-major (C-style) ordering
- Dynamic count: Number of rows depends on sparsity (unknown at compile time)
Returns
Promise<Tensor | Tensor[]>– Tensor of shape (num_nonzero, ndim) containing indices of non-zero elementsExamples
// Find indices of non-zero elements
const x = torch.tensor([[0, 1, 0], [2, 0, 3]]);
const indices = x.nonzero();
// Result shape (3, 2): [[0, 1], [1, 0], [1, 2]]
// Extract values using indices
const values = [];
for (let i = 0; i < indices.shape[0]; i++) {
const idx = indices.slice([i, 0], [i+1, 2]);
values.push(x.at(...idx.toArray()));
}
// Sparse matrix representation
const matrix = torch.randn([1000, 1000]).mul(0.01); // Mostly zero
const coordinates = matrix.nonzero();
console.log(`Non-zero count: ${coordinates.shape[0]}`);
// Boolean mask equivalent
const mask = x.ne(0);
// mask.nonzero() gives same coordinates as x.nonzero()See Also
- PyTorch torch.nonzero()
- argwhere - Async version with exact shape (returns Promise)
- ne - Boolean mask of non-zero elements
- masked_select - Extract values matching a boolean mask
- where - Conditional element selection