результаты генерации генетических алгоритмов все еще слишком далеки от цели пригодности - PullRequest
0 голосов
/ 05 марта 2019

я пытаюсь создать генетический алгоритм с кодом, подобным этому

import random
from random import randint

POPULATION_SIZE = 10
NUMB_OF_ELITE_CHROMOSOMES = 4
TARGET_CHROMOSOME = [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3]
TOURNAMENT_SELECTION_SIZE = 0.00001
MUTATION_RATE = 0.3

создать хромосому класса

class Chromosome:
    def __init__(self):
        self._genes = []
        self._fitness = 0
        i = 0
        while i < TARGET_CHROMOSOME.__len__():
            a = randint(1, 4)
            self._genes.append(a)
            i += 1

    def get_genes(self):
        return self._genes

    def get_fitness(self):
        self._fitness = 0
        for i in range(self._genes.__len__()):
            if self._genes[i] == TARGET_CHROMOSOME[i]:
                self._fitness +=1
        return self._fitness

создать популяцию классов

class Population:
    def __init__(self, size):
        self._chromosomes = []
        i = 0
        while i < size:
            self._chromosomes.append(Chromosome())
            i += 1

    def get_chromosomes(self): return self._chromosomes

класс GeneticAlgorithm

class GeneticAlgorithm:
    @staticmethod
    def envolve(pop):
        return GeneticAlgorithm._mutate_population(GeneticAlgorithm._crossover_population(pop))

    @staticmethod
    def _crossover_population(pop):
        crossover_pop = Population(0)
        for i in range(NUMB_OF_ELITE_CHROMOSOMES):
            crossover_pop.get_chromosomes().append(pop.get_chromosomes()[i])

        i = NUMB_OF_ELITE_CHROMOSOMES
        while i < POPULATION_SIZE:
            chromosome1 = GeneticAlgorithm._select_tournament_population(pop).get_chromosomes()[0]
            chromosome2 = GeneticAlgorithm._select_tournament_population(pop).get_chromosomes()[0]
            crossover_pop.get_chromosomes().append(GeneticAlgorithm._crossover_chromosomes(chromosome1,chromosome2))
            i += 1
        return crossover_pop

    @staticmethod
    def _mutate_population(pop):
        return pop

    @staticmethod
    def _crossover_chromosomes(chromosome1, chromosome2):
        crossover_chrom = Chromosome()
        return crossover_chrom

    @staticmethod
    def _mutate_chromosome(chromosome):
        for i in range(TARGET_CHROMOSOME.__len__()):
            if random.random() < 0.02:
                a = randint(1, 4)
                chromosome.get_genes()[i] = a



    @staticmethod
    def _select_tournament_population(pop):
        tournament_pop = Population(0)
        i = 0
        while i < TOURNAMENT_SELECTION_SIZE:
            tournament_pop.get_chromosomes().append(pop.get_chromosomes()[random.randrange(0, POPULATION_SIZE)])
            i += 1
        tournament_pop.get_chromosomes().sort(key=lambda x: x.get_fitness(), reverse=True)
        return tournament_pop

Поколение печати

def _print_population(pop, gen_number):
    print("\n---------------------")
    print("Generation #", gen_number, "| Fittest chromosome fitness:", pop.get_chromosomes()[0].get_fitness())
    i = 0

    for x in pop.get_chromosomes():
        print("Chromosome #", i, " :", x.get_genes(), "| Fitness: ", x.get_fitness())
        i += 1
population = Population(POPULATION_SIZE)
population.get_chromosomes().sort(key=lambda x: x.get_fitness(), reverse = True)
_print_population(population,0)
generation_number = 1

while population.get_chromosomes()[0].get_fitness() < TARGET_CHROMOSOME.__len__():
    population = GeneticAlgorithm.envolve(population)
    population.get_chromosomes().sort(key=lambda x: x.get_fitness(), reverse = True)
    _print_population(population, generation_number)
    generation_number += 1

При запуске на консоли я получаю генерацию, подобную

Generation # 18274 | Fittest chromosome fitness: 19
Chromosome # 0  : [3, 2, 3, 3, 2, 3, 2, 4, 3, 4, 3, 4, 4, 1, 3, 2, 1, 2, 1, 4, 3, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3] | Fitness:  19
Chromosome # 1  : [1, 2, 3, 4, 1, 4, 2, 2, 1, 1, 3, 1, 1, 1, 3, 4, 1, 2, 1, 4, 4, 1, 3, 3, 1, 4, 3, 3, 1, 2, 4] | Fitness:  18
Chromosome # 2  : [1, 3, 1, 4, 1, 4, 3, 4, 1, 2, 2, 4, 2, 2, 3, 4, 1, 1, 3, 3, 4, 1, 1, 3, 1, 2, 4, 2, 1, 2, 3] | Fitness:  18
Chromosome # 3  : [3, 2, 3, 4, 4, 3, 2, 4, 1, 1, 1, 3, 1, 2, 3, 4, 1, 3, 3, 4, 3, 2, 4, 3, 1, 2, 3, 1, 1, 2, 4] | Fitness:  18
Chromosome # 4  : [3, 1, 3, 4, 1, 3, 2, 1, 3, 1, 3, 4, 4, 3, 2, 4, 2, 2, 2, 2, 4, 1, 3, 2, 1, 1, 1, 4, 1, 2, 1] | Fitness:  12
Chromosome # 5  : [2, 2, 4, 4, 1, 4, 3, 1, 4, 2, 2, 3, 2, 2, 2, 1, 3, 4, 1, 1, 4, 2, 2, 4, 4, 2, 4, 3, 3, 4, 3] | Fitness:  10
Chromosome # 6  : [2, 4, 2, 3, 4, 4, 4, 2, 1, 2, 3, 1, 4, 3, 1, 2, 1, 2, 4, 4, 4, 2, 4, 2, 3, 3, 3, 2, 3, 4, 1] | Fitness:  8
Chromosome # 7  : [1, 2, 4, 2, 1, 2, 3, 1, 2, 4, 2, 2, 3, 4, 4, 3, 1, 4, 2, 1, 3, 4, 4, 1, 3, 1, 4, 1, 1, 1, 2] | Fitness:  7
Chromosome # 8  : [2, 3, 1, 2, 4, 2, 4, 2, 2, 2, 1, 1, 4, 4, 2, 3, 3, 2, 1, 1, 2, 1, 4, 1, 4, 1, 2, 4, 3, 1, 1] | Fitness:  4
Chromosome # 9  : [2, 1, 4, 2, 1, 1, 4, 2, 1, 3, 4, 4, 1, 3, 1, 2, 3, 3, 2, 2, 3, 1, 1, 3, 4, 1, 2, 1, 2, 3, 1] | Fitness:  4

Как выполнить пользовательское изменение или создать случайный массив для получения результатов с помощью

Fittest chromosome fitness: 31

на данный момент у меня сгенерировано более 100000 поколений, но максимальная хромосома максимум на 21.

Спасибо за ваши ответы

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...