-
Notifications
You must be signed in to change notification settings - Fork 0
/
secret_word_finder.py
60 lines (43 loc) · 1.42 KB
/
secret_word_finder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: jcarraascootarola
"""
from GeneticAlgorithm import GeneticAlgorithm
import time
import matplotlib.pyplot as plt
wordToGuess="paralelepipedo"
#hiperparameters
mutationRate = 0.05
populationSize = 40
numberOfGenes = len(wordToGuess)
#stopCondition Parameters
maxGenerations=100
geneValues=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," "]
def fitnessFunction(individual):
total=0
for i in range(len(individual)):
if wordToGuess[i]==individual[i]:
total+=1
return total
def stopCondition(algorithmInstance):
if algorithmInstance.numberOfGenerations == maxGenerations or fitnessFunction(algorithmInstance.best) == numberOfGenes:
return True
return False
print("Entrenando, esto puede tomar un tiempo ...")
start = time.time()
ga = GeneticAlgorithm(mutationRate, populationSize, fitnessFunction, numberOfGenes, geneValues, stopCondition)
ga.startAlgorithm()
end = time.time()
print("time elapsed: "+str(end - start))
plt.figure(1)
plt.plot(ga.generation, ga.bestFitness)
plt.xlabel('Generation')
plt.ylabel('Fittest individual fitness')
plt.title("Best individual performance")
plt.figure(2)
plt.plot(ga.generation, ga.averageFitness)
plt.xlabel('Generation')
plt.ylabel('Population average fitness')
plt.title("Average generation performance")
plt.show()