您的位置:首页 > 其它

Batch & Stochatic Gradient Descent

2015-07-22 15:11 169 查看
1. 批量梯度下降法

批量梯度下降法的原理可以参考:斯坦福机器学习第一讲

我实验所用的数据是100个二维点。

如果梯度下降算法不能正常运行,考虑使用更小的步长(也就是学习率),这里需要注意两点:

1)对于足够小的, 能保证在每一步都减小;

2)但是如果太小,梯度下降算法收敛的会很慢;

总结:

1)如果太小,就会收敛很慢;

2)如果太大,就不能保证每一次迭代都减小,也就不能保证收敛;

如何选择-经验的方法:

..., 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1...

约3倍于前一个数。

伪代码:

[cpp] view
plaincopy

function [theta0,theta1]=BGD(X,Y);

m=100; %training data一共100个点

r=0.001 %learning rate

theta0=0;

theta1=0;

temp0=0;

temp1=0;

while(true)

for i=1:1:m %100个点

temp0=temp0+(theta0+theta1*X(i,1)-Y(i,1))*1;

temp1=temp1+(theta0+theta1*X(i,1)-Y(i,1))*X(i,1);

end

temp0=theta0-r*temp0;

temp1=theta1-r*temp1;

old_theta0=theta0;

old_theta1=theta1;

theta0=temp0;

theta1=temp1;

temp0=0;

temp1=0;

if(sqrt((old_theta0-theta0)^2+(old_theta1-theta1)^2)<0.000001) % 这里是判断收敛的条件,当然可以有其他方法来做

break;

end

2. 随机梯度下降法

随机梯度下降法适用于样本点数量非常庞大的情况,算法使得总体向着梯度下降快的方向下降。

伪代码:

[cpp] view
plaincopy

function [theta0,theta1]=SGD(X,Y);

m=100; %training data一共100个点

r=0.001 %learning rate

theta0=0;

theta1=0;

temp0=0;

temp1=0;

iterNum=30;

for iter=1:1:iterNum

for i=1:1:m

temp0=theta0-r*(theta0+theta1*X(i,1)-Y(i,1))*1;

temp1=theta1-r*(theta0+theta1*X(i,1)-Y(i,1))*X(i,1);

theta0=temp0;

theta1=temp1;

end

end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: