天天看點

程式設計作業ex1:線性回歸

一、熱身練習

要求:生成一個5*5的機關矩陣

warmUpExercies 函數:

function A = warmUpExercise() %定義函數A為warmupexercise
A = eye(5);         %eye()機關矩陣,該函數的功能即生成5*5的機關矩陣
end      

調用:

fprintf('Running warmUpExercise ... \n');
fprintf('5x5 Identity Matrix: \n');
warmUpExercise()    %調用該函數

fprintf('Program paused. Press enter to continue.\n');
pause;      

輸出:

程式設計作業ex1:線性回歸

 二、繪圖(plotting)

要求:根據給出的資料(第一列為所在城市的人口,第二列為對應城市的利潤,負數表示虧損)繪制散點圖,以更好選擇餐館的位址

plotData函數:

function plotData(x, y)
plot(x,y,'rx','MarkerSize',10);
ylabel('Profit in $10,000s');   % 設定y軸标簽
xlabel('Population of City in 10,000s');  % 設定x軸标簽
end      

*MarkerSize: 标記大小,預設為6

* rx:紅色的叉号

調用:

fprintf('Plotting Data ...\n')
data = load('ex1data1.txt');    % 加載data檔案
X = data(:, 1); y = data(:, 2);  % 将第一列全部元素指派給X,第二列全部元素指派給y
m = length(y); % 定義m為訓練樣本的數量

plotData(X, y);  % 将X,y作為參數調用plotData函數

fprintf('Program paused. Press enter to continue.\n');
pause;      

輸出:

程式設計作業ex1:線性回歸

三、代價函數和梯度下降

線性回歸的目标是最小化代價函數J(θ):

程式設計作業ex1:線性回歸

,在這裡使用平方法來表示誤差,誤差越小代表拟合的越好。

其中假設 h(x) 由線性模型給出:

程式設計作業ex1:線性回歸

 模型的參數是θj 通過調整θ的值來最小化成本函數,一種方法是梯度下降,在這種算法中,每次疊代都要更新θ

程式設計作業ex1:線性回歸

 随着梯度下降的每一步,參數θj 接近實作最低成本J(θ)的最佳θ值

*與 

=

 不同,

:=

 代表着 同時更新(simultaneously update),簡單來說就是先将計算的 θ存入一個臨時變量,最後所有 θ都計算完了一起再指派回去,例如

temp1 = theta1 - (theta1 - 10 * theta2 * x1) ;
temp2 = theta2 - (theta1 - 10 * theta2 * x2) ;
theta1 = temp1 ;
theta2 = temp2 ;      

在資料中增加一列1,因為代價函數中θ0的系數為1,且将參數初始化為0,将學習率α初始化為0.01

矩陣表示的話類似于:

程式設計作業ex1:線性回歸
X = [ones(m, 1), data(:,1)];  % 向x第一列添加一列1
theta = zeros(2, 1); % 初始化拟合參數

iterations = 1500;   % 疊代次數
alpha = 0.01;    % 學習率設定為0.01      

 ==》計算代價函數J(檢測收斂性)

function J = computeCost(X, y, theta)
m = length(y);
J = 0;
J = sum((X*theta-y).^2)/(2*m);
end      

調用代價函數:

fprintf('\nTesting the cost function ...\n')
% compute and display initial cost 
J = computeCost(X, y, theta);  % 調用代價函數J
fprintf('With theta = [0 ; 0]\nCost computed = %f\n', J);
fprintf('Expected cost value (approx) 32.07\n');

% further testing of the cost function
J = computeCost(X, y, [-1 ; 2]);  % 調用代價函數J      
fprintf('\nWith theta = [-1 ; 2]\nCost computed = %f\n', J); 
fprintf('Expected cost value (approx) 54.24\n'); 
fprintf('Program paused. Press enter to continue.\n'); 
pause;      

運作結果:

程式設計作業ex1:線性回歸

 可以看到,當theta取[0;0]時的代價函數比取[-1;2]的代價函數小,說明[0;0]更優。

gradientDescent.m——運作梯度下降:

說明:驗證梯度下降是否正常工作的一種好方法是檢視J的值并檢查它是否随每一步減少。 gradientDescent.m的代碼在每次疊代時調用computeCost并列印J的值。 假設已正确實作了梯度下降和computeCost,則J的值不應該增加,并且應該在算法結束時收斂到穩定值。

在梯度下降中,每次疊代都執行下面的這個更新:

程式設計作業ex1:線性回歸

梯度下降函數:

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
%   theta = GRADIENTDESCENT(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.
    %

    theta = theta-alpha*(1/m)*X'*(X*theta-y);

    % ============================================================

    % Save the cost J in every iteration    
    J_history(iter) = computeCost(X, y, theta);

end

end      

 調用梯度下降函數:

fprintf('\nRunning Gradient Descent ...\n')
% run gradient descent  運作梯度下降函數
theta = gradientDescent(X, y, theta, alpha, iterations);

% print theta to screen 将theta值輸出
fprintf('Theta found by gradient descent:\n');  % 利用梯度下降函數計算出的theta
fprintf('%f\n', theta);
fprintf('Expected theta values (approx)\n');  % 期望的theta
fprintf(' -3.6303\n  1.1664\n\n');      

運作結果:

程式設計作業ex1:線性回歸

 将得到的參數用MATLAB進行繪制并預測35000和70000人口的利潤:

% Plot the linear fit 繪制線性拟合直線
hold on; % keep previous plot visible  指目前圖形保持,即樣本點仍然保持在圖像上
plot(X(:,2), X*theta, '-')
legend('Training data', 'Linear regression') % 建立圖例标簽
hold off % don't overlay any more plots on this figure

% Predict values for population sizes of 35,000 and 70,000
predict1 = [1, 3.5] *theta;
fprintf('For population = 35,000, we predict a profit of %f\n',...
    predict1*10000);
predict2 = [1, 7] * theta;
fprintf('For population = 70,000, we predict a profit of %f\n',...
    predict2*10000);

fprintf('Program paused. Press enter to continue.\n');
pause;      

運作結果:

程式設計作業ex1:線性回歸

 *注意A*B和A.*B的差別,前者進行矩陣乘法,後者進行逐元素乘法

四、可視化代價函數J

這部分代碼已經給出

fprintf('Visualizing J(theta_0, theta_1) ...\n')

% Grid over which we will calculate J
theta0_vals = linspace(-10, 10, 100);
theta1_vals = linspace(-1, 4, 100);

% initialize J_vals to a matrix of 0's
J_vals = zeros(length(theta0_vals), length(theta1_vals));

% 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 plot
figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0'); ylabel('\theta_1');

% Contour plot
figure;
% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
xlabel('\theta_0'); ylabel('\theta_1');
hold on;
plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);      

運作結果:

程式設計作業ex1:線性回歸
程式設計作業ex1:線性回歸

轉載于:https://www.cnblogs.com/vzyk/p/11528304.html