Matrix multiplication with numpy.einsum

I have the following two arrays with a shape:

    A = (d,w,l)
    B = (d,q)

      

And I want to combine them into a 3d array with a shape:

    C = (q,w,l)

      

To be more specific, in my case d (depth of 3d array) is 2, and I would first like to multiply all positions from w * l in the top layer A (so d = 0) with the first B value in the highest row ( so d = 0, q = 0). For d = 1, I do the same and then add the two like so:

    C_{q=0,w,l} = A_{d=0,w,l}*B_{d=0,q=0} + A_{d=1,w,l}*B_{d=1,q=0}

      

I wanted to compute C using numpy.einsum. I thought about the following code:

    A = np.arange(100).reshape(2,10,5)

    B = np.arange(18).reshape(2,9)

    C = np.einsum('ijk,i -> mjk',A,B)

      

Where ijk refers to 2,10,5 and mjk refers to 9,10,5. However, I am getting an error. Is there a way to accomplish this multiplication with numpy einsum?

thank

+3


source to share


1 answer


Your shapes A = (d,w,l), B = (d,q), C = (q,w,l)

practically write an expressioneinsum

C=np.einsum('dwl,dq->qwl',A,B)

      



which I can check with

In [457]: np.allclose(A[0,:,:]*B[0,0]+A[1,:,:]*B[1,0],C[0,:,:])
Out[457]: True

      

+4


source







All Articles