数学建模社区-数学中国

标题: 自己动手写matlab——梯度下降 [打印本页]

作者: 蘑菇先生    时间: 2015-7-16 08:49
标题: 自己动手写matlab——梯度下降
  1. %最速下降法(批量梯度下降)
  2. X=[1 4;2 5;5 1;4 2];
  3. theta_new=[2 5]';
  4. theta_old=[2 5]';
  5. theta_best=[2 5]';
  6. Y=[19 26 19 20]';
  7. learning_rate=0.01;
  8. loss = 1000;
  9. epsilon = 0.0003;
  10. i = 0;
  11. while(1)
  12.         i = i + 1;
  13.         theta_new = theta_old - learning_rate*(X'*X*theta_old-X'*Y);
  14.         theta_new
  15.         %fprintf('theta now is %2.0f\n',theta_new);
  16.         if((theta_new-theta_old)<epsilon)
  17.             theta_best=theta_new;
  18.             break;
  19.         end
  20.         theta_old = theta_new;
  21.         error = (Y - X*theta_new)'*(Y - X*theta_new);
  22.         fprintf('error now is %f\n',error);
  23.         hold on
  24.         plot(i,error,'+');        
  25. end
复制代码
  1. %随机梯度下降(下降速度快,但收敛精度没有批量梯度下降法高,适用于样本量庞大的情况下)
  2. X=[1 4;2 5;5 1;4 2];
  3. theta_new=[2 5]';
  4. theta_old=[2 5]';
  5. theta_best=[2 5]';
  6. Y=[19 26 19 20]';
  7. learning_rate=0.01;
  8. epsilon = 0.0003;
  9. j=0;
  10. while(1)
  11.     j = j + 1;
  12.     for i = 1:4
  13.         temp1 = X*theta_old;
  14.         theta_new = theta_old + learning_rate*(Y(i) - temp1(i))*X(i,:)';      
  15.         temp2 = theta_old;
  16.         theta_old = theta_new;   
  17.     end
  18.     if(abs(theta_new-temp2)<epsilon)
  19.         theta_best = theta_new;
  20.         break;
  21.     end;
  22.     error = (Y-X*theta_new)'*(Y-X*theta_new);
  23.     hold on
  24.     plot(j,error,'+');
  25. end
复制代码
参考李航的《统计学习方法》。



作者: 蘑菇先生    时间: 2015-7-16 14:03
希望可以和大家一起交流,共同进步。

作者: Macintosh2012    时间: 2015-11-10 02:53



这段时间要用,参考一下





欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5