Language Reference |
sets up the problem encoding for a genetic algorithm optimization problem
The following example demonstrates the use of several genetic algorithm subroutines.
/* Use a genetic algorithm to explore the solution space for the "traveling salesman" problem. First, define the objective function to minimize: Compute the sum of distances between sequence of cities */ start EvalFitness( pop ) global ( dist ); fitness = j( nrow(pop),1 ); do i = 1 to nrow(pop); city1 = pop[i,1]; city2 = pop[i,ncol(pop)]; fitness[i] = dist[ city1, city2 ]; do j = 1 to ncol(pop)-1; city1 = pop[i,j]; city2 = pop[i,j+1]; fitness[i] = fitness[i] + dist[city1,city2]; end; end; return ( fitness ); finish; /* Set up parameters for the genetic algorithm */ mutationProb = 0.15; /* prob that a child will be mutated */ numElite = 2; /* copy this many to next generation */ numCities = 15; /* number of cities to visit */ numGenerations = 100; /* number of generations to evolve */ seed = 54321; /* random number seed */ /* fix population size; generate random locations for cities */ popSize = max(30,2*numCities); locations = uniform( j(numCities,2,seed) ); /* calculate distances between cities one time */ dist = j( numCities, numCities, 0 ); do i = 1 to numCities; do j = 1 to i-1; v = locations[i,]-locations[j,]; dist[i,j] = sqrt( v[##] ); dist[j,i] = dist[i,j]; end; end; /* run the genetic algorithm */ id = gasetup( 3, numCities, seed); call gasetobj(id, 0, "EvalFitness" ); call gasetcro(id, 1.0, 6); call gasetmut(id, mutationProb, 3); call gasetsel(id, numElite, 1, 0.95); call gainit(id, popSize ); do i = 1 to numGenerations; if mod(i,20)=0 then do; call gagetval( value, id, 1 ); print "Iteration:" i "Top value:" value; end; call garegen(id); end; /* report final sequence for cities */ call gagetmem(mem, value, id, 1); print mem, value; call gaend(id);
Copyright © 2009 by SAS Institute Inc., Cary, NC, USA. All rights reserved.