Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

python - 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]
    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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...