Python scipy.optimize.minimize indexer与[0,0]一起使用,但不与.item()一起使用

2024-06-16 09:47:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现scipy.optimize.minimize在我使用.item()从目标函数中的numpy数组中检索值时起作用,但在通过索引[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')

如果在cost_log函数中使用[0,0]索引而不是.item(),则函数本身的工作原理与以前完全相同,但会最小化IndexError: too many indices for array中的结果。我想了解为什么会发生这种情况,以及在使用最小化时在目标函数中应该注意什么


Tags: 函数log目标lenreturndefnpreg
1条回答
网友
1楼 · 发布于 2024-06-16 09:47:06

由于您没有提供XY,我将不看:

(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.

最初编写的I item可以与单个项数组一起使用,而不考虑维度[0,0]仅适用于2d(或更高)数组

相关问题 更多 >