pythonnumpy

How to express the dot product of 3 dimensions arrays with numpy?


How do I do the following dot product in 3 dimensions with numpy?

enter image description here

I tried:

x = np.array([[[-1, 2, -4]], [[-1, 2, -4]]])
W = np.array([[[2, -4, 3], [-3, -4, 3]], 
              [[2, -4, 3], [-3, -4, 3]]])
y = np.dot(W, x.transpose())

but received this error message:

    y = np.dot(W, x)
ValueError: shapes (2,2,3) and (2,1,3) not aligned: 3 (dim 2) != 1 (dim 1)

It's 2 dimensions equivalent is:

x = np.array([-1, 2, -4])
W = np.array([[2, -4, 3],
              [-3, -4, 3]])
y = np.dot(W,x)
print(f'{y=}')

which will return:

y=array([-22, -17])

Also, y = np.dot(W,x.transpose()) will return the same answer.


Solution

  • The issue comes from the 3D transposition which does not transpose the axes you want by default. You need to specify the right axes during this call:

    W @ x.transpose(0, 2, 1)
    
    # Output:
    # array([[[-22],
    #         [-17]],
    # 
    #        [[-22],
    #         [-17]]])