Rami Janini
Rami Janini

Reputation: 593

Why does .T fix my dot product error in two dimensional arrays?

I have two, two-dimensional arrays like this:

arr1 = np.random.randn(4, 3)
arr2 = np.random.randn(4, 3)

When I try to find the dot product between them it gives me an error:

np.dot(arr1, arr2)
Error: ValueError: shapes (4,3) and (4,3) not aligned: 3 (dim 1) != 4 (dim 0)

After some research I found out by adding .T to one of the arrays it works:

np.dot(arr1.T, arr2)

But my question is why does adding .T makes it work, and what does T stand for and what does it do exactly?

Upvotes: 1

Views: 169

Answers (1)

Mercury
Mercury

Reputation: 4181

To understand this you need to understand how matrix multiplication works.

To take the dot product of any two matrices of dimensions R1xC1 and R2xC2, it is necessary that C1==R2. The output matrix will be of the shape R1xC2. So when you call .T, or transpose, rather than (4,3) and (4,3), the dot occurs between (3,4) and (4,3) giving you an output of shape (3,3).

I think you may be confusing dot product with elementwise product, where you can multiply to matrices of the same shape and get an output of the same shape. To do that, arr1*arr2 should suffice.

Upvotes: 1

Related Questions