【问题标题】:How to minimise a multivariate cost function in Julia with Optim?如何使用 Optim 最小化 Julia 中的多元成本函数?
【发布时间】:2020-05-17 15:21:37
【问题描述】:

我目前被困在尝试使用 Julia 中的 Optim 包来尝试最小化成本函数。成本函数是 L2 正则化逻辑回归的成本函数。构造如下;

using Optim

function regularised_cost(X, y, θ, λ)
    m = length(y)

    # Sigmoid predictions
    h = sigmoid(X * θ)

    # left side of the cost function
    positive_class_cost = ((-y)' * log.(h))

    # right side of the cost function
    negative_class_cost = ((1 .- y)' * log.(1 .- h))

    # lambda effect
    lambda_regularization = (λ/(2*m) * sum(θ[2 : end] .^ 2))

    # Current batch cost
    ???? = (1/m) * (positive_class_cost - negative_class_cost) + lambda_regularization

    # Gradients for all the theta members with regularization except the constant
    ∇???? = (1/m) * (X') * (h-y) + ((1/m) * (λ * θ))  

    ∇????[1] = (1/m) * (X[:, 1])' * (h-y) # Exclude the constant

    return (????, ∇????)
end

我想使用 LBFGS 算法作为求解器,根据我的训练示例和定义为的标签找到最小化此函数的最佳权重:

opt_train = [ones(size(X_train_scaled, 1)) X_train_scaled] # added intercept
initial_theta = zeros(size(opt_train, 2))

阅读文档后,这是我当前无法正常工作的当前实现:

cost, gradient! = regularised_cost(opt_train, y_train, initial_theta, 0.01)

res = optimize(regularised_cost,
               gradient!,
               initial_theta,
               LBFGS(),
               Optim.Options(g_tol = 1e-12,
                             iterations = 1000,
                             store_trace = true,
                             show_trace = true))

如何将我的训练示例和标签与梯度一起传递,以便求解器 (LBFGS) 可以为我找到最佳的 theta 权重?

【问题讨论】:

    标签: optimization julia mathematical-optimization gradient-descent


    【解决方案1】:

    您需要关闭您的训练数据并创建一个仅将参数作为输入的损失函数。

    根据dealing with constant parameterised 上的文档

    应该是这样的:

    loss_and_grad(theta) = regularised_cost(opt_train, y_train, theta, 0.01)
    
    loss(theta) = first(loss_and_grad(theta))
    
    res = optimize(loss, initial_theta)
    

    我会把它留给你看看如何挂钩渐变。

    不过提醒一下:不要使用非常量全局变量。 它们很慢,尤其是在我编写的loss_and_grad 函数中使用它们的方式会很慢。 所以你应该将opt_trainy_train 声明为const。 或者制作一个函数来接受它们并返回一个损失函数等

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多