What is the fastest way to get the dot product of a 3-dimensional matrix and a 2-dimensional matrix in numpy

Viewed 35

I'm trying to get the dot products of two np.ndarrays with one having dimensions of (N, 3, 3) and the other (N, 3). So far I'm using a for loop with np.dot() like such:

import numpy as np

np.random.seed(123)

n = 5

d = np.random.random((n, 3, 3))
e = np.random.random((n, 3))


result = np.zeros([n, d.shape[1]])

for i in range(n):
    result[i] = np.dot(d[i], e[i])

with the expected value of result being a np.ndarray of dimensions (N, 3):

array([[0.53622522, 0.90260462, 1.05042103],
       [0.50197544, 0.31242356, 0.51639033],
       [1.10575827, 1.47185964, 0.98894751],
       [0.43069599, 0.34314713, 0.42894111],
       [1.55451749, 0.9471598 , 1.02151283]])

but it's rather slow, and the "real" code is used to calculate likelihood within some optimization procedure with much larger values of N, so speed is rather important for me here.

0 Answers
Related