One liner tensor with conditions

Viewed 44

I have two tensors:

a = torch.nn.Parameter(torch.rand(7, requires_grad=True))
b = torch.randint(0,60, (20,))

Is there a one liner (or a quick & short way) that can create a tensor (call it x) of size 20 (similar to "b") with conditions?
i.e.

[b<4 use a[0], 4 <=b<12 use a[1], 12<=b<22 use a[2], <28, <38, <50, >50] for every b

So if:

b = [12, 93, 54, 0...]

I want my new tensor "x" to be:

x = [a[2],a[6], a[6]...]

I'm going to use this "x" tensor to train and need the values the be backproped and learnable

i.e.

loss = torch.rand(20) * x

loss.backward() ...

So if one of the a's is not in x I want it to not change.

1 Answers

You can sum multiplicative masks of the conditions:

x = a[0]*(b<4) + a[1]*((4<=b)&(b<12)) + a[2]*((12<=b)&(b<22)) + a[3]*((22<=b)&(b<28)) + a[4]*((28<=b)&(b<30)) + a[5]*((30<=b)&(b<50)) + a[6]*(b>=50)
Related