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

查看:32
本文介绍了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 is 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

(请注意,如果Xynumpy.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 simplifying 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天全站免登陆