以下代码崩溃并出现以下错误: ValueError:操作数无法与形状一起广播(5,5)(5,23) 我知道这两个矩阵可以相乘,所以发生了什么?
def recon_temp(recon_pc_matrix, ew, eof, n, p):
new_temps = np.zeros((p, p))
for i in range(0,p-1):
a = np.array([ew[i]*(recon_pc_matrix[i,0:p])]).T
b = np.array([eof[i, 0:n]])
new_temps = np.add(new_temps, np.multiply(a, b))
return new_temps
a = np.array([[-0.1712077 0.30916178 0.3639138 0.86173197 0.00957432]
[ 0.09886268 -0.56593983 0.75287704 -0.09865605 0.30558374]
[-0.23426853 0.07244316 0.4005179 -0.23221139 -0.85178256]
[ 0.1941591 -0.70654452 -0.339463 0.4397842 -0.39300358]
[-0.93184473 -0.28227279 -0.15840833 -0.01878062 0.16291583]])
b = np.array([[-0.89934942 1.51224286 1.17335825 -0.08218979 0.98625991 1.13124679
0.12082299 -1.45882345 -1.6897246 0.70884387 -1.21370037 -0.03640097
0.25423117 -0.34026433 -0.94905651 -0.48517389 0.05775344 0.71212526
1.11442191 0.31825772 -1.41012823 -0.59093546 1.06618286]
[ 0.85264281 1.63168765 0.80196132 0.04534459 0.48561984 -0.11086797
1.11591161 -0.24153581 0.65829793 -0.07172239 1.12920778 -0.52778775
-2.2780791 0.90289084 -0.20018346 -0.20287233 -0.31416035 -0.83016084
-0.8077091 -0.29606383 -1.19852534 -0.0768147 -0.46708139]
[ 0.67870887 -0.01875505 0.26984334 -0.6223331 0.32559298 -0.94280004
-0.81414199 -0.19893921 0.84574502 1.09421435 -0.15831082 1.81599507
0.00648578 -1.21146774 -0.3179769 1.04116227 -0.11486882 -0.31177898
-0.19821291 0.10022766 -1.09882425 -0.1149134 -0.05465211]
[-0.03707971 0.53168148 0.41874141 0.03673735 -1.33893753 0.12464263
-0.1343872 0.46679816 -0.75343034 -0.23104592 -0.22133639 0.28104257
-0.37346672 -0.65672427 0.54146026 -0.13421286 -0.18973127 -1.0554372
-0.44792916 0.85063804 -0.02023537 1.22571478 1.11649726]
[ 0.31681713 -0.12923957 -0.04577132 0.2485488 -0.03239199 -0.07354265
0.35762585 -0.97073981 -0.59382981 0.00892815 0.74089591 -0.04775075
0.30722372 -0.51731235 0.43637896 0.21612401 0.83204179 -0.29326734
-0.59640106 0.22724823 0.21728589 -0.64666786 0.03779609]])
c = np.array([ 0.92504802 0.7660462 0.540457 0.40724992 0.20059767])
temp = recon_temp(a, c, b, 23, 5)
在乘以a和b
时崩溃答案 0 :(得分:3)
np.multiply
进行元素乘法运算。形状为(5, 5)
和(5, 23)
的两个数组不能按元素相乘,因此会出错。如果要执行矩阵乘法,请使用np.dot
:
>>> a = np.random.rand(5, 5)
>>> b = np.random.rand(5, 23)
>>> np.multiply(a, b) <-- This gives a broadcasting error
>>> np.dot(a, b) <-- This gives the matrix multiplicaitn of a and b