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


Release history Release notifications

This version

1.0.0

Download files

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

Files for KerasGA, version 1.0.0
Filename, size File type Python version Upload date Hashes
Filename, size KerasGA-1.0.0-py3-none-any.whl (16.5 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size KerasGA-1.0.0.tar.gz (3.1 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page