076bct041 AI Lab5
076bct041 AI Lab5
INSTITUTE OF ENGINEERING
PULCHOWK CAMPUS
Lab - 5
Artificial Intelligence
Genetic Algorithm
Implementation
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.
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 mutation(chromosome):
"""perform two point mutation"""
index = random.randint(0, 6)
replaced_number1 = random.randint(0, 9)
replaced_number2 = random.randint(0, 9)
return chromosome[0:index] + str(replaced_number1)
+ str(replaced_number2) + chromosome[index + 2:]