【问题标题】:Optimizing a multiple output function in R using optim, preferably with gradient使用 optim 在 R 中优化多输出函数,最好使用梯度
【发布时间】:2014-04-19 22:58:44
【问题描述】:

我最近从 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) 对象不能被强制输入'double'

Q1:有没有办法指定 optim 应该使用哪个回报来最小化? (如 fn$J)

Q2:有没有可以使用我在logisticRegressionCost中计算的梯度的解决方案?

【问题讨论】:

  • 前段时间我使用optim 来拟合感知器。我的函数刚刚接受了w 并返回了错误值。

标签: r optimization


【解决方案1】:

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

也许你可以写一个辅助函数来优化。比如:

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

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

【讨论】:

    猜你喜欢
    • 2013-07-26
    • 2016-10-17
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    相关资源
    最近更新 更多