Вы находитесь на странице: 1из 7

ALGORITMO GENETICO Hello World! El algoritmo gentico Hello World!

bsicamente es un algoritmo que toma una poblacin inicial que va evolucionando hasta llegar a la frase Hello World! usando todos los pasos que conlleva la aplicacin de un algoritmo gentico a continuacin el algoritmo:
#pragma warning(disable:4786) #include #include #include #include #include #include #define #define #define #define #define #define <iostream> <vector> <string> <algorithm> <time.h> <math.h> GA_POPSIZE GA_MAXITER GA_ELITRATE GA_MUTATIONRATE GA_MUTATION GA_TARGET // disable debug warning // for cout etc. // for vector class // for string class // for sort algorithm // for random seed // for abs() 2048 // ga population size 16384 // maximum iterations 0.10f // elitism rate 0.25f // mutation rate RAND_MAX * GA_MUTATIONRATE std::string("Hello world!") // polluting global

using namespace std; namespace, but hey... struct ga_struct { string str; string unsigned int fitness; };

// the // its fitness

typedef vector<ga_struct> ga_vector;// for brevity void init_population(ga_vector &population, ga_vector &buffer ) { int tsize = GA_TARGET.size(); for (int i=0; i<GA_POPSIZE; i++) { ga_struct citizen; citizen.fitness = 0; citizen.str.erase(); for (int j=0; j<tsize; j++) citizen.str += (rand() % 90) + 32; population.push_back(citizen); } buffer.resize(GA_POPSIZE); } void calc_fitness(ga_vector &population)

{ string target = GA_TARGET; int tsize = target.size(); unsigned int fitness; for (int i=0; i<GA_POPSIZE; i++) { fitness = 0; for (int j=0; j<tsize; j++) { fitness += abs(int(population[i].str[j] target[j])); } population[i].fitness = fitness; } } bool fitness_sort(ga_struct x, ga_struct y) { return (x.fitness < y.fitness); } inline void sort_by_fitness(ga_vector &population) { sort(population.begin(), population.end(), fitness_sort); } void elitism(ga_vector &population, ga_vector &buffer, int esize ) { for (int i=0; i<esize; i++) { buffer[i].str = population[i].str; buffer[i].fitness = population[i].fitness; } } void mutate(ga_struct &member) { int tsize = GA_TARGET.size(); int ipos = rand() % tsize; int delta = (rand() % 90) + 32; member.str[ipos] = ((member.str[ipos] + delta) % 122); } void mate(ga_vector &population, ga_vector &buffer) { int esize = GA_POPSIZE * GA_ELITRATE; int tsize = GA_TARGET.size(), spos, i1, i2; elitism(population, buffer, esize); // Mate the rest for (int i=esize; i<GA_POPSIZE; i++) { i1 = rand() % (GA_POPSIZE / 2); i2 = rand() % (GA_POPSIZE / 2); spos = rand() % tsize; buffer[i].str = population[i1].str.substr(0, spos) + population[i2].str.substr(spos, esize - spos);

if (rand() < GA_MUTATION) mutate(buffer[i]); } } inline void print_best(ga_vector &gav) { cout << "Best: " << gav[0].str << " (" << gav[0].fitness << ")" << endl; } inline void swap(ga_vector *&population, ga_vector *&buffer) { ga_vector *temp = population; population = buffer; buffer = temp; } int main() { srand(unsigned(time(NULL))); ga_vector pop_alpha, pop_beta; ga_vector *population, *buffer; init_population(pop_alpha, pop_beta); population = &pop_alpha; buffer = &pop_beta; for (int i=0; i<GA_MAXITER; i++) { calc_fitness(*population); // calculate fitness sort_by_fitness(*population); // sort them print_best(*population); // print the best one if ((*population)[0].fitness == 0) break; mate(*population, *buffer); population together swap(population, buffer); } return 0; } // mate the // swap buffers

Los pasos que sigue este algoritmo son: 1. INICIALIZACION: en esta etapa el algoritmo genera un conjunto de elementos que representan las posibles soluciones al problema cada elemento es una variable de tipo struct de igual longitud que la cadena objetivo (Hello World!) y un entero que representa que tanto se ajusta a dicha cadena la funcin adems inicializa una poblacin adicional que seria la siguiente generacin
struct ga_struct { string str; string

// the

unsigned int fitness; };

// its fitness

typedef vector<ga_struct> ga_vector;// for brevity void init_population(ga_vector &population, ga_vector &buffer ) { int tsize = GA_TARGET.size(); for (int i=0; i<GA_POPSIZE; i++) { ga_struct citizen; citizen.fitness = 0; citizen.str.erase(); for (int j=0; j<tsize; j++) citizen.str += (rand() % 90) + 32; population.push_back(citizen); } buffer.resize(GA_POPSIZE); }

2. EVALUACION: en esta etapa luego de inicializar la poblacin se procede a aplicarle a cada miembro de la poblacin la funcin de aptitud que garantiza que se ha llegado ya a la frase esperada de acuerdo a un criterio de ajuste que determina que tan cerca esta dicho miembro de la poblacin de la frase objetivo dndole al final un valor de tipo entero que representa el ajuste que entre menor sea mejor se ajusta el miembro por lo tanto si el valor de ajuste es igual a 0 habremos llegado a la frase objetivo
void calc_fitness(ga_vector &population) { string target = GA_TARGET; int tsize = target.size(); unsigned int fitness; for (int i=0; i<GA_POPSIZE; i++) { fitness = 0; for (int j=0; j<tsize; j++) { fitness += abs(int(population[i].str[j] target[j])); } population[i].fitness = fitness; } }

3. SELECCIN Y REPRODUCCION: el algoritmo procede a ordenar para posteriormente seleccionar los mejores miembros de la poblacin actual para a partir de ellos generar una nueva poblacin descendiente y menor que la poblacin inicial cabe resaltar que en esta funcin tambin se hacen llamados a la funcin de mutacin
void elitism(ga_vector &population, ga_vector &buffer, int esize ) { for (int i=0; i<esize; i++) { buffer[i].str = population[i].str; buffer[i].fitness = population[i].fitness; } }

void mate(ga_vector &population, ga_vector &buffer) { int esize = GA_POPSIZE * GA_ELITRATE; int tsize = GA_TARGET.size(), spos, i1, i2; elitism(population, buffer, esize); // Mate the rest for (int i=esize; i<GA_POPSIZE; i++) { i1 = rand() % (GA_POPSIZE / 2); i2 = rand() % (GA_POPSIZE / 2); spos = rand() % tsize; buffer[i].str = population[i1].str.substr(0, spos) + population[i2].str.substr(spos, esize - spos); if (rand() < GA_MUTATION) mutate(buffer[i]); } }

4. MUTACION: el algoritmo toma los miembros de la poblacin actual y los altera de tal manera que se cubran soluciones inicialmente no tomadas en la poblacin anterior esto lo hace con la funcin mutate y a partir de un grado de mutacin (GA_MUTATIONRATE 0.25f)
void mutate(ga_struct &member) { int tsize = GA_TARGET.size(); int ipos = rand() % tsize; int delta = (rand() % 90) + 32; member.str[ipos] = ((member.str[ipos] + delta) % 122);

5. REEMPLAZO: en esta etapa lo que se hace es cambiar la poblacin resultante luego de aplicar los operadores genticos con la poblacin actual de tal manera que esta se convierta en la nueva poblacin
inline void swap(ga_vector *&population, ga_vector *&buffer) { ga_vector *temp = population; population = buffer; buffer = temp; }

Y finalmente encontramos la funcin principal del algoritmo donde se hacen los llamados a las funciones anteriormente mencionadas adems de imprimir el mejor resultado de cada iteracin del algoritmo
inline void print_best(ga_vector &gav) { cout << "Best: " << gav[0].str << " (" << gav[0].fitness << ")" << endl; } int main() { srand(unsigned(time(NULL))); ga_vector pop_alpha, pop_beta; ga_vector *population, *buffer; init_population(pop_alpha, pop_beta); population = &pop_alpha; buffer = &pop_beta; for (int i=0; i<GA_MAXITER; i++) { calc_fitness(*population); // calculate fitness sort_by_fitness(*population); // sort them print_best(*population); // print the best one if ((*population)[0].fitness == 0) break; mate(*population, *buffer); population together swap(population, buffer); } return 0; } // mate the // swap buffers

Вам также может понравиться