【问题标题】:Batch dot product with numpy?用numpy批量点积?
【发布时间】:2019-10-31 14:33:11
【问题描述】:

我需要用一个向量得到多个向量的点积。示例代码:

a = np.array([0, 1, 2])

b = np.array([
    [0, 1, 2],
    [4, 5, 6],
    [-1, 0, 1],
    [-3, -2, 1]
])

我想得到b 的每一行与a 的点积。我可以迭代:

result = []
for row in b:
    result.append(np.dot(row, a))

print(result)

给出:

[5, 17, 2, 0]

如何在不迭代的情况下获得它?谢谢!

【问题讨论】:

    标签: python numpy tensordot


    【解决方案1】:

    使用numpy.dotnumpy.matmul 而不使用for 循环:

    import numpy as np
    
    np.matmul(b, a)
    # or
    np.dot(b, a)
    

    输出:

    array([ 5, 17,  2,  0])
    

    【讨论】:

    • 哇,不知道我是如何忽略了这个解决方案的。谢谢!
    【解决方案2】:

    我只会做@

    b@a
    Out[108]: array([ 5, 17,  2,  0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-17
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      相关资源
      最近更新 更多