看了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 values
m = length(y); % number of training examples
J_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的值從而達到同時更新完
end
theta = theta_temp; %全部更新完所有的theta之後再進行下一個迭代
end
% ============================================================
% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end
最後得到的線性迴歸的結果還是比較好的。