Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

MODUL PERKULIAHAN

TEKNIK
OPTIMASI
Genetic Algorithm
On Hands

Fakultas Program Studi Tatap Muka Kode MK Disusun Oleh

14
Teknik Teknik ELektro Zendi Iklima, ST., S.Kom., M.Sc.

Abstract Kompetensi
Pada mata kuliah ini, mahasiswa belajar Ketepatan dalam menguraikan
mengenai Swarm Intelligence (SI), definisi, konsep dasar Genetic Algorithm (GA)
konsep dasar SI, serta bagaimana
penggunaan SI. Selain itu mahasiswa juga akan Ketepatan dalam memberikan
dikenalkan mengenai Swarm Robotics (SR). contoh aplikasi Genetic Algorithm
Serta mahasiswa akan belajar
mengenai konsep dasar, visualisasi, formulasi,
hingga teknik aplikasi dari beberapa algoritma
antara lain Ant Colony
Optimization (ACO), Bee Colony Optimization
(BCO), Particle Swarm Optimization (PSO),
Genetic Algorithm (GA).
Application 1: GA to Generating Words

# 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 = "Mercu Buana by GA"

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

@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
'''

2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning


2 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id
# chromosome for offspring
child_chromosome = []
for gp1, gp2 in zip(self.chromosome, par2.chromosome):

# random probability
prob = random.random()

# if prob is less than 0.45, insert gene


# from parent 1
if prob < 0.45:
child_chromosome.append(gp1)

# if prob is between 0.45 and 0.90, insert


# gene from parent 2
elif prob < 0.90:
child_chromosome.append(gp2)

# otherwise insert random gene(mutate),


# for maintaining diversity
else:
child_chromosome.append(self.mutated_genes())

# create new Individual(offspring) using


# generated chromosome for offspring
return Individual(child_chromosome)

def cal_fitness(self):
'''
Calculate fittness 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
generation = 1

found = False

2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning


3 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id
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 s
core
population = sorted(population, key = lambda x:x.fitne
ss)

# 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 = []

# Perform Elitism, that mean 10% of fittest population

# goes to the next 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:", generation)
# print("String:", population[0].chromosome)
# print("Fitness:", population[0].fitness)

generation += 1

print("Generation:", generation)

2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning


4 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id
print("String:", population[0].chromosome)
print("Fitness:", population[0].fitness)

if __name__ == '__main__':
main()

2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning


5 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id
Application 2: GA Optimizing Air Quality Sensor

import numpy

def cal_pop_fitness(equation_inputs, pop):


# Calculating the fitness value of each solution in the current pop
ulation.
# The fitness function caulcuates the sum of products between each
input and its corresponding weight.
fitness = numpy.sum(pop*equation_inputs, axis=1)
return fitness

def select_mating_pool(pop, fitness, num_parents):


# Selecting the best individuals in the current generation as paren
ts for producing the offspring of the next generation.
parents = numpy.empty((num_parents, pop.shape[1]))
for parent_num in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
max_fitness_idx = max_fitness_idx[0][0]
parents[parent_num, :] = pop[max_fitness_idx, :]
fitness[max_fitness_idx] = -99999999999
return parents

def crossover(parents, offspring_size):


offspring = numpy.empty(offspring_size)
# The point at which crossover takes place between two parents. Usu
ally it is at the center.
crossover_point = numpy.uint8(offspring_size[1]/2)

for k in range(offspring_size[0]):
# Index of the first parent to mate.
parent1_idx = k%parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1)%parents.shape[0]
# The new offspring will have its first half of its genes taken
from the first parent.
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crosso
ver_point]
# The new offspring will have its second half of its genes take
n from the second parent.
offspring[k, crossover_point:] = parents[parent2_idx, crossover
_point:]
return offspring

def mutation(offspring_crossover):
# Mutation changes a single gene in each offspring randomly.
for idx in range(offspring_crossover.shape[0]):
# The random value to be added to the gene.
random_value = numpy.random.uniform(-1.0, 1.0, 1)
offspring_crossover[idx, 4] = offspring_crossover[idx, 4] + ran
dom_value
return offspring_crossover

"""
The y=target is to maximize this equation ASAP:
y = w1x1+w2x2+w3x3+w4x4+w5x5+6wx6
where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7)
What are the best values for the 6 weights w1 to w6?
We are going to use the genetic algorithm for the best possible val
ues after a number of generations.
"""

# Inputs of the equation.


equation_inputs = [ [
80.8, 79.5,
80.5, 86.2,
88.8, 81.3,
80.5, 78.6,
82.9, 75,
62.3, 79.9,
81, 80.3,
78.6, 85.6,
82.3, 82.4,
76.2, 80.5
],
[
59.3, 56.8,
56.9, 59.3,
71.1, 70.7,
73.8, 70.8,
71.2, 72.5,
73.1, 75.9,
80.7, 78.7,
81.1, 58.5,
60.2, 59.4,
59.3, 57.9
]
]
# 1 = bising
l = [
1,0,1,1,1,1,1,
0,1,0,0,0,1,1,
0,1,1,1,0,1

2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning


7 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id
]

# Number of the weights we are looking to optimize.


num_weights = len(equation_inputs[0])

from sklearn.datasets.samples_generator import make_blobs


from matplotlib import pyplot
from pandas import DataFrame

Data_set_size=20

# X, Y = make_blobs(n_samples=20, centers=2, n_features=2,cluster_std=1


, center_box=(-4.0, 4.0),random_state=9)
# df = DataFrame(dict(x=X[:,1], y=X[:,0], label=Y))

df = DataFrame(dict(x=equation_inputs[0], y=equation_inputs[0], label=l


))
print(df)

colors = {0:'red', 1:'blue'}

fig, ax = pyplot.subplots()

grouped = df.groupby('label')

for key, group in grouped:


group.plot(ax=ax, kind='scatter', x='x', y='y', label=key, color=co
lors[key])

pyplot.xlabel("x1 (pagi)", fontsize=18)


pyplot.ylabel("x2 (siang)", rotation=0, fontsize=18)
#pyplot.show()

"""
Genetic algorithm parameters:
Mating pool size
Population size
"""
sol_per_pop = 10
num_parents_mating = 5

2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning


8 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id
# Defining the population size.
pop_size = (sol_per_pop,num_weights) # The population will have sol_per
_pop chromosome where each chromosome has num_weights genes.

#Creating the initial population.


new_population = numpy.random.uniform(low=60, high=90, size=pop_size)
# print(new_population)

num_generations = 10
for generation in range(num_generations):
print("Generation : ", generation)
# Measing the fitness of each chromosome in the population.
fitness = cal_pop_fitness(equation_inputs[0], new_population)

# Selecting the best parents in the population for mating.


parents = select_mating_pool(new_population, fitness,
num_parents_mating)

# Generating next generation using crossover.


offspring_crossover = crossover(parents,
offspring_size=(pop_size[0]-
parents.shape[0], num_weights))

# Adding some variations to the offsrping using mutation.


offspring_mutation = mutation(offspring_crossover)

# Creating the new population based on the parents and offspring.


new_population[0:parents.shape[0], :] = parents
new_population[parents.shape[0]:, :] = offspring_mutation

# The best result in the current iteration.


print("Best result : ", numpy.max(numpy.sum(new_population*equation
_inputs[0], axis=1)))

# Getting the best solution after iterating finishing all generations.


#At first, the fitness is calculated for each solution in the final gen
eration.
fitness = cal_pop_fitness(equation_inputs[0], new_population)
# Then return the index of that solution corresponding to the best fitn
ess.
best_match_idx = numpy.where(fitness == numpy.max(fitness))

print("Best solution : ", new_population[best_match_idx, :])


print("Best solution fitness : ", fitness[best_match_idx])

2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning


9 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id
2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning
10 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id
2018 Teknnik Optimasi Pusat Bahan Ajar dan eLearning
11 Zendi Iklima, ST., S.Kom,. M.Sc. http://www.mercubuana.ac.id

You might also like