【问题标题】:Multiplication of tensors with different dimensions不同维度张量的乘法
【发布时间】:2021-08-31 15:23:07
【问题描述】:

给定

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

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

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

这很好用。但是有没有更优雅的方法呢?

谢谢

【问题讨论】:

    标签: python pytorch multiplication tensor


    【解决方案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]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-05
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 2022-01-05
      • 2017-09-22
      • 2022-01-22
      相关资源
      最近更新 更多