Coursera-AndrewNg(吳恩達)機器學習筆記——第二周編程作業(線性回歸)


一.准備工作

  1. 從網站上將編程作業要求下載解壓后,在Octave中使用cd命令將搜索目錄移動到編程作業所在目錄,然后使用ls命令檢查是否移動正確。如:
  2. 提交作業:提交時候需要使用自己的登錄郵箱和提交令牌,如下:

二.單變量線性回歸

繪制圖形:rx代表圖形中標記的點為紅色的x,數字10表示標記的大小。

plot(x, y, 'rx', 'MarkerSize', 10); % Plot the data

計算代價函數(Cost Funtion):迭代次數1500,學習速率0.01.   iterations = 1500;  alpha = 0.01;

注意需給原始數據X添加一列值為1的屬性:X = [ones(m, 1), data(:,1)];  theta = zeros(2, 1);

function J = computeCost(X, y, theta)  %文件名為computeCost.m
m = length(y); % number of training examples
J = 1/(2*m)*sum((X*theta-y).^2);
end

梯度下降(Gradient Descent ):

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)  %文件名為gradientDescent.m
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
    temp=X'*(X*theta-y);
    theta=theta-1/m*alpha*temp;
    J_history(iter) = computeCost(X, y, theta);
end
end

然后繪制出我們使用經過梯度下降求出的最優參數θ值所做預測的圖形,如下:

可視化J(θ):

使用表面圖進行可視化:

theta0_vals = linspace(-10, 10, 100);  %生成范圍在[-10,10]之間100個點的線性行矢量,即維數為1*100的矩陣
theta1_vals = linspace(-1, 4, 100);  %生成范圍在[-1,4]之間100個點的線性行矢量,即維數為1*100的矩陣

J_vals = zeros(length(theta0_vals), length(theta1_vals));  %對應的代價函數值,維數為100*100
% Fill out 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

% Because of the way meshgrids work in the surf command, we need to transpose J_vals before calling surf, or else the axes will be flipped
J_vals = J_vals';    %surface函數的特性,必須進行轉置。其實就是因為θ0和θ1要和行列坐標x,y對齊。
% Surface plot
figure;
surf(theta0_vals, theta1_vals, J_vals)  %繪制表面圖
xlabel('\theta_0'); ylabel('\theta_1');

結果如下:從圖中可看出代價函數值J(θ)有全局最優解(最低點)。

使用等高線圖進行可視化:(logspace函數和linspace函數類似,此處作用生成將區間[10-2,103]等分20份的1*20矩陣)

figure;  %這里的J_vals在前面進行了轉置,所以此處不用轉置!
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))  
xlabel('\theta_0'); ylabel('\theta_1');  %用到了轉義字符'\theta_0'和'\theta_1'.
hold on;
plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);

結果如下:可以看出我們求出的最優參數θ所對應的代價值,正好位於等高線圖最低的位置!

三.多變量線性回歸(選做)

特征規則化:

function [X_norm, mu, sigma] = featureNormalize(X)  %文件名為featureNormalize.m
X_norm = X;
mu = zeros(1, size(X, 2));  %記錄每個特征xi的平均值
sigma = zeros(1, size(X, 2));  %記錄每個特征xi的標准差值

for i=1:size(X,2),
  mu(i)=mean(X(:,i));    %使用公式mean求平均值
  sigma(i)=std(X(:,i));   %使用公式std求標准差值
  X_norm(:,i)=(X_norm(:,i)-mu(i))/sigma(i);
end
end

代價函數和梯度下降:和單變量相同(省略)

不同學習速率下,隨着迭代次數的增加,代價函數值逐漸收斂圖形:可以發現學習速率為0.01最為合適!

房價預測:Estimate the price of a 1650 sq-ft, 3 br house

% Estimate the price of a 1650 sq-ft, 3 br house
% ====================== YOUR CODE HERE ======================
% Recall that the first column of X is all-ones. Thus, it does
% not need to be normalized.
x_try=[1650 3];
x_try(1)=x_try(1)-mu(1);
x_try(2)=x_try(2)-mu(2);
x_try(1)=x_try(1)/sigma(1);
x_try(2)=x_try(2)/sigma(2);
price = [ones(1, 1) x_try]*theta; % 這里的theta是我們前面經過梯度下降求出的

 正規方程求參數theta:

function [theta] = normalEqn(X, y)
theta = zeros(size(X, 2), 1);
theta=pinv(X'*X)*X'*y;
end

無~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM