Machine Learning (6) -- (ex2 / Week 3 / Coursera)

上一节中介绍了线性回归的单一变量和多变量问题,这一节的主题是逻辑回归问题。依然建议是:看视频 => 看PPT => 看Lecture Note => 自己完成练习,如果还是无法解决再来看这篇帖子。另,如果有任何问题,欢迎私戳~ 于是以下开始正文:

1.

  1. 在上一个练习中,我们练习了关于单一和多变量的线性回归,在这一个练习中我们将进行逻辑回归的练习。相关理论内容请在Machine Learning系列的理论博文中找。

这个联系中相关的文件:

ex2.m – 第一个练习的Octave/MATLAB主流程代码;

ex2_reg.m – 第二个练习的Octave/MATLAB主流程代码;

ex2data1.txt – 第一个练习训练数据集;

submit.m – 代码提交函数;

mapFeature.m – 多项特征产生函数;

plotDecisionBoundary.m – 画出分类器的决策边界的函数;

[*] plotData.m – 画出2D分类器数据的函数;

[*] sigmoid.m – S形函数;

[*] costFunction.m – 逻辑回归代价函数;

[*] predict.m – 逻辑回归预测函数;

[*] costFunctionReg.m – 规范化的逻辑回归代价值。

* 必选项。

2. 逻辑回归

2.1 在这一部分的练习中,你将会建立一个逻辑回归模型对某学生是否会被学校录取进行预测。假设你是学校的管理员,你期望通过对每个学生两次考试成绩的分析得出这个申请人是否会被大学录取。你手上现在有之前申请学生的数据,你可以用这个数据建立一个逻辑回归模型,并对未来申请人依照两次考试成绩对申请通过作出预测。

2.2 数据的可视化

  • 如ex1中提到的,在开始任何算法之前,如果可能的话,将数据进行可视化总是非常有帮助的。在ex2.m主程序的开始部分,已经加载了相应的数据集,而通过plotData函数,会将数据集中的数据绘制在二维坐标系中。
  • 注意将正类和负类用不同的符号进行区分。这一部分是选做,但是为了加深对数据可视化的理解,还是建议自己实现一下,然后再回来看参考代码段(如下)。

3. 实现

3.1 热身练习之S形函数:

  • 在开始处理代价函数之前,回忆一下逻辑回归假设函数我们所使用的形式:

  • 其中函数g是S形函数,而S形函数的形式如下所示:

  • S形函数将在文件sigmoid.m中实现,在写S形函数的实现代码时要注意,你的代码需要不仅能适用于单一数值,同样向量和矩阵也要可以实现。关于矩阵和向量的实现,是通过将每一个元素分别计算最终得到的。

3.2 代价函数梯度

  • 下一步将在文件costFunction.m中计算代价函数和梯度。
  • 回忆逻辑回归的代价函数形式如下:

  • 而代价的梯度是一个与θ向量长度相等的向量,其中第j个元素被定义为如下形式(其中j = 0,1,2,……,n):

  • 注意这个梯度计算公式与线性回归的梯度计算公式是不同的,原因是两者的假设函数就不一样。

3.3 使用fminunc函数进行参数学习

  • 在ex1中,使用了梯度下降的方法来找到代价函数的最小值,在这个例子中将不再使用ex1,而是采用Octave/Matlab的内置函数fminunc来实现这一过程,进而找到最佳的θ值,以获得。在使用fminunc函数时,会将如下参数传递给fminunc函数:

※ 需要进行优化的对应参数初值;

※ 在给定训练集合特定参数θ时,计算逻辑回归的代价和梯度的函数。

  • 在文件ex2.m中相应调用fminunc函数的代码已经写好了:

※ 在这个代码段中,首先告诉fminunc函数对应的选项内容。准确的来说,我们将GradObj项设定为on(打开),这个设定会告诉fminunc函数我们导入的函数会返回代价和梯度两个值。从而,fminunc函数可以使用梯度最小化这个函数;

※ 不仅如此,我们还将MaxIter项设定为400,即fminunc最多会运行400次就会终止;

3.4 评估逻辑回归:在文件predict.m中,会完成对上述代码运行结果的评估任务。

============================================== 代码部分 =================================================

※ ex2.m

%% Machine Learning Online Class - Exercise 2: Logistic Regression
%
%  Instructions
%  ------------
% 
%  This file contains code that helps you get started on the logistic
%  regression exercise. You will need to complete the following functions 
%  in this exericse:
%
%     sigmoid.m
%     costFunction.m
%     predict.m
%     costFunctionReg.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%

%% 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);

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

※ 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.
%

[m, n] = size(X);

for i = 1:m
    if y(i) == 1
        plot (X(i, 1), X(i, 2), 'k+', 'LineWidth', 2, 'MarkerSize', 7);
    else
        plot (X(i, 1), X(i, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);
    end
end

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



hold off;

end

※ sigmoid.m

function g = sigmoid(z)
%SIGMOID Compute sigmoid function
%   g = SIGMOID(z) computes the sigmoid of z.

% You need to return the following variables correctly 
g = zeros(size(z));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
%               vector or scalar).

g = 1 ./ (1 + exp(-z));

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

end

※ 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
%

h = sigmoid(X * theta);

J = (1/m) * sum((-y).*log(h) - (1 - y).*log(1 - h));
grad = (1/m) * sum((h - y).*X);

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

end

※ 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
%

temp = zeros(m, 1);
temp = sigmoid(X * theta);

for i = 1:m
    if temp(i) >= 0.5
        p(i) = 1;
    else
        p(i) = 0;
    end
end




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


end

============================================== 代码结束 =================================================

4. 正则化(regularization)逻辑回归

4.1 在这部分练习中,将实现逻辑回归的正则化。预测来自制造工厂的微芯片是否通过质量保证(QA)。在QA中,每个微芯片都经过各种测试,以确保它的功能正常。假设你是工厂的产品经理,你在两个不同的测试中有一些微芯片的测试结果。从这两个测试中,你想要确定芯片是否应该被接受或拒绝。为了帮助你做出决定,你在过去的微芯片上有一个测试结果的数据集,用这个你可以建立一个逻辑回归模型来进行预测。

4.2 将数据可视化:

跟前述过程一样,做任何算法之前先将参数进行可视化,方便理解和找规律,相应可视化结果如下图。

4.3 特征映射

  • 增强数据拟合的一个方法是在上图的每一个数据点创建一个特征,这听起来比较极端,在不考虑过拟合问题的情况下,这样建立起来的预测函数可以完美地预测数据集中的所有数据。但是这样显然过于极端了,所以在这个例子中的文件mapFeature.m中,我们将所有的特征映射到由x1和x2组成的最高到6次的多项式中。

  • 于是本来仅有2个特征的特征向量转化为了28维的特征向量,从而形成的决策边界可以变得更复杂。
  • 仔细观察代码,发现具体过程就是将相应X矩阵的特征列按如上规则运算后拓展为一个28列的矩阵。

4.4 代价函数梯度

  • 文件costFunctionReg.m会返回代价值和梯度。回忆逻辑回归的规范化的代价函数形式为:

  • 但是请注意,参数θ0不需要进行正则化。
  • 梯度计算公式如下:

  • 用fminunc函数进行参数学习:同未正则化逻辑回归的实现一样,下一步是使用fminuc函数学习最优的参数θ

4.5 画出决策边界

  • 为了帮助观察学习模型的效果,文件plotDecisionBoundary.m将会用非线性决策边界将正负样本分割开。
  • 对应的决策边界应该如下图所示:

※ λ = 1的情况:

※ λ = 0的情况(过拟合):

※ λ = 100的情况(欠拟合):

============================================== 代码部分 =================================================

※ ex2_reg.m

%% Machine Learning Online Class - Exercise 2: Logistic Regression
%
%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the second part
%  of the exercise which covers regularization with logistic regression.
%
%  You will need to complete the following functions in this exericse:
%
%     sigmoid.m
%     costFunction.m
%     predict.m
%     costFunctionReg.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%

%% 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');

※ mapFeature.m

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

※ 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


h = sigmoid(X * theta);

J = (1/m) * sum(((-y).*log(h)) - ((1-y).*log(1 - h))) + (lambda/(2*m)) * sum(theta.^2);

grad = (1/m) * sum((h - y).*X);
grad(2:end) = grad(2: end) + (lambda/m) .* theta(2:end)';

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

end

※ plotDecisionBoundary.m

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

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

============================================== 代码结束 =================================================

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值