一、手寫數字識别技術簡介
1 案例背景
手寫體數字識别是圖像識别學科下的一個分支,是圖像處理和模式識别研究領域的重要應用之一,并且具有很強的通用性。由于手寫體數字的随意性很大,如筆畫粗細、字型大小、傾斜角度等因素都有可能直接影響到字元的識别準确率,是以手寫體數字識别是一個很有挑戰性的課題。在過去的數十年中,研究者們提出了許多識别方法,并取得了一定的成果。手寫體數字識别的實用性很強,在大規模資料統計如例行年檢、人口普查、财務、稅務、郵件分揀等應用領域都有廣闊的應用前景"。
本案例講述了圖像中手寫阿拉伯數字的識别過程,對手寫數字識别的基于統計的方法進行了簡要介紹和分析,并通過開發一個小型的手寫體數字識别系統來進行實驗。手寫數字識别系統需要實作手寫數字圖像的讀取功能、特征提取功能、數字的模闆特征庫的建立功能及識别功能。
2 BP算法與實作過程
2.1 BP算法基本原理
将已知輸入向量和相應的輸出向量(期望輸出)作為訓練樣本,并假定即将學習的網絡已被賦予一組權值。為消除梯度幅度的不利影響,利用彈性反向傳播算法通過過如下步驟更新權值(圖1):首先,使用初始權值(不管正确與否)從輸入層開始向前傳播,計算出所有神經元的輸出,這樣輸出層的輸出與期望輸出(即輸出值與目标值)之間存在較大的誤差。然後,計算作為神經元權值函數的]誤差函數(損失函數或目标函數、代價函數)的梯度,根據誤差降低最快的方向來調整更新權值,通過将輸出誤差反向傳播給隐含層來不斷調整誤差函數。在計算誤差梯度的同時,使用與上面同樣的方法更新隐含層的權值。反複疊代更新,直到損失函數達到預定的理想目标。在彈性反向傳播算法的學習過程中,權值的修正值即為學習率,而梯度隻影影響權值變化的方向,即正負。

圖1 反向傳播神經網絡模型
1.2 感覺器神經網絡
感覺器(multilayer perceptron, MLP) 神經網絡是模式識别的簡單二進制分類人工網絡, 它通過權值模仿神經細胞的突觸,用激活函數模仿細胞體,偏置即為門檻值。單層的感覺器網絡結構如圖2所示。單層感覺器可将外部輸入x分成兩類:當感覺器的輸出y為正數或零時,輸入屬于第一類;當感覺器的輸出為負數時,輸入屬于第二類。
1.3 實作過程
(1)圖像讀取
在本文中,設計并自建了樣本的資料庫,庫中有0~9共10個阿拉伯數字的5000張不同的手寫數字圖像,均為白底黑色的bmp格式的檔案, 每個數字對應500張圖檔。實驗要從每一個數字中都随機選取450張手寫圖像作為訓練樣本,每一個數字剩下的50張作為測試樣本。部分數字樣張如圖3所示。
圖3 數字樣張
(2)提取特征
本設計中的訓練樣本數量多,而而一般神經網絡輸入層的神經元數就是訓練樣本向量的維數,是以需要對訓練樣本向量做降維預處理。預處理過程就是通過灰階門檻值函數将圖像轉換成二值圖像。降維前需先将所有圖像做一次縮放,以確定每個圖像的輸入向量都具有相同的像素。本設計標明圖像縮放的高度和寬度分别為70像素點和50像素點,符合一般手寫阿拉伯數字的高寬比。對這些縮放後的圖像作縱橫切割,如圖4所示,每10×10個像素點作為一系列像素塊,構成一張包含35個像素塊的二值圖像計算每一個像素塊中0和1的占比,并用它作為模式的一個特征值,這樣可以構成5x7的特征值矩陣。考慮到感覺器神申經網絡輸入向量隻能是一維,故需要将此矩陣轉換成一維向量作為訓練樣本的輸入,轉置後共生成35個一維向量。
圖4 縮放後的圖像切割
(3)構造标簽
無論是訓練樣本還是測試樣本,都需要構造标簽,前者用于映射的學習,後者用于判斷訓練網絡的正确率。一般地,輸出層神經元個數即為分類網絡中的分類類别數。阿拉伯數字是10類,故輸出神經元數為10。每個類由具體的500個圖像構成,包含訓練樣本和測試樣本。通過提取特征每個類均生成35個一維向量:用500個列向量(1000000000)T來标注模式1,即數字1;(0100000000)标注模式2,即數字2;(0010000000)标注模式3,即數字3;依此類推,最後的(0000000001)标注模式0,即數字0。運作代碼如下:
(4)随機標明訓練樣本和測試樣本測試
利用MATLAB中已有的rand()僞随機數生成函數來生成5000個介于0和1之間的僞随機數。将生成的僞随機數做升序排序,通過索引來記錄随機數原來的位置,并将原來的位置組合成新的行向量。在本設計中,輸入層的神經元有35個,輸出層神經元有10個,選取25為中間隐含層神經元個數。
(5)數字識别與正确率的計算
對比測試前的标簽和仿真後的輸出,用測試前的标簽值減去輸出值,得到誤內插補點,将誤差為0的視為正确識别,求出神經網絡的正确率。具體運作代碼如下:
二、部分源代碼
function varargout = findimg(varargin)
% FINDIMG MATLAB code for findimg.fig
% FINDIMG, by itself, creates a new FINDIMG or raises the existing
% singleton*.
%
% H = FINDIMG returns the handle to a new FINDIMG or the handle to
% the existing singleton*.
%
% FINDIMG('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in FINDIMG.M with the given input arguments.
%
% FINDIMG('Property','Value',...) creates a new FINDIMG or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before findimg_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to findimg_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help findimg
% Last Modified by GUIDE v2.5 23-Apr-2021 16:06:05
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @findimg_OpeningFcn, ...
'gui_OutputFcn', @findimg_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before findimg is made visible.
function findimg_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to findimg (see VARARGIN)
% Choose default command line output for findimg
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes findimg wait for user response (see UIRESUME)
% uiwait(handles.figure1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%定義全局變量
global ButtonDown pos1;
ButtonDown = [];
pos1 = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Outputs from this function are returned to the command line.
function varargout = findimg_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
axis([0 250 0 250]);
% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% hObject handle to axes1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: place code in OpeningFcn to populate axes1
%取消顯示axes的坐标軸
set((hObject),'xTick',[]);
set((hObject),'yTick',[]);
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[f,p]=uiputfile({'*.jpg'},'儲存檔案'); %儲存所畫的圖
str=strcat(p,f);
pix=getframe(handles.axes1);
imwrite(pix.cdata,str,'jpg')
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
cla(handles.axes1); %清楚axes中所畫的圖像
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
pix=getframe(handles.axes1);
imwrite(pix.cdata,'imgtest.jpg');
newimage = imread('imgtest.jpg'); %儲存新畫的數字
newimgResult = identify(newimage) ; %通過識别函數進行比較
Result = BpRecognize(newimgResult);
msgbox(num2str(Result),'識别結果','help');
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
BpTrain();
msgbox('Finish Train','提示','modal');
% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonDownFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%滑鼠按下事件
global ButtonDown pos1;
if(strcmp(get(gcf,'SelectionType'),'normal'))%判斷滑鼠按下的類型,normal為左鍵
ButtonDown=1;
pos1=get(handles.axes1,'CurrentPoint');%擷取坐标軸上滑鼠的位置
end
function [] = BpTrain()
%UNTITLED5 Summary of this function goes here
% Detailed explanation goes here
clear all;
clc
ctime = datestr(now, 30);%取系統時間
tseed = str2num(ctime((end - 5) : end)) ;%将時間字元轉換為數字
rand('seed', tseed) ;%設定種子,若不設定種子則可取到僞随機數
load Data2; %資料有10類資料,每類20行25列,有4列是标簽。共200*29
c = 0;
data = [];
for i = 1:10
for j = 1:20
c = c + 1;
data(c,:) = pattern(i).feature(j,:);
end
end
%=============訓練資料=============
Data = data(1:20, 1:25);
Data = [ Data ; data(21:40, 1:25)];
Data = [ Data ; data(41:60, 1:25)];
Data = [ Data ; data(61:80, 1:25)];
Data = [ Data ; data(81:100, 1:25)];
Data = [ Data ; data(101:120, 1:25)];
Data = [ Data ; data(121:140, 1:25)];
Data = [ Data ; data(141:160, 1:25)];
Data = [ Data ; data(161:180, 1:25)];
Data = [ Data ; data(181:200, 1:25)];
%0标簽
Data(1:20, 26) = 0;
Data(1:20, 27) = 0;
Data(1:20, 28) = 0;
Data(1:20, 29) = 0;
%1标簽
Data(21:40, 26) = 0;
Data(21:40, 27) = 0;
Data(21:40, 28) = 0;
Data(21:40, 29) = 1;
Data(41:60, 26) = 0;
Data(41:60, 27) = 0;
Data(41:60, 28) = 1;
Data(41:60, 29) = 0;
Data(61:80, 26) = 0;
Data(61:80, 27) = 0;
Data(61:80, 28) = 1;
Data(61:80, 29) = 1;
Data(81:100, 26) = 0;
Data(81:100, 27) = 1;
Data(81:100, 28) = 0;
Data(81:100, 29) = 0;
Data(101:120, 26) = 0;
Data(101:120, 27) = 1;
Data(101:120, 28) = 0;
Data(101:120, 29) = 1;
Data(121:140, 26) = 0;
Data(121:140, 27) = 1;
Data(121:140, 28) = 1;
Data(121:140, 29) = 0;
Data(141:160, 26) = 0;
Data(141:160, 27) = 1;
Data(141:160, 28) = 1;
Data(141:160, 29) = 1;
Data(161:180, 26) = 1;
Data(161:180, 27) = 0;
Data(161:180, 28) = 0;
Data(161:180, 29) = 0;
Data(181:200, 26) = 1;
Data(181:200, 27) = 0;
Data(181:200, 28) = 0;
Data(181:200, 29) = 1;
DN = size(Data, 1);
%輸入層結點數
S1N = 25;
%第二層結點數
S2N = 50;
%輸出層結點數
S3N = 4;
%學習率
sk = 0.5;
%随機初始化各層的W和B
W2 = -1 + 2 .* rand(S2N, S1N);
B2 = -1 + 2 .* rand(S2N, 1);
W3 = -1 + 2 .* rand(S3N, S2N);
B3 = -1 + 2 .* rand(S3N, 1);
%資料樣本下标
di = 1;
for i=1:50000
%第三層輸出
n3 = W3 * a2 + B3;
a3 = Logsig(n3); %第三層傳輸函數為logsig
%計算輸出層誤差
e = t - a3;
err = (e') * e;
Fd3 = diag((1 - a3) .* a3);
S3 = -2 * Fd3 * e;
Fd2 = diag((1 - a2) .* a2);
S2 = Fd2 * (W3') * S3;
W3 = W3 - sk*S3*(a2'); %梯度下降步長
B3 = B3 - sk*S3;
W2 = W2 - sk*S2*(a1');
B2 = B2 - sk*S2;
end
msgbox(num2str(err),'輸出層誤差','help');
save('W2.mat','W2');
save('W3.mat','W3');
save('B2.mat','B2');
save('B3.mat','B3');
end