0% found this document useful (0 votes)
10 views

Genetic

py

Uploaded by

ahmedabdelmoatyy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Genetic

py

Uploaded by

ahmedabdelmoatyy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Genetic Algorithm Assignment

Every step of the solution is written as a single function to increase code readability
Necessary Imports
import numpy as np

calculate_fitness(chromosome)

Calculates the fitness of a chromosome by counting the number of 1s that have 0s on


both adjacent sides.
# Fitness function to calculate the fitness of an array
def calculate_fitness(chromosome):
fitness = 0
for i in range(1, len(chromosome) - 1):
if chromosome[i] == 1 and chromosome[i - 1] == 0 and
chromosome[i + 1] == 0:
fitness += 1
return fitness

single_point_crossover(parent1, parent2)

• Performs a single-point crossover between two parent chromosomes,


producing two children by combining sections of each parent.
# Function to perform single-point crossover between two parents
def single_point_crossover(parent1, parent2):
crossover_point = np.random.randint(1, len(parent1) - 1)
child1 = np.concatenate((parent1[:crossover_point],
parent2[crossover_point:]))
child2 = np.concatenate((parent2[:crossover_point],
parent1[crossover_point:]))
return child1, child2

mutate(chromosome)

• Randomly selects one bit in an chromosome and flips its value (from 0 to 1 or
1 to 0), introducing variability in the population.
# Function to randomly mutate one bit in an array
def mutate(chromosome):
bit_to_mutate = np.random.randint(len(chromosome))
chromosome[bit_to_mutate] = 1 if chromosome[bit_to_mutate] == 0
else 0
generate_next_generation(current_generation)

• Generates the next generation by selecting the two fittest chromosomes,


performing crossover to create children, and applying mutation to one
randomly selected chromosome.
def generate_next_generation(current_generation):
fitness_values = [calculate_fitness(chromosome) for chromosome in
current_generation]
sorted_chromosomes = [arr for arr in sorted(current_generation,
key=calculate_fitness, reverse=True)]
parent1, parent2 = sorted_chromosomes[:2]
child1, child2 = single_point_crossover(parent1, parent2)
new_generation = [parent1, parent2, child1, child2]

# Mutate a random bit in a randomly chosen chromosome


chromosome_to_mutate = np.random.choice(len(new_generation))
mutate(new_generation[chromosome_to_mutate])

return new_generation

run_genetic_algorithm(num_iterations, initial_population_size=4,
array_length=9)

• Runs the genetic algorithm for a specified number of iterations, displaying


each generation and its fitness values. Returns the final generation after all
iterations.
def run_genetic_algorithm(num_iterations, initial_population_size=4,
array_length=9):

current_generation = [np.random.randint(0, 2, size=array_length)


for _ in range(initial_population_size)]

for iteration in range(num_iterations):


print(f"Iteration {iteration + 1}")
for i, arr in enumerate(current_generation):
print(f"Array {i + 1}: {arr}, Fitness:
{calculate_fitness(arr)}")

current_generation =
generate_next_generation(current_generation)
print("\n")

return current_generation
Putting All Together And Solving The Problem
num_iterations = 5
final_generation = run_genetic_algorithm(num_iterations)

print("Final generation:")
for i, chromosome in enumerate(final_generation):
print(f"Array {i + 1}: {chromosome}, Fitness:
{calculate_fitness(chromosome)}")

Iteration 1
Array 1: [1 1 0 1 0 0 0 1 1], Fitness: 1
Array 2: [1 1 0 1 0 1 1 1 0], Fitness: 1
Array 3: [0 1 0 1 1 0 0 1 1], Fitness: 1
Array 4: [0 1 1 0 0 0 1 1 1], Fitness: 0

Iteration 2
Array 1: [1 1 0 1 0 0 0 1 1], Fitness: 1
Array 2: [1 1 0 0 0 1 1 1 0], Fitness: 0
Array 3: [1 1 0 1 0 1 1 1 0], Fitness: 1
Array 4: [1 1 0 1 0 0 0 1 1], Fitness: 1

Iteration 3
Array 1: [1 1 0 1 0 1 0 1 1], Fitness: 2
Array 2: [1 1 0 1 0 1 1 1 0], Fitness: 1
Array 3: [1 1 0 1 0 1 1 1 0], Fitness: 1
Array 4: [1 1 0 1 0 0 0 1 1], Fitness: 1

Iteration 4
Array 1: [1 1 0 1 0 1 0 1 1], Fitness: 2
Array 2: [1 1 0 1 0 1 1 1 0], Fitness: 1
Array 3: [1 1 0 1 0 1 1 1 0], Fitness: 1
Array 4: [1 1 0 1 0 1 1 1 1], Fitness: 1

Iteration 5
Array 1: [1 1 0 1 0 1 0 1 1], Fitness: 2
Array 2: [1 1 0 1 0 1 1 1 0], Fitness: 1
Array 3: [1 1 1 1 0 1 1 1 0], Fitness: 0
Array 4: [1 1 0 1 0 1 0 1 1], Fitness: 2

Final generation:
Array 1: [1 1 0 1 0 1 0 1 1], Fitness: 2
Array 2: [1 1 0 1 0 1 0 1 1], Fitness: 2
Array 3: [1 1 0 1 0 1 0 1 1], Fitness: 2
Array 4: [1 1 0 1 1 1 0 1 1], Fitness: 0

You might also like