genetic-algorithm-library

A generic algorithm library

Usage no npm install needed!

<script type="module">
  import geneticAlgorithmLibrary from 'https://cdn.skypack.dev/genetic-algorithm-library';
</script>

README

Genetic Algorithm library

Usage

Here is a simple example that compute the square root of 2 using a genetic algorithm

import {GeneticOptimizer, GeneticOptimizerOptions, EvaluatedSample, MINIMIZE} from "genetic-algorithm-library";
 
/**
 * A simple optimizer that will 'compute' sqrt of 2
 */
class Optimizer extends GeneticOptimizer<number> {
 
    constructor() {
        super();
    }
 
    // OVERRIDE
    protected crossover(parents: Array<number>): Array<number> {
        // each pair of parent produces 3 children
        return [
            parents[0] * 0.3 + parents[1] * 0.7,
            (parents[0] + parents[1]) * 0.5,
            parents[0] * 0.7 + parents[1] * 0.3
        ];
    }
 
    // OVERRIDE
    protected evaluateGenotype(genotype: number): number {
        return Math.abs(Math.sqrt(2) - genotype);
    }
 
    // OVERRIDE
    protected generateOneGenotype(): number {
        // wow look at this 10
        return Math.random() * 10;
    }
 
    // OVERRIDE
    protected getNumberOfCrossoverParent(): number {
        return 2;
    }
 
    // OVERRIDE
    protected mutate(genotype: number): number {
        // because why not
        return (genotype + Math.random() * 5) * 0.5;
    }
 
    getBestSample(): EvaluatedSample<number> {
        return this.samples[0];
    }
}
 
// initialize the model
const optimizer = new Optimizer();
 
// train the model
optimizer.evolve();
optimizer.evolve();
optimizer.evolve();
optimizer.evolve();
optimizer.evolve();
 
console.log(optimizer.getBestSample());
// &> { genotype: 1.4142135623730951, score: 0 }