Skip to content

Instantly share code, notes, and snippets.

@GiliardGodoi
Created June 5, 2020 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GiliardGodoi/d132bd1039a3d1f2d7576e9a928dfaf7 to your computer and use it in GitHub Desktop.
Save GiliardGodoi/d132bd1039a3d1f2d7576e9a928dfaf7 to your computer and use it in GitHub Desktop.
import random
from evol import Population, Evolution
CHROMO_LENGTH = 30
CHROMO_PARTITION = 10
TARGET_VALUE = 52
POPULATION_SIZE = 100
def random_chromosome(size):
return ''.join(random.choices(['0', '1'], k=size))
def decode_chromosome(chromosome, size):
def bit2int(binary):
return int(binary, 2)
sequence = [chromosome[i:i+size] for i in range(0,len(chromosome), size)]
return tuple(map(bit2int,sequence))
def function(x,y,w):
return (x**2 + 2*y + w)
def eval_chromosome(chromosome):
xyz = decode_chromosome(chromosome, CHROMO_PARTITION)
value = function(*xyz)
return abs(TARGET_VALUE - value)
def crossing_chromosome(chromo1, chromo2):
idxs = random.choices(range(0, len(chromo1)), k=2)
idx1, idx2 = min(idxs), max(idxs)
new_one = chromo1[:idx1] + chromo2[idx1:idx2] + chromo1[idx2:]
# newTwo = chromo2[:idx1] + chromo1[idx1:idx2] + chromo2[idx2:]
# if (new_one == chromo1):
# print(f"Crossing >> {new_one}")
# elif (new_one == chromo2):
# print(f"Crossing :::::::::::: {new_one}")
return new_one
def mutation(chromosome, probability=0.8):
flip_bit = lambda bit : '1' if bit == '0' else '0'
genes = list(chromosome)
# print(probability)
for i in range(0,len(chromosome)):
if random.random() < probability:
genes[i] = flip_bit(genes[i])
return ''.join(genes)
def select_by_wheel(population : Population):
weights = population._individual_weights
selected = random.choices(population, weights=weights, k=len(population))
return selected
def normalize_by_windowing(population):
value = max([chromosome.score for chromosome in population]) + 1
for chromosome in population:
chromosome.fitness = abs(value - chromosome.score)
return population
def pick_random(population):
return tuple(random.choices(population, k=2))
def custom_logger(population):
best = min(p.fitness for p in population)
worst = max(p.fitness for p in population)
length = len(population)
gen = population.generation
print(f"Best: {best} | Worst: {worst} | Length {length} | Generation: {gen}")
return population
if __name__ == "__main__":
pop = (Population(chromosomes=[random_chromosome(CHROMO_LENGTH) for _ in range(POPULATION_SIZE)],
eval_function=eval_chromosome,
maximize=False).evaluate())
best = min(p.fitness for p in pop)
print("Best fitness before evolutionary ", best)
evo = (Evolution()
.survive(n=30)
.breed(parent_picker=pick_random, combiner=crossing_chromosome)
.mutate(mutation, probability=0.5)
.evaluate()
)
result = pop.evolve(evo, n=2000)
best = min(p.fitness for p in result.evaluate())
print("Best fitness after ::", best)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment