1

Given the below tensor that has vectors of all zeros and vectors with ones and zeros:

tensor([[0., 0., 0., 0.],
    [0., 1., 1., 0.],
    [0., 0., 0., 0.],
    [0., 0., 1., 0.],
    [0., 0., 0., 0.],
    [0., 0., 1., 0.],
    [1., 0., 0., 1.],
    [0., 0., 0., 0.],...])

How can I have an array of indices of the vectors with ones and zeros so the output is like this:

indices = tensor([ 1, 3, 5, 6,...])

Update

A way to do it is:

indices = torch.unique(torch.nonzero(y>0,as_tuple=True)[0])

But I'm not sure if there's a better way to do it.

1 Answer 1

2

An alternative way is to use torch.Tensor.any coupled with torch.Tensor.nonzero:

>>> x.any(1).nonzero()[:,0]
tensor([1, 3, 5, 6])

Otherwise, since the tensor contains only positive value, you can sum the columns and mask:

>>> x.sum(1).nonzero()[:,0]
tensor([1, 3, 5, 6])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.