不同维度的张量相乘

Multiplication of tensors with different dimensions

给出

a = torch.randn(40, 6)
b = torch.randn(40)

我想将 a 的每一行乘以 b 的标量,即

c0 = a[0]*b[0]
c1 = a[1]*b[1]
...

这很好用。但是有没有更优雅的方式来做到这一点?

谢谢

你想要c.shape = (40, 6)?然后,简单地:

c = a * b.unsqueeze(1)

示例 (2, 3) 以使其可读:

import torch

torch.manual_seed(2021)

a = torch.randn(2, 3)
# > tensor([[ 2.2871,  0.6413, -0.8615],
# >         [-0.3649, -0.6931,  0.9023]])

b = torch.randn(2)
# > tensor([-2.7183, -1.4478])

c = a * b.unsqueeze(1)
# > tensor([[-6.2169, -1.7434,  2.3418],
# >         [ 0.5284,  1.0035, -1.3064]])