Problem in Maximization using genetic algorithm

39 Views Asked by At

I was trying to maximize the function f(x) = x(8-x), x = [0,8] using this code

import random

def generateChromosome():
    return format(random.getrandbits(8), '0b')

def generatePopulation(size):
    return [str(generateChromosome()) for _ in range (size)]

def fitness(x):
    return x*(8-x)

def decode(x):
    x_int = int(x, 2)
    return 8*x_int/255

def selection(population):
    selected_population = []
    fitness_population = [fitness(decode(chromosome)) for chromosome in population]
    for i in range(len(population) - 1):
        if fitness_population[i] > fitness_population[i+1]:
            selected_population.append(population[i])
        else:
            selected_population.append(population[i+1])

    return selected_population

def crossover(chromosome1, chromosome2):
    new_chromosome = chromosome1[:4] + chromosome2[4:]
    return new_chromosome

def mutation(chromosome):
    random_index = random.randint(1,5)
    try:
        if chromosome[random_index] == '1':
            new_chromosome = chromosome[:random_index] + '0' + chromosome[random_index + 1:]
        else:
            new_chromosome = chromosome[:random_index] + '1' + chromosome[random_index + 1:]
    except:
        new_chromosome = str(generateChromosome())

    return new_chromosome

def offspingGenerator(population):
    offspring = population[:2]

    for i in range(0, len(population) - 1, 2):
        if random.random() <= 0.8:
            offspring.append(crossover(population[i], population[i+1]))
            offspring.append(crossover(population[i+1], population[i]))

    for chromosome in population:
        if random.random() <= 0.05:
            offspring.append(mutation(chromosome))

    while(len(offspring) < 4):
        offspring.append(str(generateChromosome()))

    return offspring

initial_population = generatePopulation(4)
threshold = 15.999

for i in range(10000):
    mating_pool = selection(initial_population)
    temp_population = offspingGenerator(mating_pool)
    temp_ranked_population = [(fitness(decode(chromosome)), chromosome) for chromosome in temp_population]
    temp_ranked_population.sort(reverse = True)
    new_population = [chromosome[1] for chromosome in temp_ranked_population][:4]

    print(f"Generation {i} best solution ---> {new_population[0]}")

    if fitness(decode(new_population[0])) >= threshold:
        print(f"The best solution is ---> {new_population[0]} and original value {decode(new_population[0])}")
        break

    initial_population = new_population

generateChromosome(): This function generates a random binary chromosome of length 8 (e.g., '01011010').

generatePopulation(size): This function generates a population of binary chromosomes of the specified size.

fitness(x): This function calculates the fitness of a chromosome using a simple quadratic fitness function: x*(8-x).

decode(x): This function decodes a binary chromosome into its decimal representation by interpreting it as an 8-bit binary fraction and converting it to the decimal range [0, 8].

selection(population): This function performs a selection process.

crossover(chromosome1, chromosome2): This function performs a single-point crossover between two chromosomes.

mutation(chromosome): This function performs bit-flip mutation on a chromosome.

offspingGenerator(population): This function generates offspring for the next generation by applying crossover and mutation to the selected individuals from the previous generation.

The goal of the algorithm is to find a chromosome whose fitness value (using the fitness(decode()) function) is greater than or equal to the threshold value (set to 15.999). When the best solution in a generation surpasses this threshold, the algorithm will terminate and print the solution.

The problem is in my solution space I'm getting binary string of 7bits where it should be of 8bits. Help me finding the issue.

0

There are 0 best solutions below