forked from handcraftsman/GeneticAlgorithmsWithPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
45ca74b
commit b37eebf
Showing
36 changed files
with
6,074 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
# Algoritmos Genéticos con Python | ||
El código del libro Algoritmos Genéticos con Python por Clinton Sheppard | ||
|
||
Descripción | ||
=== | ||
|
||
[English edition](https://github.com/handcraftsman/GeneticAlgorithmsWithPython) | ||
|
||
<img align="right" src="http:https://www.cs.unm.edu/~sheppard/img/Algoritmos_Geneticos_Cover_for_Kindle.jpg" alt="tapa del libro Algoritmos Genéticos con Python"> | ||
Obtenga una introducción práctica al aprendizaje de la máquina con algoritmos genéticos usando Python. Tutoriales paso a paso construye sus habilidades de ¡Hola Mundo! a optimizar un algoritmo genético con otro, y finalmente a la programación genética; así, preparándose para aplicar algoritmos genéticos a problemas en su propio campo de experiencia. | ||
|
||
Algoritmos genéticos son una de las herramientas que puede utilizar para aplicar el aprendizaje de la máquina a la búsqueda de soluciones buenas, a veces incluso óptimas, a los problemas que tienen miles de millones de soluciones potenciales. Este libro le da la experiencia de hacer que los algoritmos genéticos funcionen para usted, usando los problemas fáciles de seguir del ejemplo que usted puede recurrir al aprender a usar otras herramientas y técnicas de aprendizaje de la máquina. Cada capítulo es un tutorial paso a paso que ayuda a desarrollar sus habilidades en el uso de algoritmos genéticos para resolver problemas utilizando Python. | ||
|
||
- https://www.amazon.com/dp/B072NDMJ4L (Versión Kindle) | ||
|
||
Tabla de contenido | ||
=== | ||
|
||
Una breve introducción a los algoritmos genéticos | ||
|
||
Capítulo 1: ¡Hola Mundo! | ||
- Adivine una contraseña dando el número de letras correctas en el grupo. Construir un motor de mutación. | ||
|
||
Capítulo 2: El Problema One-max | ||
- Produce una matriz de bits donde todos son 1s. Expande el motor para funcionar con cualquier tipo de gene. | ||
|
||
Capítulo 3: Números ordenados | ||
- Produsca una matriz de números enteros ordenados. Demuestre el manejo de múltiples metas y restricciones entre los genes. | ||
|
||
Capítulo 4: El rompecabezas de 8 reinas | ||
- Encuentre las posiciones seguras de la reina en un tablero de ajedrez de 8x8 y luego amplíe a NxN. Demuestre la diferencia entre el fenotipo y el genotipo. | ||
|
||
Capítulo 5: Coloración gráfica | ||
- Coloree un mapa de los países donde Español es el idioma nacional usando solamente 4 colores. Introdusca grupos de datos comunes y trabaje con archivos. También introdusca el uso de reglas para funcionar con restricciones genéticas. | ||
|
||
Capítulo 6: Problema de la carta | ||
- Más restricciones genéticas. Introdusca la mutación personalizada, los algoritmos meméticos, y la técnica de suma-de-diferencia. También demuestre un cromosoma donde la forma en que se utiliza un gene depende de su posición en la matriz génica. | ||
|
||
Capítulo 7: Problema de los caballos de ajedrez | ||
- Encuentre el número mínimo de caballos necesarios para atacar todas las posiciones en un tablero de ajedrez. Presente genes personalizados y creación de matrices de genes. También demuestra mínimos y máximos locales. | ||
|
||
Capítulo 8: Cuadrados mágicos | ||
- Encuentre cuadrados donde todas las filas, columnas y ambas diagonales de una matriz de NxN tienen la misma suma. Introduce el recocido simulado. | ||
|
||
Capítulo 9: Problema de la mochila | ||
- Optimizar el contenido de un contenedor para una o más variables. Presenta rama y límite y los cromosomas de la longitud variable. | ||
|
||
Capítulo 10: Resolución de ecuaciones lineales | ||
- Encuentre las soluciones de ecuaciones lineales con 2, 3 y 4 desconocidos. Variación de ramas y límite. Refuerza la flexibilidad del genotipo. | ||
|
||
Capítulo 11: Generando Sudoku | ||
- Un ejercicio guiado en la generación de rompecabezas de Sudoku. | ||
|
||
Capítulo 12: Problema del vendedor viajero | ||
- Encuentre la ruta óptima para visitar las ciudades. Introduce intercambio de genes y una piscina de padres. | ||
|
||
Capítulo 13: Aproximación de Pi | ||
- Encuentre los dos números de 10 bits cuyo dividendo es el más cercano a Pi. Introdusca utilizando un algoritmo genético para afinar otro. | ||
|
||
Capítulo 14: Generación de ecuaciones | ||
- Encuentre la ecuación más corta que produzca un resultado específico usando suma, resta, multiplicación, etc. Introduce la programación genética simbólica. | ||
|
||
Capítulo 15: Problema de la cortadora de pasto | ||
- Genere una serie de instrucciones que hacen que una cortadora de pasto corte un campo de pasto. Programación genética con estructuras de control, objetos, y funciones definidas automáticamentes. | ||
|
||
Capítulo 16: Circuitos lógicos | ||
- Construya circuitos que se comporten como puertas lógicas básicas, combinaciones de compuertas, y finalmente un sumador de 2 bits que utilice nodos de árbol y ascenso de la colina. | ||
|
||
Capítulo 17: Expresiones regulares | ||
- Busque expresiones regulares que coincidan con las cadenas deseadas. Presente la reparación cromosómica y el control del crecimiento. | ||
|
||
Capítulo 18: Tic-tac-toe | ||
- Crear reglas para jugar el juego sin perder. Presenta la selección de torneos. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
# File: contraseña.py | ||
# Del capítulo 1 de _Algoritmos Genéticos con Python_ | ||
# | ||
# Author: Clinton Sheppard <[email protected]> | ||
# Copyright (c) 2017 Clinton Sheppard | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). | ||
# You may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# http:https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | ||
# implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
|
||
import datetime | ||
import random | ||
import unittest | ||
|
||
import genetic | ||
|
||
|
||
def obtener_aptitud(conjetura, objetivo): | ||
return sum(1 for esperado, real in zip(objetivo, conjetura) | ||
if esperado == real) | ||
|
||
|
||
def mostrar(candidato, horaInicio): | ||
diferencia = (datetime.datetime.now() - horaInicio).total_seconds() | ||
print("{}\t{}\t{}".format( | ||
candidato.Genes, candidato.Aptitud, diferencia)) | ||
|
||
|
||
# `nosetests` no admite caracteres como ñ en el nombre de la clase | ||
class PruebasDeContrasena(unittest.TestCase): | ||
geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!¡.," | ||
|
||
def test_Hola_Mundo(self): | ||
objetivo = "¡Hola Mundo!" | ||
self.adivine_contraseña(objetivo) | ||
|
||
def test_Porque_me_formaste_de_una_manera_formidable_y_maravillosa( | ||
self): | ||
objetivo = "Porque me formaste de una manera formidable y " \ | ||
"maravillosa." | ||
self.adivine_contraseña(objetivo) | ||
|
||
def adivine_contraseña(self, objetivo): | ||
horaInicio = datetime.datetime.now() | ||
|
||
def fnObtenerAptitud(genes): | ||
return obtener_aptitud(genes, objetivo) | ||
|
||
def fnMostrar(candidato): | ||
mostrar(candidato, horaInicio) | ||
|
||
aptitudÓptima = len(objetivo) | ||
mejor = genetic.obtener_mejor(fnObtenerAptitud, len(objetivo), | ||
aptitudÓptima, self.geneSet, | ||
fnMostrar) | ||
self.assertEqual(mejor.Genes, objetivo) | ||
|
||
def test_aleatorio(self): | ||
longitud = 150 | ||
objetivo = ''.join(random.choice(self.geneSet) | ||
for _ in range(longitud)) | ||
|
||
self.adivine_contraseña(objetivo) | ||
|
||
def test_comparativa(self): | ||
genetic.Comparar.ejecutar(self.test_aleatorio) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
# File: genetic.py | ||
# Del capítulo 1 de _Algoritmos Genéticos con Python_ | ||
# | ||
# Author: Clinton Sheppard <[email protected]> | ||
# Copyright (c) 2017 Clinton Sheppard | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). | ||
# You may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# http:https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | ||
# implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
|
||
import random | ||
import statistics | ||
import sys | ||
import time | ||
|
||
|
||
def _generar_padre(longitud, geneSet, obtener_aptitud): | ||
genes = [] | ||
while len(genes) < longitud: | ||
tamañoMuestral = min(longitud - len(genes), len(geneSet)) | ||
genes.extend(random.sample(geneSet, tamañoMuestral)) | ||
genes = ''.join(genes) | ||
aptitud = obtener_aptitud(genes) | ||
return Cromosoma(genes, aptitud) | ||
|
||
|
||
def _mudar(padre, geneSet, obtener_aptitud): | ||
índice = random.randrange(0, len(padre.Genes)) | ||
genesDelNiño = list(padre.Genes) | ||
nuevoGen, alterno = random.sample(geneSet, 2) | ||
genesDelNiño[índice] = alterno if nuevoGen == genesDelNiño[ | ||
índice] else nuevoGen | ||
genes = ''.join(genesDelNiño) | ||
aptitud = obtener_aptitud(genes) | ||
return Cromosoma(genes, aptitud) | ||
|
||
|
||
def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, | ||
mostrar): | ||
random.seed() | ||
mejorPadre = _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) | ||
mostrar(mejorPadre) | ||
if mejorPadre.Aptitud >= aptitudÓptima: | ||
return mejorPadre | ||
while True: | ||
niño = _mudar(mejorPadre, geneSet, obtener_aptitud) | ||
if mejorPadre.Aptitud >= niño.Aptitud: | ||
continue | ||
mostrar(niño) | ||
if niño.Aptitud >= aptitudÓptima: | ||
return niño | ||
mejorPadre = niño | ||
|
||
|
||
class Cromosoma: | ||
def __init__(self, genes, aptitud): | ||
self.Genes = genes | ||
self.Aptitud = aptitud | ||
|
||
|
||
class Comparar: | ||
@staticmethod | ||
def ejecutar(función): | ||
print(función) | ||
cronometrajes = [] | ||
stdout = sys.stdout | ||
for i in range(100): | ||
sys.stdout = None | ||
horaInicio = time.time() | ||
función() | ||
segundos = time.time() - horaInicio | ||
sys.stdout = stdout | ||
cronometrajes.append(segundos) | ||
promedio = statistics.mean(cronometrajes) | ||
if i < 10 or i % 10 == 9: | ||
print("{} {:3.2f} {:3.2f}".format( | ||
1 + i, promedio, | ||
statistics.stdev(cronometrajes, | ||
promedio) if i > 1 else 0)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
# File: contraseña.py | ||
# Del capítulo 2 de _Algoritmos Genéticos con Python_ | ||
# | ||
# Author: Clinton Sheppard <[email protected]> | ||
# Copyright (c) 2017 Clinton Sheppard | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). | ||
# You may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# http:https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | ||
# implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
|
||
import datetime | ||
import random | ||
import unittest | ||
|
||
import genetic | ||
|
||
|
||
def obtener_aptitud(conjetura, objetivo): | ||
return sum(1 for esperado, real in zip(objetivo, conjetura) | ||
if esperado == real) | ||
|
||
|
||
def mostrar(candidato, horaInicio): | ||
diferencia = (datetime.datetime.now() - horaInicio).total_seconds() | ||
print("{}\t{}\t{}".format( | ||
''.join(candidato.Genes), | ||
candidato.Aptitud, | ||
diferencia)) | ||
|
||
|
||
# `nosetests` no admite caracteres como ñ en el nombre de la clase | ||
class PruebasDeContrasena(unittest.TestCase): | ||
geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!¡.," | ||
|
||
def test_Hola_Mundo(self): | ||
objetivo = "¡Hola Mundo!" | ||
self.adivine_contraseña(objetivo) | ||
|
||
def test_Porque_me_formaste_de_una_manera_formidable_y_maravillosa(self): | ||
objetivo = "Porque me formaste de una manera formidable y maravillosa." | ||
self.adivine_contraseña(objetivo) | ||
|
||
def adivine_contraseña(self, objetivo): | ||
horaInicio = datetime.datetime.now() | ||
|
||
def fnObtenerAptitud(genes): | ||
return obtener_aptitud(genes, objetivo) | ||
|
||
def fnMostrar(candidato): | ||
mostrar(candidato, horaInicio) | ||
|
||
aptitudÓptima = len(objetivo) | ||
mejor = genetic.obtener_mejor(fnObtenerAptitud, len(objetivo), | ||
aptitudÓptima, self.geneSet, fnMostrar) | ||
self.assertEqual(''.join(mejor.Genes), objetivo) | ||
|
||
def test_aleatorio(self): | ||
longitud = 150 | ||
objetivo = ''.join(random.choice(self.geneSet) | ||
for _ in range(longitud)) | ||
|
||
self.adivine_contraseña(objetivo) | ||
|
||
def test_comparativa(self): | ||
genetic.Comparar.ejecutar(self.test_aleatorio) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
Oops, something went wrong.