Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the dot product of sub-arrays in numpy

In numpy, the numpy.dot() function can be used to calculate the matrix product of two 2D arrays. I have two 3D arrays X and Y (say), and I'd like to calculate the matrix Z where Z[i] == numpy.dot(X[i], Y[i]) for all i. Is this possible to do non-iteratively?

like image 684
Ben Kirwin Avatar asked Jun 09 '11 21:06

Ben Kirwin


People also ask

What is a dot product in NumPy?

Dot product of two arrays. Specifically, If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.

What is the dot product of two arrays?

The dot product of two vectors is the sum of the products of elements with regards to position. The first element of the first vector is multiplied by the first element of the second vector and so on. The sum of these products is the dot product which can be done with np.

What is the result of the following operation NP dot NP array ([ 1 1 ]) NP array ([ 1 1 array ([ 0 0 ]) array ([ 1 1 ]) 0?

answer is zero (0).


1 Answers

How about:

from numpy.core.umath_tests import inner1d
Z = inner1d(X,Y)

For example:

X = np.random.normal(size=(10,5))
Y = np.random.normal(size=(10,5))
Z1 = inner1d(X,Y)
Z2 = [np.dot(X[k],Y[k]) for k in range(10)]
print np.allclose(Z1,Z2)

returns True

Edit Correction since I didn't see the 3D part of the question

from numpy.core.umath_tests import matrix_multiply
X = np.random.normal(size=(10,5,3))
Y = np.random.normal(size=(10,3,5))
Z1 = matrix_multiply(X,Y)
Z2 = np.array([np.dot(X[k],Y[k]) for k in range(10)])
np.allclose(Z1,Z2)  # <== returns True

This works because (as the docstring states), matrix_multiplyprovides

matrix_multiply(x1, x2[, out]) matrix

multiplication on last two dimensions

like image 116
JoshAdel Avatar answered Sep 18 '22 11:09

JoshAdel