-1

I have two numpy arrays of the same dimension . When I tried to use dot product on them, I am getting "shapes not aligned" error.

import numpy as np

A = np.array([[2,4,6]])

Y = np.array([[1,0,1]])

np.dot(Y,A)



ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

Can someone let me know why?

Thanks

Sociopath
  • 13,068
  • 19
  • 47
  • 75
Abin John Thomas
  • 159
  • 2
  • 13
  • 2
    Either (1, 3) x (3, 1) or (3, 1) x (1, 3) is possible. Try np.dot(Y, A.T) or np.dot(Y.T, A), where `.T` returns transpose array. – dkato Feb 08 '18 at 06:14
  • or alternatively define them as 1d vectors: `A = np.array([2,4,6])` (only 1 set of brackets) – Julien Feb 08 '18 at 06:41

1 Answers1

1

Row multiplies on column. You should transpose rows to columns first:

import numpy as np
A = np.array([[2,4,6]])
Y  = np.array([[1,0,1]])
np.dot(Y, A.T)

But maybe it is better to use matrix instead of array for matrix operations:

import numpy as np
A = np.matrix([[2,4,6]])
Y  = np.matrix([[1,0,1]])
Y.dot(A.T)
FooBar167
  • 2,721
  • 1
  • 26
  • 37
  • Don't recommend np.matrix – hpaulj Feb 08 '18 at 07:21
  • Thanks for the answer. I know transposing them will work, but my query is why it is throwing error even when the dimension is the same. As per broadcasting rule, it should work if both the dimensions are same. – Abin John Thomas Feb 11 '18 at 11:54
  • @AbinJohnThomas, broadcasting rules don't apply to `np.dot`. It has its own dimension rules. Read them. – hpaulj Feb 11 '18 at 19:33