Machine_learning---Linear Regression

一、算法實現


由前面的理論,我們知道了用梯度下降解決線性迴歸的公式:


梯度下降解決線性迴歸思路:




算法實現:

ComputeCost函數:

[plain] view plaincopy
  1. function J = computeCost(X, y, theta)  
  2.       
  3.     m = length(y); % number of training examples  
  4.     J = 0;  
  5.     predictions = X * theta;  
  6.     J = 1/(2*m)*(predictions - y)'*(predictions - y);  
  7.   
  8. end  

gradientDescent函數:

[plain] view plaincopy
  1. function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)  
  2. % X is m*(n+1) matrix   
  3. % y is m*1  
  4. % theta is (n+1)*1 matrix  
  5. % alpha is a number   
  6. % num_iters is number of iterators  
  7.   
  8.       
  9.     m = length(y); % number of training examples  
  10.     J_history = zeros(num_iters, 1);  %cost function的值的變化過程  
  11.     %預先定義了迭代的次數  
  12.   
  13.     for iter = 1:num_iters  
  14.   
  15.         temp1 = theta(1) - (alpha / m) * sum((X * theta - y).* X(:,1));  
  16.         temp2 = theta(2) - (alpha / m) * sum((X * theta - y).* X(:,2));  
  17.         theta(1) = temp1;  
  18.         theta(2) = temp2;  
  19.         J_history(iter) = computeCost(X, y, theta);  
  20.   
  21.     end  
  22.   
  23. end  



二、數據可視化


我們通過算法實現能夠求出函數h(x),但是我們還需要將數據可視化:
(1)畫出訓練集的散點圖+擬合後的直線;
(2)畫出J(theta)爲z軸,theta0爲x軸,theta1爲y軸的三維曲線;
(3)畫出(2)的三維曲線的等高線圖;



1.畫散點圖+擬合的直線


描述:給定ex1data1.txt,文件中有兩列數據,每一列代表一個維度,第一列代表X,第二列代表Y,用Octave畫出散佈圖(Scalar Plot),數據的形式如下:

6.1101,17.592

5.5277,9.1302

8.5186,13.662

7.0032,11.854

5.8598,6.8233

8.3829,11.886

........


答:
(1)data = load('ex1data1.txt');             %導入該文件,並賦予data變量
(2)X = data( : , 1 );Y = data( : , 2);    %將兩列分別賦予X和Y
(3)X = [ones(size(X,1),1),X];                  %在X的左邊添加一列1
(4)plot(X,Y,'rx','MarkerSize', 4);            %畫圖,將X向量作爲X軸,Y向量作爲Y軸,每個點用“x”表示,‘r’表示紅點,每個點的大小爲4;
(5)axis([4 24 -5 25]);                             %調整x和y軸的起始座標和最高座標;
(6)xlabel('x');                                         %給x軸標號爲‘x’;
(7)ylabel('y');                                        %給y軸標號爲‘y’;

最後見下圖:


經過計算,算出theta值:
[theta,J_history] = gradientDescent(X, y, theta, alpha, num_iters);
即可通過:
plot(X(:,2), X*theta);             %畫出最後擬合的直線



以上呈現了線性迴歸的結果;

以下兩種都是可視化J(theta);


2.Surface Plot


描述:數據如上一題一樣,我們想要繪製出對於這些數據的cost function,我們將繪製出三維圖形和contour plot;

我們如果要繪製cost function,我們必須預先寫好cost function的公式:
function J = computeCost(X, y, theta)
    m = length(y); 
    J = 0;
    predictions = X * theta;
    J = 1/(2*m)*sum((predictions - y) .^ 2);
end

實現:

(1)theta0_vals = linspace(-10, 10, 100);                  %從-10到10之間取100個數組成一個向量
(2)theta1_vals = linspace(-1, 4, 100);                      %從-1到4之間取100個數組成一個向量
(3)J_vals = zeros(length(theta0_vals), length(theta1_vals));   %初始化J_vals矩陣,對於某個theta0和theta1,J_vals都有對應的cost function值;
(4)計算每個(theta0,theta1)所對應的J_vals;
for i = 1:length(theta0_vals)
    for j = 1:length(theta1_vals)
  t = [theta0_vals(i); theta1_vals(j)];    
  J_vals(i,j) = computeCost(X, y, t);
    end
end
(5)figure;                      %創建一個圖
(6)surf(theta0_vals,theta1_vals,J_vals);  %x軸爲theta0_vals,y軸爲theta1_vals,z軸爲J_vals;
(7)xlabel('\theta_0');   %添加x軸標誌
(8)ylabel('\theta_1');   %添加y軸標誌


 
此圖而且可以轉動;



2.Contour Plot

實現:

(1)theta0_vals = linspace(-10, 10, 100);                  %從-10到10之間取100個數組成一個向量
(2)theta1_vals = linspace(-1, 4, 100);                      %從-1到4之間取100個數組成一個向量
(3)J_vals = zeros(length(theta0_vals), length(theta1_vals));   %初始化J_vals矩陣,對於某個theta0和theta1,J_vals都有對應的cost function值;
(4)計算每個(theta0,theta1)所對應的J_vals;
for i = 1:length(theta0_vals)
    for j = 1:length(theta1_vals)
  t = [theta0_vals(i); theta1_vals(j)];    
  J_vals(i,j) = computeCost(X, y, t);
    end
end
(5)figure;                      %創建一個圖
(6)contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20));  %畫等高線圖
(7)xlabel('\theta_0'); ylabel('\theta_1');



如果我們想要在等高線圖上畫出線性迴歸的theta0與theta1的結果,則可以:
plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);


 

 


4.畫圖查看Learning Rate是否合理

 
我們在gradientDescent函數中返回的值裏有J_history向量,此向量記錄了每次迭代後cost function的值,因此我們只需要將x軸爲迭代的次數,y軸爲cost function的值,即可畫圖:

(1)[theta,J_history] = gradientDescent(X, y, theta, alpha, num_iters);
(2)figure;        
(3)plot(1:length(J_history), J_history, '-b', 'LineWidth', 2);   
(4)xlabel('Number of iterations');
(5)ylabel('Cost J');


 
當然,我們也可以將不同的alpha值都畫在一張圖上,可以比較取各個alpha時,cost function的變化趨勢;
 
(1)alpha=0.01;
(2)[theta,J1] = gradientDescent(X, y, zeros(3,1), alpha, num_iters);
(3)alpha=0.03;
(4)[theta,J2] = gradientDescent(X, y, zeros(3,1), alpha, num_iters);
(5)alpha=0.1;
(6)[theta,J3] = gradientDescent(X, y, zeros(3,1), alpha, num_iters);
(7)plot(1:numel(J1), J1, '-b', 'LineWidth', 2);
(8)plot(1:numel(J2), J2, '-r', 'LineWidth', 2);
(9)plot(1:numel(J3), J3, '-k', 'LineWidth', 2);




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章