简体   繁体   中英

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 . 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:

import numpy as np

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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