NadiaMe
October 21, 2020, 4:35pm
#1
If I have a 3d tensor of size
`T1 --> torch.Size([196, 14, 14])`

and a 1d tensor of size
`T2 --> torch.Size([196])`

How do I multiply matrices of size` [14, 14]`

in `T1`

by the corresponding scalar in `T2`

?

e.g if `T2[0] == 3,`

then the first multiplication would be
`T1[0] * 3`

, etc.

So the output should be with the original shape of `T1`

.

Nikronic
(Nikan Doosti)
October 21, 2020, 4:55pm
#2
Hi,

You just need to change the view of second tensor to match shapes in corresponding dimension, then PyTorch’s tensor broadcasting will take care of that. e.g.

```
t1 = torch.arange(0, 196*14*14).view((196, 14, 14)) # shape (196, 14, 14)
t2 = torch.arange(196).view(-1, 1, 1) # shape (196, 1, 1)
result = t1*t2
```

Bests

1 Like