第一部分 多分类问题
题目介绍:使用逻辑回归识别0到9的手写数字
数据集:5000个手写数字的训练样本,每一个训练样本都是20像素×20像素的灰度图像的数字,每个像素由一个表示该位置灰度强度的点编号表示,这个20x20的像素网格被“展开”成一个400维的向量。每一个训练样本都是矩阵X的一行数据,这就得到了一个5000×400矩阵X,其中每一行都是一个手写数字图像的训练示例。
训练集的第二部分是一个5000维的向量y,包含了训练集的标签,由于octave/MATLAB中没有0的索引,数字‘0’用标签‘10’代替。
1.数据可视化
代码从X中随机选择100行,构成一个100×400的新矩阵来作图,导入的时候就将构成一张图的矩阵展开为1*400的行向量。
% Randomly select 100 data points to display
rand_indices = randperm(m);
sel = X(rand_indices(1:100), :);
displayData(sel);
displayData(sel);传入一个100*400的矩阵
function [h, display_array] = displayData(X, example_width)
% Set example_width automatically if not passed in
if ~exist('example_width', 'var') || isempty(example_width)
example_width = round(sqrt(size(X, 2))); % example_width = 20
end
如果函数要求的example_width变量不存在,使用X列数的算术平方根来定义,我们使用该函数时并没有传入这一变量,因此example_width = 20。
% Compute rows, cols
[m n] = size(X); %m = 100; n =400
example_height = (n / example_width); % example_height = 20
% Compute number of items to display
display_rows = floor(sqrt(m)); % display_row =10
display_cols = ceil(m / display_rows); % display_cols =10
% 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 % 1到10
for i = 1:display_cols % 1到10
if curr_ex > m, % 不超过100
break;
end
% Copy the patch
% Get the max value of the patch
% 取 X 每一行的最大值方便后面进行按比例缩小(暂且称为标准化)
max_val = max(abs(X(curr_ex, :)));
% 把原先的 X 里面每行标准化以后按 20 * 20 的形式 替代 display_array 中的元素
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_array。举例 curr_ex = 1, i = 1, j = 1,display_array ( 1 + 0 * 21 + (1:20), 1 + 0 * 21 + (1:20))
也就是disoplay_array((2:21),(2:21)) = reshape(X(1,:), 20, 20) / max_val;这就得到图中的第一个小图‘6’。
2.向量化逻辑回归
使用one-vs-all的逻辑回归模型建立多分类器。10个类别就需要分别训练10个逻辑回归分类器。向量化的代码中不含任何循环。
2.1 向量化损失函数
首先是逻辑回归中的损失函数公式: