[Python] Invert PyTorch Indexing

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose, I have a PyTorch tensor a of shape ba,c,h,w and wish to zero out some rows of a with indices given in another tensor b of shape ba,2 of dtype=torch.int16 and b[batch, 0] <= b[batch, 1].

    The for loop way of doing is:

    for batch in range(ba):
    a[batch,:,0:b[batch,0],:] = 0 # stmnt 1
    a[batch,:,b[batch,1]:,:] = 0 # stmnt 2


    Is there a faster PyTorch way to do this?

    Specifically, firstly by combining stmnt1 and stmnt2 into a single line to tell PyTorch make all rows of a except a[batch,:,b[batch,0]:b[batch,1],:] zero. And secondly, if this can be done without needing to iterate over each batch using a for loop.

    Continue reading...

Compartilhe esta Página