1、BP神经网络
BP神经网络是将网络的输出与期望输出间的误差归结为权值和阈值的“过错”,通过反向传播把误差“分摊”给各个神经元的权值和阈值。BP神经网络由3层组成,输入层,隐含层和输出层。结构图如下图所示。
编辑
2、PSO优化BP神经网络
由于BP神经网络初始权值和阈值会导致预测效果的不佳,因此可建立相关的适应度函数,使用PSO对BP神经网络的权值和阈值进行寻优,得到较好的预测效果。
3、部分代码
clc clear all %节点个数 inputnum=2; hiddennum=5; outputnum=1; k=rand(1,40);%k是1*2000的向量,里面是0-1的随机均匀分布的数 [m,n]=sort(k);%sort默认按升序进行排列,m是排序后的矩阵,n是索引 train0=xlsread('data02c','A2:C41') % train0=xlsread('时域数据','B7:D48'); [a,b]=size(train0);%指标矩阵维度 input_train=train0(n(1:30),1:2)'; output_train=train0(n(1:30),3)'; input_test=train0(n(31:40),1:2)'; output_test=train0(n(31:40),3)'; %选连样本输入输出数据归一化 [inputn,inputps]=mapminmax(input_train); [outputn,outputps]=mapminmax(output_train); %构建网络 net=newff(inputn,outputn,hiddennum); % 参数初始化 %粒子群算法中的两个参数 c1 = 1.49445; c2 = 1.49445; maxgen=100; % 进化次数 sizepop=20; %种群规模 Vmax=1; Vmin=-1; popmax=5; popmin=-5; for i=1:sizepop pop(i,:)=5*rands(1,21); V(i,:)=rands(1,21); fitness(i)=fun(pop(i,:),inputnum,hiddennum,outputnum,net,inputn,outputn); end % 个体极值和群体极值 [bestfitness bestindex]=min(fitness); zbest=pop(bestindex,:); %全局最佳 gbest=pop; %个体最佳 fitnessgbest=fitness; %个体最佳适应度值 fitnesszbest=bestfitness; %全局最佳适应度值 %% 迭代寻优 for i=1:maxgen i for j=1:sizepop %速度更新 V(j,:) = V(j,:) + c1*rand*(gbest(j,:) - pop(j,:)) + c2*rand*(zbest - pop(j,:)); V(j,find(V(j,:)>Vmax))=Vmax; V(j,find(V(j,:)<Vmin))=Vmin; %种群更新 pop(j,:)=pop(j,:)+0.2*V(j,:); pop(j,find(pop(j,:)>popmax))=popmax; pop(j,find(pop(j,:)<popmin))=popmin; %自适应变异 pos=unidrnd(21); if rand>0.95 pop(j,pos)=5*rands(1,1); end %适应度值 fitness(j)=fun(pop(j,:),inputnum,hiddennum,outputnum,net,inputn,outputn); end for j=1:sizepop %个体最优更新 if fitness(j) < fitnessgbest(j) gbest(j,:) = pop(j,:); fitnessgbest(j) = fitness(j); end %群体最优更新 if fitness(j) < fitnesszbest zbest = pop(j,:); fitnesszbest = fitness(j); end end yy(i)=fitnesszbest; end %% 结果分析 plot(yy) title(['适应度曲线 ' '终止代数=' num2str(maxgen)]); xlabel('进化代数');ylabel('适应度'); x=zbest;
4、结果展示
编辑
编辑
编辑