如何在Python中使用BFGS最小化?

时间:2017-07-28 13:09:35

标签: python optimization

我在R中有以下代码:

LogLikelihood <- function(c, x, y) {
    p <- 1 / (1 + exp(-(c[1] + c[2] * x)))
    log_likelihood <- sum(log(p[y == 1])) + sum(log(1 - p[y == 0]))
    return(-log_likelihood) # minus ll because we minimize in R
}

start_params <- c(1, 1)
optim_log_regression = optim(
    start_params,
    LogLikelihood,
    x = x,
    y = y,
    method = 'BFGS'
)

我需要一个用于Python最小化的等效代码。到目前为止,我认为它可能看起来像这样:

start_params = np.array([1, 1])
res = minimize(log_likelihood, start_params, method='BFGS', options={'gtol': 
               1e-6, 'disp': True})

如何告诉最小化函数仅优化参数“c”,并且我需要提供“x”和“y”。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

使用args

中的scipy.optimize.minimize(fun, x0, args=()...关键字
  

args:元组,可选

Extra arguments passed to the objective function and its derivatives (Jacobian, Hessian).

目标函数可能需要几个参数,如果优化是多维的,第一个参数总是一维优化的标量或numpy数组/列表。

您可以像

一样调用优化功能
res = minimize(log_likelihood, start_params, args=(x, y), method='BFGS', ... 
相关问题