A list,

BP (Back Propagation) neural network was proposed by Rumelhart and McCelland in 1986. See their paper Learning Representations by Back-propagating Errors published in Nature.

BP neural network is one of the most widely used neural network models. BP network can learn and store a large number of input-output mode mappings without revealing the mathematical equations describing the mappings in advance. Its learning rule is to use the fastest descent method, through back propagation to constantly adjust the weight and threshold of the network, so as to minimize the sum of squares of error of the network.

Last time we said that the multilayer perceptron has a bottleneck in how to obtain the weights of hidden layers. Since we can’t get the weight of the hidden layer directly, can we adjust the weight of the hidden layer indirectly by getting the error of the output result and the expected output of the output layer first? BP algorithm is designed with this idea. Its basic idea is that the learning process is composed of two processes: signal forward propagation and error back propagation. In the forward propagation, the input sample is introduced from the input layer, and then transmitted to the output layer after being processed layer by layer by layer. If the actual output of the output layer is not consistent with the desired output (teacher signal), then the back propagation stage of the error is entered. In reverse transmission, the output is transmitted back to the input layer layer by layer through the hidden layer in some form, and the error is apportioned to all the units of each layer, so as to obtain the error signal of each unit, which is used as the basis for correcting the weight of each unit. The detailed flow of these two processes will be described later.

The signal flow diagram of BP algorithm is shown in the figure belowWhen we analyze an ANN, we usually start from its three elements, that is, 1) network topology; 2) Transfer function; 3) Learning algorithm.

The characteristics of each element add up to determine the functional characteristics of the ANN. Therefore, we also start from these three elements of BP network research. 3.1 Topology of BP Network As mentioned last time, BP network is actually a multi-layer perceptron, so its topology is the same as that of multi-layer perceptron. Because the single hidden layer (three layer) perceptron has been able to solve simple nonlinear problems, it is the most common application. The topology of the three-layer perceptron is shown in the figure below. A simple three-layer BP:3.2 Transfer Function of BP Network The transfer function of BP network is nonlinear transformation function — Sigmoid function (also known as S function). Its characteristic is that the function itself and its derivative are continuous, so it is very convenient to deal with. Why this function is chosen will be further explained later when we introduce the learning algorithm of BP networks. The unipolar S-type function curve is shown in the figure below.The bipolar S-type function curve is shown in the figure below.The learning algorithm of BP network is BP algorithm, also known as δ algorithm (in the learning process of ANN, we will find many terms with multiple names). Taking 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.

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

Forward transmission, layer by layer wave transfer output value; Reverse feedback, reverse layer by layer adjustment of weight and bias; Let’s look at forward transmission first. Before training the network, we need to randomly initialize weights and biases, take a random real number of [−1,1] [-1,1][−1,1] for each weight, take a random real number of [0,1][0,1] [0,1] for each bias, Then forward transmission begins.

The training of neural network is completed by multiple iterations, each iteration uses all the records of the training set, while each training network uses only one record, which is described abstractly as follows:

whileTermination conditions not met:for record:dataset:
        trainModel(record)

Copy the code

4.1 Backpropagation 4.2 Training Termination Conditions All records of the data set are used in each training round, but when to stop, there are two stopping conditions: Set the maximum number of iterations, for example, stop the training after 100 iterations of the data set, calculate the prediction accuracy of the training set on the network, and stop the training after reaching a certain threshold value

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 Definition of Variables Step 9: Judge the rationality of the model judge whether the network error meets the requirements. When the error reaches the preset precision or the number of learning times is greater than the maximum number designed, the algorithm ends. Otherwise, select the next learning sample and the corresponding output expectation, return the third part, and enter the next round of learning.

In the design of BP network, the number of layers of the network, the number of neurons in each layer, the activation function, the initial value and the learning rate should generally be considered. The following are some selection principles. 6.1 Layer theory of Network has proved that a network with deviation and at least one S-type hidden layer plus one linear output layer can approach any rational function. Increasing the number of layers can further reduce the error and improve the accuracy, but it also complicates the network. Also not to be used only with nonlinear activation function of single-layer network to solve the problem, because you can do it with a single network problems, using adaptive linear network will be solved, and the adaptive linear network speed, for the nonlinear function can only be used to solve the problem, single precision is high enough, also only add layer can achieve the desired results. 6.2 Number of Hidden Layer Neurons Network training accuracy can be improved by adopting a hidden layer and increasing the number of its neurons, which is much simpler than increasing the number of network layers in structural implementation. Generally speaking, we use precision and training network time to measure the design quality of a neural network: (1) When the number of neurons is too small, the network cannot learn well, and the number of training iterations is relatively large, and the training accuracy is not high. (2) When there are too many neurons, the network has more powerful functions and higher accuracy, and the number of training iterations is also larger, which may lead to over fitting. Thus, the principle of selecting the number of hidden layer neurons of neural network is as follows: on the premise of solving the problem, add one or two neurons to accelerate the error reduction speed.

6.3 Selection of Initial Weights Generally, the initial weights are random numbers ranging from −1 to 1. In addition, After analyzing how the two-layer network trains a function, Widelow et al. proposed a strategy of selecting an initial weight of S √r, where R is the number of inputs and S is the number of neurons at the first layer.

6.4 Learning Rate The learning rate ranges from 0.01 to 0.8. A large learning rate may cause system instability, but a small learning rate causes slow convergence and requires a long training time. For a more complex network, different learning rates may be required at different positions of the error surface. In order to reduce the training times and time for finding the learning rate, a more appropriate method is to adopt a variable adaptive learning rate, so that the network can set different learning rates at different stages.

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

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

(1) Long training time is needed: 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. Usually, in order to avoid this situation, one is to choose a smaller initial weight and adopt a smaller learning rate. (3) Local minimum: The gradient descent method adopted here may converge to the local minimum, and better results may be obtained by using multi-layer networks or more neurons.

The main objective of P algorithm is to speed up the training speed and avoid falling into local minimum, etc. Common improvement methods include driving factor algorithm, adaptive learning rate, changing learning rate and action function shrinkage 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 adaptive learning rate method is for some specific problems. The principle of the method to change the learning rate is that, in successive iterations, if the reciprocal sign of the objective function is the same for a certain weight, the learning rate of the weight increases; otherwise, if the sign is opposite, the learning rate of the weight decreases. And the shrink-back rule is to shift the function, which is to add a constant.

Ii. 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 anew 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 a global variable global ButtonDown pos1; ButtonDown = []; pos1 = []; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Outputs fromthis 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 notCreated until after all CreateFcns called % Hint: place code in OpeningFcn to populate AXes1%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 drawn figure 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 image painted in pushbutton3 -- Executes on button press in Pushbutton3function 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 the newly drawn number newimgResult = identify(newImage); % compare by identifying function Result = BpRecognize(newimgResult); msgbox(num2str(Result),'Recognition 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(a);
msgbox('Finish Train'.'tip'.'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'Normal: ButtonDown=1;  
    pos1=get(handles.axes1,'CurrentPoint'); End function [] = BpTrain() %UNTITLED5 Summary ofthis function goes here
%   Detailed explanation goes here

clear all;
clc

ctime = datestr(now, 30); % tseed = str2num(ctime(end -5) : end)) ; % convert time characters to numbers rand('seed', tseed) ; % set seed, if no seed can be set to pseudo-random number load Data2; % data have10Class data, per class20line25The column,4Columns are labels. A total of200*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)];

%0The tag Data (1:20.26)   = 0;
Data(1:20.27)   = 0;
Data(1:20.28)   = 0;
Data(1:20.29)   = 0;
%1The tag 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); % Input node number S1N =25; % Second layer node number S2N =50; % Number of nodes in output layer S3N =4; % learning rate sk =0.5; % randomly initializes W and B for each layer 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 third layer transfer function is logsig % Calculate the 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



Copy the code

3. Operation results

Fourth, note

Version: 2014 a