遺傳bp演算法
❶ 有沒有用python實現的遺傳演算法優化BP神經網路的代碼
下面是函數實現的代碼部分:
clc
clear all
close all
%% 載入神經網路的訓練樣本 測試樣本每列一個樣本 輸入P 輸出T,T是標簽
%樣本數據就是前面問題描述中列出的數據
%epochs是計算時根據輸出誤差返回調整神經元權值和閥值的次數
load data
% 初始隱層神經元個數
hiddennum=31;
% 輸入向量的最大值和最小值
threshold=[0 1;0 1;0 1;0 1;0 1;0 1;0 1;0 1;0 1;0 1;0 1;0 1;0 1;0 1;0 1];
inputnum=size(P,1); % 輸入層神經元個數
outputnum=size(T,1); % 輸出層神經元個數
w1num=inputnum*hiddennum; % 輸入層到隱層的權值個數
w2num=outputnum*hiddennum;% 隱層到輸出層的權值個數
N=w1num+hiddennum+w2num+outputnum; %待優化的變數的個數
%% 定義遺傳演算法參數
NIND=40; %個體數目
MAXGEN=50; %最大遺傳代數
PRECI=10; %變數的二進制位數
GGAP=0.95; %代溝
px=0.7; %交叉概率
pm=0.01; %變異概率
trace=zeros(N+1,MAXGEN); %尋優結果的初始值
FieldD=[repmat(PRECI,1,N);repmat([-0.5;0.5],1,N);repmat([1;0;1;1],1,N)]; %區域描述器
Chrom=crtbp(NIND,PRECI*N); %初始種群
%% 優化
gen=0; %代計數器
X=bs2rv(Chrom,FieldD); %計算初始種群的十進制轉換
ObjV=Objfun(X,P,T,hiddennum,P_test,T_test); %計算目標函數值
while gen
❷ matlab的遺傳演算法優化BP神經網路
對y=x1^2+x2^2非線性系統進行建模,用1500組數據對網路進行構建網路,500組數據測試網路。由於BP神經網路初始神經元之間的權值和閾值一般隨機選擇,因此容易陷入局部最小值。本方法使用遺傳演算法優化初始神經元之間的權值和閾值,並對比使用遺傳演算法前後的效果。
步驟:
未經遺傳演算法優化的BP神經網路建模
1、 隨機生成2000組兩維隨機數(x1,x2),並計算對應的輸出y=x1^2+x2^2,前1500組數據作為訓練數據input_train,後500組數據作為測試數據input_test。並將數據存儲在data中待遺傳演算法中使用相同的數據。
2、 數據預處理:歸一化處理。
3、 構建BP神經網路的隱層數,次數,步長,目標。
4、 使用訓練數據input_train訓練BP神經網路net。
❸ 遺傳演算法優化BP神經網路是不是會使訓練時間變慢!
1、遺傳演算法優化BP神經網路是指優化神經網路的參數;
2、因此,對訓練時間沒有影響。
❹ 關於遺傳演算法優化BP神經網路的問題
程序:
1、未經遺傳演算法優化的BP神經網路建模
clear;
clc;
%%%%%%%%%%%%%輸入參數%%%%%%%%%%%%%%
N=2000; %數據總個數
M=1500; %訓練數據
%%%%%%%%%%%%%訓練數據%%%%%%%%%%%%%%
for i=1:N
input(i,1)=-5+rand*10;
input(i,2)=-5+rand*10;
end
output=input(:,1).^2+input(:,2).^2;
save data input output
load data.mat
%從1到N隨機排序
k=rand(1,N);
[m,n]=sort(k);
%找出訓練數據和預測數據
input_train=input(n(1:M),:)';
output_train=output(n(1:M),:)';
input_test=input(n((M+1):N),:)';
output_test=output(n((M+1):N),:)';
%數據歸一化
[inputn,inputs]=mapminmax(input_train);
[outputn,outputs]=mapminmax(output_train);
%構建BP神經網路
net=newff(inputn,outputn,5);
net.trainParam.epochs=100;
net.trainParam.lr=0.1;
net.trainParam.goal=0.0000004;
%BP神經網路訓練
net=train(net,inputn,outputn);
%測試樣本歸一化
inputn_test=mapminmax('apply',input_test,inputs);
%BP神經網路預測
an=sim(net,inputn_test);
%%網路得到數據反歸一化
BPoutput=mapminmax('reverse',an,outputs);
figure(1)
%plot(BPoutput,':og');
scatter(1:(N-M),BPoutput,'rx');
hold on;
%plot(output_test,'-*');
scatter(1:(N-M),output_test,'o');
legend('預測輸出','期望輸出','fontsize',12);
title('BP網路預測輸出','fontsize',12);
xlabel('樣本','fontsize',12);
xlabel('優化前輸出的誤差','fontsize',12);
figure(2)
error=BPoutput-output_test;
plot(1:(N-M),error);
xlabel('樣本','fontsize',12);
ylabel('優化前輸出的誤差','fontsize',12);
%save net net inputs outputs
2、遺傳演算法優化的BP神經網路建模
(1)主程序
%清空環境變數
clc
clear
%讀取數據
load data.mat
%節點個數
inputnum=2;
hiddennum=5;
outputnum=1;
%訓練數據和預測數據
input_train=input(1:1500,:)';
input_test=input(1501:2000,:)';
output_train=output(1:1500)';
output_test=output(1501:2000)';
%選連樣本輸入輸出數據歸一化
[inputn,inputps]=mapminmax(input_train);
[outputn,outputps]=mapminmax(output_train);
%構建網路
net=newff(inputn,outputn,hiddennum);
%% 遺傳演算法參數初始化
maxgen=10; %進化代數,即迭代次數
sizepop=30; %種群規模
pcross=[0.3]; %交叉概率選擇,0和1之間
pmutation=[0.1]; %變異概率選擇,0和1之間
%節點總數
numsum=inputnum*hiddennum+hiddennum+hiddennum*outputnum+outputnum;
lenchrom=ones(1,numsum);
bound=[-3*ones(numsum,1) 3*ones(numsum,1)]; %數據范圍
%------------------------------------------------------種群初始化------------------------------%------------------
--------
indivials=struct('fitness',zeros(1,sizepop), 'chrom',[]); %將種群信息定義為一個結構體
%avgfitness=[]; %每一代種群的平均適應度
bestfitness=[]; %每一代種群的最佳適應度
bestchrom=[]; %適應度最好的染色體
%初始化種群
for i=1:sizepop
%隨機產生一個種群
indivials.chrom(i,:)=Code(lenchrom,bound); %編碼
x=indivials.chrom(i,:);
%計算適應度
indivials.fitness(i)=fun(x,inputnum,hiddennum,outputnum,net,inputn,outputn); %染色體的適應度
end
%找最好的染色體
[bestfitness bestindex]=min(indivials.fitness);
bestchrom=indivials.chrom(bestindex,:); %最好的染色體
%avgfitness=sum(indivials.fitness)/sizepop; %染色體的平均適應度
% 記錄每一代進化中最好的適應度和平均適應度
%trace=[avgfitness bestfitness];
%% 迭代求解最佳初始閥值和權值
% 進化開始
for i=1:maxgen
i
% 選擇
indivials=Select(indivials,sizepop);
% avgfitness=sum(indivials.fitness)/sizepop;
%交叉
indivials.chrom=Cross(pcross,lenchrom,indivials.chrom,sizepop,bound);
% 變異
indivials.chrom=Mutation(pmutation,lenchrom,indivials.chrom,sizepop,i,maxgen,bound);
% 計算適應度
for j=1:sizepop
x=indivials.chrom(j,:); %解碼
indivials.fitness(j)=fun(x,inputnum,hiddennum,outputnum,net,inputn,outputn);
end
%找到最小和最大適應度的染色體及它們在種群中的位置
[newbestfitness,newbestindex]=min(indivials.fitness);
[worestfitness,worestindex]=max(indivials.fitness);
% 代替上一次進化中最好的染色體
if bestfitness>newbestfitness
bestfitness=newbestfitness;
bestchrom=indivials.chrom(newbestindex,:);
end
indivials.chrom(worestindex,:)=bestchrom;
indivials.fitness(worestindex)=bestfitness;
%avgfitness=sum(indivials.fitness)/sizepop;
% trace=[trace;avgfitness bestfitness]; %記錄每一代進化中最好的適應度和平均適應度
end
%% 遺傳演算法結果分析
%figure(3)
%[r c]=size(trace);
%plot([1:r]',trace(:,2),'b--');
%title(['適應度曲線 ' '終止代數=' num2str(maxgen)]);
%xlabel('進化代數');ylabel('適應度');
%legend('平均適應度','最佳適應度');
disp('適應度 變數');
x=bestchrom;
%% 把最優初始閥值權值賦予網路預測
% %用遺傳演算法優化的BP網路進行值預測
w1=x(1:inputnum*hiddennum);
B1=x(inputnum*hiddennum+1:inputnum*hiddennum+hiddennum);
w2=x(inputnum*hiddennum+hiddennum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum);
B2=x
(inputnum*hiddennum+hiddennum+hiddennum*outputnum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum+outputnum);
net.iw{1,1}=reshape(w1,hiddennum,inputnum);
net.lw{2,1}=reshape(w2,outputnum,hiddennum);
net.b{1}=reshape(B1,hiddennum,1);
net.b{2}=B2;
%% BP網路訓練
%網路進化參數
net.trainParam.epochs=100;
net.trainParam.lr=0.1;
%net.trainParam.goal=0.00001;
%網路訓練
[net,per2]=train(net,inputn,outputn);
%% BP網路預測
%數據歸一化
inputn_test=mapminmax('apply',input_test,inputps);
an=sim(net,inputn_test);
test_simu=mapminmax('reverse',an,outputps);
error=test_simu-output_test;
%figure(4);
hold on;plot(1:500,error,'r');
legend('優化前的誤差','優化後的誤差','fontsize',12)
(2)編碼子程序code.m
function ret=Code(lenchrom,bound)
%本函數將變數編碼成染色體,用於隨機初始化一個種群
% lenchrom input : 染色體長度
% bound input : 變數的取值范圍
% ret output: 染色體的編碼值
flag=0;
while flag==0
pick=rand(1,length(lenchrom));
ret=bound(:,1)'+(bound(:,2)-bound(:,1))'.*pick; %線性插值,編碼結果以實數向量存入ret中
flag=test(lenchrom,bound,ret); %檢驗染色體的可行性
end
(3)適應度函數fun.m
function error = fun(x,inputnum,hiddennum,outputnum,net,inputn,outputn)
%該函數用來計算適應度值
%x input 個體
%inputnum input 輸入層節點數
%outputnum input 隱含層節點數
%net input 網路
%inputn input 訓練輸入數據
%outputn input 訓練輸出數據
%error output 個體適應度值
%提取
w1=x(1:inputnum*hiddennum);
B1=x(inputnum*hiddennum+1:inputnum*hiddennum+hiddennum);
w2=x(inputnum*hiddennum+hiddennum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum);
B2=x(inputnum*hiddennum+hiddennum+hiddennum*outputnum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum+outputnum);
net=newff(inputn,outputn,hiddennum);
%網路進化參數
net.trainParam.epochs=20;
net.trainParam.lr=0.1;
net.trainParam.goal=0.00001;
net.trainParam.show=100;
net.trainParam.showWindow=0;
%網路權值賦值
net.iw{1,1}=reshape(w1,hiddennum,inputnum);
net.lw{2,1}=reshape(w2,outputnum,hiddennum);
net.b{1}=reshape(B1,hiddennum,1);
net.b{2}=B2;
%網路訓練
net=train(net,inputn,outputn);
an=sim(net,inputn);
error=sum(abs(an-outputn));
(4)選擇操作Select.m
function ret=select(indivials,sizepop)
% 該函數用於進行選擇操作
% indivials input 種群信息
% sizepop input 種群規模
% ret output 選擇後的新種群
%求適應度值倒數
[a bestch]=min(indivials.fitness);
%b=indivials.chrom(bestch);
%c=indivials.fitness(bestch);
fitness1=10./indivials.fitness; %indivials.fitness為個體適應度值
%個體選擇概率
sumfitness=sum(fitness1);
sumf=fitness1./sumfitness;
%採用輪盤賭法選擇新個體
index=[];
for i=1:sizepop %sizepop為種群數
pick=rand;
while pick==0
pick=rand;
end
for i=1:sizepop
pick=pick-sumf(i);
if pick<0
index=[index i];
break;
end
end
end
%index=[index bestch];
%新種群
indivials.chrom=indivials.chrom(index,:); %indivials.chrom為種群中個體
indivials.fitness=indivials.fitness(index);
%indivials.chrom=[indivials.chrom;b];
%indivials.fitness=[indivials.fitness;c];
ret=indivials;
(5)交叉操作cross.m
function ret=Cross(pcross,lenchrom,chrom,sizepop,bound)
%本函數完成交叉操作
% pcorss input : 交叉概率
% lenchrom input : 染色體的長度
% chrom input : 染色體群
% sizepop input : 種群規模
% ret output : 交叉後的染色體
for i=1:sizepop %每一輪for循環中,可能會進行一次交叉操作,染色體是隨機選擇的,交叉位置也是隨機選擇的,%但該輪for循環中是否進行交叉操作則由交叉概率決定(continue控制)
% 隨機選擇兩個染色體進行交叉
pick=rand(1,2);
while prod(pick)==0
pick=rand(1,2);
end
index=ceil(pick.*sizepop);
% 交叉概率決定是否進行交叉
pick=rand;
while pick==0
pick=rand;
end
if pick>pcross
continue;
end
flag=0;
while flag==0
% 隨機選擇交叉位
pick=rand;
while pick==0
pick=rand;
end
pos=ceil(pick.*sum(lenchrom)); %隨機選擇進行交叉的位置,即選擇第幾個變數進行交叉,注意:兩個染色體交叉的位置相同
pick=rand; %交叉開始
v1=chrom(index(1),pos);
v2=chrom(index(2),pos);
chrom(index(1),pos)=pick*v2+(1-pick)*v1;
chrom(index(2),pos)=pick*v1+(1-pick)*v2; %交叉結束
flag1=test(lenchrom,bound,chrom(index(1),:)); %檢驗染色體1的可行性
flag2=test(lenchrom,bound,chrom(index(2),:)); %檢驗染色體2的可行性
if flag1*flag2==0
flag=0;
else flag=1;
end %如果兩個染色體不是都可行,則重新交叉
end
end
ret=chrom;
(6)變異操作Mutation.m
function ret=Mutation(pmutation,lenchrom,chrom,sizepop,num,maxgen,bound)
% 本函數完成變異操作
% pcorss input : 變異概率
% lenchrom input : 染色體長度
% chrom input : 染色體群
% sizepop input : 種群規模
% opts input : 變異方法的選擇
% pop input : 當前種群的進化代數和最大的進化代數信息
% bound input : 每個個體的上屆和下屆
% maxgen input :最大迭代次數
% num input : 當前迭代次數
% ret output : 變異後的染色體
for i=1:sizepop %每一輪for循環中,可能會進行一次變異操作,染色體是隨機選擇的,變異位置也是隨機選擇的,
%但該輪for循環中是否進行變異操作則由變異概率決定(continue控制)
% 隨機選擇一個染色體進行變異
pick=rand;
while pick==0
pick=rand;
end
index=ceil(pick*sizepop);
% 變異概率決定該輪循環是否進行變異
pick=rand;
if pick>pmutation
continue;
end
flag=0;
while flag==0
% 變異位置
pick=rand;
while pick==0
pick=rand;
end
pos=ceil(pick*sum(lenchrom)); %隨機選擇了染色體變異的位置,即選擇了第pos個變數進行變異
pick=rand; %變異開始
fg=(rand*(1-num/maxgen))^2;
if pick>0.5
chrom(i,pos)=chrom(i,pos)+(bound(pos,2)-chrom(i,pos))*fg;
else
chrom(i,pos)=chrom(i,pos)-(chrom(i,pos)-bound(pos,1))*fg;
end %變異結束
flag=test(lenchrom,bound,chrom(i,:)); %檢驗染色體的可行性
end
end
ret=chrom;
❺ 遺傳神經網路識別原理
4.3.1 遺傳BP簡介
遺傳識別是遺傳演算法+神經網路的一種新興的尋優技術,適合於復雜的、疊加的非線性系統的辨識描述。神經網路演算法是當前較為成熟的識別分類方法,但網路權值的訓練一直存在著缺陷。為此結合具體應用,在對遺傳演算法進行改進的基礎上,本文採用了一種基於遺傳學習權值的神經網路識別方法,並取得了較好的效果。
盡管常規遺傳演算法是穩健的,但針對一個具體問題遺傳演算法只有和其他方法(或稱原有演算法)有效地結合在一起,組成一個新的混合演算法,才能在實際中得到廣泛應用。混合演算法既要保持原有演算法的長處,又要保持遺傳演算法的優點,因此常規遺傳演算法中的適應值函數、編碼、遺傳運算元等必須做適當的修改以適應混合演算法的要求。
4.3.1.1 適應值信息
常規演算法中,適應值常被表示為全局極小,用歐氏距離來實現。例如,適應值常被表示為如下形式:
圖4-5 改進的 GABP計算流程圖
GABP的計算過程圖如圖4-5所示。
❻ 利用遺傳演算法優化的bp神經網路怎麼畫出誤差與訓練時間的變化
這個得靠你自己編程實現,沒有現成的函數。具體流程如下:
初始化:將各個權值、閾值都作為實數編碼,構成染色體,並產生初始種群;
選擇、交叉、變異:注意各個概率和交叉方式;
檢驗:將染色體解碼進神經網路,代入樣本計算誤差。可能你還可以使用最優個體保存策略。
循環迭代上述過程,直至誤差滿足條件。
將遺傳演算法的代數和誤差記錄下來,用plot函數就可以畫出變化曲線了。
❼ 遺傳演算法為什麼可以優化bp神經網路
遺傳演算法(Genetic Algorithm)是模擬達爾文生物進化論的自然選擇和遺傳學機理的生物進化過程的計算模型,是一種通過模擬自然進化過程搜索最優解的方法。遺傳演算法是從代表問題可能潛在的解集的一個種群(population)開始的,而一個種群則由經過基因(gene)編碼的一定數目的個體(indivial)組成。每個個體實際上是染色體(chromosome)帶有特徵的實體。染色體作為遺傳物質的主要載體,即多個基因的集合,其內部表現(即基因型)是某種基因組合,它決定了個體的形狀的外部表現,如黑頭發的特徵是由染色體中控制這一特徵的某種基因組合決定的。因此,在一開始需要實現從表現型到基因型的映射即編碼工作。由於仿照基因編碼的工作很復雜,我們往往進行簡化,如二進制編碼,初代種群產生之後,按照適者生存和優勝劣汰的原理,逐代(generation)演化產生出越來越好的近似解,在每一代,根據問題域中個體的適應度(fitness)大小選擇(selection)個體,並藉助於自然遺傳學的遺傳運算元(genetic operators)進行組合交叉(crossover)和變異(mutation),產生出代表新的解集的種群。這個過程將導致種群像自然進化一樣的後生代種群比前代更加適應於環境,末代種群中的最優個體經過解碼(decoding),可以作為問題近似最優解。
❽ 運行遺基於遺傳演算法的BP神經網路MATLAB代碼程序時總是出錯!!!
這個問題也困擾了我好久,終於解決了。給你個ga.m程序,新建m文件復制進去,再運行程序試試。
%ga.m
function [x,endPop,bPop,traceInfo] = ga(bounds,evalFN,evalOps,startPop,opts,...
termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)
% GA run a genetic algorithm
% function [x,endPop,bPop,traceInfo]=ga(bounds,evalFN,evalOps,startPop,opts,
% termFN,termOps,selectFN,selectOps,
% xOverFNs,xOverOps,mutFNs,mutOps)
%
% Output Arguments:
% x - the best solution found ring the course of the run
% endPop - the final population
% bPop - a trace of the best population
% traceInfo - a matrix of best and means of the ga for each generation
%
% Input Arguments:
% bounds - a matrix of upper and lower bounds on the variables
% evalFN - the name of the evaluation .m function
% evalOps - options to pass to the evaluation function ([NULL])
% startPop - a matrix of solutions that can be initialized
% from initialize.m
% opts - [epsilon prob_ops display] change required to consider two
% solutions different, prob_ops 0 if you want to apply the
% genetic operators probabilisticly to each solution, 1 if
% you are supplying a deterministic number of operator
% applications and display is 1 to output progress 0 for
% quiet. ([1e-6 1 0])
% termFN - name of the .m termination function (['maxGenTerm'])
% termOps - options string to be passed to the termination function
% ([100]).
% selectFN - name of the .m selection function (['normGeomSelect'])
% selectOpts - options string to be passed to select after
% select(pop,#,opts) ([0.08])
% xOverFNS - a string containing blank seperated names of Xover.m
% files (['arithXover heuristicXover simpleXover'])
% xOverOps - A matrix of options to pass to Xover.m files with the
% first column being the number of that xOver to perform
% similiarly for mutation ([2 0;2 3;2 0])
% mutFNs - a string containing blank seperated names of mutation.m
% files (['boundaryMutation multiNonUnifMutation ...
% nonUnifMutation unifMutation'])
% mutOps - A matrix of options to pass to Xover.m files with the
% first column being the number of that xOver to perform
% similiarly for mutation ([4 0 0;6 100 3;4 100 3;4 0 0])
% Binary and Real-Valued Simulation Evolution for Matlab
% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay
%
% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function
% optimization: A Matlab implementation. ACM Transactions on Mathmatical
% Software, Submitted 1996.
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 1, or (at your option)
% any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. A of the GNU
% General Public License can be obtained from the
% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
%%$Log: ga.m,v $
%Revision 1.10 1996/02/02 15:03:00 jjoine
% Fixed the ordering of imput arguments in the comments to match
% the actual order in the ga function.
%
%Revision 1.9 1995/08/28 20:01:07 chouck
% Updated initialization parameters, updated mutation parameters to reflect
% b being the third option to the nonuniform mutations
%
%Revision 1.8 1995/08/10 12:59:49 jjoine
%Started Logfile to keep track of revisions
%
n=nargin;
if n<2 | n==6 | n==10 | n==12
disp('Insufficient arguements')
end
if n<3 %Default evalation opts.
evalOps=[];
end
if n<5
opts = [1e-6 1 0];
end
if isempty(opts)
opts = [1e-6 1 0];
end
if any(evalFN<48) %Not using a .m file
if opts(2)==1 %Float ga
e1str=['x=c1; c1(xZomeLength)=', evalFN ';'];
e2str=['x=c2; c2(xZomeLength)=', evalFN ';'];
else %Binary ga
e1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...
evalFN ';'];
end
else %Are using a .m file
if opts(2)==1 %Float ga
e1str=['[c1 c1(xZomeLength)]=' evalFN '(c1,[gen evalOps]);'];
e2str=['[c2 c2(xZomeLength)]=' evalFN '(c2,[gen evalOps]);'];
else %Binary ga
e1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' evalFN ...
'(x,[gen evalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];
end
end
if n<6 %Default termination information
termOps=[100];
termFN='maxGenTerm';
end
if n<12 %Default muatation information
if opts(2)==1 %Float GA
mutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation'];
mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];
else %Binary GA
mutFNs=['binaryMutation'];
mutOps=[0.05];
end
end
if n<10 %Default crossover information
if opts(2)==1 %Float GA
xOverFNs=['arithXover heuristicXover simpleXover'];
xOverOps=[2 0;2 3;2 0];
else %Binary GA
xOverFNs=['simpleXover'];
xOverOps=[0.6];
end
end
if n<9 %Default select opts only i.e. roullete wheel.
selectOps=[];
end
if n<8 %Default select info
selectFN=['normGeomSelect'];
selectOps=[0.08];
end
if n<6 %Default termination information
termOps=[100];
termFN='maxGenTerm';
end
if n<4 %No starting population passed given
startPop=[];
end
if isempty(startPop) %Generate a population at random
%startPop=zeros(80,size(bounds,1)+1);
startPop=initializega(80,bounds,evalFN,evalOps,opts(1:2));
end
if opts(2)==0 %binary
bits=calcbits(bounds,opts(1));
end
xOverFNs=parse(xOverFNs);
mutFNs=parse(mutFNs);
xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness
numVar = xZomeLength-1; %Number of variables
popSize = size(startPop,1); %Number of indivials in the pop
endPop = zeros(popSize,xZomeLength); %A secondary population matrix
c1 = zeros(1,xZomeLength); %An indivial
c2 = zeros(1,xZomeLength); %An indivial
numXOvers = size(xOverFNs,1); %Number of Crossover operators
numMuts = size(mutFNs,1); %Number of Mutation operators
epsilon = opts(1); %Threshold for two fittness to differ
oval = max(startPop(:,xZomeLength)); %Best value in start pop
bFoundIn = 1; %Number of times best has changed
done = 0; %Done with simulated evolution
gen = 1; %Current Generation Number
collectTrace = (nargout>3); %Should we collect info every gen
floatGA = opts(2)==1; %Probabilistic application of ops
display = opts(3); %Display progress
while(~done)
%Elitist Model
[bval,bindx] = max(startPop(:,xZomeLength)); %Best of current pop
best = startPop(bindx,:);
if collectTrace
traceInfo(gen,1)=gen; %current generation
traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
traceInfo(gen,4)=std(startPop(:,xZomeLength));
end
if ( (abs(bval - oval)>epsilon) | (gen==1)) %If we have a new best sol
if display
fprintf(1,'\n%d %f\n',gen,bval); %Update the display
end
if floatGA
bPop(bFoundIn,:)=[gen startPop(bindx,:)]; %Update bPop Matrix
else
bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
startPop(bindx,xZomeLength)];
end
bFoundIn=bFoundIn+1; %Update number of changes
oval=bval; %Update the best val
else
if display
fprintf(1,'%d ',gen); %Otherwise just update num gen
end
end
endPop = feval(selectFN,startPop,[gen selectOps]); %Select
if floatGA %Running with the model where the parameters are numbers of ops
for i=1:numXOvers,
for j=1:xOverOps(i,1),
a = round(rand*(popSize-1)+1); %Pick a parent
b = round(rand*(popSize-1)+1); %Pick another parent
xN=deblank(xOverFNs(i,:)); %Get the name of crossover function
[c1 c2] = feval(xN,endPop(a,:),endPop(b,:),bounds,[gen xOverOps(i,:)]);
if c1(1:numVar)==endPop(a,(1:numVar)) %Make sure we created a new
c1(xZomeLength)=endPop(a,xZomeLength); %solution before evaluating
elseif c1(1:numVar)==endPop(b,(1:numVar))
c1(xZomeLength)=endPop(b,xZomeLength);
else
%[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
eval(e1str);
end
if c2(1:numVar)==endPop(a,(1:numVar))
c2(xZomeLength)=endPop(a,xZomeLength);
elseif c2(1:numVar)==endPop(b,(1:numVar))
c2(xZomeLength)=endPop(b,xZomeLength);
else
%[c2(xZomeLength) c2] = feval(evalFN,c2,[gen evalOps]);
eval(e2str);
end
endPop(a,:)=c1;
endPop(b,:)=c2;
end
end
for i=1:numMuts,
for j=1:mutOps(i,1),
a = round(rand*(popSize-1)+1);
c1 = feval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);
if c1(1:numVar)==endPop(a,(1:numVar))
c1(xZomeLength)=endPop(a,xZomeLength);
else
%[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
eval(e1str);
end
endPop(a,:)=c1;
end
end
else %We are running a probabilistic model of genetic operators
for i=1:numXOvers,
xN=deblank(xOverFNs(i,:)); %Get the name of crossover function
cp=find(rand(popSize,1)<xOverOps(i,1)==1);
if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); end
cp=reshape(cp,size(cp,1)/2,2);
for j=1:size(cp,1)
a=cp(j,1); b=cp(j,2);
[endPop(a,:) endPop(b,:)] = feval(xN,endPop(a,:),endPop(b,:),...
bounds,[gen xOverOps(i,:)]);
end
end
for i=1:numMuts
mN=deblank(mutFNs(i,:));
for j=1:popSize
endPop(j,:) = feval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);
eval(e1str);
end
end
end
gen=gen+1;
done=feval(termFN,[gen termOps],bPop,endPop); %See if the ga is done
startPop=endPop; %Swap the populations
[bval,bindx] = min(startPop(:,xZomeLength)); %Keep the best solution
startPop(bindx,:) = best; %replace it with the worst
end
[bval,bindx] = max(startPop(:,xZomeLength));
if display
fprintf(1,'\n%d %f\n',gen,bval);
end
x=startPop(bindx,:);
if opts(2)==0 %binary
x=b2f(x,bounds,bits);
bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
startPop(bindx,xZomeLength)];
else
bPop(bFoundIn,:)=[gen startPop(bindx,:)];
end
if collectTrace
traceInfo(gen,1)=gen; %current generation
traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
end
❾ 我用遺傳演算法優化BP網路權值和閾值 ,可訓練出來和標准BP差不多,並且誤差很大,這是什麼情況
說你很好的人,不一定和你在一起,因為他只是安慰你。說愛你的人,不一定會愛下去,因為他不過是敷衍