Genetic Algorithm AI ML
Genetic Algorithm AI ML
Subject: AI/ML
Initialization
Fitness assignment
The fitness function helps in establishing the fitness of all individuals
in the population. It assigns a fitness score to every individual, which
further determines the probability of being chosen for reproduction.
The higher the fitness score, the higher the chances of being chosen
for reproduction.
Selection
The main objective of this phase is to establish the region with high
chances of generating the best solution to the problem (better than
the previous generation). The genetic algorithm uses the fitness
proportionate selection technique to ensure that useful solutions are
used for recombination.
Reproduction
Replacement
Termination
Application areas
Genetic algorithms are applied in the following fields:
Example
Code for Finding the value of x, y, z where 6*x^3+9*y^2+90*Z=25
import random
def foo(x,y,z):
return 6*x**3 + 9*y**2 + 90*z - 25
def fitness(x,y,z):
ans = foo(x,y,z)
if ans == 0:
return 9999999
else:
return(1/ans)
solutions = []
for s in range(1000):
solutions.append((random.uniform(0,10000),random.uniform(0,10000),random.u
niform(0,10000)))
for i in range(10000):
ranked_solutions= []
for s in solutions:
ranked_solutions.append( ( fitness(s[0],s[1],s[2]),s ) )
ranked_solutions.sort()
ranked_solutions.reverse()
print(f"=== gen {i} best solutions ===")
print(ranked_solutions[0])
newgen = []
solutions = newgen
if ranked_solutions[0][0] > 999:
break
best_solutions = ranked_solutions[:100]
elements = []
for s in best_solutions:
elements.append(s[1][0])
elements.append(s[1][1])
elements.append(s[1][2])
for _ in range(1000):
e1 = random.choice(elements) * random.uniform(0.99,1.01)
e2 = random.choice(elements) * random.uniform(0.99,1.01)
e3 = random.choice(elements) * random.uniform(0.99,1.01)
newgen.append((e1,e2,e3))
Conclusion
These algorithms are important because they are efficient and fast.