本作業使用神經網絡(neural networks)識別手寫的阿拉伯數字(0-9)
關於使用邏輯回歸實現多分類問題:識別手寫的阿拉伯數字(0-9),請參考:http://www.cnblogs.com/hapjin/p/6085278.html
由於邏輯回歸是線性分類(它的假設函數是一個線性函數,就是划一條直線,把數據分成了兩類。可參考這篇文章中的:②使用邏輯回歸來實現多分類問題(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 values
m = 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 unit a_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的預測結果如下: