点积和2个numpy数组的正常乘法结果是否相同? [英] Is dot product and normal multiplication results of 2 numpy arrays same?

查看:111
本文介绍了点积和2个numpy数组的正常乘法结果是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python中的内核PCA,在将原始数据投影到主要组件之后必须找到值.我使用等式

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

其中K是维数(150x150)的内核矩阵,ncomp是主分量的数量.当fv具有维数(150x150)时,代码工作得很好.但是当我选择ncomp为3时,fv为(150x3) )作为维度,出现错误提示操作数不能一起广播.我引用了各种链接并尝试使用点积(例如 td=np.dot(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...

请帮助...

推荐答案

*运算符取决于数据类型.在Numpy arrays 上,它按元素进行乘法运算( 而不是矩阵 ); numpy.vdot()进行两个向量的点"标量积(返回简单的标量结果)

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]])


要正确地将2个数组作为矩阵相乘,请使用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]])


然后有 numpy.matrix ,数组的特殊化,其中*表示矩阵乘法,而**表示矩阵乘方;所以一定要知道您正在使用哪种数据类型.


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.

即将到来的Python 3.5将具有一个新的运算符@,该运算符可用于矩阵乘法;那么您可以编写x @ x.T来替换上一个示例中的代码.

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.

这篇关于点积和2个numpy数组的正常乘法结果是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆