我最近从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'
问题1:有没有办法指定优化用于最小化的回归?(比如fn $ J)
Q2:有没有一个解决方案可以使用我在logisticRegressionCost中计算的渐变?
小智 6
我认为你不能这样做,因为optim所说的文档fn应该返回一个标量结果.
也许你可以编写一个帮助函数进行优化.就像是:
logisticRegressionCost.helper <- function(theta, X, y) {
   logisticRegressionCost(theta, X, y)$J
}
另外,你不需要半冒号来抑制R中的输出.当我从MatLab切换时,我也有同样的习惯:)