機器學習: 邏輯迴歸(Logistic Regression) 小項目

該項目的所有代碼在我的github上,歡迎有興趣的同學與我探討研究~
地址:Machine-Learning/machine-learning-ex2/


1. Introduction

邏輯迴歸(Logistic Regression), 在Wiki上的定義如下:

In statistics, logistic regression, or logit regression, or logit model[1] is a regression model where the dependent variable (DV) is categorical. This article covers the case of a binary dependent variable—that is, where it can take only two values, “0” and “1”, which represent outcomes such as pass/fail, win/lose, alive/dead or healthy/sick. Cases where the dependent variable has more than two outcome categories may be analysed in multinomial logistic regression, or, if the multiple categories are ordered, in ordinal logistic regression.[2] In the terminology of economics, logistic regression is an example of a qualitative response/discrete choice model.

以我的理解,邏輯迴歸也是數據擬合的一種工具,它用於解決分類問題,即結果是離散型的,而這類問題往往用線性迴歸不能很好的解決。因此,對於分類問題,我們應當選擇邏輯迴歸而不是線性迴歸。

邏輯迴歸主要有兩類:

  • Logistic Regression with two outcome, it often called logistic regression.
  • Logistic Regression with more than two outcome, it often call multinomial logistic Regression

對於邏輯迴歸,那麼不得不提到Decision Boundary(決策邊界)。決策邊界是用於將不同類別的數據劃分開來,它也有兩種類型:

  • Linear decision boundaries 線性決策邊界
  • Non-linear decision boundaries 非線性決策邊界

通常,我們會通過梯度下降或者其它優化算法得到最終的theta。然後利用theta,劃出決策邊界。注意:決策邊界是假設函數的屬性,與訓練集並沒有直接關係,它是由假設函數的theta決定的。

邏輯迴歸的假設函數,Sigmoid函數,這個函數的特徵如下:

  • 當X爲0時,函數值爲0.5;
  • 當X<0時,函數值< 0.5, 當X > 0時,函數值>0.5;
  • 當X趨近於負無窮時,函數值趨近於0;
  • 當X趨近於正無窮時,函數值趨近於1;
  • 函數形狀類似於一個S,所以稱爲S型函數。

假設函數的函數值代表的是是輸出爲1的概率,可以設置一個值如0.5:當函數值>=0.5時,output爲1, 當函數值 < 0.5時, output爲0.

對於損失函數,如果直接以代入假設函數求得,那麼該損失函數將會是“non-convex”(非凸性),這將對梯度下降的速率有很大的影響。所以便有了對數形式的損失函數。因爲是分類問題,所以損失函數有兩種情況,但通過一些技巧可以將它們合二爲一。

在編寫代碼時,將式子以向量化(Vectorization)的形式也是很方便的。

梯度,就是損失函數J(theta)對theta的偏導

爲了解決多結果的迴歸問題,我們要使用的是one-VS-all的算法。例如我的結果有三類(A、B、C),我可以用3個分類器實現(AB,AC,BC)。然後將X帶入每個分類器,哪個值高選哪個

對於擬合,有三類情況:

  • Underfitting 欠擬合: 沒有較好擬合數據,預測準確率不高
  • Overfitting 過擬合 :過分擬合數據,導致泛化程度不高,影響預測的準確率
  • Oridinary 普通 : 較好擬合數據

Underfitting, or high bias, is when the form of our hypothesis function h maps poorly to the trend of the data. It is usually caused by a function that is too simple or uses too few features. At the other extreme, overfitting, or high variance, is caused by a hypothesis function that fits the available data but does not generalize well to predict new data. It is usually caused by a complicated function that creates a lot of unnecessary curves and angles unrelated to the data.

解決Overfitting,主要有兩種方法:

  • Reduce the number of features;
    • Manually select which features to keep.
    • Use a model selection algorithm (studied later in the course).
  • Regularization.
    • Keep all the features, but reduce the magnitude of parameters theta
    • Regularization works well when we have a lot of slightly useful features

下面談談Regularization (正規化)

正規化就是通過添加多餘的項以減少theta的大小,從而避免出現過擬合的情況。我們知道,當feature過多時,會導致過擬合的情況。爲了解決這一問題,我們要減少feature的影響,即我們需要適當減少theta的值,極限情況下是對應theta等於0,那麼feature也就不發揮作用了。

那如何衡量正規化的程度呢?有lambda參數。合適的lambda參數可以使過擬合變成正常擬合,但是太大的lambada值也有可能將過擬合變成欠擬合。所以選擇一個合適的lambada值也是很重要的。待會project會有所涉及。

需要掌握:
1. 邏輯迴歸的假設函數、損失函數、梯度下降的迭代函數;
2. 邏輯迴歸的梯度計算;
3. 正規化後邏輯迴歸的假設函數、損失函數、梯度下降的迭代函數。

2. Logistic Regression

主函數

%% Initialization
clear ; close all; clc

%% Load Data
%  The first two columns contains the exam scores and the third column
%  contains the label.

data = load('ex2data1.txt');
X = data(:, [1, 2]); y = data(:, 3);

%% ==================== Part 1: Plotting ====================
%  We start the exercise by first plotting the data to understand the 
%  the problem we are working with.

fprintf(['Plotting data with + indicating (y = 1) examples and o ' ...
         'indicating (y = 0) examples.\n']);

plotData(X, y);

% Put some labels 
hold on;
% Labels and Legend
xlabel('Exam 1 score')
ylabel('Exam 2 score')

% Specified in plot order
legend('Admitted', 'Not admitted')
hold off;

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


%% ============ Part 2: Compute Cost and Gradient ============
%  In this part of the exercise, you will implement the cost and gradient
%  for logistic regression. You neeed to complete the code in 
%  costFunction.m

%  Setup the data matrix appropriately, and add ones for the intercept term
[m, n] = size(X);

% Add intercept term to x and X_test
X = [ones(m, 1) X];

% Initialize fitting parameters
initial_theta = zeros(n + 1, 1);

% Compute and display initial cost and gradient
[cost, grad] = costFunction(initial_theta, X, y);

fprintf('Cost at initial theta (zeros): %f\n', cost);
fprintf('Expected cost (approx): 0.693\n');
fprintf('Gradient at initial theta (zeros): \n');
fprintf(' %f \n', grad);
fprintf('Expected gradients (approx):\n -0.1000\n -12.0092\n -11.2628\n');

% Compute and display cost and gradient with non-zero theta
test_theta = [-24; 0.2; 0.2];
[cost, grad] = costFunction(test_theta, X, y);

fprintf('\nCost at test theta: %f\n', cost);
fprintf('Expected cost (approx): 0.218\n');
fprintf('Gradient at test theta: \n');
fprintf(' %f \n', grad);
fprintf('Expected gradients (approx):\n 0.043\n 2.566\n 2.647\n');

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


%% ============= Part 3: Optimizing using fminunc  =============
%  In this exercise, you will use a built-in function (fminunc) to find the
%  optimal parameters theta.

%  Set options for fminunc
options = optimset('GradObj', 'on', 'MaxIter', 400);

%  Run fminunc to obtain the optimal theta
%  This function will return theta and the cost 
[theta, cost] = ...
    fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);

% Print theta to screen
fprintf('Cost at theta found by fminunc: %f\n', cost);
fprintf('Expected cost (approx): 0.203\n');
fprintf('theta: \n');
fprintf(' %f \n', theta);
fprintf('Expected theta (approx):\n');
fprintf(' -25.161\n 0.206\n 0.201\n');

% Plot Boundary
plotDecisionBoundary(theta, X, y);

% Put some labels 
hold on;
% Labels and Legend
xlabel('Exam 1 score')
ylabel('Exam 2 score')

% Specified in plot order
legend('Admitted', 'Not admitted')
hold off;

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

%% ============== Part 4: Predict and Accuracies ==============
%  After learning the parameters, you'll like to use it to predict the outcomes
%  on unseen data. In this part, you will use the logistic regression model
%  to predict the probability that a student with score 45 on exam 1 and 
%  score 85 on exam 2 will be admitted.
%
%  Furthermore, you will compute the training and test set accuracies of 
%  our model.
%
%  Your task is to complete the code in predict.m

%  Predict probability for a student with score 45 on exam 1 
%  and score 85 on exam 2 

prob = sigmoid([1 45 85] * theta);
fprintf(['For a student with scores 45 and 85, we predict an admission ' ...
         'probability of %f\n'], prob);
fprintf('Expected value: 0.775 +/- 0.002\n\n');

% Compute accuracy on our training set
p = predict(theta, X);

% 如果矩陣中所有元素一一對應,則mean(double(p == y))的值爲1
% 如果不對應,則值相應減少。如四個中有三個一一對應,那麼則其值爲0.75

fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);
fprintf('Expected accuracy (approx): 89.0\n');
fprintf('\n');

Part1: 將訓練集呈現在圖中,“+”表示Admitted, “o”表示Not Admitted。而這一結果是由兩個exam的分數決定的,即包含兩個feature決定最後的結果。
plotData.m

function plotData(X, y)
%PLOTDATA Plots the data points X and y into a new figure 
%   PLOTDATA(x,y) plots the data points with + for the positive examples
%   and o for the negative examples. X is assumed to be a Mx2 matrix.

% Create New Figure
figure; hold on;

% ====================== YOUR CODE HERE ======================
% Instructions: Plot the positive and negative examples on a
%               2D plot, using the option 'k+' for the positive
%               examples and 'ko' for the negative examples.
%

% Find Indices of Positive and Negative Example
pos = find(y == 1);
neg = find(y == 0);

% Plot Examples
% Attention: cannot add '' to the number, such as '2', '7', it's wrong
plot(X(pos, 1), X(pos, 2), 'k+', 'LineWidth', 2, 'MarkerSize', 7);
plot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);

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

hold off;

end

這裏寫圖片描述

Part2:計算損失函數和梯度

costFunction.m

function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
%   J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
%   parameter for logistic regression and the gradient of the cost
%   w.r.t. to the parameters.

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta
%
% Note: grad should have the same dimensions as theta
%

% Calulate the function h, we know it's sigmoid function
h = sigmoid(X*theta);
% Calculate the cost function
J = 1/m*(-y'*log(h)-(1-y)'*log(1-h));
% Calculate the Gradient
grad = 1/m*X'*(h-y);

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

end

Part3: 使用優化函數fminunc來得到使Cost Function函數值最小的theta, 然後使用該theta值畫出決策邊界。

plotDecisionBoundary.m
此處分了兩類情況:如果feature小於等於2,則決策邊界是線性的;如果feature大於2,則決策邊界是非線性的。至於它爲什麼這麼定義決策邊界我就不大清楚了,如果有大神指點一下表示感謝耶~

function plotDecisionBoundary(theta, X, y)
%PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with
%the decision boundary defined by theta
%   PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the 
%   positive examples and o for the negative examples. X is assumed to be 
%   a either 
%   1) Mx3 matrix, where the first column is an all-ones column for the 
%      intercept.
%   2) MxN, N>3 matrix, where the first column is all-ones

% Plot Data
plotData(X(:,2:3), y);
hold on

% size < 3, it means that the feature is less than or equal to 2
if size(X, 2) <= 3
    % Only need 2 points to define a line, so choose two endpoints
    plot_x = [min(X(:,2))-2,  max(X(:,2))+2];

    % Calculate the decision boundary line
    plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));

    % Plot, and adjust axes for better viewing
    plot(plot_x, plot_y)

    % Legend, specific for the exercise
    legend('Admitted', 'Not admitted', 'Decision Boundary')
    axis([30, 100, 30, 100])
else
    % Here is the grid range
    u = linspace(-1, 1.5, 50);
    v = linspace(-1, 1.5, 50);

    z = zeros(length(u), length(v));
    % Evaluate z = theta*x over the grid
    for i = 1:length(u)
        for j = 1:length(v)
            z(i,j) = mapFeature(u(i), v(j))*theta;
        end
    end
    z = z'; % important to transpose z before calling contour

    % Plot z = 0
    % Notice you need to specify the range [0, 0]
    contour(u, v, z, [0, 0], 'LineWidth', 2)
end
hold off

end

這裏寫圖片描述

mapFeature.m
這個函數適用於產生多項式項,即可以增加feature的數量,使得決策邊界更貼近訓練集。

function out = mapFeature(X1, X2)
% MAPFEATURE Feature mapping function to polynomial features
%
%   MAPFEATURE(X1, X2) maps the two input features
%   to quadratic features used in the regularization exercise.
%
%   Returns a new feature array with more features, comprising of 
%   X1, X2, X1.^2, X2.^2, X1*X2, X1*X2.^2, etc..
%
%   Inputs X1, X2 must be the same size
%

degree = 6;
out = ones(size(X1(:,1)));
for i = 1:degree
    for j = 0:i
        out(:, end+1) = (X1.^(i-j)).*(X2.^j);
    end
end

end

Part4: 使用上述方法進行訓練,進而對exam1(45分)、exam2(85分)進行預測並計算出預測準確率。

predict.m

function p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic 
%regression parameters theta
%   p = PREDICT(theta, X) computes the predictions for X using a 
%   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters. 
%               You should set p to a vector of 0's and 1's
%

% 這個函數的目的是:計算你的預測的準確率
% 方法是用你得到的theta作爲h(x)的參數,對訓練集中的數據全都預測一遍
% 然後與訓練集中對應的y值進行對比,計算出準確率

% 對訓練集進行逐行便利,計算出每個訓練樣例的y值準確率
% 如果大於或等於0.5,則將p對應位置設爲1,否則爲0

for i = 1: m
  if (sigmoid(X(i,:)*theta) >= 0.5)
    p(i) = 1;
  else
    p(i) = 0;
  end

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


end

輸出結果:
這裏寫圖片描述

3. Regularization

主函數:

%% Initialization
clear ; close all; clc

%% Load Data
%  The first two columns contains the X values and the third column
%  contains the label (y).

data = load('ex2data2.txt');
X = data(:, [1, 2]); y = data(:, 3);

plotData(X, y);

% Put some labels
hold on;

% Labels and Legend
xlabel('Microchip Test 1')
ylabel('Microchip Test 2')

% Specified in plot order
legend('y = 1', 'y = 0')
hold off;


%% =========== Part 1: Regularized Logistic Regression ============
%  In this part, you are given a dataset with data points that are not
%  linearly separable. However, you would still like to use logistic
%  regression to classify the data points.
%
%  To do so, you introduce more features to use -- in particular, you add
%  polynomial features to our data matrix (similar to polynomial
%  regression).
%

% Add Polynomial Features

% Note that mapFeature also adds a column of ones for us, so the intercept
% term is handled
X = mapFeature(X(:,1), X(:,2));

% Initialize fitting parameters
initial_theta = zeros(size(X, 2), 1);

% Set regularization parameter lambda to 1
lambda = 1;

% Compute and display initial cost and gradient for regularized logistic
% regression
[cost, grad] = costFunctionReg(initial_theta, X, y, lambda);

fprintf('Cost at initial theta (zeros): %f\n', cost);
fprintf('Expected cost (approx): 0.693\n');
fprintf('Gradient at initial theta (zeros) - first five values only:\n');
fprintf(' %f \n', grad(1:5));
fprintf('Expected gradients (approx) - first five values only:\n');
fprintf(' 0.0085\n 0.0188\n 0.0001\n 0.0503\n 0.0115\n');

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

% Compute and display cost and gradient
% with all-ones theta and lambda = 10
test_theta = ones(size(X,2),1);
[cost, grad] = costFunctionReg(test_theta, X, y, 10);

fprintf('\nCost at test theta (with lambda = 10): %f\n', cost);
fprintf('Expected cost (approx): 3.16\n');
fprintf('Gradient at test theta - first five values only:\n');
fprintf(' %f \n', grad(1:5));
fprintf('Expected gradients (approx) - first five values only:\n');
fprintf(' 0.3460\n 0.1614\n 0.1948\n 0.2269\n 0.0922\n');

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

%% ============= Part 2: Regularization and Accuracies =============
%  Optional Exercise:
%  In this part, you will get to try different values of lambda and
%  see how regularization affects the decision coundart
%
%  Try the following values of lambda (0, 1, 10, 100).
%
%  How does the decision boundary change when you vary lambda? How does
%  the training set accuracy vary?
%

% Initialize fitting parameters
initial_theta = zeros(size(X, 2), 1);

% Set regularization parameter lambda to 1 (you should vary this)
lambda = 1;

% Set Options
options = optimset('GradObj', 'on', 'MaxIter', 400);

% Optimize
[theta, J, exit_flag] = ...
    fminunc(@(t)(costFunctionReg(t, X, y, lambda)), initial_theta, options);

% Plot Boundary
plotDecisionBoundary(theta, X, y);
hold on;
title(sprintf('lambda = %g', lambda))

% Labels and Legend
xlabel('Microchip Test 1')
ylabel('Microchip Test 2')

legend('y = 1', 'y = 0', 'Decision boundary')
hold off;

% Compute accuracy on our training set
p = predict(theta, X);

fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);
fprintf('Expected accuracy (with lambda = 1): 83.1 (approx)\n');

Part1: 正規化邏輯迴歸

訓練集分佈如下:
這裏寫圖片描述

costFunctionReg.m

function [J, grad] = costFunctionReg(theta, X, y, lambda)
%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization
%   J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using
%   theta as the parameter for regularized logistic regression and the
%   gradient of the cost w.r.t. to the parameters. 

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta

% Calulate the function h, we know it's sigmoid function
h = sigmoid(X*theta);
% Calculate the cost function
% 因爲theta1不參與正規化,所以應當把theta1去掉(而且式子中也是不包含這一項的)
% 注意:式子中向量下標是從0開始的,而在Octave中,向量下標是從1開始的。

J = 1/m*(-y'*log(h)-(1-y)'*log(1-h))+lambda/(2*m)*(sum(theta.^2)-theta(1)^2);
% Calculate the Gradient
grad = 1/m*X'*(h-y)+lambda/m*theta;
% It must start at 1
grad(1) = (1/m*X'*(h-y))(1);

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

end

Part2: 正規化與準確率

lambda爲0:
這裏寫圖片描述

lambda爲1:
這裏寫圖片描述

lambda爲10:
這裏寫圖片描述

lambda爲100:
這裏寫圖片描述

從lambda = 0與 lambda = 1對比可知,正規化削弱了過擬合;
從lambda = 10 與 lambda = 100可知,正規化參數過大會導致欠擬合。

輸出結果:
這裏寫圖片描述

3. Conclusion

本篇博文簡要介紹了與邏輯迴歸的相關知識以及小項目,同時還介紹了Regularization來提高預測的準確性。雖然在項目中只對邏輯迴歸進行正規化,但是Regularization同樣可以運用到線性迴歸、梯度下降、正規方程等中

通過這個小項目,不僅對邏輯迴歸有了進一步的瞭解,還了解到了正規化的方法。不過這篇博文涉及的邏輯迴歸主要是隻有兩個outcomes的,對於多outcomes的沒有涉及到,這也是這個project的侷限性所在。以後如果接觸了多outcomes的邏輯迴歸再進一步介紹。


以上內容皆爲本人觀點,歡迎大家提出批評和知道,我們一起探討!


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