向量在SciPy/NumPy中的点积(获取ValueError:对象未对齐) [英] Dot product of a vector in SciPy/NumPy (getting ValueError: objects are not aligned)

查看:117
本文介绍了向量在SciPy/NumPy中的点积(获取ValueError:对象未对齐)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚刚开始学习SciPy,并在最基本的功能上苦苦挣扎.

I just started learning SciPy and am struggling with the most basic features.

请考虑以下标准向量:

In [6]: W=array([[1],[2]])

In [7]: print W
[[1]
 [2]]

如果我正确理解的话,这应该是标准2x1数学向量的SciPy表示形式,如下所示:

If I understand it correctly, this should be the SciPy representation of a standard 2x1 mathematical vector, like this:

(1)    
(2)

此向量的点积应简单地为1*1+2*2=5.但是,这在SciPy中不起作用:

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

请注意以下工作.如果我没记错的话,这应该是(1 2)形式的向量.

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?

推荐答案

此处的关键是numpy/scipy在计算点积时采用数组的形状.看您的第一个示例,W是一个2x1数组:

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)

因此,有必要使用转置运算符来计算W与自身的点(内)积:

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

这篇关于向量在SciPy/NumPy中的点积(获取ValueError:对象未对齐)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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