[handwritten numeral recognition] handwritten numeral recognition based on matlab GUI BP neural network [including Matlab source code phase 1118]

Posted by patrick99e99 on Thu, 20 Jan 2022 14:10:56 +0100

1, Introduction

1 Overview
BP (Back Propagation) neural network was proposed by the scientific research team headed by Rumelhart and McCelland in 1986. See their paper learning representations by Back Propagation errors published in Nature.

BP neural network is a multilayer feedforward network trained by error back propagation algorithm. It is one of the most widely used neural network models at present. BP network can learn and store a large number of input-output mode mapping relationships without revealing the mathematical equations describing this mapping relationship in advance. Its learning rule is to use the steepest descent method and continuously adjust the weight and threshold of the network through back propagation to minimize the sum of squares of the network error.

2 basic idea of BP algorithm
Last time we mentioned that multilayer perceptron encountered a bottleneck in how to obtain the weight of hidden layer. Since we can't get the weight of the hidden layer directly, can we indirectly adjust the weight of the hidden layer by getting the error between the output result and the expected output from the output layer first? BP algorithm is designed with this idea. Its basic idea is that the learning process consists of two processes: forward propagation of signal and back propagation of error.
During forward propagation, the input samples are transmitted from the input layer, processed layer by layer by hidden layer, and then transmitted to the output layer. If the actual output of the output layer is inconsistent with the expected output (teacher signal), it will turn to the back propagation stage of error.
During back propagation, the output is transmitted back to the input layer layer by layer through the hidden layer in some form, and the error is allocated to all units of each layer, so as to obtain the error signal of each layer unit, which is used as the basis for correcting the weight of each unit.
The specific processes of these two processes will be introduced later.

The signal flow diagram of BP algorithm is shown in the figure below

3 characteristic analysis of BP Network - three elements of BP
When we analyze an ANN, we usually start with its three elements, namely
1) Network topology;
2) Transfer function;
3) Learning algorithm.

The characteristics of each element together determine the functional characteristics of the ANN. Therefore, we also study BP network from these three elements.
3.1 topology of BP network
As I said last time, BP network is actually a multilayer perceptron, so its topology is the same as that of multilayer perceptron. Because the single hidden layer (three-layer) perceptron can solve simple nonlinear problems, it is most widely used. The topology of the three-layer perceptron is shown in the figure below.
The simplest three-layer BP:

3.2 transfer function of BP network
The transfer function used in BP network is a nonlinear transformation function - Sigmoid function (also known as S function). Its characteristic is that the function itself and its derivatives are continuous, so it is very convenient in processing. Why should we choose this function? I will give a further introduction when introducing the learning algorithm of BP network.
Unipolar S-type function curve is shown in the figure below.

Bipolar S-type function curve is shown in the figure below.

3.3 learning algorithm of BP network
The learning algorithm of BP network is BP algorithm, also known as BP algorithm δ Algorithm (we will find many terms with multiple names in the learning process of ANN). Taking the three-layer perceptron as an example, when the network output is different from the expected output, there is an output error E, which is defined as follows




Next, we will introduce the specific process of BP network learning and training.

4 training decomposition of BP network
Training a BP neural network is actually adjusting the weight and bias of the network. The training process of BP neural network is divided into two parts:

Forward transmission, wave transmission output value layer by layer;
Reverse feedback, reverse layer by layer adjustment of weight and bias;
Let's first look at forward transmission.
Forward transmission (feed forward feedback)
Before training the network, we need to initialize weights and offsets randomly, take a random real number of [− 1,1] [- 1,1] [− 1,1] for each weight, and a random real number of [0,1] [0,1] [0,1] for each offset, and then start forward transmission.

The training of neural network is completed by multiple iterations. Each iteration uses all records of the training set, while each training network uses only one record. The abstract description is as follows:

while Termination conditions not met:
    for record:dataset:
        trainModel(record)



4.1 back propagation


4.2 training termination conditions
Each round of training uses all records of the data set, but when to stop, the stop conditions are as follows:
Set the maximum number of iterations, such as stopping training after 100 iterations with the dataset
Calculate the prediction accuracy of the training set on the network, and stop the training after reaching a certain threshold

5. Specific process of BP network operation
5.1 network structure
There are n nn neurons in the input layer, p pp neurons in the hidden layer and q qq neurons in the output layer.
5.2 variable definition








Step 9: judge the rationality of the model
Judge whether the network error meets the requirements.
When the error reaches the preset accuracy or the learning times are greater than the designed maximum times, the algorithm ends.
Otherwise, select the next learning sample and the corresponding output expectation, return to the third part and enter the next round of learning.

6 design of BP network
In the design of BP network, we should generally consider the number of layers of the network, the number of neurons and activation function in each layer, initial value and learning rate. The following are some selection principles.
6.1 network layers
Theory has proved that the network with deviation and at least one S-type hidden layer plus a linear output layer can approach any rational function. Increasing the number of layers can further reduce the error and improve the accuracy, but it is also the complexity of the network. In addition, the single-layer network with only nonlinear activation function can not be used to solve the problem, because the problems that can be solved with single-layer network can also be solved with adaptive linear network, and the operation speed of adaptive linear network is faster. For the problems that can only be solved with nonlinear function, the single-layer accuracy is not high enough, and only increasing the number of layers can achieve the desired results.
6.2 number of neurons in the hidden layer
The improvement of network training accuracy can be obtained by using a hidden layer and increasing the number of neurons, which is much simpler in structure than increasing the number of network layers. Generally speaking, we use the accuracy and the time of training the network to measure the quality of a neural network design:
(1) When the number of neurons is too small, the network can not learn well, the number of training iterations is relatively large, and the training accuracy is not high.
(2) When the number of neurons is too large, the more powerful the function of the network is, the higher the accuracy is, and the number of training iterations is also large, which may lead to over fitting.
Therefore, we get that the selection principle of the number of hidden layer neurons of neural network is: on the premise of solving the problem, add one or two neurons to speed up the decline of error.

6.3 selection of initial weight
Generally, the initial weight is a random number with a value between (− 1,1). In addition, after analyzing how the two-layer network trains a function, wedrow et al. Proposed a strategy to select the initial weight order as s √ r, where r is the number of inputs and S is the number of neurons in the first layer.

6.4 learning rate
The learning rate is generally 0.01 − 0.8. A large learning rate may lead to the instability of the system, but a small learning rate leads to too slow convergence and requires a long training time. For more complex networks, different learning rates may be required at different positions of the error surface. In order to reduce the training times and time to find the learning rate, a more appropriate method is to use the variable adaptive learning rate to set different learning rates in different stages.

6.5 selection of expected error
In the process of designing the network, the expected error value should also determine an appropriate value after comparative training, which is determined relative to the required number of hidden layer nodes. Generally, two networks with different expected error values can be trained at the same time, and finally one of them can be determined by comprehensive factors.

7 limitations of BP network
BP network has the following problems:

(1) Long training time is required: This is mainly caused by the small learning rate, which can be improved by changing or adaptive learning rate.
(2) Completely unable to train: This is mainly reflected in the paralysis of the network. Generally, in order to avoid this situation, first, select a smaller initial weight, but use a smaller learning rate.
(3) Local minimum value: the gradient descent method adopted here may converge to the local minimum value, and better results may be obtained by using multi-layer network or more neurons.

8 improvement of BP network
The main goal of the improvement of P algorithm is to speed up the training speed and avoid falling into local minimum. The common improvement methods include the algorithm with momentum factor, adaptive learning rate, changing learning rate and action function contraction method. The basic idea of momentum factor method is to add a value proportional to the previous weight change to each weight change on the basis of back propagation, and generate a new weight change according to the back propagation method. The method of adaptive learning rate is aimed at some specific problems. The principle of the method of changing the learning rate is that if the sign of the objective function for the reciprocal of a weight is the same in several consecutive iterations, the learning rate of this weight will increase, on the contrary, if the sign is opposite, the learning rate will decrease. The contraction rule of the action function is to translate the action function, that is, add a constant.

2, Source code

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);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Define global variables
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
%Cancel display axes Coordinate axis of
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'},'Save file');  %Save the drawing
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);   %clear axes Images drawn in

% --- 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');           %Save new numbers

newimgResult = identify(newimage) ;                  %Compare by identifying functions
Result = BpRecognize(newimgResult);
msgbox(num2str(Result),'Identification results','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','Tips','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)
%Mouse down event
global ButtonDown pos1;  
if(strcmp(get(gcf,'SelectionType'),'normal'))%Determine the type of mouse press, normal Left key  
    ButtonDown=1;  
    pos1=get(handles.axes1,'CurrentPoint');%Gets the position of the mouse on the axis  
end  
function [] = BpTrain()
%UNTITLED5 Summary of this function goes here
%   Detailed explanation goes here

clear all;
clc

ctime = datestr(now, 30);%Take system time
tseed = str2num(ctime((end - 5) : end)) ;%Convert time characters to numbers
rand('seed', tseed) ;%Set the seed. If you do not set the seed, you can get the pseudo-random number

load Data2;  %There are 10 types of data, 20 rows and 25 columns in each type, and 4 columns are labels. Total 200*29 
c = 0;
data = [];
for i = 1:10
    for j = 1:20
        c = c + 1;
        data(c,:) = pattern(i).feature(j,:);
    end
end
 
%=============Training data=============
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 label
Data(1:20, 26)   = 0;
Data(1:20, 27)   = 0;
Data(1:20, 28)   = 0;
Data(1:20, 29)   = 0;
%1 label
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);

%Enter the number of layer nodes
S1N = 25;

%Number of nodes in the second layer
S2N = 50;

%Number of output layer nodes
S3N = 4;

%Learning rate
sk = 0.5;


%Random initialization of each layer W and 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);

%Data sample subscript
di = 1; 


for i=1:50000
    
    
    %Layer 3 output
    n3 = W3 * a2 + B3;
    a3 = Logsig(n3);   %The transfer function of the third layer is logsig
    
    %Calculate output layer error
    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'); %Gradient descent step
    B3 = B3 - sk*S3;
    
    W2 = W2 - sk*S2*(a1');
    B2 = B2 - sk*S2;
end
msgbox(num2str(err),'Output layer error','help');
save('W2.mat','W2');
save('W3.mat','W3');
save('B2.mat','B2');
save('B3.mat','B3');


end



3, Operation results










4, Remarks

Version: 2014a

Topics: MATLAB image processing