我目前正试图利用 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) 可以为我找到 θ 的最佳权重?
最佳答案
您需要关闭训练数据并创建一个仅将参数作为输入的损失函数。
根据 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)
我将让您看看如何 Hook 渐变。
提醒一下:不要使用非常量全局变量。
它们很慢,特别是在我编写的loss_and_grad函数中使用它们的方式会很慢。
因此,您应该将 opt_train
和 y_train
声明为 const
。
或者创建一个接受它们并返回损失函数等的函数
关于optimization - 如何使用 Optim 最小化 Julia 中的多元成本函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60012645/