Alex Rivera | Logout

Dot product of a vector in SciPy/NumPy (getting ValueError: objects are not aligned)

Asked 2012-02-10T13:54:48.287
18

I just started learning SciPy and am struggling with the most basic features.

Consider the following standard vector:

In [6]: W=array([[1],[2]])

In [7]: print W
[[1]
 [2]]

If I understand it correctly, this should be the SciPy representation of a standard 2x1 mathematical vector, like this:

(1)    
(2)

The dot product of this vector should simply be 1*1+2*2=5. However, this does not work in SciPy:

In [16]: dot(W, W)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/ingo/<ipython-input-16-961b62a82495> in <module>()
----> 1 dot(W, W)

ValueError: objects are not aligned

Note that the following works. This should be a vector of the form (1 2) if I am not mistaken.

In [9]: V=array([1,2])

In [10]: print V
[1 2]

In [11]: dot(V, V)
Out[11]: 5

What is my misconception? What am I doing wrong?

Edit
Report

1 Answer

16

The key here is that numpy/scipy honours the shape of arrays when computing dot products. Looking at your first example, W is a 2x1 array:

In [7]: W=array([[1],[2]])

In [8]: print W.shape
------> print(W.shape)
(2, 1)

it is, therefore, necessary to use the transpose operator to compute the dot (inner) product of W with itself:

In [9]: print dot(W.T,W)
------> print(dot(W.T,W))
[[5]]

In [10]: print np.asscalar(dot(W.T,W))
-------> print(np.asscalar(dot(W.T,W)))
5
answered 2012-02-10T14:09:20.800

Your Answer