【发布时间】: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