Why I can't change value of tensor with this way?

Hi I have a question about change the tensor value.

If I change the value of tensor this way, works well.

a=torch.zeros(5,3,2)
b=torch.Tensor([True,False,True,False,True]).bool()
a[b]=2 #shape 3,3,2
print(a)
###tensor([[[2., 2.],
         [2., 2.],
         [2., 2.]],

        [[0., 0.],
         [0., 0.],
         [0., 0.]],

        [[2., 2.],
         [2., 2.],
         [2., 2.]],

        [[0., 0.],
         [0., 0.],
         [0., 0.]],

        [[2., 2.],
         [2., 2.],
         [2., 2.]]])

However,why I cant change the value of tensor in this way?

a=torch.zeros(5,3,2)
b=torch.Tensor([True,False,True,False,True]).bool()
a[b][:,2,:]=2
print(a)
###
tensor([[[0., 0.],
         [0., 0.],
         [0., 0.]],

        [[0., 0.],
         [0., 0.],
         [0., 0.]],

        [[0., 0.],
         [0., 0.],
         [0., 0.]],

        [[0., 0.],
         [0., 0.],
         [0., 0.]],

        [[0., 0.],
         [0., 0.],
         [0., 0.]]])

My desired output is

Tensor([[[0., 0.],
         [0., 0.],
         [2., 2.]],

        [[0., 0.],
         [0., 0.],
         [2., 2.]],

        [[0., 0.],
         [0., 0.],
         [2., 2.]],

        [[0., 0.],
         [0., 0.],
         [2., 2.]],

        [[0., 0.],
         [0., 0.],
         [2., 2.]]])

Thanks in advance.

Hi, if you do a[b], the b will only indicate a’s first dimension.
So if you want to change the last rows of batch 0, 2, 4 of a, what you want to do is:
a[b, 2, :] = 2.

On the other hand, if you want to make it to your desired output,
you don’t have to use b and just have to do a[:, 2, :] = 2.

1 Like

Sorry to miswrite desired output. I want.

Tensor([[[0., 0.],
         [0., 0.],
         [2., 2.]],

        [[0., 0.],
         [0., 0.],
         [0., 0.]],

        [[0., 0.],
         [0., 0.],
         [2., 2.]],

        [[0., 0.],
         [0., 0.],
         [0., 0.]],

        [[0., 0.],
         [0., 0.],
         [2., 2.]]])

Thanks for kind explanation!

1 Like