python - 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
. 我想了解为什么会发生这种情况,以及在使用最小化时在目标函数中应该注意什么。
解决方案
由于您没有提供X
or 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.
我最初写item
的可以与单个项目数组一起使用,而不管维度如何。 [0,0]
仅适用于二维(或更高)数组。
推荐阅读
- php - 解析错误:第 28 行 C:\xampp\htdocs\php\order\instagramapi.php 中的语法错误、意外的 ':'、期待 ',' 或 ')'
- cplex - 在 OPL 的后处理执行命令中创建元组
- c++ - 在 C++ 中打开一个 ifstream 文件
- javascript - 在 Pyppeteer 中,设置超时时间并非在所有情况下都有效
- javascript - 如何在对象的字符串中调用函数?
- javascript - 如何即时发送 UTC 格式的长值?
- php - 存储 100 万行的最佳和最安全的方法
- python - python - 嵌套字典作为参数
- c# - 获取包含某个属性值的 jtoken 列表
- axios - $axios.onError 不是函数