机器学习中的参数值同时更新问题

来源:互联网 发布:excel会计记账软件 编辑:程序博客网 时间:2024/06/07 03:15

看了NG的机器学习coursera上的斯坦福课,觉得讲的还是很不错的(coursera机器学习课程)。

然后自己做了课后的作业(第一次的作业,需要用matlab实现linear regression,具体还请参见视频)。在线性回归的算法中,比较重要的就是权值更新,也就是theta的更新。如图中的算法


自己一开始编程的时候是在做两层嵌套循环的,但是做了之后发现,自己并没有考虑同时更新这点,所以最后编写函数会出现偏差。后来修正了算法之后,问题得到了解决,也算是自己学习的一点体会,现在与大家分享。

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)%GRADIENTDESCENT Performs gradient descent to learn theta%   theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by %   taking num_iters gradient steps with learning rate alpha% Initialize some useful valuesm = length(y); % number of training examplesJ_history = zeros(num_iters, 1);for iter = 1:num_iters    % ====================== YOUR CODE HERE ======================    % Instructions: Perform a single gradient step on the parameter vector    %               theta.     %    % Hint: While debugging, it can be useful to print out the values    %       of the cost function (computeCost) and gradient here.    %n = length(theta);theta_temp = theta;for j =1:n;        temp = 0;                           % 计算theta要减去的值for i = 1:m    temp_h = X(i,:)*theta;    temp = temp + (temp_h - y(i))*X(i,j);end    temp = alpha * temp/m;     theta_temp(j) = theta_temp(j) - temp;   %同时更新所有的theta_temp但是不能修改theta的值从而达到同时更新完endtheta = theta_temp;                     %全部更新完所有的theta之后再进行下一个迭代end    % ============================================================    % Save the cost J in every iteration        J_history(iter) = computeCost(X, y, theta);end
最后得到的线性回归的结果还是比较好的。

0 0
原创粉丝点击