我正在尝试为斯坦福机器学习讲座中解释的梯度下降算法编写一些代码(第二讲 25:00左右 http://www.youtube.com/watch?v=5u4G23_OohI#t=25m)。下面是我最初使用的实现,我认为它是从讲座中正确复制的,但是当我添加大量数字时它不会收敛(>8
) 到训练集。
我正在输入一个数字X
,以及point (X,X)
被添加到训练集中,所以目前,我只是想让它收敛到y=ax+b
where a=1=theta\[1\]
and b=0=theta\[0\]
。
训练集是数组x
and y
, where (x[i],y[i])
是一个点。
void train()
{
double delta;
for (int i = 0; i < x.size(); i++)
{
delta = y[i]-hypothesis(x[i]);
theta[1] += alpha*delta*x[i];
theta[0] += alpha*delta*1;
}
}
void C_Approx::display()
{
std::cout<<theta[1]<<"x + "<<theta[0]<<" \t "<<"f(x)="<<hypothesis(1)<<std::endl;
}
我得到的一些结果:
我输入一个数字,它运行train()
几次,然后display()
1
0.33616x + 0.33616 f(x)=0.67232
1
0.482408x + 0.482408 f(x)=0.964816
1
0.499381x + 0.499381 f(x)=0.998762
1
0.499993x + 0.499993 f(x)=0.999986
1
0.5x + 0.5 f(x)=1
通过后发生分歧的一个例子8
:
1
0.33616x + 0.33616 f(x)=0.67232
2
0.705508x + 0.509914 f(x)=1.21542
3
0.850024x + 0.449928 f(x)=1.29995
4
0.936062x + 0.330346 f(x)=1.26641
5
0.951346x + 0.231295 f(x)=1.18264
6
0.992876x + 0.137739 f(x)=1.13062
7
0.932206x + 0.127372 f(x)=1.05958
8
1.00077x + 0.000493063 f(x)=1.00126
9
-0.689325x + -0.0714712 f(x)=-0.760797
10
4.10321e+08x + 4.365e+07 f(x)=4.53971e+08
11
1.79968e+22x + 1.61125e+21 f(x)=1.9608e+22
12
-3.9452e+41x + -3.26957e+40 f(x)=-4.27216e+41
我尝试了建议的解决方案here https://stackoverflow.com/questions/3837692/how-to-create-a-simple-gradient-descent-algorithm缩放步骤并最终得到类似的结果。
我究竟做错了什么?