我剛剛開始學(xué)習(xí) Python/NumPy。我想編寫一個(gè)函數(shù),該函數(shù)將應(yīng)用具有 2 個(gè)輸入和 1 個(gè)輸出以及給定權(quán)重矩陣的運(yùn)算,即兩個(gè)形狀為 (2,1) 的 NumPy 數(shù)組,并應(yīng)使用 tanh 返回形狀為 (1,1) 的 NumPy 數(shù)組。這是我想出的:import numpy as npdef test_neural(inputs,weights): result=np.matmul(inputs,weights) print(result) z = np.tanh(result) return (z)x = np.array([[1],[1]])y = np.array([[1],[1]])z=test_neural(x,y)print("final result:",z)但我收到以下 matmul 錯(cuò)誤:ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 1)有人可以告訴我我缺少什么嗎?
1 回答

白衣非少年
TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
問題是矩陣乘法的維度。
您可以將矩陣與共享維度相乘,如下所示(在此處了解更多信息):
(M , N) * (N , K) => Result dimensions is (M, K)
你嘗試乘法:
(2 , 1) * (2, 1)
但尺寸是非法的。
因此,您必須inputs在乘法之前進(jìn)行轉(zhuǎn)置(只需應(yīng)用于.T矩陣),這樣您就可以獲得乘法的有效維度:
(1, 2) * (2, 1) => Result dimension is (1, 1)
代碼:
import numpy as np
def test_neural(inputs,weights):
result=np.matmul(inputs.T, weights)
print(result)
z = np.tanh(result)
return (z)
x = np.array([[1],[1]])
y = np.array([[1],[1]])
z=test_neural(x,y)
# final result: [[0.96402758]]
print("final result:",z)
添加回答
舉報(bào)
0/150
提交
取消