numpy 矩阵向量相除
报错ValueError: operands could not be broadcast together with shapes (4,3) (4,)
下面看一个简单的例子就明白了
import numpy as np
a = np.array([[1,2,3],[1,2,3],[1,2,3],[1,2,3]]) # a维度为(4, 3)
b = np.array([1,2,3,4]) # b为(4, )
print(a/b) #报错:ValueError: operands could not be broadcast together with shapes (4,3) (4,)
#此时修改如下:
c = b.reshape(-1,1)# 第二维置为1,-1表示自动计算第一维。即c的维度为(4,1)
print(a/c) #此时正确
#打印结果为:
array([[1. , 2. , 3. ],
[0.5 , 1. , 1.5 ],
[0.33333333, 0.66666667, 1. ],
[0.25 , 0.5 , 0.75 ]])