https://github.com/willguimont/simplegeneticalgorithm
Simple Genetic Algorithm written in Python
https://github.com/willguimont/simplegeneticalgorithm
dna genetic-algorithm python python-library
Last synced: 8 months ago
JSON representation
Simple Genetic Algorithm written in Python
- Host: GitHub
- URL: https://github.com/willguimont/simplegeneticalgorithm
- Owner: willGuimont
- License: mit
- Created: 2018-09-15T22:10:18.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-06-15T20:47:26.000Z (almost 7 years ago)
- Last Synced: 2025-04-05T03:02:45.076Z (about 1 year ago)
- Topics: dna, genetic-algorithm, python, python-library
- Language: Python
- Homepage:
- Size: 10.7 KB
- Stars: 0
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# SimpleGeneticAlgorithm
Really simple genetic algorithm in Python
# Example
```python
import random
import random_generator
from dna import DNA
TARGET = 'This is the target'
LENGTH_TARGET = len(TARGET)
POPULATION_SIZE = 100
AGENTS_INDEX = 0
FITNESS_SCORES_INDEX = 1
def fitness(agent):
correct = 0
for i in range(LENGTH_TARGET):
if TARGET[i] == agent.dna[i]:
correct += 1
return correct / LENGTH_TARGET
last_population = []
current_population = [[], []] # current_population[0] = agent
# current_population[1] = fitness
for _ in range(POPULATION_SIZE):
agent = DNA(size=LENGTH_TARGET, random_generator=random_generator.RandomLetterGenerator())
fitness_score = fitness(agent)
current_population[AGENTS_INDEX].append(agent)
current_population[FITNESS_SCORES_INDEX].append(fitness_score)
best_dna = ''
while best_dna != TARGET:
last_population = current_population
current_population = [[], []]
for i in range(POPULATION_SIZE):
random_agent, another_random_agent = random.choices(population=last_population[AGENTS_INDEX], weights=last_population[FITNESS_SCORES_INDEX], k=2)
child_agent = random_agent.crossover(another_random_agent).mutated(mutation_rate=0.01)
child_fitness_score = fitness(child_agent)
current_population[AGENTS_INDEX].append(child_agent)
current_population[FITNESS_SCORES_INDEX].append(child_fitness_score)
best_fitness = max(current_population[FITNESS_SCORES_INDEX])
best_agent = current_population[AGENTS_INDEX][current_population[FITNESS_SCORES_INDEX].index(best_fitness)]
best_dna = ''.join(best_agent.dna)
print(best_dna)
```