I found that scipy.optimize.minimize works when I use .item() to retrieve a value from an numpy array in the objective function, but it fails when I retrieve by indexing [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')
If I use [0,0]
indexing instead of .item()
in the cost_log
function, the function itself works exactly the same as before, but minimize results in IndexError: too many indices for array
. I want to understand why this happens and what I should be careful of in the objective function when using minimize.