Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Matrix Multiplication Broadcast

I have an array comprised of N 3x3 arrays (a collection of matrices, although the data type is np.ndarray) and I have an array comprised of N 3x1 arrays (a collection of vectors). What I want to do is multiply each matrix by each vector, so I expect to get back N 3x1 arrays.

Simple example:

A = np.ones((6,3,3))
B = np.ones((6,3,1))
np.dot(A,B) # This gives me a 6x3x6x1 array, which is not what I want
np.array(map(np.dot,A,B)) # This gives me exactly what I want, but I don't want to have to rely on map

I've tired all kinds of reshaping, explored einsum, etc., but can't get this to work the way I want it to. How do I get this to work with numpy broadcasting? This operation will ultimately need to be done many thousands of times, and I don't want map or list comprehension operations to slow things down.

like image 417
hobscrk777 Avatar asked Nov 10 '14 17:11

hobscrk777


People also ask

What is broadcasting in matrix multiplication?

The term broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.

Does NumPy have broadcast?

The term broadcasting refers to how numpy treats arrays with different Dimension during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes.

When broadcasting an operation in NumPy which dimensions get broadcast first?

NumPy broadcasting typically matches dimensions from the last dimension, so usual broadcasting will not work (it would require the first array to have dimension (y,z) ). Background: I'm working with images, some of which are RGB (shape (h,w,3) ) and some of which are grayscale (shape (h,w) ).


1 Answers

You can use np.einsum to calculate the dot products and create the matrix of the desired shape:

np.einsum('ijk,ikl->ijl', A, B)
like image 184
Alex Riley Avatar answered Sep 22 '22 08:09

Alex Riley