首页 > 解决方案 > Python scipy.optimize.minimize IndexError with [0,0] 但不是 .item()

问题描述

当我使用 .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. 我想了解为什么会发生这种情况,以及在使用最小化时在目标函数中应该注意什么。

标签: pythonnumpynumpy-ndarrayscipy-optimizescipy-optimize-minimize

解决方案


由于您没有提供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

但是,如果您将其赋予thetaminimize它会将其分解为 (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.

我最初写item的可以与单个项目数组一起使用,而不管维度如何。 [0,0]仅适用于二维(或更高)数组。


推荐阅读