亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python scipy.optimize.minimize IndexError 使用 [0,0]

Python scipy.optimize.minimize IndexError 使用 [0,0]

四季花海 2023-02-22 15:24:55
我發現當我使用 .item() 從目標函數中的 numpy 數組中檢索值時 scipy.optimize.minimize 有效,但是當我通過索引 [0,0] 檢索時它失敗了:def sigmoid(Z):    return 1 / (1 + np.exp(-Z))def hyp_log(X, theta):    return sigmoid(X @ theta)def cost_log(theta, X, Y, reg_const=0):    hyp = hyp_log(X, theta)    return  (Y.T @ -np.log(hyp) + (1-Y).T @ -np.log(1-hyp)).item() / len(X) + reg_const * (theta[1:].T @ theta[1:]).item() / (2 * len(X))result = minimize(cost_log, theta, args=(X,Y,reg_const), method='TNC')如果我使用[0,0]索引而不是.item()在cost_log函數中使用索引,函數本身的工作方式與以前完全相同,但將IndexError: too many indices for array. 我想了解為什么會發生這種情況以及在使用最小化時在目標函數中應注意的事項。
查看完整描述

1 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

由于您沒有提供Xor Y,我不會看:


(Y.T @ -np.log(hyp) + (1-Y).T @ -np.log(1-hyp))

但與:


(theta[1:].T @ theta[1:]).item()

如果theta是(n,1):


In [15]: theta = np.arange(5)[:,None]                                                   

In [16]: theta.shape                                                                    

Out[16]: (5, 1)

In [17]: (theta[1:].T @ theta[1:])                                                      

Out[17]: array([[30]])

In [18]: (theta[1:].T @ theta[1:])[0,0]                                                 

Out[18]: 30

In [19]: (theta[1:].T @ theta[1:]).item()                                               

Out[19]: 30

但是如果你把它theta給minimize,它會把它分解成 (n,) 形狀:


In [20]: theta=theta.ravel()                                                            

In [21]: (theta[1:].T @ theta[1:])                                                      

Out[21]: 30

In [22]: (theta[1:].T @ theta[1:]).shape                                                

Out[22]: ()

In [23]: (theta[1:].T @ theta[1:]).item()                                               

Out[23]: 30

In [24]: (theta[1:].T @ theta[1:])[0,0]                                                 

...

IndexError: invalid index to scalar variable.

I 正如最初所寫的那樣,item可以與單個項目數組一起使用,而不管尺寸如何。 [0,0]僅適用于二維(或更高)數組。


查看完整回答
反對 回復 2023-02-22
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號