📄 ga_approx.m
字号:
% tune the GA in this case by changing the 1 in the numerator to another % constant and the .1 to a different value.sumfitness = sumfitness + fitness(chrom_number); % Store this for % use below end% Next, determine the most fit and least fit chromosome and % the chrom_numbers (which we call bestmember and worstmember). [bestfitness(popcount),bestmember]=max(fitness);[worstfitness(popcount),worstmember]=min(fitness);% Next, save these (if want to save worstindividual can too)bestindividual(:,popcount)=trait(:,bestmember,popcount);%worstindividual(:,popcount)=trait(:,worstmember,popcount);% Compute the average fitness in case you want to plot it.avefitness(popcount) = sumfitness / POP_SIZE; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Create the next generation%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% First, form the mating pool. % To do this we select as parents the% chromosomes that are most fit. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for pop_member = 1:POP_SIZE, if ELITISM ==1 & pop_member==bestmember % If elitism on, and have % the elite member parent_chrom(:,pop_member)=trait(:,pop_member,popcount); % Makes sure that % the elite member gets into the next % generation. else pointer=rand*sumfitness; % This makes the pointer for the roulette % wheel. member_count=1; % Initialization total=fitness(1); while total < pointer, % This spins the wheel to the % pointer and finds the % chromosome there - which is % identified by member_count member_count=member_count+1; total=total+fitness(member_count); end % Next, make the parent chromosome parent_chrom(:,pop_member)=trait(:,member_count,popcount); end end%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Reproduce section (i.e., make off-spring - "children")%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% In the approach below each individual gets to mate and% they randomly pick someone else (not themselves) in the % mating pool to mate with. Resulting children are % composed of a combination of genetic material of their% parents. For the AGA crossover is different since% we have not split the numbers up into sequences of % digits. We can, however, achieve essentially the same effect as% the generation of a random cross site by the random% generation of how much of each trait will be swapped% with the corresponding trait from the mate and by% randomly selecting a trait that is crossed over.% Next, notice that if elitism is on, when the elite % member gets a chance to mate they do not; they are % simply copied over to the next generation.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%for parent_number1 = 1:POP_SIZE, % Crossover (parent_number1 is the % individual who gets to mate if ELITISM ==1 & parent_number1==bestmember % If elitism on, and % have the elite member child(:,parent_number1)=parent_chrom(:,parent_number1); else parent_number2=parent_number1; % Initialize who the mate is while parent_number2 == parent_number1 % Iterate until find % a mate other than % yourself parent_number2 = rand*POP_SIZE; % Choose parent number 2 % randomly (a random mate) parent_number2 = parent_number2-rem(parent_number2,1)+1; end if CROSS_PROB > rand % If true then crossover occurs % and here we simply then crossover % all the traits on an individual alpha=rand; % Specifies a random proportion of genetic % material that is going to be kept % by parent_number1 in mating trait_site = rand*NUM_TRAITS; % Pick the trait that % is crossed over (i.e., where the split is made trait_site = trait_site-rem(trait_site,1)+1; % The next lines form the child by the swapping of genetic% material between the parents. child(trait_site,parent_number1)=... alpha*parent_chrom(trait_site,parent_number1)+... (1-alpha)*parent_chrom(trait_site,parent_number2); % This takes part of parent_number1 (as given by % alpha) and part of parent_number2 (specified % by 1-alpha, the remaining portion) % and makes a child from thischild(1:trait_site-1,parent_number1)=... parent_chrom(1:trait_site-1,parent_number1);child(trait_site:NUM_TRAITS,parent_number1)=... parent_chrom(trait_site:NUM_TRAITS,parent_number2); % These last two lines make the child have the first % part of parent1 and the last part of parent2 % In this way, at the trait site we think of randomly % splitting the two traits, and the child gets the % first traits of parent1 and the last traits of parent2 % (clearly there are many other ways to do this - here we % simply pick one way to make it analogous to the standard % GA) % Note that it is easy to modify the above code so that% all traits are crossed over in different proportions. This % would then be a "multiple crossover point" strategy.% One way to do this would be to simply let%child(:,parent_number1)=...% alpha*parent_chrom(:,parent_number1)+...% (1-alpha)*parent_chrom(:,parent_number2); % This crossover operation can result in traits that are out% of the range specified by HIGHTRAIT and LOWTRAIT so we % put them back in range here.if child(trait_site,parent_number1)>HIGHTRAIT(trait_site) % The trait has went higher than the upper % bound so let the trait equal to the % HIGHTRAIT bound.child(trait_site,parent_number1)=HIGHTRAIT(trait_site);% Now consider the other case:elseif child(trait_site,parent_number1)<LOWTRAIT(trait_site) % The trait has went lower than the lower % bound so let the trait equal to the % LOWTRAIT boundchild(trait_site,parent_number1)=LOWTRAIT(trait_site); end else % No crossover occurs% Copy non-crossovered chromosomes into next generation% In this case we simply take one parent and make them% the child.child(:,parent_number1)=parent_chrom(:,parent_number1); end % Ends if CROSS_PROB... statement end % End the "if ELITISM..." statementend % End "for parent_number1=..." loop%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Mutate children.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Here, we mutate to a different trait% with a probability MUTAT_PROB. Notice% that this achieves a different, but similar% effect to the standard approach to mutation.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for pop_member= 1:POP_SIZE, if ELITISM ==1 & pop_member==bestmember % If elitism on, and % have the elite member child(:,pop_member)=child(:,pop_member); % Do not mutate % the elite member else for current_trait = 1:NUM_TRAITS, if MUTAT_PROB > rand % If true then mutate % To mutate simply change the trait to any allowable % one on the search space (hence this is a "trait mutation" % rather than a "gene mutation" child(current_trait,pop_member)=... (rand-(1/2))*(HIGHTRAIT(current_trait)-LOWTRAIT(current_trait))+... (1/2)*(HIGHTRAIT(current_trait)+LOWTRAIT(current_trait)); end % End "if MUTAT_PROB > rand ... end end % End "if ELITISM..." end % End for pop_member loop%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Create the next generation (this completes the main part of the GA)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% popcount=popcount+1; % Increment to the next generation trait(:,:,popcount)=child; % Create next generation (children % become parents) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Terminate the program when the best fitness has not changed% more than EPSILON over the last DELTA generations. It would also% make sense to use avefitness rather than bestfitness in this test.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if popcount > DELTA+1 & ... max(abs(bestfitness(popcount-DELTA:popcount-1)-... bestfitness(popcount-DELTA-1:popcount-2)))<=EPSILON break; end%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%end % End "for pop_count=..." loop - the main loop.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Next, provide some plots of the results of the simulation.% These are for the example function that we seek to maximize; however% for other applications it is not difficult to modify this code% to show plots that are informative for the application at hand.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%t=1:popcount-1; % For use in plottingx=0:31/100:30; % For our function the range of values we are consideringy=x;% Compute the function that we are trying to find the maximum of.for jj=1:length(x) for ii=1:length(y) z(ii,jj)=... +5*exp(-0.1*((x(jj)-15)^2+(y(ii)-20)^2))... -2*exp(-0.08*((x(jj)-20)^2+(y(ii)-15)^2))... +3*exp(-0.08*((x(jj)-25)^2+(y(ii)-10)^2))... +2*exp(-0.1*((x(jj)-10)^2+(y(ii)-10)^2))... -2*exp(-0.5*((x(jj)-5)^2+(y(ii)-10)^2))... -4*exp(-0.1*((x(jj)-15)^2+(y(ii)-5)^2))... -2*exp(-0.5*((x(jj)-8)^2+(y(ii)-25)^2))... -2*exp(-0.5*((x(jj)-21)^2+(y(ii)-25)^2))... +2*exp(-0.5*((x(jj)-25)^2+(y(ii)-16)^2))... +2*exp(-0.5*((x(jj)-5)^2+(y(ii)-14)^2)); endend% First, show the actual function to be maximized and its contour mapfigure(1)clfsurf(x,y,z);colormap(jet)% Use next line for generating plots to put in black and white documents.colormap(gray);xlabel('x');ylabel('y');zlabel('z');title('Fitness function');figure(2) clfcontour(x,y,z,25)colormap(jet)% Use next line for generating plots to put in black and white documents.colormap(gray);xlabel('x');ylabel('y');zlabel('z');title('Fitness function (contour map)');hold on% Next, add on the evolution of the other population% members over time.for pop_member = 1:POP_SIZE xx=squeeze(trait(1,pop_member,:)); yy=squeeze(trait(2,pop_member,:)); traitplot=plot(xx,yy,'k.'); set(traitplot,'MarkerSize',6);end% Then, add on the evolution of the best individual over % time that the GA finds.btraitplot=plot(bestindividual(1,:),bestindividual(2,:),'ko');set(btraitplot,'MarkerSize',4)hold off% Next, plot some data on the operation of the GAfigure (3)clfsubplot(211)plot(t,bestfitness,'k--',t,avefitness,'k-',t,worstfitness,'k-.')xlabel('Generation')ylabel('Best, average, and worst fitness')title('Best and worst fitness vs. generation')subplot(212)plot(t,bestindividual(1,:),'k-',t,bestindividual(2,:),'k--')xlabel('Generation')ylabel('Best individuals')title('Best individuals vs. generation')%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% End of program%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -