0% found this document useful (0 votes)
19 views5 pages

Genetic Algorithm Implementation Overview

Genetic algorithms are optimization techniques that use principles of natural selection and genetics. They initialize a population of random solutions, select the fittest for reproduction, and apply genetic operators like crossover and mutation to generate new solutions over multiple iterations until a stopping criteria is met. This document implements a genetic algorithm to optimize a problem with 8-digit chromosomes, calculating fitness as a sum formula and using two-point crossover and mutation to evolve solutions over 1,000 generations. The algorithm successfully finds fitter solutions over time, demonstrated through plotting the increasing total fitness values.

Uploaded by

Nishant Luitel
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)
19 views5 pages

Genetic Algorithm Implementation Overview

Genetic algorithms are optimization techniques that use principles of natural selection and genetics. They initialize a population of random solutions, select the fittest for reproduction, and apply genetic operators like crossover and mutation to generate new solutions over multiple iterations until a stopping criteria is met. This document implements a genetic algorithm to optimize a problem with 8-digit chromosomes, calculating fitness as a sum formula and using two-point crossover and mutation to evolve solutions over 1,000 generations. The algorithm successfully finds fitter solutions over time, demonstrated through plotting the increasing total fitness values.

Uploaded by

Nishant Luitel
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

TRIBHUVAN UNIVERSITY

INSTITUTE OF ENGINEERING
PULCHOWK CAMPUS

Lab - 5
Artificial Intelligence

Genetic Algorithm
Implementation

Submitted By: Submitted To


Name: Nirajan Bekoju Department of Electronics
Roll No: 076BCT039 and Computer Engineering
Group: B
Genetic Algorithm
Genetic algorithm is a computational method based on the principles of natural
selection and genetic inheritance that is used to optimize complex problems. It
is an iterative method that starts with a population of candidate solutions and
uses a selection process to determine which solutions are the most fit, and then
applies genetic operators such as mutation and crossover to generate new
candidate solutions. The process continues until a satisfactory solution is found
or a stopping criterion is met.

There are typically four main phases in a genetic algorithm:

Initialization: The first step is to create an initial population of candidate


solutions randomly. The solutions are typically represented as a string of binary
digits, where each digit represents a specific parameter of the problem being
solved. The size of the population is determined by the problem being solved
and the available computational resources.

Selection: The selection process is used to determine which solutions are the
most fit and should be used to create the next generation of candidate solutions.
This process is based on the principle of natural selection, where individuals
with the best fitness have a higher chance of being selected for reproduction.
There are several methods for selection, such as tournament selection, roulette
wheel selection, and rank-based selection.

Reproduction: Once the selection process is complete, the next step is to create
new candidate solutions through reproduction. This is done by applying genetic
operators such as mutation and crossover to the selected individuals. Mutation
involves randomly changing one or more digits in the binary string, while
crossover involves combining two selected individuals to create a new
individual that inherits traits from both parents.

Termination: The final phase is termination, which occurs when a satisfactory


solution is found or a stopping criterion is met. The stopping criterion is
typically based on the number of generations or the amount of time that has
elapsed. Once termination occurs, the best solution found is returned as the
output of the algorithm.
In summary, genetic algorithms are a powerful optimization technique that uses
principles of natural selection and genetic inheritance to solve complex
problems. The four phases of initialization, selection, reproduction, and
termination are used iteratively to create and refine a population of candidate
solutions until a satisfactory solution is found.

Problem : Suppose a genetic algorithm uses chromosomes of form x =


abcdefgh with a fixed length of eight genes. Each gene can have any digits
between 0 and 9. Let the fitness of individual x be calculated as : f(x) = (a +
b) - (c + d) + (e + f) - (g + h) and let the initial population be random
initialization in the for abcdefgh where the value of these alphabets can
range from 0 to 9 with repetition. Calculate the fittest individuals using two
point crossover at points b and f.

def getFittestChromosomes(chromosomes, value, top_k_value = 3):


zipped_list = list(zip(chromosomes, value))
zipped_list.sort(key = lambda x : x[1], reverse = True)
chromosomes, values = zip(*zipped_list)
return chromosomes, values

def fitnessValue(chromosome):
a, b, c, d, e, f, g, h = [int(digit) for digit in chromosome]
return (a + b) - (c + d) + (e + f) - (g + h)

def crossover(chromosomeA, chromosomeB):


"""perform two point crossover at point b and f i.e, 2 and 4"""
os1 = chromosomeA[0:2] + chromosomeB[2:6] + chromosomeA[6:]
os2 = chromosomeB[0:2] + chromosomeA[2:6] + chromosomeB[6:]
return os1, os2

def mutation(chromosome):
"""perform two point mutation"""
index = [Link](0, 6)
replaced_number1 = [Link](0, 9)
replaced_number2 = [Link](0, 9)
return chromosome[0:index] + str(replaced_number1) +
str(replaced_number2) + chromosome[index + 2:]

chromosomes = ["65413532", "12345423", "23921285", "41852094", "12349872"]


total_value = 0
total_value_list = []
total_generation = 1000
for i in range(total_generation):
value = [fitnessValue(chromosome) for chromosome in chromosomes]
total_value = sum(value)
total_value_list.append(total_value)
print(f"Generation {i} :: Total value : {total_value} {value}")
if total_value > 200:
break
chromosomes, value = getFittestChromosomes(chromosomes, value)
os1, os2 = crossover(chromosomes[0], chromosomes[1])
mutated_chromosome = mutation(chromosomes[2])
# next generation chromosomes
chromosomes = chromosomes[0], chromosomes[1], os1, os2,
mutated_chromosome

import [Link] as plt


import seaborn as sns
%matplotlib inline
x = list(range(0, total_generation))
[Link](y = total_value_list, x = x)
idx = total_value_list.index(max(total_value_list))
[Link](x=x[idx], color='red', linestyle='--')
[Link](y=max(total_value_list), color='green', linestyle='--')
[Link]("Generation")
[Link]("Total Value of the generation")
[Link]()
Conclusion
Based on the implementation of the genetic algorithm in this lab report, it can be
concluded that genetic algorithms are a powerful optimization technique that
can be used to solve complex problems. The four phases of initialization,
selection, reproduction, and termination were used iteratively to create and
refine a population of candidate solutions until a satisfactory solution was
found.

One advantage of genetic algorithms is that they are able to explore a wide
range of potential solutions to a problem, which can lead to finding better
solutions than other optimization techniques. Additionally, genetic algorithms
are relatively easy to implement and can be adapted to a wide range of
problems.

Common questions

Powered by AI

The fitness function in genetic algorithms acts as a measure of solution quality, influencing which individuals are selected for reproduction. Solutions with higher fitness scores are more likely to be selected, ensuring that favorable traits are passed on to subsequent generations. This drives the algorithm towards increasingly better solutions as it iteratively refines the population. By shaping the selection process around fitness scores, genetic algorithms are effectively guided towards identifying optimal solutions relative to the defined problem .

The fitness function f(x) = (a + b) - (c + d) + (e + f) - (g + h) evaluates the quality of a solution represented by the chromosome 'abcdefgh'. It guides the optimization process by assigning a fitness score to each solution, indicating its suitability for the problem at hand. Solutions with higher fitness scores are more likely to be selected for reproduction, thereby propagating favorable traits through the population and steering the genetic algorithm toward optimal solutions over generations .

Two-point crossover is performed by selecting two crossover points in the parent chromosomes and exchanging the segments between these points to create new offspring. This technique increases genetic diversity and aids in exploring the solution space. For example, with parent chromosomes '65413532' and '12345423' and crossover points between positions 2 and 4, the offspring would be '65215432' and '12344532' by swapping the middle segments .

Interpreting results from genetic algorithms can be challenging due to the stochastic nature of the search process and the complex interactions between genetic operators. Graphical tools, such as plotting fitness scores over generations, can provide insight into convergence behavior and the effectiveness of the algorithm in exploring the solution space. Visualizations help in identifying trends, understanding the impact of parameter settings, and assessing the algorithm's progress towards optimization, allowing for more informed decisions in tuning algorithm parameters for improved performance .

Crossover and mutation are complementary processes in genetic algorithms that balance exploration and exploitation. Crossover exploits the existing genetic material by combining it to form new solutions, thus focusing on refining and exploiting known good solutions. Mutation introduces randomness by altering solution components, thereby promoting exploration of the solution space to discover new potential solutions that may not arise from crossover alone. This balance is crucial as it allows genetic algorithms to navigate complex landscapes effectively, avoiding local optima through mutation while converging towards global optima through crossover .

Mutation introduces random changes to individual solutions in a population, which helps maintain genetic diversity and prevents premature convergence on local optima. By introducing variability, mutation allows the algorithm to explore new regions in the solution space that may not be accessed through crossover alone. In this context, mutation is crucial for adapting the population over generations and improving the chances of finding an optimal solution .

Termination criteria are vital in genetic algorithms to prevent unnecessary computation and to indicate when a satisfactory solution has been reached. Common criteria include a predetermined number of generations, reaching a fitness threshold, or lack of significant improvement over a set number of generations. Choosing appropriate termination criteria balances the need for computational efficiency with ensuring a quality solution is found, and is often based on the specific application's needs and computational resources available .

The four main phases of a genetic algorithm include Initialization, Selection, Reproduction, and Termination. Initialization involves creating an initial population of candidate solutions randomly. Selection is used to determine which solutions are most fit for reproducing the next generation. Reproduction applies genetic operators like mutation and crossover to selected individuals to create new solutions. Termination occurs when a satisfactory solution is found or a stopping criterion such as a set number of generations or elapsed time is met .

Fitter individuals are selected for reproduction in a genetic algorithm through a selection process that is based on the principle of natural selection. Individuals with better fitness scores have a higher chance of being selected for reproduction. Commonly used selection methods include tournament selection, where subsets of the population are chosen and the fittest individual in each subset is selected; roulette wheel selection, which involves selecting individuals based on their proportionate fitness; and rank-based selection, where individuals are ranked according to their fitness and selection is based on their rank .

Genetic algorithms can be adapted to a variety of optimization problems by customizing parameters such as chromosome representation, selection mechanisms, mutation rates, and stopping criteria. They hold several advantages over traditional optimization techniques, including their ability to explore a broad range of possible solutions, providing flexibility in the search process, and finding better solutions for complex problems with high-dimensional or non-linear solution spaces. Additionally, genetic algorithms do not require gradient information or continuity of the objective function, making them suitable for problems where these conditions are hard to meet .

You might also like