Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 324
Ingo Avatar asked Feb 10 '12 13:02

Ingo


People also ask

What is the difference between Matmul and dot in NumPy?

matmul differs from dot in two important ways. Multiplication by scalars is not allowed. Stacks of matrices are broadcast together as if the matrices were elements.

Is Matmul faster than dot?

matmul and both outperform np. dot . Also note, as explained in the docs, np.

Is NumPy dot matrix multiplication?

dot() will compute the dot product of the inputs. If both inputs are 2-dimensional arrays, then np. dot() will perform matrix multiplication.


1 Answers

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
like image 102
talonmies Avatar answered Oct 03 '22 01:10

talonmies