浅谈BP神经网络的Matlab实现

1.人工神经网络的概述(Artificial neural networks)

net_{i} = \sum_{j=1}^{n}w_{ij}x_{j}-\theta y{_{i}} =f(net{_{i}})

其中w_{ij}为连接权的权值, \theta为阈值,f(net_{i})为激活函数。

2.常用的激活函数

 线性函数 f(x)=k \ast x+c
斜坡函数 f(x)=\left\{\begin{matrix} T &, x>c & \\ k*x&,\left | x \right |<c & \\ -T&,x<-c & \end{matrix}\right.
阈值函数 f(x) = \left\{\begin{matrix} 1 &,x\geqslant c \\ 0& ,x< c \end{matrix}\right.
S型函数 f(x)=\frac{1}{1+e^{^{-\alpha x}}} (0<f(x)<1)
双极S型函数 f(x)=\frac{2}{1+e^{-\alpha x}}-1(-1<f(x)<1)

3.数据归一化

  1. 什么是归一化:将数据映射到[0,1]或[-1,1]区间或者其他区间。
  2. 为什么要进行归一化:数据范围大与数据范围小的在神经网络的训练时间会存在较大的差异
  3. 归一化算法:y=(x-min)/(max-min)   &   y=2*(x-min)/(max-min)-1

4.重要函数说明

mapminmax process matrices by mapping row minimun and maximum values to[-1,1]
newff

create feed-forward backpropagation network (创造前向反馈神经网络)

net = newff(P,T,[S1,S2...S(N-1)],{TF1,TF2...TFNI},BTF,BLF,PF,IPF,OPF,DDF)

train

train neural network (训练神经网络)

[net,tr,Y,E,Pf,Af] = train(net,P,T,Pi,Ai)

sim Simulate neural network(仿真神经网络)

5.注意点

留一法(leave one out, LOO)

这种方法用于样本量(即所需训练集)比较小,比如20个或者30个左右,采用留一法就是,多次循环,每次只留一个样本充当测试集。比如20个样本进行学习,第一次使用第一个样本充当测试集,剩下的19个充当训练集;第二次使用第二个样本充当测试集,其他19个充当训练集;即每个样本都有充当测试集的机会。

6.代码块

%% I. 训练集/测试集产生
% 1. 导入数据
load inputoutputvariable_data.mat
% 2. 随机产生训练集和测试集
temp = randperm(size(inputvariable,1));
% 训练集——假设有20个样本
P_train = inputvariable(temp(1:20),:)';
T_train = outputvariable(temp(1:20),:)';
% 测试集——19个样本
P_test = inputvariable(temp(21:end),:)';
T_test = outputvariable(temp(21:end),:)';
N = size(P_test,2);

%% II. 数据归一化
[p_train, ps_input] = mapminmax(P_train,0,1);
p_test = mapminmax('apply',P_test,ps_input);
[t_train, ps_output] = mapminmax(T_train,0,1);

%% III. BP神经网络创建、训练及仿真测试
% 1. 创建网络
net = newff(p_train,t_train,9);
% 2. 设置训练参数
net.trainParam.epochs = 1000;
net.trainParam.goal = 1e-3;
net.trainParam.lr = 0.01;
% 3. 训练网络
net = train(net,p_train,t_train);
% 4. 仿真测试
t_sim = sim(net,p_test);
% 5. 数据反归一化
T_sim = mapminmax('reverse',t_sim,ps_output);

%% IV. 性能评价
% 1. 相对误差error
error = abs(T_sim - T_test)./T_test;
% 2. 决定系数R^2
R2 = (N * sum(T_sim .* T_test) - sum(T_sim) * sum(T_test))^2 / ((N * sum((T_sim).^2) - (sum(T_sim))^2) * (N * sum((T_test).^2) - (sum(T_test))^2)); 
% 3. 结果对比
result = [T_test' T_sim' error']

%% V. 绘图
figure; plot(1:N,T_test,'b:*',1:N,T_sim,'r-o')
legend('真实值','预测值')
xlabel('预测样本')
ylabel('目标值')
string = {'测试目标值预测结果对比';['R^2=' num2str(R2)]};
title(string)

猜你喜欢

转载自blog.csdn.net/ChenQihome9/article/details/81508916