Is dot product and normal multiplication results of 2 numpy arrays same?

点点圈 提交于 2019-12-13 08:04:17

问题


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]
    print(len(fv))
    td = fv.T * K.T

where K is the kernel matrix of dimension (150x150),ncomp is the number of principal components.The code works perfectly fine when fv has dimension (150x150).But when I select ncomp as 3 making fv to be of (150x3) as dimension,there occurs error stating operands could not be broadcast together.I referred various links and tried using dot products like td=np.dot(fv.T,K.T). I dont get any error now.But I dont know whether the values retrieved are correct or not...

Plz help...


回答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.



来源:https://stackoverflow.com/questions/29254123/is-dot-product-and-normal-multiplication-results-of-2-numpy-arrays-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!