optimization - 如何使用 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 权重?
解决方案
您需要关闭您的训练数据并创建一个仅将参数作为输入的损失函数。
它应该是这样的。像:
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_train
and y_train
as const
。或者制作一个函数来接受它们并返回一个损失函数等
推荐阅读
- python - Python kivy 本地在手机之间共享一个变量
- wso2 - 如何从文件 WSO2 ESB 设置有效负载?
- rust - 如何将元组收集到 HashMap 中?
- c - 如何为标准库函数创建别名?
- shopify - 如何访问 json_string 类型的 Shopify 中的键名?
- r - Extracting conditional rows from a list of dataframes in a loop
- c - 创建一个递归函数,该函数从 C 中的前缀表达式(在 char 数组中)创建表达式树
- android - 打开最近在 android 中使用 Intent.ACTION_VIEW 创建的图像
- mysql - MySQL-从 5 个表中查找最新数据
- java - 获取图像大小而无需从java中的Web下载它们