Skip to content Skip to sidebar Skip to footer

Is Dot Product And Normal Multiplication Results Of 2 Numpy Arrays Same?

I am working with kernel PCA in Python and I have to find the values after projecting the original data to the principal components.I use the equation fv = eigvecs[:,:ncomp]

Solution 1:

The * operator depends on the data type. On Numpy arrays it does an element-wise multiplication (not the matrix multiplication); numpy.vdot() does the "dot" scalar product of two vectors (which returns a simple scalar result)

>>> import numpy as np
>>> x = np.array([[1,2,3]])
>>> np.vdot(x, x)
14
>>> x * x
array([[1, 4, 9]])

To multiply 2 arrays as matrices properly, use numpy.dot:

>>> np.dot(x, x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: objects are not aligned
>>> np.dot(x.T, x)
array([[ 1,  4,  9],
       [ 4, 16, 36],
       [ 9, 36, 81]])
>>> np.dot(x, x.T)
array([[98]])

Then there is numpy.matrix, a specialization of array for which the * means matrix multiplication, and ** means matrix power; so be sure to know what datatype you are operating on.


The upcoming Python 3.5 will have a new operator @ that can be used for matrix multiplication; then you could write x @ x.T to replace the code in the last example.

Post a Comment for "Is Dot Product And Normal Multiplication Results Of 2 Numpy Arrays Same?"