[ML] ex report 3 Multi-class Classification

Introduction

用one-vs-all logistic regression和neural networks識(shí)別手寫阿拉伯?dāng)?shù)字。

1 Multi-class Classification

多分類問題是二分類問題的擴(kuò)展。在二分類問題中,一類為正項(xiàng),一類為負(fù)項(xiàng),線性回歸所擬合的這條decision boundary,在使用sigmoid函數(shù)之后,代入函數(shù)算出預(yù)測(cè)值y代表為正項(xiàng)的概率。
一個(gè)疑問,如果把正負(fù)項(xiàng)的值對(duì)換,再學(xué)習(xí)出來的theta會(huì)不變嗎,但是decision boundary兩邊的值變了啊?
在1v1中,我們只做了一個(gè)分類器,在one-vs-all中,可以做n個(gè)(=類數(shù))分類器,每個(gè)分類器負(fù)責(zé)該類的預(yù)測(cè),該類為正項(xiàng),其他類為負(fù)項(xiàng)。在predict的時(shí)候,計(jì)算這n個(gè)分類器的值,代表屬于該類的概率,選擇概率值最高的類。

1.1 Dataset

一共有5000個(gè)訓(xùn)練樣本,每個(gè)訓(xùn)練樣本是400維的列向量(20X20像素的 grayscale image),用矩陣 X 保存。樣本的結(jié)果(label of training set)保存在向量 y 中,y 是一個(gè)5000行1列的列向量。比如 y = (1,2,3,4,5,6,7,8,9,10......)T,注意,由于Matlab下標(biāo)是從1開始的,故用 10 表示數(shù)字 0

load('ex3data1.mat');可以將數(shù)據(jù)加載到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

報(bào)警了,不想看。

% 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

熟悉的向量化,基本寫三次就會(huì)了,寫出routine了都。代價(jià)函數(shù)就是同一個(gè)套路。不懂得地方在于regularize。
后面加上一項(xiàng)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

要注意的一點(diǎn)是the extra bias unit 項(xiàng)不需要regularize,有好幾種寫法,都可以把bias項(xiàng)置為0。

1.3.3 Vectorizing regularized logistic regressionA

在寫gradient的regularization的那一項(xiàng)不需要求和的。

1.4 One-vs-all Classification

num_labels 為分類器個(gè)數(shù),共10個(gè),每個(gè)分類器(模型)用來識(shí)別10個(gè)數(shù)字中的某一個(gè)。
我們一共有5000個(gè)樣本,每個(gè)樣本有400中特征變量,因此:模型參數(shù)θ 向量有401個(gè)元素。
all_theta是一個(gè)10*401的矩陣,每一行存儲(chǔ)著一個(gè)分類器(模型)的模型參數(shù)θ 向量。

不知道怎么把theta行向量逐條依次插入到all_theta矩陣中。
一開始根本沒有想到theta有四百個(gè)(大霧
沒有見過這么多參數(shù)的線性方程,嚇得我以為自己寫錯(cuò)了什么。
應(yīng)該是沒錯(cuò)的。

1.4.1 One-vs-all Prediction

主要是matlab不太會(huì)使,對(duì)于每一條X,這里要找出算出10個(gè)分類器的10個(gè)假設(shè)函數(shù)的值中最大的一項(xiàng),返回它的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向量記錄每列最大值的行號(hào)。



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


end

補(bǔ)充一下max函數(shù)的用法
求矩陣A的最大值的函數(shù)有3種調(diào)用格式,分別是:
(1) max(A):返回一個(gè)行向量,向量的第i個(gè)元素是矩陣A的第i列上的最大值。
(2) [Y,U]=max(A):返回行向量Y和U,Y向量記錄A的每列的最大值,U向量記錄每列最大值的行號(hào)。
(3) max(A,[],dim):dim取1或2。dim取1時(shí),該函數(shù)和max(A)完全相同;dim取2時(shí),該函數(shù)返回一個(gè)列向量,其第i個(gè)元素是A矩陣的第i行上的最大值。
求最小值的函數(shù)是min,其用法和max完全相同。

C = max(A,[],dim)
返回A中有dim指定的維數(shù)范圍中的最大值。比如C=max(A,[],2),在矩陣中,第1維度表示列,第2維度表示行,這個(gè)例子就是將第二維度,也就是行這個(gè)維度中,將同一行的不同列的最大值提取出來:


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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容