Skip to main content

A simple and easy-to-use implementation of Genetic Algorithm for Keras NN models in Python.

Project description

KerasGA

A simple and easy-to-use implementation of Genetic Algorithm for Keras NN models in Python.

Features

  • create an initial population (of size: population_size) of randomly initialized chromosomes (i.e model weights).
  • You can adjust the selection_rate & the mutation_rate.
  • Perform the different GA operations (i.e Selection, Crossover, & Mutation).

Examples

Here are a few projects based on this package:

Usage

  • Install KerasGA :
$ pip install KerasGA
  • import GeneticAlgorithm from KerasGA and initiate an object :
from KerasGA import GeneticAlgorithm

population_size =  10
GA = GeneticAlgorithm(model, population_size = population_size, selection_rate = 0.1, mutation_rate = 0.2)

PS: model is a Keras model.

  • Generate the initial population:
population = GA.initial_population()
  • To set the wights of a model you can use .set_weights() built-in function:
for chromosome in population:
	model.set_weights(chromosome)
	# then evaluate the chromosome (i.e assign its final score)
  • After calculating the scores for each chromosome, it's time to select the top-performers:
# Selection:
# 'scores' is a list of length = population_size
# 'top_performers' is a list of tuples: (chromosome, it's score)
top_performers = GA.strongest_parents(population,scores)

# Make pairs:
# 'GA.pair' return a tuple of type: (chromosome, it's score)
pairs = []
while len(pairs) != GA.population_size:
	pairs.append( GA.pair(top_performers) )

# Crossover:
base_offsprings =  []
for pair in pairs:
	offsprings = GA.crossover(pair[0][0], pair[1][0])
	# 'offsprings' contains two chromosomes
	base_offsprings.append(offsprings[-1])

# Mutation:
new_population = GA.mutation(base_offsprings)

And that's it :)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

KerasGA-1.0.0.tar.gz (3.1 kB view hashes)

Uploaded Source

Built Distribution

KerasGA-1.0.0-py3-none-any.whl (16.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page