ale*_*kow 9 matlab machine-learning gradient-descent logistic-regression
我正在尝试开发随机梯度下降,但我不知道它是否100%正确.
以下是我使用10,000个元素和num_iter = 100或500的训练集获得的一些结果
FMINUC :
Iteration #100 | Cost: 5.147056e-001
BACTH GRADIENT DESCENT 500 ITER
Iteration #500 - Cost = 5.535241e-001
STOCHASTIC GRADIENT DESCENT 100 ITER
Iteration #100 - Cost = 5.683117e-001 % First time I launched
Iteration #100 - Cost = 7.047196e-001 % Second time I launched
Run Code Online (Sandbox Code Playgroud)
Logistic回归的梯度下降实现
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
[J, gradJ] = lrCostFunction(theta, X, y, lambda);
theta = theta - alpha * gradJ;
J_history(iter) = J;
fprintf('Iteration #%d - Cost = %d... \r\n',iter, J_history(iter));
end
Run Code Online (Sandbox Code Playgroud)
Logistic回归的随机梯度下降实现
% number of training examples
m = length(y);
% STEP1 : we shuffle the data
data = [y, X];
data = data(randperm(size(data,1)),:);
y = data(:,1);
X = data(:,2:end);
for iter = 1:num_iters
for i = 1:m
x = X(i,:); % Select one example
[J, gradJ] = lrCostFunction(theta, x, y(i,:), lambda);
theta = theta - alpha * gradJ;
end
J_history(iter) = J;
fprintf('Iteration #%d - Cost = %d... \r\n',iter, J);
end
Run Code Online (Sandbox Code Playgroud)
作为参考,这是我的例子中使用的逻辑回归成本函数
function [J, grad] = lrCostFunction(theta, X, y, lambda)
m = length(y); % number of training examples
% We calculate J
hypothesis = sigmoid(X*theta);
costFun = (-y.*log(hypothesis) - (1-y).*log(1-hypothesis));
J = (1/m) * sum(costFun) + (lambda/(2*m))*sum(theta(2:length(theta)).^2);
% We calculate grad using the partial derivatives
beta = (hypothesis-y);
grad = (1/m)*(X'*beta);
temp = theta;
temp(1) = 0; % because we don't add anything for j = 0
grad = grad + (lambda/m)*temp;
grad = grad(:);
end
Run Code Online (Sandbox Code Playgroud)
这基本没问题。如果您担心选择合适的学习率alpha,您应该考虑应用线搜索方法。
线搜索是一种在每次迭代时为梯度下降选择最佳学习率的方法,这比在整个优化过程中使用固定学习率要好。学习率的最佳值alpha是局部(从当前theta负梯度方向)最小化成本函数的值。
例如,在梯度下降的每次迭代中,从学习率开始alpha = 0并逐渐增加alpha固定步长。deltaAlpha = 0.01重新计算参数theta并评估成本函数。由于成本函数是凸的,因此通过增加alpha(即,通过向负梯度方向移动)成本函数将首先开始减少,然后(在某个时刻)增加。此时停止线搜索并alpha在成本函数开始增加之前取最后一个。theta现在用那个更新参数alpha。如果成本函数永远不会开始增加,则停止在 处alpha = 1。
注意:对于大的正则化因子(lambda = 100, lambda = 1000),可能deltaAlpha太大并且梯度下降发散。如果是这种情况,请减少deltaAlpha10 倍 ( deltaAlpha = 0.001, deltaAlpha = 0.0001),直到达到deltaAlpha梯度下降收敛的适当值。
另外,您应该考虑使用除迭代次数之外的某些终止条件,例如,当两个后续迭代中的成本函数之间的差异变得足够小时(小于 some epsilon)。
| 归档时间: |
|
| 查看次数: |
9722 次 |
| 最近记录: |