gpt4 book ai didi

r - 使用 optim 优化 R 中的多输出函数,最好使用梯度

转载 作者:行者123 更新时间:2023-12-03 16:29:54 25 4
gpt4 key购买 nike

我最近从 matlab 切换到 R,我想运行一个优化场景。

在 matlab 中我能够:

options = optimset('GradObj', 'on', 'MaxIter', 400);
[theta, cost] = fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);

这是 costFunctionReg 的等价物(这里我称之为 logisticRegressionCost)

logisticRegressionCost <- function(theta, X, y) {
J = 0;
theta = as.matrix(theta);
X = as.matrix(X);
y = as.matrix(y);

rows = dim(theta)[2];
cols = dim(theta)[1];
grad = matrix(0, rows, cols);

predicted = sigmoid(X %*% theta);
J = (-y) * log(predicted) - (1 - y) * log(1 - predicted);

J = sum(J) / dim(y)[1];

grad = t(predicted - y);
grad = grad %*% X;
grad = grad / dim(y)[1];

return(list(J = J, grad = t(grad)));
}

然而,当我尝试对其进行优化时:

o = optim(theta <- matrix(0, dim(X)[2]), fn = logisticRegressionCost, X = X, y = y, method="Nelder-Mead")

由于列表返回,我得到一个错误。 (当我只返回 J 时它有效)

错误:

(list) object cannot be coerced to type 'double'

问题 1:有没有办法指定 optim 应该使用哪个返回来进行最小化? (比如 fn$J)

问题 2:有没有一种解决方案可以使用我在 logisticRegressionCost 中计算的梯度?

最佳答案

我不认为你可以这样做,因为 optim 的文档说 fn 应该返回一个标量结果。

或许您可以编写一个辅助函数来进行优化。像这样的东西:

logisticRegressionCost.helper <- function(theta, X, y) {
logisticRegressionCost(theta, X, y)$J
}

此外,您不需要分号来抑制 R 中的输出。我从 MatLab 切换时也有同样的习惯:)

关于r - 使用 optim 优化 R 中的多输出函数,最好使用梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22408611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com