Hello Trinh!



 l4zyf9x:

Hi all, I have tensor 2D data.size=[4,8]. For each row in data, i want create a mask from begin_index to end_index, eg:
pair_index = torch.LongTensor([[0,2],[2,7],[1,3],[0,5]])
tensor([[0, 2],
        [2, 7],
        [1, 3],
        [0, 5]])

So my expected mask output will be:
tensor([[1, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 1, 1, 1, 1, 0],
        [0, 1, 1, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 0, 0, 0]])



There might be a cleaner way, but here’s the best I could do:
import torch
print (torch.__version__)
pair_index = torch.LongTensor([[0,2],[2,7],[1,3],[0,5]])
cols = torch.LongTensor (range (8)).repeat (4, 1)
beg = pair_index[:,0].unsqueeze (1).repeat (1, 8)
end = pair_index[:,1].unsqueeze (1).repeat (1, 8)
mask = cols.ge (beg) & cols.lt (end)
print (mask)

Here’s the output:
>>> import torch
>>> print (torch.__version__)
0.3.0b0+591e73e
>>> pair_index = torch.LongTensor([[0,2],[2,7],[1,3],[0,5]])
>>> cols = torch.LongTensor (range (8)).repeat (4, 1)
>>> beg = pair_index[:,0].unsqueeze (1).repeat (1, 8)
>>> end = pair_index[:,1].unsqueeze (1).repeat (1, 8)
>>> mask = cols.ge (beg) & cols.lt (end)
>>> print (mask)

    1     1     0     0     0     0     0     0
    0     0     1     1     1     1     1     0
    0     1     1     0     0     0     0     0
    1     1     1     1     1     0     0     0
[torch.ByteTensor of size 4x8]

(It’s easy and straightforward to do this with a loop, but I always
assume these questions are about using tensor operations and
avoiding loops.)
Good luck.
K. Frank