[ML] ex report 3 Multi-class Classification

Introduction

用one-vs-all logistic regression和neural networks识别手写阿拉伯数字。

1 Multi-class Classification

多分类问题是二分类问题的扩展。在二分类问题中,一类为正项,一类为负项,线性回归所拟合的这条decision boundary,在使用sigmoid函数之后,代入函数算出预测值y代表为正项的概率。
一个疑问,如果把正负项的值对换,再学习出来的theta会不变吗,但是decision boundary两边的值变了啊?
在1v1中,我们只做了一个分类器,在one-vs-all中,可以做n个(=类数)分类器,每个分类器负责该类的预测,该类为正项,其他类为负项。在predict的时候,计算这n个分类器的值,代表属于该类的概率,选择概率值最高的类。

1.1 Dataset

一共有5000个训练样本,每个训练样本是400维的列向量(20X20像素的 grayscale image),用矩阵 X 保存。样本的结果(label of training set)保存在向量 y 中,y 是一个5000行1列的列向量。比如 y = (1,2,3,4,5,6,7,8,9,10......)T,注意,由于Matlab下标是从1开始的,故用 10 表示数字 0

load('ex3data1.mat');可以将数据加载到matlab。

%% Machine Learning Online Class - Exercise 3 | Part 1: One-vs-all

%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the
%  linear exercise. You will need to complete the following functions
%  in this exericse:
%
%     lrCostFunction.m (logistic regression cost function)
%     oneVsAll.m
%     predictOneVsAll.m
%     predict.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

%% Setup the parameters you will use for this part of the exercise
input_layer_size  = 400;  % 20x20 Input Images of Digits
num_labels = 10;          % 10 labels, from 1 to 10
                          % (note that we have mapped "0" to label 10)

%% =========== Part 1: Loading and Visualizing Data =============
%  We start the exercise by first loading and visualizing the dataset.
%  You will be working with a dataset that contains handwritten digits.
%

% Load Training Data
fprintf('Loading and Visualizing Data ...\n')

load('ex3data1.mat'); % training data stored in arrays X, y
m = size(X, 1);

1.2 Visualizing the data

报警了,不想看。

% Randomly select 100 data points to display
rand_indices = randperm(m);
sel = X(rand_indices(1:100), :);

displayData(sel);

fprintf('Program paused. Press enter to continue.\n');
pause;
function [h, display_array] = displayData(X, example_width)
%DISPLAYDATA Display 2D data in a nice grid
%   [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data
%   stored in X in a nice grid. It returns the figure handle h and the 
%   displayed array if requested.

% Set example_width automatically if not passed in
if ~exist('example_width', 'var') || isempty(example_width) 
    example_width = round(sqrt(size(X, 2)));
end

% Gray Image
colormap(gray);

% Compute rows, cols
[m n] = size(X);
example_height = (n / example_width);

% Compute number of items to display
display_rows = floor(sqrt(m));
display_cols = ceil(m / display_rows);

% Between images padding
pad = 1;

% Setup blank display
display_array = - ones(pad + display_rows * (example_height + pad), ...
                       pad + display_cols * (example_width + pad));

% Copy each example into a patch on the display array
curr_ex = 1;
for j = 1:display_rows
    for i = 1:display_cols
        if curr_ex > m, 
            break; 
        end
        % Copy the patch
        
        % Get the max value of the patch
        max_val = max(abs(X(curr_ex, :)));
        display_array(pad + (j - 1) * (example_height + pad) + (1:example_height), ...
                      pad + (i - 1) * (example_width + pad) + (1:example_width)) = ...
                        reshape(X(curr_ex, :), example_height, example_width) / max_val;
        curr_ex = curr_ex + 1;
    end
    if curr_ex > m, 
        break; 
    end
end

% Display Image
h = imagesc(display_array, [-1 1]);

% Do not show axis
axis image off

drawnow;

end

1.3 Vectorizing Logistic Regression

熟悉的向量化,基本写三次就会了,写出routine了都。代价函数就是同一个套路。不懂得地方在于regularize。
后面加上一项lambda来regularize是为了防止过拟合,但是我忘记为什么这样可以防止过拟合了。

%% ============ Part 2a: Vectorize Logistic Regression ============
%  In this part of the exercise, you will reuse your logistic regression
%  code from the last exercise. You task here is to make sure that your
%  regularized logistic regression implementation is vectorized. After
%  that, you will implement one-vs-all classification for the handwritten
%  digit dataset.
%

% Test case for lrCostFunction
fprintf('\nTesting lrCostFunction() with regularization');

theta_t = [-2; -1; 1; 2];
X_t = [ones(5,1) reshape(1:15,5,3)/10];
y_t = ([1;0;1;0;1] >= 0.5);
lambda_t = 3;
[J grad] = lrCostFunction(theta_t, X_t, y_t, lambda_t);

fprintf('\nCost: %f\n', J);
fprintf('Expected cost: 2.534819\n');
fprintf('Gradients:\n');
fprintf(' %f \n', grad);
fprintf('Expected gradients:\n');
fprintf(' 0.146561\n -0.548558\n 0.724722\n 1.398003\n');

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

1.3.1 Vectorizing the cost function

function [J, grad] = lrCostFunction(theta, X, y, lambda)
%LRCOSTFUNCTION Compute cost and gradient for logistic regression with 
%regularization
%   J = LRCOSTFUNCTION(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
%
% Hint: The computation of the cost function and gradients can be
%       efficiently vectorized. For example, consider the computation
%
%           sigmoid(X * theta)
%
%       Each row of the resulting matrix will contain the value of the
%       prediction for that example. You can make use of this to vectorize
%       the cost function and gradient computations. 
%
% Hint: When computing the gradient of the regularized cost function, 
%       there're many possible vectorized solutions, but one solution
%       looks like:
%           grad = (unregularized gradient for logistic regression)
%           temp = theta; 
%           temp(1) = 0;   % because we don't add anything for j = 0  
%           grad = grad + YOUR_CODE_HERE (using the temp variable)
%

%theta_s = [0; theta(2:end)];
J=(-y'*log(sigmoid(X*theta))-(1-y)'*log(1-sigmoid(X*theta)))/m+lambda * sum(theta(2:end).^2)/(2*m);

grad=(X'*(sigmoid(X*theta)-y))/m;
temp=theta;
temp(1)=0;
%grad=grad+lambda/m*sum(temp);
grad=grad+lambda/m*temp;




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

grad = grad(:);

end

1.3.2 Vectorizing the gradient

要注意的一点是the extra bias unit 项不需要regularize,有好几种写法,都可以把bias项置为0。

1.3.3 Vectorizing regularized logistic regressionA

在写gradient的regularization的那一项不需要求和的。

1.4 One-vs-all Classification

num_labels 为分类器个数,共10个,每个分类器(模型)用来识别10个数字中的某一个。
我们一共有5000个样本,每个样本有400中特征变量,因此:模型参数θ 向量有401个元素。
all_theta是一个10*401的矩阵,每一行存储着一个分类器(模型)的模型参数θ 向量。

不知道怎么把theta行向量逐条依次插入到all_theta矩阵中。
一开始根本没有想到theta有四百个(大雾
没有见过这么多参数的线性方程,吓得我以为自己写错了什么。
应该是没错的。

1.4.1 One-vs-all Prediction

主要是matlab不太会使,对于每一条X,这里要找出算出10个分类器的10个假设函数的值中最大的一项,返回它的num_labels。

function p = predictOneVsAll(all_theta, X)
%PREDICT Predict the label for a trained one-vs-all classifier. The labels 
%are in the range 1..K, where K = size(all_theta, 1). 
%  p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions
%  for each example in the matrix X. Note that X contains the examples in
%  rows. all_theta is a matrix where the i-th row is a trained logistic
%  regression theta vector for the i-th class. You should set p to a vector
%  of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2
%  for 4 examples) 

m = size(X, 1);
num_labels = size(all_theta, 1);

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

% Add ones to the X data matrix
X = [ones(m, 1) X];

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters (one-vs-all).
%               You should set p to a vector of predictions (from 1 to
%               num_labels).
%
% Hint: This code can be done all vectorized using the max function.
%       In particular, the max function can also return the index of the 
%       max element, for more information see 'help max'. If your examples 
%       are in rows, then, you can use max(A, [], 2) to obtain the max 
%       for each row.
%       


[maxnum, p]=max(sigmoid(X*all_theta'),[],2);
% [maxnum,p]=max(A):返回行向量maxnum和p,maxnum向量记录A的每列的最大值,p向量记录每列最大值的行号。



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


end

补充一下max函数的用法
求矩阵A的最大值的函数有3种调用格式,分别是:
(1) max(A):返回一个行向量,向量的第i个元素是矩阵A的第i列上的最大值。
(2) [Y,U]=max(A):返回行向量Y和U,Y向量记录A的每列的最大值,U向量记录每列最大值的行号。
(3) max(A,[],dim):dim取1或2。dim取1时,该函数和max(A)完全相同;dim取2时,该函数返回一个列向量,其第i个元素是A矩阵的第i行上的最大值。
求最小值的函数是min,其用法和max完全相同。

C = max(A,[],dim)
返回A中有dim指定的维数范围中的最大值。比如C=max(A,[],2),在矩阵中,第1维度表示列,第2维度表示行,这个例子就是将第二维度,也就是行这个维度中,将同一行的不同列的最大值提取出来:


参考 https://www.cnblogs.com/hapjin/p/6085278.html

你可能感兴趣的:([ML] ex report 3 Multi-class Classification)