HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Genetic Algorithm in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
geneticpythonalgorithm

Problem

I'm a new programmer, so any help is welcome. Preferably to make it faster, avoid heavy memory usage, and so on.

```
#! /usr/bin/env python
"""
This module is a frame work for a Genetic Algorithm.

:param GenePool: See this documentation for how to use this module..
:type GenePool: GenePool

Author: Fernando Rodrigues dos Santos
"""
import random
import math
import pickle
import itertools
import sys

class GenePool():
""""
Place a gene in the desired program using GenePool.nextGene().
Place the genes variables(Gene.dna[id]) in the desired program.
Reward good choices.
Punish bad choices.

Call GenePool.return_result() and pass the gene and the result to start the GA.

After this the Genetic Algorithm will:
- Save the top genes without modification and duplicate them(the amount is set by the elitism).

- Remove the random genes to fit the population(the amount is set by the elitism).

- Randomly choose genes based on their rank(roulette-wheel selection).

- Cross-over the selected genes using the two-points cut method.(the amount of genes crossed is set by the
cross_coefficient).

- Finally it will apply the mutation to each gene(expect the top-rated).

- It will repeat until find a convergence or stop if maxIteration is set.

:param sample: The pattern of genes to be created.
:type sample: list
:param population: How many genes will be in the gene_pool.
:type population: int
:param cross_coefficient: The percentage of genes to do a random cross-over.
:type cross_coefficient: float
:param elitism: The amount of best-fitted genes to remain intact.
:type elitism: float
:param mutation: The chance that a dna will randomly mutate.
:type mutation: float
:param max_iterations: How many times it will try to find a convergence, if -1 it will run indefinitely

Solution

One thing you should do is not place code you always want run at the lowest level in the file, you should place it in a function called main() and call main() with if __name__ == "__main__":. This will help you when you start creating modules and importing them, and is discussed here.

Other than this, your code is very neat, and it is good that it follows PEP-8 standards. I cannot comment on the performance as I do not have Python in my system at the time of writing this.

Context

StackExchange Code Review Q#55197, answer score: 3

Revisions (0)

No revisions yet.