【发布时间】:2015-01-31 07:33:22
【问题描述】:
我正在尝试实现逻辑回归,并且我正在使用 Scipy 的优化模块来查找优化的 theta 值。使用 fmin 函数时,我能够获得正确的值。但是我想在使用需要渐变的 fmin_bfgs 函数时这样做。
这是一个代码sn-p:
#Returns Cost of current theta values and gradient of cost w.r.t theta.
def costFunction(theta, X, y, _lambda):
#Initializes useful variables
m = len(y)
grad = np.zeros((np.shape(theta)))
#Solves for Hypothesis for input X.
h_x = Sigmoid(np.dot(X,theta))
#Reshaped because numpy kept returning row vector, not column.
h_x = h_x.reshape((m,1))
#Cost is broken up into terms for simplicity.
term1 = -y*np.log(h_x)
term2 = (1-y)*np.log((1-h_x))
#Regularized Cost FUnction
J = (1/m) * sum(term1-term2) + (_lambda/(2*m)) * sum(np.square(theta[1:][:]))
#Gradient for Theta1
grad_reg = (_lambda/m)*theta[1:]
#Combines gradient for Theta1 and onward.
grad = (1/m)* (np.dot(np.transpose(X),(h_x-y))) + np.vstack(([0],grad_reg))
return J,grad
#Finds Optimal Value for theta
cost, grad = costFunction(initial_theta, X,y, _lambda)
opt_theta = fmin_bfgs(cost,x0=initial_theta,fprime=grad, args = (X,y,_lambda))
我得到的错误是'numpy.ndarray' object is not callable,它来自优化模块中的function_wrapper 函数。我什至尝试在两个不同的函数中返回梯度和成本,但得到了某种vstack 错误(如果这很重要/有帮助的话)。
据我所知,我已经提供了优化功能的要求。
编辑/更新:我意识到我得到的错误是因为我传递了成本,并且当它期望函数返回这些参数时,将 grad numpy 数组作为参数。我意识到我可以创建一个包装函数?为了在不使用两个单独的函数的情况下获得这两个值,但出于临时目的,我更改了 costFunction 以便它只返回成本,并创建了一个全新的函数Grad()(尽管具有相同的代码),它只返回 grad。这又给了我all the input array dimensions except for the concatenation axis must match exactly vstack 错误。
【问题讨论】:
标签: python optimization numpy machine-learning scipy