记录下,减少折腾。希望帮助到需要的老板。

使用Python时可能会遇到的一个错误是:

ValueError: operands could not be broadcast together with shapes (100,) (71,) 

很重要哦😯

当您尝试在Python中使用乘法符号(*)而不是numpy.dot()函数执行矩阵乘法时,会出现此错误。

重现错误

import numpy as np

假设我们有一个2×2矩阵C,它有2行和2列:
C = np.array([7, 5, 6, 3]).reshape(2, 2)
假设我们还有一个2×3矩阵D,它有2行和3列:
D = np.array([2, 1, 4, 5, 1, 2]).reshape(2, 3)

print(C)

[[7 5]
 [6 3]]

print(D)

[[2 1 4]
 [5 1 2]]

以下是将矩阵C乘以矩阵D的方法:
C*D

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

我们可以这样处理:

修复此错误的最简单方法是简单地使用numpy.dot()函数执行矩阵乘法:

import numpy as np


C = np.array([7, 5, 6, 3]).reshape(2, 2)
D = np.array([2, 1, 4, 5, 1, 2]).reshape(2, 3)


C.dot(D)

array([[39, 12, 38],
       [27,  9, 30]])

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐