在我的代码中,我将两个矩阵相乘:
c = b*a
a
输出为
array([array([-0.08358731, 0.07145386, 0.1052811 , -0.05362566]),
array([-0.05335939, -0.03136824, -0.01260714, 0.11532605]),
array([-0.09164538, 0.02280118, -0.00290509, 0.09415849])], dtype=object)
和b
输出为
array([ 0.60660017, 0.54703557, 0.69928535, 0.70157223])
...这应该可以正常工作(b 的值乘以 a 中每一行的每个值)?
相反,我得到
ValueError: operands could not be broadcast together with shapes (3) (4)
但是当我在一个单独的 python 控制台中尝试它时,它工作得很好。
(请记住,我已经设置了 array = np.array
)
>>> aa = array([array([-0.12799382, 0.07758469, -0.02968546, -0.01811048]),
array([-0.00465869, -0.00483031, -0.00591955, -0.00386022]),
array([-0.02036786, 0.0078658 , 0.09493727, -0.01790333])], dtype=object)
>>> bb = array([ 0.16650179, 0.74140229, 0.60859776, 0.37505098])
>>> aa * bb
array([[-0.021311200138937801, 0.057521466834940096, -0.0180665044605696,
-0.0067923532722703999],
[-0.00077568022405510005, -0.0035812028954099002,
-0.0036026248702079999, -0.0014477792940156],
[-0.0033912851484694004, 0.0058317221326819992, 0.0577786098625152,
-0.0067146614617633995]], dtype=object)
它在这里工作的事实真的让我感到困惑......
最佳答案
您的第一个数组只有 1 个维度和 3 个“对象”元素,而您的第二个数组有 1 个维度和 4 个浮点元素。 numpy使用逐元素算术运算,并且它无法通过一个 3 项数组和一个 4 项数组做到这一点,因此出现异常。
>>> x = np.empty(3, dtype=object)
>>> x[0] = np.array([-0.08358731, 0.07145386, 0.1052811 , -0.05362566])
>>> x[1] = np.array([-0.05335939, -0.03136824, -0.01260714, 0.11532605])
>>> x[2] = np.array([-0.09164538, 0.02280118, -0.00290509, 0.09415849])
>>> x.shape
(3, )
上面的例子是创建 numpy.array
的糟糕方式,应该避免!
与第二个示例的不同之处在于它在数组中没有 numpy 数组,它创建了一个多维 (3x4) 数组:
>>> x_new = np.array(list(x))
>>> x_new # no nested arrays!
array([[-0.12799382, 0.07758469, -0.02968546, -0.01811048],
[-0.00465869, -0.00483031, -0.00591955, -0.00386022],
[-0.02036786, 0.0078658, 0.09493727, -0.01790333]], dtype=object)
>>> x_new.shape
(3, 4)
乘法运算适用于新数组(x_new
或您的 aa
)是因为 numpy 广播数组。这里每一行都将乘以第二个数组中的一个项目。
关于python - 基本 numpy 乘法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41106436/