exercise 3 --神经网络进行手写体识别

来源:互联网 发布:php设计思想 编辑:程序博客网 时间:2024/06/04 23:34

本作业使用神经网络(neural networks)识别手写的阿拉伯数字(0-9)


由于逻辑回归是线性分类(它的假设函数是一个线性函数,就是划一条直线,把数据分成了两类。可参考这篇文章中的:②使用逻辑回归来实现多分类问题(one-vs-all) 部分 的图片)

对于一些复杂的类别,逻辑回归就解决不了了。比如下面这个图片中的分类。(无法通过 划直线 将 叉叉 和 圆圈 分开)

 

而神经网络,则能够实现很复杂的非线性分类问题。

对于神经网络而言,同样有一个训练样本矩阵 X,同时还有一个模型参数 Theta 矩阵,通过某种算法将 模型参数矩阵 训练好之后(求出 Theta 矩阵),再使用前向传播算法( feedforward propagation algorithm)(感觉就像是矩阵相乘嘛), 就可以对输入的测试样本进行预测了。

本作业中, 模型参数 Theta 矩阵是已经训练好了的,直接 load 到Matlab中即可。

 

 

整个Matlab实现代码如下:predict.m

 

复制代码
function p = predict(Theta1, Theta2, X)%PREDICT Predict the label of an input given a trained neural network%   p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the%   trained weights of a neural network (Theta1, Theta2)% Useful valuesm = size(X, 1);num_labels = size(Theta2, 1);% You need to return the following variables correctly p = zeros(size(X, 1), 1);% p 是 5000*1向量% ====================== YOUR CODE HERE ======================% Instructions: Complete the following code to make predictions using%               your learned neural network. You should set p to a %               vector containing labels between 1 to num_labels.%% Hint: The max function might come in useful. 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.%% 模拟实现前向传播算法X = [ones(m, 1) X];a_super_2 = sigmoid(Theta1 * X');a_super_2 = [ones(1,m); a_super_2];% add bias unita_super_3 = sigmoid(Theta2 * a_super_2);%==================================[~,p] = max( a_super_3' ,[], 2 ); % 对样本的结果进行预测,与逻辑回归的预测类似,选取输出的最大值 作为最终的预测结果% =========================================================================end
复制代码

 注意:我们正是通过Matlab 的 max 函数,求得矩阵 a_super3 每一行的最大值。将每一行的中的最大值 的索引 赋值给向量p。其中,a_super3 是一个5000行乘10列的矩阵 

向量p就是预测的结果向量。而由于 a_super3 有10列,故 p 中每个元素的取值范围为[1,10],即分别代表了数字 0-9(其中10 表示 0)

 

Matlab 实现结果:

Loading Saved Neural Network Parameters ...Training Set Accuracy: 97.520000

 

比如对于下面的输入:数字 9

 

Neural NetWork的预测结果如下:

原创粉丝点击