本文是小俞在导师的指导下,完成的整理与编写。如有不正确之处,望大家积极指出,谢谢!
BP神经网络及其应用示例
1.什么是BP神经网络
BP(Back Propagation,BP)神经网络是1986年由Rumelhart和McCelland为首的科学家小组提出的,是一种按误差反向传播算法训练的多层前向网络,也是目前应用最广泛的神经网络模型之一。BP神经网络能学习和存储大量的输入-输出模式映射关系,且无须事先揭示描述这种映射关系的数学方程。
1.1神经元的结构
神经网络是受到人类大脑结构的启发而创造出来的。如下图1-1所示,在我们的大脑中有数十亿个称为神经元的细胞,它们互相连接形成了一个个神经网络。
1.2 BP神经网络的结构
1.3 BP神经网络的算法
1.3.1 前向传播算法
1.3.2 误差的反馈传播算法
1.3.3 训练终止条件
1.4BP神经网络的局限性
2. Matlab 神经网络工具箱
2.1 常用函数
2.1.1 BP神经网络常用函数
2.1.2 其他神经网络常用函数
2.2 图形工具箱的应用
2.2.1 BP拟合应用
2.2.2 导入软件数据的应用流程
2.2.3 导入外部数据的应用流程
3.Matlab下BP神经网络的应用示例
3.1 数据拟合
3.1.1 应用要求与建模流程
3.1.2源程序
%% 清除历史信息
clc,clear,close all;
%% 读取数据
data=xlsread('\2023030800to2214');
x=linspace(1,23,12);x1=linspace(2,24,12);
y=data(1:2:24,1)';y1=data(2:2:24,1);
%% 绘制原图
plot([1:2:24],y,'*-');hold on;
plot([2:2:24],y1,'--gs','LineWidth',2,'MarkerSize',10,'MarkerEdgeColor','b','MarkerFaceColor',[0.5,0.5,0.5]);hold on
%% 归一化
[x,ps_x]=mapminmax(x);% 归一化
x1=mapminmax('apply',x1,ps_x);
[y,ps_y]=mapminmax(y);
%% 搭建神经网络及训练条件设置
net = newff(x,y,5,{'logsig','purelin'},'traingdm');
net.trainParam.epochs =1000;% 训练最大的步数
net.trainParam.time = 5;% 训练最大时长
net.trainParam.show =3;% 迭代显示
net.trainParam.lr = 0.88;% 学习速率
net.divideFcn = '';%取消验证。
Param.goal = 0.000001;% 最小训练精度
net.trainParam.min_grad = 1e-24;% 最小梯度值
%% 训练网络
[net,tr1]=train(net,x,y);
%% BP神经网络拟合
[T_sim_bp,tr2]=sim(net,x1);
T_sim_bp=mapminmax('reverse',T_sim_bp,ps_y);
plot([2:2:24],T_sim_bp,'r-*');xlabel('小时');ylabel('温度');title('某一天的温度拟合效果');hold on;
%% 搭建径向基神经网络
net=newrbe(x,y,0.1);%数字是径向基函数的扩展速度。不同的值,拟合效果不一样。
%% 径向基神经网络拟合
T_sim_rbf=sim(net,x1);
T_sim_rbf=mapminmax('reverse',T_sim_rbf,ps_y);
plot([2:2:24],T_sim_rbf,'g-o');hold off
legend('训练值','真实值','BP拟合','径向基网络拟合');
%% 误差计算
error_bp=abs(T_sim_bp-y1');
error_rbf=abs(T_sim_rbf-y1');
figure;
subplot(1,2,1);bar([2:2:24],error_bp,'r');title('BP绝对误差');ylabel('摄氏度');xlabel('小时');axis([0,24,0,5]);
subplot(1,2,2);bar([2:2:24],error_rbf,'g');title('径向基绝对误差');xlabel('小时');axis([0,24,0,5]);
mse_bp=mse(error_bp);
mse_rbf=mse(error_rbf);
fprintf('BP均方误差:%.4f,径向基神经网络均方误差:%.4f\n',mse_bp,mse_rbf);
3.1.3 拟合结果分析
图3-1给出了该实例的训练终止条件为最大迭代次数1000(根据建模过程的要求设置)。
图3-2中,蓝色实星线表示训练值,即第1、3、5、……、23时的温度,蓝色框绿色实线表示真实值,即第2、4、6、……、24时的温度,红色实星线为BP拟合值,绿色实圈线为径向基网络拟合值。
图3-3和3-4中,BP神经网络和径向基神经网络在该实例中,都存在绝对误差且效果差不多,但从均方误差上看,可以得到在该实例中,BP 神经网络的拟合效果要比径向基网络的拟合效果差。
3.2预测建模
3.2.1应用要求与建模流程
3.2.2源程序
%% 清除历史记录
clc;close all;clear;
%% 读取数据
files = xlsread('\2023030800to2214.xlsx');%read input data
input_train = files(1:end-1,1:40);%用前40天前23个小时数据作为输入训练
output_train = files(end,1:40);%用后前40天23时数据训练作为输出训练
% 绘图
figure(),subplot(2,1,1),bar3(input_train);title('温度训练输入集');xlabel('小时'),ylabel('天数');zlabel('温度值');
subplot(2,1,2),bar(output_train);title('温度训练目标集');
%% 数据集处理
input_test = files(1:end-1,41:end);%测试集
output_test = files(end,41:end);
%% normalization归一化
[fy,fps] = mapminmax(input_train);%normalizaion,y means output from files which normalized by mapminmax,ps is process settings that allow consistent processing of values;
[Fy,Fps] = mapminmax(output_train);
%% 设置神经网络神经元个数
hiddennum = 5;% the number of hidden layer nodes
%% 搭建BP神经网络
net = newff(fy,Fy,hiddennum,{'logsig','purelin'},'traingdm');% newff Create a feed-forward backpropagation network.
w1 = net.iw{1,1};%zeros(size( net.iw{1,1}))+0.1;
w2 = net.lw{2,1};%zeros(size(net.lw{2,1}))+0.2;
b1 = net.b{1};
b2 = net.b{2};
%% 设置BP神经网络参数及训练终止条件
net.trainParam.epochs =10000;% training number训练最大的步数
net.trainParam.time = 30;% training time 训练最大时长
net.trainParam.show =3;% show the iteration process
net.trainParam.lr = 0.7;%learning rate学习速率
net.divideFcn = '';%取消Validation checks。
Param.goal = 0.000001;% the minimun error of training goal训练精度
net.trainParam.min_grad = 1e-24;% the minimun gradient value 最小梯度值
%%训练网络
[net,mse] = train(net,fy,Fy);
%% 反归一化
fy_test_out = mapminmax('apply',input_test,fps);
%% 预测
an = sim(net,fy_test_out);
%% 误差计算
test_simu = mapminmax('reverse',an,Fps);
error = abs(test_simu-output_test);
%% 绘图
figure;
plot(t(1:9),output_test,'b*-');hold on;
plot(t(1:9),test_simu,'r*-');hold on;
plot(t(1:9),error,'g');
ylabel('摄氏度');xlabel('记录天数');
legend('真实标签','预测数据','误差');
title('连续九天23时的温度预测');
[c,l] = size(output_test);
MAE = sum(abs(error))/l;
disp(['平均绝对误差MAE为',num2str(MAE)]);
3.2.3 预测结果分析
图3-5中,给出了BP神经网络训练的终止条件为最大迭代次数10000(根据建模过程的要求设置)。
图3-6中,上图为前40天连续23个小时的温度训练集,下图为前40天23时的温度目标值。
图3-7中,蓝色实点线表示连续九天23时的真实温度,红色实点线表示连续九天23时的预测温度,蓝色实线表示真实温度与预测温度之间的绝对误差。
图3-8中,给出了连续九天23时的温度预测的平均绝对误差值为1.0856.从中,可以得出,BP神经网络对温度的预测效果较好,但与真实标签值之间存在一定的误差。
3.3模式分类
3.3.1应用要求与建模流程
3.3.2 源程序
%% 清除历史信息
clear
close all
clc
%% 读取数据
load beer_dataset
%% 输入输出数据
input=beer_inputs;
output=beer_Targets;
for i=1:1:size(beer_Targets,2) %%size函数用于返回坐标,1表示行,2表示列
output1(i)=find(beer_Targets(:,i)==max(beer_Targets(:,i)));%返回对应样本的标签
end
%% 设置训练数据和预测数据
%1-18列是第一类(蓝带),19-36是第二类(雪花),37-54第三类(五星),55-72第四类(哈尔滨),73-90第五类(青岛),训练集是65个,测试集共25个
input_train=input(:,[1:13 19:31 37:49 55:67 73:85]);
output_train=output(:,[1:13 19:31 37:49 55:67 73:85]);
input_test=input(:,[14:18 32:36 50:54 68:72 86:90]);
output_test=output(:,[14:18 32:36 50:54 68:72 86:90]);
figure,subplot(2,1,1),bar3(input_train);xlabel('第i个啤酒');ylabel('参数类别');zlabel('参数值');title('啤酒分类训练集');
subplot(2,1,2),bar3(output_train);xlabel('第i个啤酒');ylabel('种类');zlabel('分类');title('训练分类的目标');
%% output1的输出值为:类别,output的输出值为类别的位置编码
train_output1=output1([1:13 19:31 37:49 55:67 73:85]); %对应的啤酒类别输出值
test_output1=output1([14:18 32:36 50:54 68:72 86:90]);
%% 节点个数
inputnum=size(input_train,1); %size(X,1)返回的是矩阵X的行数(输入神经元个数等于特征的个数也等于样本的行数)
hiddennum=12; %隐藏层神经元个数
outputnum=size(output_train,1); %输出层神经元个数
%% 数据归一化
[inputn,inputps]=mapminmax(input_train);%归一化到(-1,1)之间,inputps用来作下一次同样的归一化,
[outputn,outputps]=mapminmax(output_train);
%% 构建BP神经网络
net=newff(inputn,outputn,hiddennum,{'tansig','purelin'},'trainlm');%建立模型,传递函数使用purelin,
W1=net.iw{1,1};%输入层到中间层的权值
B1=net.b{1};%中间各层神经元阈值
W2=net.iw{2,1};%中间层到输出层的权值
B2=net.b{2};%输出各层神经元阈值
%% 网络参数配置(训练次数,学习速率,训练目标最小误差,显示频率,动量因子,最小性能梯度,最高失败次数)
net.trainParam.epochs=1000;%训练次数,这里设置为1000次
net.trainParam.lr=0.01;%学习速率,这里设置为0.01
net.trainParam.goal=0.0001;%训练目标最小误差,这里设置为0.0001
net.trainParam.show=25;%显示频率,这里设置为每训练25次显示一次
net.trainParam.mc=0.01;%动量因子
net.trainParam.min_grad=1e-6;%最小性能梯度
net.trainParam.max_fail=6;%最高失败次数
%% BP神经网络训练
[net,tr]=train(net,inputn,outputn);%开始训练,其中inputn,outputn分别为输入输出样本
figure(1),plotperform(tr) %误差MSE下降线
%% 训练集的输出
an0=sim(net,inputn);
aaa=size(an0,2);
train_simu=mapminmax('reverse',an0,outputps);
%% 计算训练集分类结果和误差
for i=1:1:aaa
train_output(i)=find(train_simu(:,i)==max(train_simu(:,i)));
end
error0=train_output-train_output1; %计算训练集分类的误差
%% 测试样本归一化
inputn_test=mapminmax('apply',input_test,inputps);%对样本数据进行归一化
%% BP神经网络进行预测
an1=sim(net,inputn_test);%用训练好的模型进行仿真
bbb=size(an1,2);
test_simu=mapminmax('reverse',an1,outputps);%把仿真得到的数据还原为原始数量级
%% 计算测试集分类结果和误差
for i=1:1:bbb
test_output(i)=find(test_simu(:,i)==max(test_simu(:,i)));
end
error=test_output-test_output1;%计算测试集分类的误差
%% 网络预测图形
%画出预测啤酒类别和实际啤酒类别的分类图像
figure(2)
plot(test_output,'ro')
hold on
plot(test_output1,'b*')
xlabel('测试样本组数','fontsize',12)
ylabel('类别','fontsize',12)
legend('预测啤酒类型','实际啤酒类型')
%% 画出测试集误差图
figure(3)
stem(error,'g')
set(gca,'color','white')
ylim([-3.5 4])
title('BP网络啤酒类型误差','fontsize',12)
xlabel('测试样本组数','fontsize',12)
ylabel('分类误差','fontsize',12)
%% 画出训练集和测试集的误差分布直方图
figure(4)
ploterrhist(error0,'Train',error,'Test')
%% 输出测试的啤酒数据真实类别和预测类别对比结果
disp('**********测试的啤酒真实类别和预测类别对比***********')
for pp=1:1:size(test_output1,2)
disp(['第',num2str(pp),'个啤酒样本的实际类别为:',num2str(test_output1(pp)),'预测类别为:',num2str(test_output(pp))])
end
error=zeros(1,25);
for i=1:25
if train_simu(i)-test_output1(i)~=0
error(i)=1;
end
end
3.3.3 分类结果分析
图3-9中,给出了BP神经网络分类过程中的训练终止条件为最小精度0.0001(根据建模过程的要求设置)。
图3-10中,上图为8*65的训练集,下图为5*65的训练目标集。
图3-11中,蓝色点星表示实际啤酒的分类类型,红色圆圈表示预测的啤酒分类类型。
图3-12中,给出了啤酒分类的误差很小。说明,经过对65个5种啤酒分类类型的训练后,BP神经网络对25个5种啤酒的预测分类效果很好。