You are on page 1of 5

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 = 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
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.

You might also like