首页 > 解决方案 > 如何使用 Optim 最小化 Julia 中的多元成本函数?

问题描述

我目前被困在尝试使用 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 权重?

标签: optimizationjuliamathematical-optimizationgradient-descent

解决方案


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

根据处理常量参数化的文档

它应该是这样的。像:

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_trainand y_trainas const。或者制作一个函数来接受它们并返回一个损失函数等


推荐阅读