Search code examples
pythonpytorchmultiplicationtensor

Multiplication of tensors with different dimensions


Given

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

I want to multiply each row of a with scalar of b,i.e

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

This works just fine. But is there more elegant way of doing this?

Thanks


Solution

  • You want c.shape = (40, 6)? Then, simply:

    c = a * b.unsqueeze(1)
    

    Example with (2, 3) to make it readable:

    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]])