import torch # create a tensor x = torch.tensor([[0, 2, 0], [4, 0, 1]]) # get the indices of non-zero elements indices = x._indices() print(indices)
tensor([[0, 1, 1], [0, 1, 2]])
import torch # create a tensor x = torch.tensor([[1, 0, 0], [0, 1, 0]]) # get the indices of non-zero elements indices = x._indices() print(indices)
tensor([[0, 1], [1, 2]])This example creates a tensor `x` with two rows and three columns, and then gets the indices of its non-zero elements using the `_indices()` function. The resulting tensor is printed to the screen. Package library: PyTorch.