我发现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
中的结果。我想了解为什么会发生这种情况,以及在使用最小化时在目标函数中应该注意什么
由于您没有提供
X
或Y
,我将不看:但是:
如果
theta
是(n,1):但是如果你把
theta
给minimize
,它会把它变成一个(n,)形状:最初编写的I
item
可以与单个项数组一起使用,而不考虑维度[0,0]
仅适用于2d(或更高)数组相关问题 更多 >
编程相关推荐