【预测模型】基于灰狼算法优化BP神经网络实现数据预测matlab代码

1 简介

信息化时代的快速发展,给人们的生活带来了很大的便捷。越来越多的人习惯在网上办事、网络购物、在线支付,俨然成为了一种常态。通过网络来获取各类信息也更加方便,这就给网络钓鱼带来了肥沃的生存土壤。网络钓鱼的不断泛滥,给人们的生产生活带来了巨大威胁,网民的财产安全受到侵犯,不利于经济的发展和社会的稳定。因此,加大网络钓鱼检测技术的研究成为当下的重点课题。目前网络钓鱼检测存在着效率不高、稳定性和泛化性较差等缺点,对于网络钓鱼检测技术的研究与改进变得尤为重要。本文在机器学习算法研究的基础上,通过灰狼算法对BP神经网络进行优化,并将其应用到钓鱼网站的检测上,取得了较好的效果。具体模型参靠底下文献​。​

2 部分代码

% Improved Grey Wolf Optimizer
function [Alpha_scores_CGWO,Alpha_pos_CGWO,Convergence_curve1]=GWO(SearchAgents_no,Max_iter,lb,ub,dim,objfun)
global kkk
%display('CGWO is optimizing your problem');
% SearchAgents_no=30;
% Max_iter=500;
% dim=10;
% objfun=@(x)sum(x.^2);
% ub=1; %/*lower bounds of the parameters. */
% lb=-1;%/*upper bound of the parameters.*/

%Alpha_scores_CGWO = zeros(1,runtime);

%for r=1:runtime
   
% initialize alpha, beta, and delta_pos
Alpha_pos_CGWO=zeros(1,dim);
Alpha_score=inf; %change this to -inf for maximization problems

Beta_pos=zeros(1,dim);
Beta_score=inf; %change this to -inf for maximization problems

Delta_pos=zeros(1,dim);
Delta_score=inf; %change this to -inf for maximization problems

%% Initialize the positions of search agents
% ub=ones(1,dim)*1; %/*lower bounds of the parameters. */
% lb=ones(1,dim)*(-1);%/*upper bound of the parameters.*/
% Range = repmat((ub-lb),[SearchAgents_no 1]);
% Lower = repmat(lb, [SearchAgents_no 1]);
% % 在搜索空间初始化食物源在-1和1之间
% Positions = rand(SearchAgents_no,dim) .* Range + Lower;

%% cat映射
% %灰狼位置混沌初始化种群
% x=double(zeros(1,dim));             % 定义初始序列
% X0=[0.1,0.3284];                   % 初值
% y=x;
% z1=rand(1,dim);
% z2=rand(1,dim);
% % 赋初值
% z1(1)=X0(1);
% z2(1)=X0(2);
% 
% for i=1:SearchAgents_no
%     for j=1:dim  
%         x(i,j)=mod(z1(j)+z2(j),1);     % 取余
%         y(i,j)=mod(z1(j)+2*z2(j),1);   % 取余
%         z1(j)= x(i,j);
%         z2(j)= y(i,j); 
%     end
% end
% 
% X=y; % 利用y序列
% 
% for i=1:SearchAgents_no
%     for j=1:dim
%         Positions_1(i,j) = lb+X(i,j)*(ub-lb);
%         %Positions(i,j) = lb+X(i,j)*(ub-lb);
%     end
% end

%% Logistic映射
%Logistic映射公式:x(t+1)=u*x(t)*(1-x(t))
% X1=double(zeros(1,dim));             % 定义初始序列
% z0 = rand(1,dim);
% u=4;                             % 混沌系统初始条件
% for i=1:SearchAgents_no
%     for j=1:dim  
%     X1(i,j) = u*z0(j)*(1-z0(j));
%     z0(j) = X1(i,j);
%     end

% end
% 
% for i=1:SearchAgents_no
%     for j=1:dim
%         Positions_1(i,j) = lb+X1(i,j)*(ub-lb);
%     end
% end
%% Fuch映射
% X3=double(zeros(1,dim));
% z2=rand(1,dim);
% % 赋初值
% z2(1)=0.4835;
% 
% for i=1:SearchAgents_no
%     for j=1:dim 
%         X3(i,j) = cos(1/(z2(j)^2)); %产生混沌序列1
%         z2(j) = X3(i,j);
%     end
% end
% 
% for i=1:SearchAgents_no
%     for j=1:dim
%         Positions_1(i,j) = lb+X3(i,j)*(ub-lb);
%     end
% end



%% Tent映射

X2=double(zeros(1,dim));
z1=rand(1,dim);
% 赋初值
z1(1)=0.4835;
for i=1:SearchAgents_no
   for j=1:dim 
       
   if z1(j)<=0.51 && z1(j)>=0
     X2(i,j)=1/0.5*z1(j);
     z1(j)= X2(i,j);
   elseif z1(j)<=1 && z1(j)>0.5
     X2(i,j)=1/0.5*(1-z1(j));  
     z1(j)= X2(i,j);
   end
   
   end
end

for i=1:SearchAgents_no
   for j=1:dim
%         Positions_1(i,j) = lb(j)+X2(i,j)*(ub(j)-lb(j));%求初始解x_i
         Positions_1(i,j) = lb+X2(i,j)*(ub-lb);
   end
end
%%
% 反向学习策略
 min_number = min(Positions_1(i,:));
 max_number = max(Positions_1(i,:));
 
   for i=1:size(Positions_1,1)
       for j=1:size(Positions_1,2)
           Positions_2(i,j) = rand()*(min_number+max_number) - Positions_1(i,j);%每个初始解x_i对应的反向解OP_i
%           Positions_2(i,j) = lb+ub - Positions_1(i,j);
       end
   end
   Positions = [Positions_1;Positions_2];%两种解合并组成新的种群
   for z =1: size(Positions,1)
     
      fitness1(z,: )=feval(objfun,Positions(z,:));%求适应度函数
   end
   
  [m,index] = sort(fitness1);%适应度按升序排列
   
   Positions = Positions(index(1:SearchAgents_no),:);%取前no最优的初始解得到新的灰狼初始种群
   
%% 同随机初始化位置对比
% 在搜索空间初始化食物源在-1和1之间
% ub1=ones(1,dim)*1; %/*lower bounds of the parameters. */
% lb1=ones(1,dim)*(-1);%/*upper bound of the parameters.*/
% Range1 = repmat((ub1-lb1),[SearchAgents_no 1]);
% Lower1 = repmat(lb1, [SearchAgents_no 1]);
% Positions_old = rand(SearchAgents_no,dim) .* Range1 + Lower1;  
% figure
% h1 = plot(1:SearchAgents_no,x,'+','MarkerSize',4);
% xlabel('迭代次数','FontSize',10,'FontName','Times New Roman')
% ylabel('Cat混沌序列值','FontSize',10,'FontName','Times New Roman')

% 行数为40,列数为30
%此处的初始种群可以加以改进,比如混沌初始化,反向学习策略产生初始种群,已经有佳点集理论应用到这上面了。

l=1;% Loop counter

% Main loop
while l<=Max_iter
   % 种群适应度和边界初始化
   for i=1:size(Positions,1)  % 其实是SearchAgents_no 种群个数 ,i 表示每一个灰狼个体
       
      % Return back the search agents that go beyond the boundaries of the search space
       Flag4ub=Positions(i,:)>ub;
       Flag4lb=Positions(i,:)<lb;
       Positions(i,:)=(Positions(i,:).*(~(Flag4ub+Flag4lb)))+ub.*Flag4ub+lb.*Flag4lb;               
       
     % Calculate objective function for each search agent
     % 适应度函数
     %   fitness=fobj(Positions(i,:));
     
     fitness = feval(objfun,Positions(i,:));

       % Update Alpha, Beta, and Delta
       % 更新 Alpha, Beta, and Delta 位置
       if fitness<Alpha_score 
           Alpha_score=fitness; % Update alpha
           Alpha_pos_CGWO=Positions(i,:);
       end
       fitness_Alpha = feval(objfun,Alpha_pos_CGWO); %fitness_Alpha的值是为了进行后面计算权重系数
       
       % 关键是这个优先顺序
       if fitness>Alpha_score && fitness<Beta_score 
           Beta_score=fitness; % Update beta
           Beta_pos=Positions(i,:);
       end
       fitness_Beta = feval(objfun,Beta_pos); %同fitness_Alpha
       
       if fitness>Alpha_score && fitness>Beta_score && fitness<Delta_score 
           Delta_score=fitness; % Update delta
           Delta_pos=Positions(i,:);
       end
       fitness_Delta = feval(objfun,Delta_pos);%同fitness_Alpha
               
   end
   
   %% 利用Cat混沌局部搜索
           min_X = min(Alpha_pos_CGWO);
           max_X = max(Alpha_pos_CGWO);
           for j=1:size(Alpha_pos_CGWO,2)
                Z0(j) = (Alpha_pos_CGWO(j)-min_X)/(max_X-min_X);% 将最优位置映射到(0,1)之间
           end
           % 进行Tent映射迭代       
           M=double(zeros(1,dim));             % 定义初始序列
           Z1=[0.1,0.4835];                    % 初值
           N=M;
           z1=rand(1,dim);
           z2=rand(1,dim);
           % 赋初值
           z1(1)=Z1(1);
           z2(1)=Z1(2);
            % 设置混沌迭代次数C_max
            C_max=50;
            
           for t=1:C_max
             for j=1:size(Alpha_pos_CGWO,2)  
                 M(t,j)=mod(z1(j)+z2(j),1);      % 取余
                 N(t,j)=mod(z1(j)+2*z2(j),1);    % 取余
                 z1(j)= M(t,j);
                 z2(j)= N(t,j); 
             end
           end
            V=N(t,:); % 得到第t次迭代混度搜索的序列(y序列)
            % 下面开始进行载波到原解空间,产生最优解的邻域解
            for j=1:size(Alpha_pos_CGWO,2)
                %Alpha_pos_new(j) = Alpha_pos(j)+ (max_X-min_X)*(2*V(j)-1)/2;% 将最优位置映射到(0,1)之间
                Alpha_pos_new(j) = Alpha_pos_CGWO(j)+ 3*(max_X-min_X)*(2*V(j)-1)/10;% 将最优位置映射到(0,1)之间
            end
           % 与原来的解相比较,保留最优解
           if  feval(objfun,Alpha_pos_new)>feval(objfun,Alpha_pos_CGWO)
               Alpha_pos_CGWO=Alpha_pos_CGWO;
           else
               Alpha_pos_CGWO=Alpha_pos_new;
           end 
  
   % 该算法考虑了群体的历史最优位置 &&保证了群体历史最优位置,并实现了狼群之间的交流,但并未考虑灰狼个体自身的经验
   % 因此可以考虑引入PSO算法中的个体记忆功能
   
   %a=2-l*((2)/Max_iter); % a decreases linearly fron 2 to 0
   a=2*(1-(l/Max_iter)^2);

   % Update the Position of search agents including omegas
   for i=1:size(Positions,1)  % 其实是SearchAgents_no 种群个数
       for j=1:size(Positions,2)  % 其实是变量维数 dim   
                      
           r1=rand(); % r1 is a random number in [0,1] 产生一个数
           r2=rand(); % r2 is a random number in [0,1]
           
          % 此处可以改进
           A1=2*a*r1-a; % Equation (3.3)
           C1=2*r2;     % Equation (3.4)
           
          
           % 衡量灰狼与猎物之间的距离
           D_alpha=abs(C1*Alpha_pos_CGWO(j)-Positions(i,j)); % Equation (3.5)-part 1
           % 更新头狼位置
           X1=Alpha_pos_CGWO(j)-A1*D_alpha;                  % Equation (3.6)-part 1
           
           
           %更新副头狼位置
           r1=rand();
           r2=rand();
           
           A2=2*a*r1-a; % Equation (3.3)
           C2=2*r2;     % Equation (3.4)
           
           D_beta=abs(C2*Beta_pos(j)-Positions(i,j)); % Equation (3.5)-part 2
           X2=Beta_pos(j)-A2*D_beta;                  % Equation (3.6)-part 2       
           
           % 更新普通狼位置
           r1=rand();
           r2=rand(); 
           
           A3=2*a*r1-a; % Equation (3.3)
           C3=2*r2;     % Equation (3.4)
           
           D_delta=abs(C3*Delta_pos(j)-Positions(i,j)); % Equation (3.5)-part 3
           X3=Delta_pos(j)-A3*D_delta;                  % Equation (3.5)-part 3             
           
           
         % 可以采用三者的权值改进,不用1/3
        
           w_Alpha = fitness_Alpha/(fitness_Alpha+fitness_Beta+fitness_Delta);
           w_Beta = fitness_Beta/(fitness_Alpha+fitness_Beta+fitness_Delta);
           w_Delta = fitness_Delta/(fitness_Alpha+fitness_Beta+fitness_Delta);
           
           Positions(i,j)=w_Alpha*X1+w_Beta*X2+w_Delta*X3;                 % Equation (3.7)
           
           %Positions(i,j)=(X1+X2+X3)/3;% Equation (3.7)
           
           % 此处的灰狼最优位置更新可以结合人工蜂群算法的贪婪选择或者别的选择 
           %Positions(i,j) = Positions(i,j)+b*r3*(pBest(i,j)-Positions(i,j))+ (1-b)*rand()*( Alpha_pos_gbest(i,:)-Positions(i,j));
           %Positions(i,j) = Positions(i,j)+b*rand()*(pBest(i,j)-Positions(i,j))+ (1-b)*rand()*( Alpha_pos_gbest(i,j)-Positions(i,j)); 
               
       end % 每一只灰狼位置变量的更新完成
                    
%             r4=randn();
%             Positions_new(i,:) = Positions(i,:)*(1+r4);
%             % 优胜劣汰选择
%             r5=rand();
%             p = 0.1;
%             if feval(objfun,Positions_new(i,:))>feval(objfun,Positions(i,:))&&r5<p          
%                 Positions(i,:)=Positions(i,:);
%             else
%                 Positions(i,:)=Positions_new(i,:);
%             end 
         
                       
   end % 该种群的所有灰狼位置更新
   
   
         % 保存最优解的适应度
         % Alpha_scores_CGWO(r,l)=Alpha_score;
         Alpha_scores_CGWO(l)=Alpha_score;
        
    
%     if mod(l,50)==0
%         display(['At iteration ', num2str(l), ' the best fitness is ', num2str(Alpha_score)]);
%     end
   
   l=l+1;

   Convergence_curve1(l)=Alpha_score;

end
% display([' CGWO 第 ', num2str(r), ' 次运行结束 ']);
% end

end

3 仿真结果

4 参考文献

[1]刘栋. (2019). 基于改进灰狼算法优化BP神经网络的研究和应用. (Doctoral dissertation, 安徽大学).

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是MATLAB实现基于BP神经网络优化算法的多输入寻优的完整代码: ``` function [xopt,fopt]=GWO_BP(Function_name,ub,lb,dim,SearchAgents_no,Max_iter) % 输入: % Function_name: 测试函数名 % ub: 自变量上界 % lb: 自变量下界 % dim: 自变量维度 % SearchAgents_no: 群数量 % Max_iter: 最大迭代次数 % 输出: % xopt: 最优解 % fopt: 最优值 % BP神经网络初始化 net=feedforwardnet([10 5 1]); % 三层前馈神经网络 net.trainFcn='trainlm'; % Levenberg-Marquardt算法 net.trainParam.showWindow=0; % 不显示窗口 net.trainParam.showCommandLine=0; % 不显示命令行 net.trainParam.epochs=100; % 训练次数 net=init(net); % 优化初始化 Alpha_pos=zeros(1,dim); % Alpha位置 Alpha_score=inf; % Alpha得分 Beta_pos=zeros(1,dim); % Beta位置 Beta_score=inf; % Beta得分 Delta_pos=zeros(1,dim); % Delta位置 Delta_score=inf; % Delta得分 Positions=initialization(SearchAgents_no,dim,ub,lb); % 群位置 Convergence_curve=zeros(1,Max_iter); % 收敛曲线 % 优化主循环 for iter=1:Max_iter for i=1:size(Positions,1) % 计算适应度 fitness=calculate_fitness(Positions(i,:),net,Function_name); % 更新Alpha、Beta、Delta if fitness<Alpha_score Alpha_score=fitness; Alpha_pos=Positions(i,:); end if fitness>Alpha_score && fitness<Beta_score Beta_score=fitness; Beta_pos=Positions(i,:); end if fitness>Alpha_score && fitness>Beta_score && fitness<Delta_score Delta_score=fitness; Delta_pos=Positions(i,:); end end % 更新参数a和A a=2-iter*((2)/Max_iter); A=2*a*rand()-a; % 更新群位置 for i=1:size(Positions,1) D_alpha=abs(A*Alpha_pos-Positions(i,:)); D_beta=abs(A*Beta_pos-Positions(i,:)); D_delta=abs(A*Delta_pos-Positions(i,:)); X1=Alpha_pos-A*D_alpha; X2=Beta_pos-A*D_beta; X3=Delta_pos-A*D_delta; Positions(i,:)=mean([X1;X2;X3]); end % 更新神经网络参数 for i=1:size(Positions,1) net=configure(net,Positions(i,:)',zeros(dim,1)'); net=train(net,Positions(i,:)',fitness); end % 更新收敛曲线 Convergence_curve(iter)=Alpha_score; end % 输出结果 xopt=Alpha_pos; fopt=Alpha_score; % 绘制收敛曲线 figure; plot(Convergence_curve); xlabel('迭代次数'); ylabel('最优值'); title('收敛曲线'); end % 群初始化函数 function Positions=initialization(SearchAgents_no,dim,ub,lb) Positions=rand(SearchAgents_no,dim).*(ub-lb)+lb; end % 计算适应度函数 function fitness=calculate_fitness(Position,net,Function_name) if strcmp(Function_name,'BP') % 神经网络预测 % ... % 计算误差 % ... % 适应度为误差的相反数 fitness=-error; else % 其他测试函数 % ... end end ``` 在上述代码中,我们使用了feedforwardnet函数初始化了一个三层前馈神经网络,并使用trainlm算法训练网络。在calculate_fitness函数中,我们对输入的位置进行神经网络预测,并计算误差,最终将误差的相反数作为适应度。在主循环中,我们按照优化算法的步骤逐步更新了群位置和参数,同时利用每个位置对神经网络进行训练。最终输出最优解和最优值,并绘制了收敛曲线。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Matlab科研辅导帮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值