1 Multi-class Classification
1.1 Dataset
% Load Training Data
fprintf('Loading and Visualizing Data ...\n')
load('ex3data1.mat'); % training data stored in arrays X, y
m = size(X, 1);
在ex3data1.mat中一共有5000个样本,每一个样本是20 * 20,把每一个样本展开成列向量再转置,最后的X是5000 * 400的矩阵
1.2 Visualizing the data
% Randomly select 100 data points to display
rand_indices = randperm(m);
sel = X(rand_indices(1:100), :);
displayData(sel);
这段代码是随机的从X中选出100行,然后调用displayData函数
下面是displayData.m
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
首先来看这段
if ~exist('example_width', 'var') || isempty(example_width)
example_width = round(sqrt(size(X, 2)));
end
这段的作用是,如果我们没有传入example_width那么就程序自动补充example_width = round(sqrt(size(X,2)))
,round函数四舍五入为最近的整数,在这里example_width = 20
coloemap(gray)
是将图片格式设置为灰度图
% Compute rows, cols
[m n] = size(X); % X : 100 * 400
example_height = (n / example_width); % height = 20
% Compute number of items to display
display_rows = floor(sqrt(m)); % rows = 10
display_cols = ceil(m / display_rows);% cols = 10
下面就是关键了,u1s1看得懂但是根本没想到要这么写orz
% 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;
1.3 Vectorizing Logistic Regression
首先来看一下ex3.m里的相关代码
%% ============ 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;
X_t = [ones(5,1) reshape(1:15,5,3)/10];
reshape是把向量转换成矩阵的形式,reshape(1:15,5,3)/10]
就是变成5 * 3的矩阵,前面又加了5 * 1的,所以最后的X_t是5 * 4的矩阵
y_t = ([1;0;1;0;1] >= 0.5)
是判断每个位置是是不是≥0.5,是为1,否则为0
在MATLAB中运行这两句的结果如下
X_t =
1.0000 0.1000 0.6000 1.1000
1.0000 0.2000 0.7000 1.2000
1.0000 0.3000 0.8000 1.3000
1.0000 0.4000 0.9000 1.4000
1.0000 0.5000 1.0000 1.5000
y_t =
5×1 logical 数组
1
0
1
0
1
下面就是调用逻辑回归,之前的知识就不细写了
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)
%
h_theta = sigmoid(X*theta);% compute the value of h_theta
J = 1/m*(sum(-y.*log(h_theta)-(1-y).*log(1-h_theta)))+lambda/2/m*sum(theta(2:end).^2);
grad_temp = 1/m*X'*(h_theta-y);
grad = grad_temp + lambda/m*theta;
grad(1) = grad_temp(1);
% =============================================================
grad = grad(:);
end
1.4 One-vs-all Classification
OneVsAll.m中需要补充的内容是
initial_theta = zeros(n + 1, 1);% 最后的output是(n+1)*1的形式
for c = 1:num_labels,%有0~9十个数字,要训练10次,其中用10来表示0
options = optimset('GradObj', 'on', 'MaxIter', 50);
all_theta(c,:) = fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), initial_theta, options);
end;
PredictOneVsAll.m中要补充的内容是
temp_p=sigmoid(X*((all_theta)'));% temp_p 5000*10 5000个训练样本,每个样本10个output
[temp_max,p]=max( temp_p ,[],2);
max(A,[],2)可以获得每一行的最大值,并返回index
%% ============ Part 2b: One-vs-All Training ============
fprintf('\nTraining One-vs-All Logistic Regression...\n')
lambda = 0.1;
[all_theta] = oneVsAll(X, y, num_labels, lambda);
fprintf('Program paused. Press enter to continue.\n');
pause;
%% ================ Part 3: Predict for One-Vs-All ================
pred = predictOneVsAll(all_theta, X);
fprintf('\nTraining Set Accuracy: %f\n', mean(double(pred == y)) * 100);
以上就是ex3.m的实现啦,ex3_nn.m下次再写啦要溜去上课了