python numpy ValueError:操作数不能与形状一起广播 [英] python numpy ValueError: operands could not be broadcast together with shapes

查看:371
本文介绍了python numpy ValueError:操作数不能与形状一起广播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在numpy中,我有两个数组",X(m,n)y是向量(n,1)

In numpy, I have two "arrays", X is (m,n) and y is a vector (n,1)

使用

X*y

我遇到了错误

ValueError: operands could not be broadcast together with shapes (97,2) (2,1) 

(97,2)x(2,1)显然是合法的矩阵运算,应该给我一个(97,1)向量

When (97,2)x(2,1) is clearly a legal matrix operation and should give me a (97,1) vector

我已使用X.dot(y)更正了此问题,但原始问题仍然存在.

I have corrected this using X.dot(y) but the original question still remains.

推荐答案

dot是矩阵乘法,但是*做其他事情.

dot is matrix multiplication, but * does something else.

我们有两个数组:

  • X,形状(97,2)
  • y,形状(2,1)
  • X, shape (97,2)
  • y, shape (2,1)

对于Numpy数组,该操作

With Numpy arrays, the operation

X * y

是逐个元素完成的,但是可以在一个或多个维度上扩展其中一个或两个值以使其兼容.此操作称为广播.尺寸为1或缺少尺寸的尺寸可以在广播中使用.

is done element-wise, but one or both of the values can be expanded in one or more dimensions to make them compatible. This operation are called broadcasting. Dimensions where size is 1 or which are missing can be used in broadcasting.

在上面的示例中,尺寸不兼容,原因是:

In the example above the dimensions are incompatible, because:

97   2
 2   1

此处第一维中的数字有冲突(97和2).这就是上面的ValueError所抱怨的.第二个维度可以,因为数字1不会与任何东西冲突.

Here there are conflicting numbers in the first dimension (97 and 2). That is what the ValueError above is complaining about. The second dimension would be ok, as number 1 does not conflict with anything.

有关广播规则的更多信息: http://docs.scipy .org/doc/numpy/user/basics.broadcasting.html

For more information on broadcasting rules: http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

(请注意,如果Xy的类型为numpy.matrix,则可以将星号用作矩阵乘法.我的建议是远离numpy.matrix,它倾向于使事情复杂化,而不是简化事情)

(Please note that if X and y are of type numpy.matrix, then asterisk can be used as matrix multiplication. My recommendation is to keep away from numpy.matrix, it tends to complicate more than simplify things.)

您的数组应该与numpy.dot匹配;如果您在numpy.dot上遇到错误,则必须有其他错误.如果numpy.dot的形状不正确,则会得到另一个异常:

Your arrays should be fine with numpy.dot; if you get an error on numpy.dot, you must have some other bug. If the shapes are wrong for numpy.dot, you get a different exception:

ValueError: matrices are not aligned

如果仍然出现此错误,请发布问题的最小示例.与形状像您的数组一样的示例乘法成功了:

If you still get this error, please post a minimal example of the problem. An example multiplication with arrays shaped like yours succeeds:

In [1]: import numpy

In [2]: numpy.dot(numpy.ones([97, 2]), numpy.ones([2, 1])).shape
Out[2]: (97, 1)

这篇关于python numpy ValueError:操作数不能与形状一起广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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