Expand description
§neat
Implementation of the NEAT algorithm using genetic-rs.
§Features
- serde - Implements
SerializeandDeserializeon most of the types in this crate.
Do you like this crate and want to support it? If so, leave a ⭐
§How To Use
The NeuralNetwork<I, O> struct is the main type exported by this crate. The I is the number of input neurons, and O is the number of output neurons. It implements GenerateRandom, RandomlyMutable, Mitosis, and Crossover, with a lot of customizability. This means that you can use it standalone as your organism’s entire genome:
use neat::*;
fn fitness(net: &NeuralNetwork<5, 6>) -> f32 {
// ideally you'd test multiple times for consistency,
// but this is just a simple example.
// it's also generally good practice to normalize your inputs between -1..1,
// but NEAT is usually flexible enough to still work anyways
let inputs = [1.0, 2.0, 3.0, 4.0, 5.0];
let outputs = net.predict(inputs);
// simple fitness: sum of outputs
// you should replace this with a real fitness test
outputs.iter().sum()
}
fn main() {
let mut rng = rand::rng();
let mut sim = GeneticSim::new(
Vec::gen_random(&mut rng, 100),
FitnessEliminator::new_without_observer(fitness),
CrossoverRepopulator::new(0.25, ReproductionSettings::default()),
);
sim.perform_generations(100);
}Or just a part of a more complex genome:
ⓘ
use neat::*;
#[derive(Clone, Debug)]
struct PhysicalStats {
strength: f32,
speed: f32,
// ...
}
// ... implement `RandomlyMutable`, `GenerateRandom`, `Crossover`, `Default`, etc.
#[derive(Clone, Debug, GenerateRandom, RandomlyMutable, Mitosis, Crossover)]
#[randmut(create_context(name = MyGenomeMutate, derive(Default, Clone, Debug)))]
#[mitosis(create_context(name = MyGenomeReproduce, derive(Default, Clone, Debug)))]
#[crossover(with_context = MyGenomeReproduce)]
struct MyGenome {
brain: NeuralNetwork<4, 2>,
stats: PhysicalStats,
}
fn fitness(genome: &MyGenome) -> f32 {
let inputs = [1.0, 2.0, 3.0, 4.0];
let outputs = genome.brain.predict(inputs);
// fitness uses both brain output and stats
outputs.iter().sum::<f32>() + genome.stats.strength + genome.stats.speed
}
// main is the exact same as before
fn main() {
let mut rng = rand::rng();
let mut sim = GeneticSim::new(
Vec::gen_random(&mut rng, 100),
FitnessEliminator::new_without_observer(fitness),
CrossoverRepopulator::new(0.25, MyGenomeReproduce::default()),
);
sim.perform_generations(100);
}If you want more in-depth examples, look at the examples. You can also check out the genetic-rs docs to see what other options you have to customize your genetic simulation.
§License
This crate falls under the MIT license
Re-exports§
pub use genetic_rs;pub use neuralnet::*;
Modules§
- activation
- Contains the types surrounding activation functions.
- genetic_
rs_ common - The crate containing the core traits and structs of genetic-rs.
- neuralnet
- Contains the
NeuralNetworkand related types.
Macros§
- activation_
fn - Creates an
ActivationFnobject from a function
Structs§
- Crossover
Repopulator - Repopulator that uses crossover reproduction to create new genomes.
- Fitness
Eliminator - A fitness-based eliminator that eliminates genomes based on their fitness scores.
- Fitness
Eliminator Builder - A builder for
FitnessEliminatorto make it easier to construct with default parameters. - Fitness
Knockout Fn - A knockout function that uses a fitness function to determine the winner.
- Genetic
Sim - This struct is the main entry point for the simulation. It handles the state and evolution of the genomes based on what eliminator and repopulator it receives.
- Knockout
Eliminator - Eliminator that pits genomes against each other and eliminates the weaker ones.
- Layered
Observer - An observer that calls two observers in sequence.
Created by
FitnessObserver::layer. - Mitosis
Repopulator - Repopulator that uses division reproduction to create new genomes.
- Small
Rng - A small-state, fast, non-crypto, non-portable PRNG
- Speciated
Crossover Repopulator - Repopulator that uses crossover reproduction to create new genomes, but only between genomes of the same species.
- StdRng
- A strong, fast (amortized), non-portable RNG
- Thread
Rng - A reference to the thread-local generator
Enums§
- Action
IfOdd - The action a knockout eliminator should take if the number of genomes is odd.
- Knockout
Winner - A distinct type to help clarify the result of a knockout function.
Traits§
- Crossover
- Used in crossover-reproducing
Repopulators - Crypto
Rng - A marker trait for securely unpredictable infallible RNGs
- Distribution
- Types (distributions) that can be used to create a random instance of
T. - Eliminator
- Tests and eliminates the unfit from the simulation.
- Fitness
Fn - A trait for fitness functions. This allows for more flexibility in defining fitness functions.
Any
Fn(&G) -> f32can be used as a fitness function. - Fitness
Observer - A trait for observing fitness scores. This can be used to implement things like logging or statistics collection.
- Generate
Random - Helper trait used in the generation of random starting populations
- Generate
Random Collection - Blanket trait used on collections that contain objects implementing
GenerateRandom - Generate
Random Collection Parallel - Rayon version of the
GenerateRandomCollectiontrait - Indexed
MutRandom - Extension trait on indexable lists, providing random sampling methods.
- Indexed
Random - Extension trait on indexable lists, providing random sampling methods.
- Iterator
Random - Extension trait on iterators, providing random sampling methods.
- Knockout
Fn - A function that pits two genomes against each other and determines a winner.
- MaxIndex
- A trait for getting the index of the maximum element.
- Mitosis
- Used in dividually-reproducing
Repopulators - Randomly
Mutable - Used in other traits to randomly mutate genomes a given amount
- Repopulator
- Refills the population of the simulation based on survivors.
- Rng
- Trait for infallible random number generators
- RngExt
- User-level interface for RNGs
- Seedable
Rng - A random number generator that can be explicitly seeded.
- Slice
Random - Extension trait on slices, providing shuffling methods.
- Speciated
- Used in speciated crossover nextgens. Allows for genomes to avoid crossover with ones that are too different.