多分类问题——识别手写体数字0-9

一.逻辑回归解决多分类问题

1.图片像素为20*20,X的属性数目为400,输出层神经元个数为10,分别代表1-10(把0映射为10)。

通过以下代码先形式化展示数据 ex3data1.mat内容:

load('ex3data1.mat'); % training data stored in arrays X, y
m = size(X, 1); %求出样本总数
% Randomly select 100 data points to display
rand_indices = randperm(m); %函数功能随机打乱这m个数字,输出给rand_indices.
sel = X(rand_indices(1:100), :); %按照打乱后的数列取出100个数字,作为X矩阵的行数。

displayData(sel); %通过本函数将选出的X矩阵中100个样本进行图形化

函数displayData()实现解析如下:

function [h, display_array] = displayData(X, example_width)
%DISPLAYDATA Display 2D data in a nice grid

if ~exist('example_width', 'var') || isempty(example_width) 
    example_width = round(sqrt(size(X, 2)));   %四舍五入求出图片的宽度
end

colormap(gray); %将图片定义为灰色系

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

pad = 1; %图片之间间隔

% Setup blank display 创建要展示的图片像素大小,空像素,数字图片之间有1像素间隔
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% 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; %reshape函数进行矩阵维数转换
        curr_ex = curr_ex + 1;
    end
    if curr_ex > m, 
        break; 
    end
end

h = imagesc(display_array, [-1 1]); %将像素点画为图片
axis image off %不显示坐标轴
drawnow; %刷新屏幕
end

 

2.向量化逻辑回归

向量化代价函数和梯度下降,代码同第三周编程练习相同:http://www.cnblogs.com/LoganGo/p/9009767.html

核心代码如下:

function [J, grad] = lrCostFunction(theta, X, y, lambda)

m = length(y); % number of training examples

J = 0;
grad = zeros(size(theta));
%分别计算代价值J和梯度grad J
=1/m*(-(y')*log(sigmoid(X*theta))-(1-y)'*log(1-sigmoid(X*theta)))+lambda/(2*m)*(theta'*theta-theta(1)^2); %grad = 1/m*X'*(sigmoid(X*theta)-y)+lambda*theta/m; %grad(1) = grad(1)-lambda*theta(1)/m; grad=1/m*X'*(sigmoid(X*theta)-y)+lambda/m*([0;theta(2:end)]); grad = grad(:);

end

 

3.逻辑回归解决多分类问题

oneVsAll.m函数解析:通过阅读原文中所给的英文解析,足够完成本函数的编写

function [all_theta] = oneVsAll(X, y, num_labels, lambda)

m = size(X, 1);
n = size(X, 2);

all_theta = zeros(num_labels, n + 1); %为训练1-10个便签,所以需要矩阵为10*n+1

X = [ones(m, 1) X];
%运用了fmincg()函数求参数,与函数fminunc()相比,处理属性过多时更高效!
options = optimset('GradObj', 'on', 'MaxIter', 50); 
for c=1:num_labels,
  all_theta(c,:)=fmincg(@(t)(lrCostFunction(t, X, (y==c), lambda)), all_theta(c,:)', options)';
end
end

预测函数predictOneVsAll()函数编写:

function p = predictOneVsAll(all_theta, X)

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

p = zeros(size(X, 1), 1);
X = [ones(m, 1) X];
index=0;
pre=zeros(num_labels,1); %存储每个样本对应数字1-10的预测值
for c=1:m, for d=1:num_labels, pre(d)=sigmoid(X(c,:)*(all_theta(d,:)')); end [maxnum index]=max(pre); p(c)=index; %找到该样本最大的预测值所对应的数字,作为实际预测值 end end

 

二.神经网络解决多分类问题

使用已经训练好的参数θ1θ2来做预测,predict.m如下:

function p = predict(Theta1, Theta2, X)

m = size(X, 1);
num_labels = size(Theta2, 1);
X=[ones(m,1) X]; %为a1添加为1的偏置

p = zeros(size(X, 1), 1);

for i=1:m, %分别对m个样本做预测
  a2=sigmoid(Theta1*X(i,:)'); %计算a2
  a2=[1;a2];                  %为a2添加为1的偏置
  a3=sigmoid(Theta2*a2);      %计算a3
  [manum index]=max(a3);      %求出哪个数字的预测值最大
  p(i)=index;                 %得出预测值
end
end

 

posted on 2018-05-22 17:03  LoganGo  阅读(5222)  评论(1编辑  收藏  举报