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

076bct041 AI Lab5

The document describes the implementation of a genetic algorithm to solve an optimization problem. It discusses the key steps: initializing a random population, calculating fitness values, selecting fit individuals for reproduction, applying crossover and mutation to produce new individuals, and repeating until a termination criterion is met. The problem involves optimizing chromosomes represented as 8-digit strings by maximizing a fitness function. The algorithm runs for 1000 generations, tracking total fitness at each generation and plotting the results. It finds solutions exceeding a fitness of 200, demonstrating genetic algorithms' ability to solve complex optimization problems.

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)
23 views5 pages

076bct041 AI Lab5

The document describes the implementation of a genetic algorithm to solve an optimization problem. It discusses the key steps: initializing a random population, calculating fitness values, selecting fit individuals for reproduction, applying crossover and mutation to produce new individuals, and repeating until a termination criterion is met. The problem involves optimizing chromosomes represented as 8-digit strings by maximizing a fitness function. The algorithm runs for 1000 generations, tracking total fitness at each generation and plotting the results. It finds solutions exceeding a fitness of 200, demonstrating genetic algorithms' ability to solve complex optimization problems.

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
You are on page 1/ 5

TRIBHUVAN UNIVERSITY

INSTITUTE OF ENGINEERING
PULCHOWK CAMPUS
Lab - 5
Artificial Intelligence

Genetic Algorithm
Implementation

Submitted By: Submitted To


Name: Nishant Luitel Department of Electronics
Roll No: 076BCT041 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 = 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:]

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 matplotlib.pyplot as plt


import seaborn as sns
%matplotlib inline
x = list(range(0, total_generation))
sns.lineplot(y = total_value_list, x = x)
idx = total_value_list.index(max(total_value_list))
plt.axvline(x=x[idx], color='red', linestyle='--')
plt.axhline(y=max(total_value_list), color='green', linestyle='--')
plt.xlabel("Generation")
plt.ylabel("Total Value of the generation")
plt.show()
Conclusion
After reviewing the use of genetic algorithms in this lab report, it can be inferred that they are a potent
method of optimization for intricate problems. The four stages of initialization, selection,
reproduction, and termination were applied repeatedly to develop and enhance a pool of possible
solutions until an acceptable solution was obtained. A significant benefit of genetic algorithms is their
capability to investigate a vast range of solutions, potentially resulting in more optimal solutions than
other optimization methods. Moreover, genetic algorithms are simple to implement and adaptable to a
diverse range of problems

You might also like