Soft Computing Lab Manual
Soft Computing Lab Manual
LAB MANUAL
FOR
B.E. COMPUTER (SEM – VIII)
LABORATORY PRACTICE VI
SUBJECT CODE:
410256
1
Course Outcomes:
CO1: Apply basic principles of elective subjects to problem solving and modeling
CO2: Use tools and techniques in the area of software development to build mini projects
CO3: Design and develop applications on subjects of their choice.
CO4: Generate and manage deployment, administration & security.
2
INDEX
Assignments: Group 1
1. Design an X-OR Gate with feed-forward neural network (also popularly known as a Multilayer
Perceptron) classifier.
3. Implement Union, Intersection, Complement and Difference operations on fuzzy sets. Also create
fuzzy relation by Cartesian product of any two fuzzy sets and perform max-min composition on any
two fuzzy relations.
4. Implement genetic algorithm for benchmark function (eg. Square, Rosenbrock function etc)
Initialize the population from the Standard Normal Distribution. Evaluate the fitness of all its
individuals. Then you will do multiple generation of a genetic algorithm. A generation consists of
applying selection, crossover, mutation, and replacement. Use: Tournament selection without
replacement with tournament size s, One point crossover with probability Pc, bit-flip mutation with
probability Pm, use full replacement strategy
Assignments: Group 2
(Any 1 Mini project from group 2 is mandatory)
1. Mini Project - Create a small hybrid system for solving a chosen problem by following the given
steps below.1. Explain on one page the main characteristics of hybrid systems.2. For the task
chosen from the list below, create a multi modular block diagram of a possible solution to the
problem.3. Choose appropriate techniques for solving each sub problem represented as a module.
What alternatives are there for each of them? 4. Create subsystems for solving each of the sub
problems. Compile the whole hybrid system.5. Make experiments with the hybrid system and
validate the results.
5. Mini Project: Spoken words recognition, for example, "on"/"off"; "yes''/"no"; "stop"/ "go."
Prepared By Approved By
Mr. R. B. Mandlik Dr. D. V. Patil
3
HOD
Group 1
Assignment No- 01 Date:___/___/______
Title:- Design an X-OR Gate with feed-forward neural network (also popularly known as a Multilayer
Perceptron) classifier.
Theory: Artificial Neural Network (ANN) is a computational model based on the biological neural networks
of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and
an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes
are connected with weighted edges (like synapses in biological brains) between two layers. Initially, with the
forward propagation function, the output is predicted. Then through back propagation, the weight and bias to
the nodes are updated to minimizing the error in prediction to attain the convergence of cost function in
determining the final output.
XOR logical function truth table for 2-bit binary variables, i.e., the input vector x: (x1, x2) and the
corresponding output y’.
x1 x2 y
Algorithm: 0 0 0
0 1 1
Step1: Import the required Python 1 0 1 libraries
Step2: Define Activation Function: 1 1 0 Sigmoid Function
Step3: Initialize neural network parameters (weights, bias) and define
model hyper parameters
(number of iterations, learning rate)
Step4: Forward Propagation
Step5: Backward Propagation
Step6: Update weight and bias parameters
Step7: Train the learning model
Step8: Plot Loss value vs Epoch
Step9: Test the model performance
Python Code:
# import Python Libraries
import numpy as np
from matplotlib import pyplot as plt
# Sigmoid Function
def sigmoid(z):
return 1 / (1 + np.exp(-z))
W2 = np.random.randn(outputFeatures, neuronsInHiddenLayers)
b1 = np.zeros((neuronsInHiddenLayers, 1))
4
b2 = np.zeros((outputFeatures, 1))
# Forward Propagation
def forwardPropagation(X, Y, parameters):
m = X.shape[1]
W1 = parameters["W1"]
W2 = parameters["W2"]
b1 = parameters["b1"]
b2 = parameters["b2"]
Z1 = np.dot(W1, X) + b1
A1 = sigmoid(Z1)
Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)
# Backward Propagation
def backwardPropagation(X, Y, cache):
m = X.shape[1]
(Z1, A1, W1, b1, Z2, A2, W2, b2) = cache
dZ2 = A2 - Y
dW2 = np.dot(dZ2, A1.T) / m
db2 = np.sum(dZ2, axis = 1, keepdims = True)
5
neuronsInHiddenLayers = 2 # number of hidden layer neurons (2)
inputFeatures = X.shape[0] # number of input features (2)
outputFeatures = Y.shape[0] # number of output features (1)
parameters = initializeParameters(inputFeatures, neuronsInHiddenLayers,
outputFeatures)
epoch = 100000
learningRate = 0.01
losses = np.zeros((epoch, 1))
for i in range(epoch):
losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters)
gradients = backwardPropagation(X, Y, cache)
parameters = updateParameters(parameters, gradients, learningRate)
# Testing
X = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # XOR input
cost, _, A2 = forwardPropagation(X, Y, parameters)
prediction = (A2 > 0.5) * 1.0
# print(A2)
print(prediction)
Output:
[[ 1. 0. 0. 1.]]
Outcomes:- Here, the model predicted output for each of the test inputs are exactly matched with the XOR
logic gate conventional output (y) according to the truth table and the cost function is also continuously
converging. Hence, it signifies that the Artificial Neural Network for the XOR logic gate is correctly
implemented.
6
Assignment No- 02 Date:___/___/______
Theory:
The Particle Swarm Optimizer employs a form of artificial intelligence to solve problems. It is particularly
good at finding solutions to functions that use multiple, continuously variable, values. This piece is
concerned with modifying the algorithm to tackle problems, such as the travelling salesman problem, that use
discrete, fixed values.
the basic idea is to move (fly) a group (swarm) of problem solving entities (particles) throughout the range of
possible solutions to a problem. This range is known as the problem space. The movement of particles within
the problem space has a random component but is mainly guided by three factors.
1. The present position of the particle.
2. The best position found by the particle, known as personal best or pBest.
3. The best position found in the swarm, known a global best or gBest.
The problem is to find the shortest distance that a salesman has to travel to visit every city on his route only
once and to arrive back at the place he started from. It’s not a totally academic exercise. A similar situation
arises in the design of wiring diagrams and printed circuit boards. It is a well-documented problem with
many standard example lists of cities. There have been lots of papers written on how to use a PSO to solve
this problem. The method used here is based on an article named, a combination of genetic algorithm and
particle swarm optimization method for solving traveling salesman problem.
In the diagram above, the section selected from the Current Route is 6,3,5. These cities are added to the new
route. The Personal Best Route has the section 1,3,2 selected. Selection 3 has already been added, so only
cities 1 and 2 are added. The Local Best Route has section 7,3 selected. City 3 has already been added so
only city 7 gets selected. Finally, the two cities that have not been selected, cities 0 and 4, are added to the
new route in the order that they appear in the Current Route.
The selection of cities to be added is facilitate by using BitArrays. One BitArray is used as an availability
7
mask with all the bits being set initially to true. Another BitArray is used as a Selection Mask for the segment
to be added. To illustrate this, consider the situation after the Current Segment has been added.
Algorithm:
procedure PSO
Initialize a population of particles
do
for each particle p with position xp do
if (xp is better than pbestp) then
pbestp ← xp
end_if
end_for
Define gbestp as the best position found so far by any of p’s neighbors
for each particle p do
vp ← Compute_velocity(xp, pbestp, gbestp)
xp ← update_ position(xp, vp)
end_for
while (a stop criterion is not satisfied)
Python Code:
'''
Solution for Travelling Salesman Problem using PSO (Particle Swarm
Optimization)
Discrete PSO for TSP
References:
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.258.7026&rep=rep1&type
=pdf
http://www.cs.mun.ca/~tinayu/Teaching_files/cs4752/Lecture19_new.pdf
http://www.swarmintelligence.org/tutorials.php
8
References are in the folder "references" of the repository.
'''
from operator import attrgetter
import random, sys, time, copy
9
random_paths.append(list_temp)
return random_paths
# class that represents a complete graph
class CompleteGraph(Graph):
# generates a complete graph
def generates(self):
for i in range(self.amount_vertices):
for j in range(self.amount_vertices):
if i != j:
weight = random.randint(1, 10)
self.addEdge(i, j, weight)
# class that represents a particle
class Particle:
def __init__(self, solution, cost):
# current solution
self.solution = solution
# best solution (fitness) it has achieved so far
self.pbest = solution
# set costs
self.cost_current_solution = cost
self.cost_pbest_solution = cost
# velocity of a particle is a sequence of 4-tuple
# (1, 2, 1, 'beta') means SO(1,2), prabability 1 and compares with "beta"
self.velocity = []
# set pbest
def setPBest(self, new_pbest):
self.pbest = new_pbest
# returns the pbest
def getPBest(self):
return self.pbest
# set the new velocity (sequence of swap operators)
def setVelocity(self, new_velocity):
self.velocity = new_velocity
# returns the velocity (sequence of swap operators)
def getVelocity(self):
return self.velocity
# set solution
def setCurrentSolution(self, solution):
self.solution = solution
# gets solution
def getCurrentSolution(self):
return self.solution
# set cost pbest solution
def setCostPBest(self, cost):
self.cost_pbest_solution = cost
# gets cost pbest solution
def getCostPBest(self):
return self.cost_pbest_solution
# set cost current solution
def setCostCurrentSolution(self, cost):
self.cost_current_solution = cost
# gets cost current solution
def getCostCurrentSolution(self):
return self.cost_current_solution
# removes all elements of the list velocity
10
def clearVelocity(self):
del self.velocity[:]
# PSO algorithm
class PSO:
def __init__(self, graph, iterations, size_population, beta=1, alfa=1):
self.graph = graph # the graph
self.iterations = iterations # max of iterations
self.size_population = size_population # size population
self.particles = [] # list of particles
self.beta = beta # the probability that all swap operators in swap
sequence (gbest - x(t-1))
self.alfa = alfa # the probability that all swap operators in swap
sequence (pbest - x(t-1))
# initialized with a group of random particles (solutions)
solutions = self.graph.getRandomPaths(self.size_population)
# checks if exists any solution
if not solutions:
print('Initial population empty! Try run the algorithm again...')
sys.exit(1)
# creates the particles and initialization of swap sequences in all the
particles
for solution in solutions:
# creates a new particle
particle = Particle(solution=solution,
cost=graph.getCostPath(solution))
# add the particle
self.particles.append(particle)
# updates "size_population"
self.size_population = len(self.particles)
# set gbest (best particle of the population)
def setGBest(self, new_gbest):
self.gbest = new_gbest
# returns gbest (best particle of the population)
def getGBest(self):
return self.gbest
# shows the info of the particles
def showsParticles(self):
print('Showing particles...\n')
for particle in self.particles:
print('pbest: %s\t|\tcost pbest: %d\t|\tcurrent solution:
%s\t|\tcost current solution: %d' \
% (str(particle.getPBest()), particle.getCostPBest(),
str(particle.getCurrentSolution()),
particle.getCostCurrentSolution()))
print('')
def run(self):
# for each time step (iteration)
for t in range(self.iterations):
# updates gbest (best particle of the population)
self.gbest = min(self.particles, key=attrgetter('cost_pbest_solution'))
11
solution_gbest = copy.copy(self.gbest.getPBest())
# gets solution of the gbest
solution_pbest = particle.getPBest()[:]
# copy of the pbest solution
solution_particle = particle.getCurrentSolution()[:]
# gets copy of the current solution of the particle
for i in range(self.graph.amount_vertices):
if solution_particle[i] != solution_pbest[i]:
# generates swap operator
swap_operator = (i,
solution_pbest.index(solution_particle[i]), self.alfa)
# append swap operator in the list of velocity
temp_velocity.append(swap_operator
# makes the swap
aux = solution_pbest[swap_operator[0]]
solution_pbest[swap_operator[0]] = solution_pbest[swap_operator[1]]
solution_pbest[swap_operator[1]] = aux
# generates all swap operators to calculate (gbest - x(t-1))
for i in range(self.graph.amount_vertices):
if solution_particle[i] != solution_gbest[i]:
# generates swap operator
swap_operator = (i, solution_gbest.index(solution_particle[i]), self.beta)
# append swap operator in the list of velocity
temp_velocity.append(swap_operator)
# makes the swap
aux = solution_gbest[swap_operator[0]]
solution_gbest[swap_operator[0]] = solution_gbest[swap_operator[1]]
solution_gbest[swap_operator[1]] = aux
# updates velocity
particle.setVelocity(temp_velocity)
# generates new solution for particle
for swap_operator in temp_velocity:
if random.random() <= swap_operator[2]:
# makes the swap
aux = solution_particle[swap_operator[0]]
solution_particle[swap_operator[0]] =
solution_particle[swap_operator[1]]
solution_particle[swap_operator[1]] = aux
# updates the current solution
particle.setCurrentSolution(solution_particle)
# gets cost of the current solution
cost_current_solution = self.graph.getCostPath(solution_particle)
# updates the cost of the current solution
particle.setCostCurrentSolution(cost_current_solution)
# checks if current solution is pbest solution
if cost_current_solution < particle.getCostPBest():
particle.setPBest(solution_particle)
particle.setCostPBest(cost_current_solution)
if __name__ == "__main__":
12
graph = Graph(amount_vertices=5)
'''
# random graph
print('Random graph...')
random_graph = CompleteGraph(amount_vertices=20)
random_graph.generates()
pso_random_graph = PSO(random_graph, iterations=10000, size_population=10,
beta=1, alfa=1)
pso_random_graph.run()
print('gbest: %s | cost: %d\n' % (pso_random_graph.getGBest().getPBest(),
pso_random_graph.getGBest().getCostPBest()))
'''
Output:
Showing particles...
pbest: [2, 4, 3, 0, 1] | cost pbest: 9 | current solution: [2, 4, 3, 0, 1] | cost current solution: 9
pbest: [2, 4, 3, 0, 1] | cost pbest: 9 | current solution: [2, 4, 3, 0, 1] | cost current solution: 9
pbest: [2, 4, 3, 0, 1] | cost pbest: 9 | current solution: [2, 4, 3, 0, 1] | cost current solution: 9
pbest: [2, 4, 3, 0, 1] | cost pbest: 9 | current solution: [2, 4, 3, 0, 1] | cost current solution: 9
pbest: [2, 4, 3, 0, 1] | cost pbest: 9 | current solution: [2, 4, 3, 0, 1] | cost current solution: 9
pbest: [2, 1, 0, 3, 4] | cost pbest: 9 | current solution: [2, 4, 0, 3, 1] | cost current solution: 15
pbest: [2, 4, 3, 0, 1] | cost pbest: 9 | current solution: [2, 4, 3, 0, 1] | cost current solution: 9
pbest: [2, 4, 3, 0, 1] | cost pbest: 9 | current solution: [2, 4, 3, 0, 1] | cost current solution: 9
13
pbest: [2, 1, 0, 3, 4] | cost pbest: 9 | current solution: [2, 1, 0, 3, 4] | cost current solution: 9
Outcome: A Particle swarm optimizer can be used to solve highly complicated problems by multiple
repetitions of a simple algorithm.
Title: - Implement Union, Intersection, Complement and Difference operations on fuzzy sets. Also
create fuzzy relation by Cartesian product of any two fuzzy sets and perform max-min composition on
any two fuzzy relations.
Theory:
Fuzzy refers to something that is unclear or vague. Hence, Fuzzy Set is a Set where every key is
associated with value, which is between 0 to 1 based on the certainty .This value, is often called as
degree of membership. Fuzzy Set is denoted with a Tilde Sign on top of the normal Set notation.
Fuzzy logic is a superset of conventional (Boolean) logic that has been extended to handle the concept
of partial truth- truth values between "completely true" and "completely false". As its name suggests, it
is the logic underlying modes of reasoning which are approximate rather than exact. The importance
of fuzzy logic derives from the fact that most modes of human reasoning and especially common-sense
reasoning are approximate in nature.
The essential characteristics of fuzzy logic as founded by Zader Lotfi are as follows.
• In fuzzy logic, exact reasoning is viewed as a limiting case of approximate reasoning.
• In fuzzy logic everything is a matter of degree.
• Any logical system can be fuzzified.
• In fuzzy logic, knowledge is interpreted as a collection of elastic or, equivalently, fuzzy constraint on a
collection of variables
• Inference is viewed as a process of propagation of elastic constraints. The third statement, hence,
defines Boolean logic as a subset of Fuzzy logic.
Python Code:
import numpy as np
def union(A,B):
result={}
for i in A:
if(A[i]>B[i]):
result[i]=A[i]
else:
result[i]=B[i]
print("Union of two sets is",result)
def intersection(A,B):
result={}
for i in A:
if(A[i]<B[i]):
result[i]=A[i]
else:
result[i]=B[i]
print("Intersection of two sets is",result)
def complement(A,B):
result={}
result1={}
for i in A:
result[i]=round(1-A[i],2)
for i in B:
result1[i]=round(1-B[i],2)
print("Complement of 1st set is”, result)
print("Complement of 2nd set is",result1)
def difference(A,B):
result={}
for i in A:
result[i]=round(min(A[i],1-B[i]),2)
print("Difference of two sets is”, result)
def cartprod(A,B):
R = [[] for i in range(len(A))]
i = 0
for x in A:
for y in B:
R[i].append(min(A[x], B[y]))
i += 1
print("Cartesian Product is",np.array(R),"\n")
15
def maxmin():
R = None
S = None
with open("./relations.json") as f:
relations = json.load(f)
R = relations["R"]
S = relations["S"]
print("\nR: " + str(R))
print("S: " + str(S))
m, n = len(R), len(R[0])
o = len(S[0])
composition = dict()
for i in range(m):
composition[i] = dict()
for k in range(o):
composition[i][k] = max([min(R[i][j], S[j][k]) for j in range(n)])
return composition
import json
def main():
while True:
print("Menu Driven Program")
print("1.Union")
print("2.Intersection")
print("3.Complement")
print("4.Difference")
print("5.Cartesian product")
print("6.MaxMin Composition")
print("7.Exit")
choice=int(input("Enter your choice:"))
if choice==1:
union(d,d1)
elif choice==2:
intersection(d,d1)
elif choice==3:
complement(d,d1)
elif choice==4:
difference(d,d1)
elif choice==5:
cartprod(d,d1)
elif choice==6:
composition=maxmin()
print("\nMax-min composition:", composition, sep="\n")
elif choice==7:
break
else:
print("Wrong choice")
if __name__ == "__main__":
print("----------------------"+
"FUZZY SET OPERATIONS"+
"----------------------")
n = int(input("enter no.of elements of set 1:"))
16
d = {}
for i in range(n):
keys = input()
values = float(input())
d[keys] = values
n1 = int(input("enter no.of elements of set 2:"))
d1 = {}
for i in range(n1):
keys1 = input()
values1 = float(input())
d1[keys1] = values1
main()
Output:
enter no.of elements of set 1:3
x1
0.2
x2
0.5
x3
0.8
enter no.of elements of set 2:3
x1
0.4
x2
0.2
x3
0.1
Menu Driven Program
1.Union
2.Intersection
3.Complement
4.Difference
5.Cartesian product
6.MinMax Transformation
7.Exit
Enter your choice:3
Complement of 1st set is {'x1': 0.8, 'x2': 0.5, 'x3': 0.2}
Complement of 2nd set is {'x1': 0.6, 'x2': 0.8, 'x3': 0.9}
Menu Driven Program
1.Union
2.Intersection
3.Complement
4.Difference
5.Cartesian product
6.MinMax Transformation
7.Exit
Enter your choice:4
Difference of two sets is {'x1': 0.2, 'x2': 0.5, 'x3': 0.8}
Menu Driven Program
1.Union
2.Intersection
3.Complement
4.Difference
5.Cartesian product
17
6.MinMax Transformation
7.Exit
Enter your choice:5
Cartesian Product is [[0.2 0.2 0.1]
[0.4 0.2 0.1]
[0.4 0.2 0.1]]
Max-min composition:
{0: {0: 0.6, 1: 0.5, 2: 0.3}, 1: {0: 0.8, 1: 0.4, 2: 0.7}}
Menu Driven Program
1.Union
2.Intersection
3.Complement
4.Difference
5.Cartesian product
6.MinMax Transformation
7.Exit
Enter your choice:7
Outcome:
Thus we have implemented Union, Intersection, Complement and Difference operations on fuzzy sets.
18
Assignment No- 04 Date:___/___/______
Title: - Implement genetic algorithm for benchmark function (eg. Square, Rosenbrock function etc)
Initialize the population from the Standard Normal Distribution. Evaluate the fitness of all its
individuals. Then you will do multiple generation of a genetic algorithm. A generation consists of
applying selection, crossover, mutation, and replacement.
Use:
• Tournament selection without replacement with tournament size s
• One point crossover with probability Pc
• bit-flip mutation with probability Pm
• use full replacement strategy
Theory:
Genetic Algorithms (GAs) are adaptive heuristic search algorithms that belong to the larger part of
evolutionary algorithms.
Genetic algorithms are based on the ideas of natural selection and genetics. These are intelligent
exploitation of random search provided with historical data to direct the search into the region of
better performance in solution space.
They are commonly used to generate high-quality solutions for optimization problems and search
problems. Genetic algorithms simulate the process of natural selection which means those species who
can adapt to changes in their environment are able to survive and reproduce and go to next
generation. In simple words, they simulate “survival of the fittest” among individual of consecutive
generation for solving a problem. Each generation consist of a population of individuals and each
individual represents a point in search space and possible solution. Each individual is represented as a
string of character/integer/float/bits. This string is analogous to the Chromosome.
Following is the foundation of GAs based on this analogy –
1. Individual in population compete for resources and mate
2. Those individuals who are successful (fittest) then mate to create more offspring than others
3. Genes from “fittest” parent propagate throughout the generation, that is sometimes parents
create offspring which is better than either parent.
4. Thus each successive generation is more suited for their environment.
Search space
The population of individuals is maintained within search space. Each individual represents a solution
in search space for given problem. Each individual is coded as a finite length vector (analogous to
19
chromosome) of components. These variable components are analogous to Genes. Thus a chromosome
(individual) is composed of several genes (variable components).
Fitness Score
A Fitness Score is given to each individual which shows the ability of an individual to “compete”. The
individual having optimal fitness score (or near optimal) are sought.
The GAs maintains the population of n individuals (chromosome/solutions) along with their fitness
scores.The individuals having better fitness scores are given more chance to reproduce than others.
The individuals with better fitness scores are selected who mate and produce better offspring by
combining chromosomes of parents. The population size is static so the room has to be created for new
arrivals. So, some individuals die and get replaced by new arrivals eventually creating new generation
when all the mating opportunity of the old population is exhausted. It is hoped that over successive
generations better solutions will arrive while least fit die.
Each new generation has on average more “better genes” than the individual (solution) of previous
generations. Thus each new generations have better “partial solutions” than previous generations.
Once the offspring produced having no significant difference from offspring produced by previous
populations, the population is converged. The algorithm is said to be converged to a set of solutions for
the problem.
Operators of Genetic Algorithms
Once the initial generation is created, the algorithm evolves the generation using following operators
– 1) Selection Operator: The idea is to give preference to the individuals with good fitness scores and
allow them to pass their genes to successive generations.
2) Crossover Operator: This represents mating between individuals. Two individuals are selected
using selection operator and crossover sites are chosen randomly. Then the genes at these crossover
sites are exchanged thus creating a completely new individual (offspring).
For example –
3) Mutation Operator: The key idea is to insert random genes in offspring to maintain the diversity in
the population to avoid premature convergence.
For example –
20
The whole algorithm can be summarized as –
1) Randomly initialize population’s p
2) Determine fitness of population
3) Until convergence repeat:
a) Select parents from population
b) Crossover and generate new population
c) Perform mutation on new population
d) Calculate fitness for new population
Code:
# Python3 program to create target string, starting from
# random string using Genetic Algorithm
import random
# Number of individuals in each generation
POPULATION_SIZE = 100
# Valid genes
GENES = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP
QRSTUVWXYZ 1234567890, .-;:_!"#%&/()=?@${[]}'''
# Target string to be generated
TARGET = "I love GESCOE"
class Individual(object):
'''
Class representing individual in population
'''
def __init__(self, chromosome):
self.chromosome = chromosome
self.fitness = self.cal_fitness()
@classmethod
def mutated_genes(self):
'''
create random genes for mutation
'''
global GENES
gene = random.choice(GENES)
return gene
21
@classmethod
def create_gnome(self):
'''
create chromosome or string of genes
'''
global TARGET
gnome_len = len(TARGET)
return [self.mutated_genes() for _ in range(gnome_len)]
def cal_fitness(self):
'''
Calculate fitness score, it is the number of
characters in string which differ from target
string.
'''
global TARGET
fitness = 0
for gs, gt in zip(self.chromosome, TARGET):
if gs != gt: fitness+= 1
return fitness
# Driver code
def main():
global POPULATION_SIZE
#current generation
22
generation = 1
found = False
population = []
# create initial population
for _ in range(POPULATION_SIZE):
gnome = Individual.create_gnome()
population.append(Individual(gnome))
while not found:
# sort the population in increasing order of fitness score
population = sorted(population, key = lambda x:x.fitness)
if __name__ == '__main__':
main()
23
Output:
Outcome:
Thus we implemented genetic algorithm.
24