Python的乘法出错问题,operands could not be broadcast together with shapes (3,3) (3,2)


import numpy as np
A = np.array([5, -2])
B = np.array([1, 6, 2, 0, -1, -1])
C = np.array([2, 0, -1, 3, -1, 6])
D = np.array([3, 0, 1, 1, -2, 2, 3, 4, -1])

E = A.reshape((2, 1))
F = B.reshape((3, 2))
G = C.reshape((3, 2))
H = D.reshape((3, 3))

print(-2*E)
print(G + F)
print(4*F - G)
print(np.multiply(H*G))
print(np.dot(G*E))

最后两行总是出错,是个什么原因?(倒数第二行是一个(3,3)(3,2)的矩阵,倒数第一行是一个(3,2)(2,1)的矩阵)

  • *是对应位置相乘
  • 你写数字 *矩阵可以,但是最后两行是矩阵 *矩阵了,维度没法对应相乘,就报错了
  • np.multiply(H,G)和H *G是一个意思,表示矩阵点乘

我看你测试的样子,应该是想测试multiply和dot函数吧,应该写:

print(np.multiply(H,G))   #这里也会报错,因为维度不匹配
print(np.dot(G,E))

有帮助麻烦点个采纳~~

img