python numpy ValueError:操作数不能与形状一起广播

2024-05-09 15:00:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

使用

X*y

我明白了

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

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

编辑:

我已经用X.dot(y)更正了这个问题,但原始问题仍然存在。


Tags: numpy编辑withnot矩阵数组be向量
3条回答

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

我们有两个阵列:

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

对于Numpy数组,操作

X * y

是按元素执行的,但可以在一个或多个维度中展开其中一个或两个值,以使它们兼容。这个操作叫做广播。尺寸为1或丢失的尺寸可用于广播。

在上面的示例中,维度不兼容,因为:

97   2
 2   1

在第一维度(97和2)中有冲突的数字。这就是上面的ValueError所抱怨的。第二个维度可以,因为数字1与任何内容都不冲突。

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

(请注意,如果Xynumpy.matrix类型,则星号可用作矩阵乘法。我的建议是远离numpy.matrix,它往往会使事情复杂化,而不是简单化。)

数组应该可以使用numpy.dot;如果在numpy.dot上得到错误,则必须有其他错误。如果形状不适合numpy.dot,则会出现不同的异常:

ValueError: matrices are not aligned

如果你仍然得到这个错误,请张贴一个最小的问题的例子。一个使用类似于您的数组的乘法示例成功:

In [1]: import numpy

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

这个错误可能不是在点积中发生的,而是在点积之后。 例如,试试这个

a = np.random.randn(12,1)
b = np.random.randn(1,5)
c = np.random.randn(5,12)
d = np.dot(a,b) * c

np.dot(a,b)可以;但是np.dot(a,b)*c显然是错误的(12x1x1x1x5=12x5,不能按元素相乘5x12),但是numpy会给你

ValueError: operands could not be broadcast together with shapes (12,1) (1,5)

这一错误是误导性的;然而,这方面存在一个问题。

numpy docs

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when:

  • they are equal, or
  • one of them is 1

换言之,如果您尝试将两个矩阵相乘(在线性代数意义上),则需要X.dot(y),但如果您尝试将标量从矩阵y广播到X,则需要执行X * y.T

示例:

>>> import numpy as np
>>>
>>> X = np.arange(8).reshape(4, 2)
>>> y = np.arange(2).reshape(1, 2)  # create a 1x2 matrix
>>> X * y
array([[0,1],
       [0,3],
       [0,5],
       [0,7]])

相关问题 更多 >