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

📄 selectga7.m

📁 GA/SVM 程序包含三个文件: 1。MainGA12.m 2。selectGA12.m 3。svmc12.m MainGA12.m是主文件
💻 M
字号:
function [xpopn,fitness,meanf,maxf,xopt,iterropt]=selectGA7(fun,popnsize,pc,pm,numgens,vlb,vub,options,...
   datas,realClass,i_datas,i_realClass,setNum,direct)
% numbGA maximises a function of several variables subject to bounds:
% 		vlb <= x <= vub
% The objective function is defined in fun which is supplied by the user
% 		function fitness = fun(popn), where popn is a population of x values
%
% options contains the following:
%	options(1)	=	0	no printout
%					1	prints out summary statistics only
%					2	prints out summary statistics and initial and final populations
%	options(2)	=	0	uniform mutation
%					b	dynamic mutation, b is a parameter determining degree of
%							non-uniformity
%	options(3)	=	0   uses standard replacement for the next generation
%					N	combine offspring with best N parents to form next generation
%	options(4)	=	0	roulette wheel selection
%					1	stochastic universal sampling
%	options(5)	=	0	one-point crossover
%				=	1	uniform crossover
%				
%	options(6)	=	0	no fitness scaling
%				=	1	linear fitness scaling (scaling parameter c=2)


meanfhistory=[];
maxfhistory=[];
xopthistory=[];
%%%pairErrHist=[];

%form class mean vectors and cov matrices
if 0
noClass = max(realClass);
for i=1:noClass
   temp = [];
   for j=1:size(datas,2)
      if realClass(j)==i
         temp = [temp datas(:,j)]; 
      end
   end
   %size(temp)
   classMat(:,:,i) = 1;%temp;
   means(:,i) = mean(temp,2);
   covs(:,:,i) = cov(temp');
end
end


% Generate the initial population
gen=0;
%popn=Initialise(popnsize,vlb,vub);%#############################
%pop=[30	2	20	46	55	59	82	88	148	200	277	301	486	563	736	782 895 903	908	947	955	959	967	974	980	981	986	987	991	996	369];
    
pop1=[10	2070	2493	3814	4945	3307	2880	1942	2002	3660	2756];%6	1144	3012	4240	6347	71	7098
popn=[pop1;pop1;pop1;pop1;pop1;pop1;pop1;pop1;pop1;pop1;pop1;pop1];

% Obtain fitness statistics for the initial population and save the history
% parameters for use in Report

xpopn=Decode(popn,vlb,vub,options);
%%%[fitness,pairErr]=feval(fun,xpopn,datas,realClass,i_datas,i_realClass);
[fitness,newxpopnHist]=feval(fun,xpopn,datas,realClass,i_datas,i_realClass,gen);
meanf=sum(fitness)/size(newxpopnHist,1);
[maxf,imax]=max(fitness); 
xopt2=newxpopnHist(imax,:);
%%%pairErrBest = pairErr(imax,:);


xopthistory=[xopthistory;xopt2];
maxfhistory=[maxfhistory;maxf];
meanfhistory=[meanfhistory;meanf];
%%%pairErrHist=[pairErrHist;pairErrBest]; 
%%%iterropt = pairErrHist;

% Call Report for the printout of the initial population and the initial population
% statistics
%%%Report(gen,numgens,popn,xpopn,fitness,meanfhistory,maxfhistory,xopthistory,pairErrHist,...
 %%%  options,setNum,pc,pm,direct);
 
 Report(gen,numgens,popn,xpopn,fitness,meanfhistory,maxfhistory,xopthistory,options,setNum,pc,pm,direct);


% Main generation loop

for gen=1:numgens

	
  	% Reproduce
  	matingpairs = Reproduce(popn,fitness,options);

  	% Crossover
  	offspring = Crossover(matingpairs,pc,options);

  	% Mutate
  	newpopn = Mutation(offspring,pm,options,gen,numgens,vlb,vub);
   
   % Obtain fitness of the current population
   if 0
      disp(sprintf('xpopn')); disp(xpopn); pause;
   end

	xpopn=round(newpopn); %Decode(newpopn,vlb,vub,options);
    
   [newfitness,newxpopnHist]=feval(fun,xpopn,datas,realClass,i_datas,i_realClass,gen);

   if 0
      disp(sprintf('xpopn1')); disp(xpopn); pause;
   end
  
	% Calculate population statistics to be saved in the history parameters
	meanf=sum(newfitness)/size(newxpopnHist,1);
   [maxf,imax]=max(newfitness);
   
   if 0
      disp(sprintf('imax')); disp(imax);
      disp(sprintf('maxf')); disp(maxf);

      disp(sprintf('xpopn')); disp(xpopn); pause;
   %   qwq=99;
   end
   
   xopt=newxpopnHist(imax,:); %(imax(1),:);
   

	xopthistory=[xopthistory;xopt];
	maxfhistory=[maxfhistory;maxf];
   meanfhistory=[meanfhistory;meanf];
	
	% Selection procedure for the next generation
	if options(3) == 0
		% Replace parents by offspring
		popn=newpopn;
		fitness=newfitness;        
	else
		% Sort parent population and combine offspring with best options(3) of parents
		[parsort,sorti]=sort(-fitness); %disp(size(fitness)); disp(size(newfitness));
		combpopn=[popn(sorti(1:options(3)),:);newpopn];
		combfit=[fitness(sorti(1:options(3)));newfitness];
		% Sort combined population and choose best of parents and offspring
		[fitsort,fiti]=sort(-combfit);
		popn=combpopn(fiti(1:popnsize),:);
		fitness=combfit(fiti(1:popnsize));
		xpopn=Decode(popn,vlb,vub,options);
	end


% Call Report for the printout of the final population and a summary of the population
% statistics over all generations
%%%Report(gen,numgens,popn,xpopn,fitness,meanfhistory,maxfhistory,xopthistory,pairErrHist,...
  %%% options,setNum,pc,pm,direct);
  Report(gen,numgens,popn,xpopn,fitness,meanfhistory,maxfhistory,xopthistory,options,setNum,pc,pm,direct);

end;
% next 3 lines may not be used.
%xopt=xopthistory;
%maxf=maxfhistory;
%meanf=meanfhistory;

% End of binaryGA

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function popn=Initialise(popnsize,vlb,vub)
% Initial generates the initial population

xint = rand(popnsize,size(vlb,2));
factor = (vub-vlb);
popn = round( ones(popnsize,1)*vlb + xint*diag(factor) );


% End of Initial

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%function Report(gen,numgens,popn,xpopn,fitness,meanfhistory,maxfhistory,xopthistory,...
 %%%  pairErrHist,options,setNum,pc,pm,direct) 
 function Report(gen,numgens,popn,xpopn,fitness,meanfhistory,maxfhistory,xopthistory,options,setNum,pc,pm,direct) 
% report outputs the population (strings and reals) and the fitness values for the
% current generation, together with a history of mean and maximum fitness values


filename = strcat(direct,'rec');

filename = strcat(filename,'_s',num2str(setNum),'_n',num2str(size(xpopn,2)),'.txt');

fid = fopen(filename,'a');


if ((options(1)>1) & (gen==0))
	disp(' ');disp(' ');disp(' ');
	disp([sprintf('                     Generation %5.0f',gen)]);
	disp(' ');
	disp(['     fitness               x ']);


	% Output the current population details
	for i=1:size(popn,1)
      contents = [fitness(i) xpopn(i,:)];
      fprintf(fid,'%g\t',contents'); fprintf(fid,'\n');
	end;
end

if options(1)>0
	if gen==0
	%	disp(' ');
	%	disp('                       Fitness History Statistics');
   %  disp('Generation   Mean Fitness    Max Fitness            Optimal x');
      
      fprintf(fid,'pc\t pm\t generation\t mean fitness\t max fitness\t R\t Gene indices\n');
	end

   history=[pc pm gen meanfhistory(gen+1) maxfhistory(gen+1)  xopthistory(gen+1,:)];

   disp(sprintf('.'));
   fprintf(fid,'%g\t',history'); fprintf(fid,'\n');    
   
end

if ((options(1)>1) & (gen==numgens))
	disp(' ');disp(' ');disp(' ');
	disp([sprintf('                     Generation %5.0f',gen)]);
	disp(' ');
	disp(['     fitness               x ']);


	% Output the current population details
	for i=1:size(popn,1)
      %disp([sprintf('%g',fitness(i),xpopn(i,:))]);
      contents = [fitness(i) xpopn(i,:)];
      fprintf(fid,'%g\t',contents'); fprintf(fid,'\n');
	end;
end
fclose(fid);
% End of Report	

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function writeFile(gen,numgens,popn,xpopn,fitness,...
   meanfhistory,maxfhistory,xopthistory,options,pc,pm) 
% report outputs the population (strings and reals) and the fitness values for the
% current generation, together with a history of mean and maximum fitness values

if ((options(1)>1) & (gen==0))
	disp(' ');disp(' ');disp(' ');
	disp([sprintf('                     Generation %5.0f',gen)]);
	disp(' ');
	disp(['     fitness               x ']);


	% Output the current population details
	for i=1:size(popn,1)
      disp([sprintf('%12.4g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g %3.0g',...
            fitness(i),xpopn(i,:))]);
	end;
end

if options(1)>0
	if gen==0
		disp(' ');
		disp('                       Fitness History Statistics');
		disp('Generation   Mean Fitness    Max Fitness            Optimal x');
	end
   history=[gen meanfhistory(gen+1,1) maxfhistory(gen+1,1) round(xopthistory(gen+1,:))];
   %history=[gen meanfhistory(gen+1,1) maxfhistory(gen+1,1)];
	disp([sprintf('%g\t',history')]);
end

if ((options(1)>1) & (gen==numgens))
	disp(' ');disp(' ');disp(' ');
	disp([sprintf('                     Generation %5.0f',gen)]);
	disp(' ');
	disp(['     fitness               x ']);


	% Output the current population details
	for i=1:size(popn,1)
		disp([sprintf('%12.6g %12.6g %10.6g',fitness(i),xpopn(i,:))]);
	end;
end
	
% End of writeFile	

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function [matingpairs,select]=Reproduce(popn,fitness,options)
% Reproduce produces the mating pairs for crossover.
% select contains the numbers of each string in popn which has been added to
% the mating pool

if options(6)>0
	% First call for linear fitness scaling
	fitness=Scalefitness(fitness,2);
end

if options(4)==0
	% Roulette wheel selection
	randnums=rand(size(fitness));
    %pause;
else
	% Stochastic universal sampling
	rr=rand;
	spacing=1/length(fitness);
	randnums=sort(mod(rr:spacing:1+rr-0.5*spacing,1));
end
%randnums=rand(size(fitness));
%disp(sprintf('fit1 = %f, sum = %f', fitness(1), sum(fitness)));
normfit=fitness/sum(fitness);
partsum=0;
count(1)=0;
matepool=[];

for i=1:length(fitness)
	partsum=partsum+normfit(i);
	count(i+1)=length(find(randnums<partsum));
	select(i,1)=count(i+1)-count(i);
	matepool=[matepool;ones(select(i,1),1)*popn(i,:)];
end;
%mat=88;

% Now re-order the strings for mating so that the string in row 1 
% is to be mated with the string in row 2, etc.
[junk,mating] = sort(rand(size(matepool,1),1));
matingpairs = matepool(mating,:);
mat=99;
% End of Reproduce

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function offspring=Crossover(popn,pc,options)
% Crossover creates offspring from a population (ordered mating pool)
% using crossover with probability pc.

if options(5)==0
	% One-point crossover
	lbits = size(popn,2);
%	size(popn,1)
	sites = ceil(rand(size(popn,1)/2,1)*(lbits-1));
    pp=sites;
	sites = sites.*(rand(size(sites))<pc);
    p=sites;

	for j = 1:length(sites);
   		offspring(2*j-1,:) = [popn(2*j-1,1:sites(j)) popn(2*j,sites(j)+1:lbits)];
   		offspring(2*j,:) = [popn(2*j,1:sites(j)) popn(2*j-1,sites(j)+1:lbits)];
   end
      
elseif options(5)==1
	% Uniform crossover
	for i=1:size(popn,1)/2
		if rand<pc
			template=rand(1,size(popn,2))<0.5;
			offspring(2*i-1,:)=template.*popn(2*i-1,:)+(1-template).*popn(2*i,:);
			offspring(2*i,:)=template.*popn(2*i,:)+(1-template).*popn(2*i-1,:);
		else
			offspring(2*i-1,:)=popn(2*i-1,:);
			offspring(2*i,:)=popn(2*i,:);
		end		
   end
else
   % convex crossover
   l1 = options(5);
   if (l1<0 | l1>1)
      l1 = 0.5; 
      % return to default (average crossover if errouneous values passed)
   end
   
   for j = 1:size(popn,1)/2
      if rand<pc
	  		offspring(2*j-1,:) = l1.*popn(2*j-1,:) + (1-l1).*popn(2*j,:);
         offspring(2*j,:) = l1.*popn(2*j,:) + (1-l1).*popn(2*j-1,:);
      else
         offspring(2*j-1,:)=popn(2*j-1,:);
			offspring(2*j,:)=popn(2*j,:);
		end		
           
   end
   
end
offspring = round(offspring);
% End of Crossover

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function newpopn = Mutation(offspring,pm,options,curGen,numgens,vlb,vub)
% Mutation changes a gene of the offspring with probability pm.
mutate = find(rand(size(offspring))<pm);
popnRow = size(offspring,1);

% mutate contains the positions of the genes to be mutated as a column vector
% going down the columns of the matrix offspring
newpopn = offspring;
b = options(2);

% dynamic mutation
r = rand(size(offspring));
choice = (rand(size(offspring))<0.5);


newpopn(mutate) = (choice(mutate)).*(offspring(mutate) ...
   + r(mutate).*((vub(ceil(mutate/popnRow)))'-offspring(mutate))...
   .*(1-curGen/numgens).^b)...
   +(1-choice(mutate)).*(offspring(mutate)...
   - r(mutate).*(offspring(mutate)-(vlb(ceil(mutate/popnRow)))')...
   .*(1-curGen/numgens).^b);

newpopn = round(newpopn);
%uu=99;
% End of Mutation

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function xpopn = Decode(popn,vlb,vub,options)
% Decode converts a population (popn) of strings from binary to real.
% Each string in popn is of length sum(lbits) and consists of m=length(lbits)
% substrings which decode to the variables x_1,...,x_m
% If options(2)=1, first decodes Gray code into binary

% assign base 2 if binary or gray coding, base 10 if real coding

% First decode each substring to an unsigned decimal integer: xint
%index1=1;
%index2=0;
%newpopn=popn;

%for i=1:length(lbits)
%	index2=index2+lbits(i);
%	tenpowers=10.^(lbits(i)-1:-1:0);
%	xint(:,i)=newpopn(:,index1:index2)*tenpowers';
%   index1=index1+lbits(i);  
%end

% Now calculate the x values
%factor=(vub-vlb)./(10.^lbits-1);
%xpopn=ones(size(popn,1),1)*vlb+xint*diag(factor);

xpopn = round(popn);

% End of Decode

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function scfitness=Scalefitness(fitness,fmultiple)
% Scalefitness performs linear scaling on the fitness values and returns the
% results in scfitness

% Calculate the parameters a and b
favg=sum(fitness)/length(fitness);
[fmax,i]=max(fitness);
[fmin,j]=min(fitness);

den1 = fmax-favg;
den2 = favg-fmin;
error = 1e-6;

if abs(den1) > error
   a=favg*(fmultiple-1)/den1;
   b=favg*(1-a);
elseif abs(den2) > error
   a=favg/den2;
   b=favg*(1-a);
else 
   a=1;
   b=0;
end

if a*fmin+b<0
	a=favg/(favg-fmin);
    b=favg*(1-a);
end

% The scaled fitness
scfitness=a*fitness+b*ones(size(fitness));

% End of Scalefitness

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%%%End of file

⌨️ 快捷键说明

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