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

Lab 7 - Genetic Algo

The document outlines a lab task focused on solving the knapsack problem using Genetic Algorithms (GAs). It details the steps involved in GAs, including population initialization, fitness evaluation, selection, crossover, and mutation. Additionally, it provides a code implementation for generating a target string through a genetic algorithm approach.

Uploaded by

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

Lab 7 - Genetic Algo

The document outlines a lab task focused on solving the knapsack problem using Genetic Algorithms (GAs). It details the steps involved in GAs, including population initialization, fitness evaluation, selection, crossover, and mutation. Additionally, it provides a code implementation for generating a target string through a genetic algorithm approach.

Uploaded by

hamidraza
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

4/24/24, 12:08 PM Lab 7 - Genetic Algo.

ipynb - Colab

Search Algorithm

keyboard_arrow_down Genetic Algorithms


1. GAs begin with a set of k randomly generated states, called the population.

Each state, or individual, is represented as a string over a finite alphabet—most


commonly, a string of 0s and 1s.
2. each state is rated by the objective function, or (in GA terminology) the fitness function.

A fitness function should return higher values for better states


3. Selection: two pairs are selected at random for reproduction, in accordance with the
probabilities in Step 2.

one individual is selected twice and one not at all.

4. Crossover: For each pair to be mated, a crossover point is chosen randomly from the
positions in the string.

the offspring themselves are created by crossing over the parent strings at the
crossover point.
For example, the first child of the first pair gets the first three digits from the first
parent and the remaining digits from the second parent,
whereas the second child gets the first three digits from the second parent and the
rest from the first parent.
5. Mutation: each location is subject to random mutation with a small independent
probability.

https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 1/5
4/24/24, 12:08 PM Lab 7 - Genetic Algo.ipynb - Colab

Lab Task: S2024


Given is the knapsack problem having Finite weight of sack in (KG), with finite number of item,
where each item has some weight and value. Write the following functions to solve the problem
using Genetic Algorithm:

1. input function: takes size of sack, number of items in sack from user and then ask user to
choose whether

weights and values enter by user


weights and values randolmly genetrated
Display Problem

https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 2/5
4/24/24, 12:08 PM Lab 7 - Genetic Algo.ipynb - Colab

2. Choose the right encoding to express these items for random inital population generation,
where N=12

Display intial Population


3. Evaluate inital population based on fitness function to get most fitted genes

Display fitness of population

4. Select the genes (most fitted) according to your problem using rank based, roulette wheel,
tournament selction method

Display Selected individuals of population

5. Apply Crossover on selected individuals

Display childs after cross over along with parents to show comparison

6. Apply Mutaion on any 3 child/offsprings

Display childs after mutaion along with privious childs to show comparison
7. repeat this process till termination condition or you find a sloution.

keyboard_arrow_down Lab Task: perform in LAB


Solve this problem using genetic algorithm where number of population N=50, compute
fittness using fitness function using

fitness value is number of 1's and 0's m = 3

Target is 111000 m=2 , larger value is better

Perform Crossover:in mate function Next generation is created as: m = 3 where

parent 1 = 101010 and parent 2 = 111100 ,


if p <0.5 then Child1 = 101100
if p <0.8 then Child2 = 010111
else child is a mutated

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 Artificial Intelligence"

class Individual(object):
'''
https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 3/5
4/24/24, 12:08 PM Lab 7 - Genetic Algo.ipynb - Colab

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

@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 mate(self, par2):


'''
Perform mating and produce new offspring
'''

def cal_fitness(self):
'''
Calculate fitness score, it is the number of
characters in string which differ from target
string.
'''

# Driver code
def main():
global POPULATION_SIZE

#current generation
generation = 1

found = False
population = []

# create initial population


for _ in range(POPULATION_SIZE):
gnome = Individual.create_gnome()
population.append(Individual(gnome))

https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 4/5
4/24/24, 12:08 PM Lab 7 - Genetic Algo.ipynb - Colab

while not found:

# sort the population in increasing order of fitness score


population = sorted(population, key = lambda x:x.fitness)

# if the individual having lowest fitness score ie.


# 0 then we know that we have reached to the target
# and break the loop
if population[0].fitness <= 0:
found = True
break

# Otherwise generate new offsprings for new generation


new_generation = []

s = int((10*POPULATION_SIZE)/100)
new_generation.extend(population[:s])

# From 50% of fittest population, Individuals


# will mate to produce offspring
s = int((90*POPULATION_SIZE)/100)
for _ in range(s):
parent1 = random.choice(population[:50])
parent2 = random.choice(population[:50])
child = parent1.mate(parent2)
new_generation.append(child)

population = new_generation

print("Generation: {}\tString: {}\tFitness: {}".\


format(generation,
"".join(population[0].chromosome),
population[0].fitness))

generation += 1

print("Generation: {}\tString: {}\tFitness: {}".\


format(generation,
"".join(population[0].chromosome),
population[0].fitness))

if __name__ == '__main__':
main()

https://colab.research.google.com/drive/18NlJfDIfS_WcGc1hW9Sn-NozUwJ86wRF#scrollTo=1T-wXbIg68RG&printMode=true 5/5

You might also like