Rate this Page

torch.nonzero#

torch.nonzero(input,*,out=None,as_tuple=False)LongTensorortupleofLongTensors#

Note

torch.nonzero(...,as_tuple=False) (default) returns a2-D tensor where each row is the index for a nonzero value.

torch.nonzero(...,as_tuple=True) returns a tuple of 1-Dindex tensors, allowing for advanced indexing, sox[x.nonzero(as_tuple=True)]gives all nonzero values of tensorx. Of the returned tuple, each index tensorcontains nonzero indices for a certain dimension.

See below for more details on the two behaviors.

Wheninput is on CUDA,torch.nonzero() causeshost-device synchronization.

Whenas_tupleisFalse(default):

Returns a tensor containing the indices of all non-zero elements ofinput. Each row in the result contains the indices of a non-zeroelement ininput. The result is sorted lexicographically, withthe last index changing the fastest (C-style).

Ifinput hasnn dimensions, then the resulting indices tensorout is of size(z×n)(z \times n), wherezz is the total number ofnon-zero elements in theinput tensor.

Whenas_tupleisTrue:

Returns a tuple of 1-D tensors, one for each dimension ininput,each containing the indices (in that dimension) of all non-zero elements ofinput .

Ifinput hasnn dimensions, then the resulting tuple containsnntensors of sizezz, wherezz is the total number ofnon-zero elements in theinput tensor.

As a special case, wheninput has zero dimensions and a nonzero scalarvalue, it is treated as a one-dimensional tensor with one element.

Parameters:

input (Tensor) – the input tensor.

Keyword Arguments:

out (LongTensor,optional) – the output tensor containing indices

Returns:

Ifas_tuple isFalse, the outputtensor containing indices. Ifas_tuple isTrue, one 1-D tensor foreach dimension, containing the indices of each nonzero element along thatdimension.

Return type:

LongTensor ortuple of LongTensor

Example:

>>>torch.nonzero(torch.tensor([1,1,1,0,1]))tensor([[ 0],        [ 1],        [ 2],        [ 4]])>>>torch.nonzero(torch.tensor([[0.6,0.0,0.0,0.0],...[0.0,0.4,0.0,0.0],...[0.0,0.0,1.2,0.0],...[0.0,0.0,0.0,-0.4]]))tensor([[ 0,  0],        [ 1,  1],        [ 2,  2],        [ 3,  3]])>>>torch.nonzero(torch.tensor([1,1,1,0,1]),as_tuple=True)(tensor([0, 1, 2, 4]),)>>>torch.nonzero(torch.tensor([[0.6,0.0,0.0,0.0],...[0.0,0.4,0.0,0.0],...[0.0,0.0,1.2,0.0],...[0.0,0.0,0.0,-0.4]]),as_tuple=True)(tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3]))>>>torch.nonzero(torch.tensor(5),as_tuple=True)(tensor([0]),)