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?
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.
matmul and both outperform np. dot . Also note, as explained in the docs, np.
dot() will compute the dot product of the inputs. If both inputs are 2-dimensional arrays, then np. dot() will perform matrix multiplication.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With