简体   繁体   English

用numpy批处理点产品?

[英]Batch dot product with numpy?

I need to get the dot product of many vectors with one vector. 我需要用一个向量获得许多向量的点积。 Example code: 示例代码:

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

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

I would like to get the dot product of each row of b against a . 我想得到b的每一行相对于a的点积。 I can iterate: 我可以迭代:

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

print(result)

which gives: 这使:

[5, 17, 2, 0]

How can I get this without iterating? 我如何不进行迭代就得到它? Thanks! 谢谢!

I will just do @ 我会做@

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

Use numpy.dot or numpy.matmul without for loop: 使用不带for循环的numpy.dotnumpy.matmul

import numpy as np

np.matmul(b, a)
# or
np.dot(b, a)

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM