⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nnmodref.m

📁 RBF网络逼近、RBF-建模、RBF网络训练与测试程序
💻 M
📖 第 1 页 / 共 5 页
字号:
      mM=[mM;minp maxp];
    end
    for k=1:Nrc
      mM=[mM;min_r max_r];
    end
    netn = newff(mM,[S1c S2 S1 S2],{f1,f2,f1,f2},'trainlm');
  
    IW_y=netn.IW{1,1}(1:S1c,1:Njc);
    IW_u=netn.IW{1,1}(1:S1c,Njc+1:Njc+Nic);
    IW_r=netn.IW{1,1}(1:S1c,Njc+Nic+1:Njc+Nic+Nrc);
    B1_c=netn.b{1};
    B2_c=netn.b{2};
    LW_c=netn.LW{2,1};
  
    if Use_Previous_Weights & ~isempty(strvcat(get_param(arg1,'IW_y')))
      IW_rb = get(H.IW_r_ptr,'userdata');
      IW_ub = get(H.IW_u_ptr,'userdata');
      IW_yb = get(H.IW_y_ptr,'userdata');
      LW_cb = get(H.LW_c_ptr,'userdata');
      B1_cb = get(H.B1_c_ptr,'userdata');
      B2_cb = get(H.B2_c_ptr,'userdata');
  
      IW_y2 = eval(strvcat(get_param(arg1,'IW_y')));
      IW_r2 = eval(strvcat(get_param(arg1,'IW_r')));
      IW_u2 = eval(strvcat(get_param(arg1,'IW_u')));
      LW_c2 = eval(strvcat(get_param(arg1,'LW_c')));
      B1_c2 = eval(strvcat(get_param(arg1,'B1_c')));
      B2_c2 = eval(strvcat(get_param(arg1,'B2_c')));
      if (size(IW_y2)==size(IW_y)) & (size(IW_r2)==size(IW_r)) & (size(IW_u2)==size(IW_u)) & (size(LW_c2)==size(LW_c)) & (size(B1_c2)==size(B1_c)) & (size(B2_c2)==size(B2_c)) 
           % If Weights different from last generated, we use Simulink weights.
        if (size(IW_yb)==size(IW_y)) & (size(IW_rb)==size(IW_r)) & (size(IW_ub)==size(IW_u)) & (size(LW_cb)==size(LW_c)) & (size(B1_cb)==size(B1_c)) & (size(B2_cb)==size(B2_c)) 
              % We only compare IW1_1 to see if we have same values in simulink model and menu.
           cx=IW_yb==IW_y2;
              % Different weights, we ask which we want we prefer.
           if sum(cx(:))~=size(IW_y(:),1)
              if ishandle(HH)
                 delete(HH);
              end
              switch questdlg(...
                    {'You have a set of weights in the Simulink model and another set of weights generated in the current training process.'
                     ' ';
                     'Select which set of weights you want to use. If you select Simulink model weights, the generated weights are discarded.'
                     ' '},...
                     'Weight Selection','Simulink Model Weights','Generated Weights','Generated Weights');
              case 'Simulink Model Weights'
                 overwriteOK = 1;
              case 'Generated Weights'
                 overwriteOK = 0;
              end % switch questdlg
           else
              overwriteOK = 0;
           end
        else
           overwriteOK = 0;
        end
        if overwriteOK
           IW_y = IW_y2;
           IW_r = IW_r2;
           IW_u = IW_u2;
           LW_c = LW_c2;
           B1_c = B1_c2;
           B2_c = B2_c2;
        else
           IW_y = IW_yb;
           IW_r = IW_rb;
           IW_u = IW_ub;
           LW_c = LW_cb;
           B1_c = B1_cb;
           B2_c = B2_cb;
        end
      end
    end
    
    netn = newff([mint maxt],[S1c S2 S1 S2],{f1,f2,f1,f2},'trainbfgc');
  
    netn.trainParam.show=1;
    netn.trainParam.epochs=epochs_c;
     
    netn.layerConnect(1,2)=1;
    netn.layerWeights{1,2}.delays=[1:Nic];
    netn.layerConnect(1,4)=1;
    netn.layerWeights{1,4}.delays=[1:Njc];
    netn.LW{1,2}=IW_u;
    netn.LW{1,4}=IW_y;
    netn.layerWeights{3,2}.delays=[0:Ni-1];
    netn.LW{3,2}=IW;
    netn.layerConnect(3,4)=1;
    netn.layerWeights{3,4}.delays=[1:Nj];
    netn.LW{3,4}=LW1_2;
    netn.LW{4,3}=LW2_1;
    netn.b{3}=B1;
    netn.b{4}=B2;
    netn.layerWeights{3,4}.learn=0;
    netn.layerWeights{3,2}.learn=0;
    netn.layerWeights{4,3}.learn=0;
    netn.biases{3}.learn=0;
    netn.biases{4}.learn=0;
    netn.inputWeights{1,1}.delays=[0:Nrc-1];
    netn.IW{1,1}=IW_r;
    netn.b{1}=B1_c;
    netn.b{2}=B2_c;
    netn.LW{2,1}=LW_c;
     
  end
  retraining_size=fix(sam_training_c/retraining_c);
  
  if Normalize
     U=(tr_dat.U-min_r)*2/(max_r-min_r)-1;
     Y=(tr_dat.Y-mint)*2/(maxt-mint)-1;
  else
     U=tr_dat.U;
     Y=tr_dat.Y;
  end
  if ishandle(HH)
     delete(HH);
  end
  pause(1);            % works better than drawnow
  if Use_Inc_training==0
     for rt=1:retraining_c
        Partition=retraining_size; %min([retraining_size max([200 fix(sam_training_c/retraining_c/25)])]);
        for k=1:Partition
           rrxx{k}=(U(retraining_size*(rt-1)+k:Partition:retraining_size*rt-Partition+k)');
           yyxx{k}=(Y(retraining_size*(rt-1)+k+1:Partition:retraining_size*rt-Partition+k+1)');
        end
        ui=cell(0,0);
        par_size=size(rrxx{1},2);
        for kk=1:Nrc-1
           ui{kk}=[];
           for k2=1:par_size
              up=retraining_size*(rt-1)+Partition*(k2-1)-Nrc+2;
              if up<=0
                 ui{kk}=[ui{kk} 0];
              else
                 ui{kk}=[ui{kk} U(up)];
              end
           end
        end
        st=sprintf('Training segment # %d of %d: ',rt,retraining_c);
        set(H.error_messages,'string',st);   
     
        if rt==1
           [netn,tr,Yout,E,Pf,Af,flag_stop] = trainbfgc(netn,rrxx,yyxx,ui,[],epochs_c,Partition,par_size);
        else
           Ai=Af;
        %  Only important last Af value
           for kk=1:size(Af,1)
              for k2=1:size(Af,2)
                 Ai{kk,k2}(1:size(Af{1},2))=Af{kk,k2}(size(Af{1},2));
              end
           end
           [netn,tr,Yout,E,Pf,Af,flag_stop] = trainbfgc(netn,rrxx,yyxx,ui,Ai,epochs_c,Partition,par_size);
        end
        if flag_stop
           break
        end
     end
  else
     Partition=0; 
     for rt=1:retraining_c
        Partition=Partition+retraining_size; 
        for k=1:Partition
           rrxx{k}=(U(k:Partition:retraining_size*rt-Partition+k)');
           yyxx{k}=(Y(k+1:Partition:retraining_size*rt-Partition+k+1)');
        end
        ui{1}=[];
        par_size=size(rrxx{1},2);
        for kk=1:Nrc-1
           for k2=1:par_size
              up=Partition*(k2-1)-Nrc+2;
              if up<=0
                 ui{kk}=[ui{kk} 0];
              else
                 ui{kk}=[ui{kk} U(up)];
              end
           end
        end
        st=sprintf('Training segment # %d of %d: ',rt,retraining_c);
        set(H.error_messages,'string',st);   
     
        [netn,tr,Yout,E,Pf,Af,flag_stop] = trainbfgc(netn,rrxx,yyxx,ui,[],epochs_c,Partition,par_size);
        if flag_stop
           break
        end
     end
  end

  if flag_stop
     set(H.error_messages,'string','Training stopped by the user. You can generate or import new data, continue training or save results by selecting OK or Apply.');
     HH=msgbox({['Training stopped by the user.'] ['Plots with the reference input, and reference output and neural network output (controller + plant) will be presented shortly.'] },me,'warn'); 
     delete(findobj(HH,'style','pushbutton'));
else
     set(H.error_messages,'string','Training complete. You can generate or import new data, continue training or save results by selecting OK or Apply.');
     HH=msgbox({['Training complete.'] ['Plots with the reference input, and reference output and neural network output (controller + plant) will be presented shortly.'] },me,'warn'); 
     delete(findobj(HH,'style','pushbutton'));
  end
  pause(1);   % Pause works better here that drawnow.
    
  xx=mat2cell(U(1:sam_training_c)',1,ones(sam_training_c,1));
  [Yout,Pf,Af,E,perf] =sim(netn,xx);
  Yout=cell2mat(Yout);
  
  fig2=findall(0,'type','figure','tag','ind_adap_data0');
  if (size(fig2,1)==0), fig2=0; end
  matlab_position=get(0,'screensize');
  matlab_units=get(0,'units');
  if strcmp(matlab_units,'pixels');
     matlab_position=matlab_position*H.PointsToPixels;
  end
  if fig2==0
      units_fig2=get(fig,'Units');
      pos_fig2=[max([30 matlab_position(3)-410]) 90 328 335];
      fig2 = figure('Units',        units_fig2,...
                 'Interruptible','off', ...
                 'BusyAction','cancel', ...
                 'HandleVis','Callback', ...
                 'Name',           'Plant Response for NN Model Reference Control',...
                 'Tag',            'ind_adap_data0',...
                 'NumberTitle',    'off',...
                 'Position',       pos_fig2, ...
                 'IntegerHandle',  'off',...
                 'Toolbar',        'none');
      f2.h1=axes('Position',[0.13 0.60 0.74 0.32],'Parent',fig2);
      f2.h2=axes('Position',[0.13 0.15 0.74 0.32],'Parent',fig2);
  else
      f2=get(fig2,'userdata');
      figure(fig2);
  end            
  
  plot((0:sam_training_c-1)*Ts,tr_dat.U(1:sam_training_c),'Parent',f2.h1);
  if Normalize
     plot((0:sam_training_c-1)*Ts,tr_dat.Y(2:sam_training_c+1),'b',(0:sam_training_c-1)*Ts, ...
          (Yout(1:sam_training_c)+1)*(maxt-mint)/2+mint,'g','Parent',f2.h2);
  else
     plot((0:sam_training_c-1)*Ts,tr_dat.Y(2:sam_training_c+1),'b',(0:sam_training_c-1)*Ts, ...
          Yout(1:sam_training_c),'g','Parent',f2.h2);
  end
  set(f2.h1,'xlim',[0 (sam_training_c-1)*Ts]);
  set(f2.h2,'xlim',[0 (sam_training_c-1)*Ts]);

  set(get(f2.h1,'Title'),'string','Reference Model Input','fontweight','bold');
  set(get(f2.h2,'Title'),'string','Reference Model Output (blue), Neural Network Output (green)','fontweight','bold');
  set(get(f2.h1,'XLabel'),'string','time (s)');
  set(get(f2.h2,'XLabel'),'string','time (s)');
    
  set(fig2,'UserData',f2);
  save(cat(2,tempdir,'nnmodrefdata.mat'));
  
  set(H.IW_r_ptr,'userdata',netn.IW{1,1}); 
  set(H.IW_u_ptr,'userdata',netn.LW{1,2}); 
  set(H.IW_y_ptr,'userdata',netn.LW{1,4}); 
  set(H.LW_c_ptr,'userdata',netn.LW{2,1}); 
  set(H.B1_c_ptr,'userdata',netn.b{1}); 
  set(H.B2_c_ptr,'userdata',netn.b{2}); 

  H.Training_done=1;
  set(H.Apply_but,'enable','on');
  set(H.OK_but,'enable','on');
  set(H.Handles.Menus.File.Save_NN,'enable','on')
  set(H.Handles.Menus.File.Save_Exit_NN,'enable','on')
  set(H.Train_con,'enable','on')
  set(H.Cancel_but,'enable','on')
  
  set(H.Use_Previous_Weights_ptr,'userdata',1);
  set(H.Use_Previous_Weights_but,'value',1);
  
  if ishandle(HH)
     delete(HH);
  end
  arg1=get(H.gcbh_ptr,'userdata');
  arg2=get(H.gcb_ptr,'userdata');
  nncontrolutil('nnmodref','',arg1,arg2,'');
  
elseif strcmp(cmd,'browsesim')
   filterspec = '*.mdl';
   
   udFileEdit = get(H.reference_model,'UserData');
   LastPath = udFileEdit.PathName;
   CurrentPath=pwd;
   if ~isempty(LastPath),
      cd(LastPath);
   end
   [filename,pathname] = uigetfile(filterspec,'Simulink Reference Model:');
   if ~isempty(LastPath),
      cd(CurrentPath);
   end
   
   if filename,
      if ~strcmpi(pathname(1:end-1),CurrentPath)
         ImportStr = [pathname,filename(1:end-4)];
      else
         ImportStr = filename(1:end-4);
      end
      udFileEdit.PathName=pathname;
      udFileEdit.FileName=filename;
      set(H.reference_model,'String',filename(1:end-4),'UserData',udFileEdit);
   end
   
elseif strcmp(cmd,'clearpath') & (fig)
   %---Callback for the SImulink File box
   %    Whenever a new name is entered, update the Userdata
   NewName = get(gcbo,'String');
   indDot = findstr(NewName,'.');
   if ~isempty(indDot),
      NewName=NewName(1:indDot(end)-1);
      set(H.reference_model,'String',NewName)   
   end
      
elseif strcmp(cmd,'erase_data') & (fig)
  set(H.max_r_edit,'enable','on')
  set(H.max_r_text,'enable','on')
  set(H.min_r_edit,'enable','on')
  set(H.min_r_text,'enable','on')
  set(H.max_r_int_edit,'enable','on')
  set(H.max_r_int_text,'enable','on')
  set(H.min_r_int_edit,'enable','on')
  set(H.min_r_int_text,'enable','on')
  set(H.sam_training_c_text,'enable','on')
  set(H.sam_training_c_edit,'enable','on')
  set(H.BrowseButton,'enable','on');
  set(H.reference_model,'enable','on');
  set(H.reference_model_text,'enable','on');
  
  H.Data_Generated=0;
  H.Data_Imported=0;
  H.Data_Available=0;
  set(H.Train_con,'enable','off')
  if exist(cat(2,tempdir,'ind_adap_data2.mat'))
     delete(cat(2,tempdir,'ind_adap_data2.mat'));
  end
  if exist(cat(2,tempdir,'nnmodrefdata.mat'))
     delete(cat(2,tempdir,'nnmodrefdata.mat'));
  end
  set(fig,'UserData',H);
  set(H.Gen_data_but,'String','Generate Training Data', ...
           'Callback','nncontrolutil(''nnmodref'',''gen_data'')', ...
           'TooltipString','Generate data to be used in training the neural network controller.');
  set(H.error_messages,'string',sprintf('Generate or import data before training the neural network controller.'));
        
elseif strcmp(cmd,'data_no_ok') & (fig)
  
  set(H.Cancel_but,'enable','on')
  if H.Training_done
     set(H.OK_but,'enable','on')
     set(H.Apply_but,'enable','on')
     set(H.Handles.Menus.File.Save_NN,'enable','on')
     set(H.Handles.Menus.File.Save_Exit_NN,'enable','on')
  end
  if H.Data_Available
    load(cat(2,tempdir,'nnmodrefdata.mat'),'N2');

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -