Neat gru rust

Overview

neat-gru-rust

CICD Crates.io Downloads License

Documentation

Crates.io doc

Examples

XOR

Snake

Right now this is the only working example. You can run it via:

cargo run --example example

How to use

In Cargo.toml:

[dependencies]
neat-gru = 1.0.0"

Create a struct that implements the Game trait

use neat_gru::game::Game;
use neat_gru::neural_network::NeuralNetwork;
use neat_gru::topology::Topology;
struct Player {
    pub net: NeuralNetwork<f64>,
}

impl Player {
    pub fn new(net: NeuralNetwork<f64>) -> Player {
        Player {
            net,
        }
    }
}

struct Simulation {
    players: Vec<Player>,
}

impl Simulation {
    pub fn new() -> Simulation {
        Simulation {
            players: Vec::new(),
        }
    }
}

impl Game<f64> for Simulation {
    // Loss function
    fn run_generation(&mut self) -> Vec<f64> {
        let inputs = get_inputs();
        self.players.iter().map(|p| {
            let output = p.net.compute(inputs);
            let scores = compute_score(output, target);
            scores
        }).collect()
    }

    // Reset networks
    fn reset_players(&mut self, nets: Vec
   <
   f64>>) {
        
   self.players.
   clear();
        
   self.players 
   = nets
            .
   into_iter()
            .
   map(Player
   ::new)
            .
   collect();
    }

    
   // Called at the end of training
    
   fn 
   post_training(
   &
   mut 
   self, history: 
   &[Topology<
   f64>]) {
        
   // Iter on best topologies and upload the best one
    }
}

  

Async run_generation (has to be run inside an async runtime like Tokio)

#[async_trait]
impl GameAsync<f64> for Simulation {
    // Loss function
    async fn run_generation(&mut self) -> Vec<f64> {
        let inputs = get_inputs().await;
        self.players.iter().map(|p| {
            let output = p.net.compute(inputs);
            let scores = compute_score(output, target);
            scores
        }).collect()
    }
}

Launch a training

fn run_sim() {
    let mut sim = Simulation::new();

    let mut runner = Train::new(&mut sim);
    runner
        .inputs(input_count)
        .outputs(output_count as i32)
        .iterations(nb_generations as i32)
        .max_layers((hidden_layers + 2) as i32)
        .max_per_layers(hidden_layers as i32)
        .max_species(max_species as i32)
        .max_individuals(max_individuals as i32)
        .delta_threshold(2.) // Delta parameter from NEAT paper
        .formula(0.8, 0.8, 0.3) // c1, c2 and c3 from NEAT paper
        .access_train_object(Box::new(|train| {
            let species_count = train.species_count();
            println!("Species count: {}", species_count);
        })) // Callback called after `reset_players` that gives you access to the train object during training
        .start(); // .start_async().await for async version
}
Comments
  • What does GRU mean for this crate?

    What does GRU mean for this crate?

    I know GRU is a variant of RNN in the context of neural network of machine learning. And in the original NEAT paper, the author did mention a kind of RNN, with which the game double pole is solved----the RNN here is not what we refer to in the context of machine learning, right?

    But what does GRU mean in the context of NEAT for this crate? Does it mean that NEAT could generate GRU structure (like in this paper), and with which could solve non-Markov decision problem?

    opened by dbsxdbsx 10
  • Cleanup

    Cleanup

    These changes are sometimes simplifications sometimes unnecessary references. None of them change the functionality of anything but are mostly just easier to read or slightly increase Performance(like using Mutex::get_mut instead of Mutex::lock).

    opened by Nereuxofficial 5
  • Error Handling and further cleanup

    Error Handling and further cleanup

    While the examples do successfully compile but do not really work yet, there are some further Cleanups along with Changes like deriving the Debug trait to many structs which makes it possible to use it on types like the Snake in the example.

    I also made an error.rs for the train module which makes error handling possible and is shorter than using panic twice.

    opened by Nereuxofficial 2
  • README example doesn't work currently

    README example doesn't work currently

    Here is my current (edited) code from the README. Upon putting it in a main function there are multiple functions that don't exist(compute_score and get_inputs()). My proposal to fix this would be to put the example in an examples folder similar to this blog. This makes it easier to check if the code in the examples code works. I will work on this in the following days.

    use neat_gru::game::{Game, GameAsync};
    use neat_gru::neural_network::nn::NeuralNetwork;
    use neat_gru::topology::topology::Topology;
    use async_trait::async_trait;
    use neat_gru::train::train::Train;
    struct Player {
        pub net: NeuralNetwork<f64>,
    }
    
    impl Player {
        pub fn new(net: NeuralNetwork<f64>) -> Player {
            Player {
                net,
            }
        }
    }
    
    struct Simulation {
        players: Vec<Player>,
    }
    
    impl Simulation {
        pub fn new() -> Simulation {
            Simulation {
                players: Vec::new(),
            }
        }
    }
    
    impl Game<f64> for Simulation {
        /// Loss function
        fn run_generation(&mut self) -> Vec<f64> {
            let inputs = get_inputs();
            self.players.iter().map(|p| {
                let output = p.net.compute(inputs);
                let scores = compute_score(output, target);
                scores
            }).collect()
        }
    
        /// Reset networks
        fn reset_players(&mut self, nets: Vec<NeuralNetwork<f64>>) {
            self.players.clear();
            self.players = nets
                .into_iter()
                .map(Player::new)
                .collect();
        }
    
        /// Called at the end of training
        fn post_training(&mut self, history: &[Topology<f64>]) {
            // Iter on best topologies and upload the best one
        }
    }
    
    const INPUT_COUNT: usize = 2;
    const OUTPUT_COUNT: usize = 1;
    const NB_GENERATIONS: usize = 5;
    const ITERATIONS: usize = 1000;
    const HIDDEN_LAYERS: usize = 2;
    const MAX_INDIVIDUALS: usize = 100;
    fn run_sim() {
        let mut sim = Simulation::new();
    
        let mut runner = Train::new(&mut sim);
        runner
            .inputs(INPUT_COUNT)
            .outputs(OUTPUT_COUNT)
            .iterations(NB_GENERATIONS)
            .max_layers(HIDDEN_LAYERS + 2)
            .max_per_layers(HIDDEN_LAYERS)
            .max_individuals(MAX_INDIVIDUALS)
            .delta_threshold(2.) // Delta parameter from NEAT paper
            .formula(0.8, 0.8, 0.3) // c1, c2 and c3 from NEAT paper
            .access_train_object(Box::new(|train| {
                let species_count = train.species_count();
                println!("Species count: {}", species_count);
            })) // Callback called after `reset_players` that gives you access to the train object during training
            .start(); // .start_async().await for async version
    }
    fn main(){
        run_sim();
    }
    
    opened by Nereuxofficial 1
  • Update licensing wiht authors list

    Update licensing wiht authors list

    @Nereuxofficial @BenInTheBox Following the recent event with Microsoft, I added an AUTHORS file, feel free to edit or remove your information from the list

    opened by sakex 0
  • Feature/relu

    Feature/relu

    I finally had time to implement this. This time i implemented it as a feature, which should be nicer to use, since it allows users this: neat-gru-rust = { version="1.1.1", features="relu"} but without it the tanh function will be used.

    opened by Nereuxofficial 1
  • Using ReLu as an Option instead of Sigmoid

    Using ReLu as an Option instead of Sigmoid

    This is more of a proof of concept since in order for it to get merged it would have to be optional, i think it's a nice idea since it would be much faster. You can also try it out using my flappy bird for or just replace the version with { git = "https://github.com/Nereuxofficial/neat-gru-rust"} in another project

    Using Cargo criterion and looking at the generated HTML pages you can also see the performance difference between sigmoid and ReLu with nice charts.

    opened by Nereuxofficial 2
Owner
I like computers
null
A stupid macro that compiles and executes Rust and spits the output directly into your Rust code

inline-rust This is a stupid macro inspired by inline-python that compiles and executes Rust and spits the output directly into your Rust code. There

William 19 Nov 29, 2022
Learn-rust - An in-depth resource to learn Rust 馃

Learning Rust ?? Hello friend! ?? Welcome to my "Learning Rust" repo, a home for my notes as I'm learning Rust. I'm structuring everything into lesson

Lazar Nikolov 7 Jan 28, 2022
A highly modular Bitcoin Lightning library written in Rust. Its Rust-Lightning, not Rusty's Lightning!

Rust-Lightning is a Bitcoin Lightning library written in Rust. The main crate, lightning, does not handle networking, persistence, or any other I/O. Thus, it is runtime-agnostic, but users must implement basic networking logic, chain interactions, and disk storage. More information is available in the About section.

Lightning Dev Kit 850 Jan 3, 2023
Telegram bot help you to run Rust code in Telegram via Rust playground

RPG_BOT (Rust Playground Bot) Telegram bot help you to run Rust code in Telegram via Rust playground Bot interface The bot supports 3 straightforward

TheAwiteb 8 Dec 6, 2022
`Debug` in rust, but only supports valid rust syntax and outputs nicely formatted using pretty-please

dbg-pls A Debug-like trait for rust that outputs properly formatted code Showcase Take the following code: let code = r#" [ "Hello, World!

Conrad Ludgate 12 Dec 22, 2022
Playing with web dev in Rust. This is a sample Rust microservice that can be deployed on Kubernetes.

Playing with web dev in Rust. This is a sample Rust microservice that can be deployed on Kubernetes.

Andr茅 Gomes 10 Nov 17, 2022
馃悁 Building a federated alternative to reddit in rust

Lemmy A link aggregator / Reddit clone for the fediverse. Join Lemmy 路 Documentation 路 Report Bug 路 Request Feature 路 Releases 路 Code of Conduct About

LemmyNet 7.2k Jan 3, 2023
Applied offensive security with Rust

Black Hat Rust - Early Access Deep dive into offensive security with the Rust programming language Buy the book now! Summary Whether in movies or main

Sylvain Kerkour 2.2k Jan 2, 2023
Rholang runtime in rust

Rholang Runtime A rholang runtime written in Rust.

Jerry.Wang 17 Sep 23, 2022
Easy-to-use optional function arguments for Rust

OptArgs uses const generics to ensure compile-time correctness. I've taken the liberty of expanding and humanizing the macros in the reference examples.

Jonathan Kelley 37 Nov 18, 2022
A language server for lua written in rust

lua-analyzer lua-analyzer is a lsp server for lua. This is mostly for me to learn the lsp protocol and language analysis so suggestions are helpful. T

null 61 Dec 11, 2022
Rust library that can be reset if you think it's slow

GoodbyeKT Rust library that can be reset if you think it's slow

null 39 Jun 16, 2022
Cargo - The Rust package manager

Cargo downloads your Rust project鈥檚 dependencies and compiles your project.

The Rust Programming Language 9.5k Jan 4, 2023
A copypastable guide to implementing simple derive macros in Rust.

A copypastable guide to implementing simple derive macros in Rust. The goal Let's say we have a trait with a getter trait MyTrait {

Imbolc 131 Dec 27, 2022
Rust ABI safe code generator

CGlue offers an easy way to ABI (application binary interface) safety. Just a few annotations and your trait is ready to go!

Auri 142 Jan 2, 2023
An example project demonstrating integration with Rust for the ESP32-S2 and ESP32-C3 microcontrollers.

Rust ESP32 Example An example project demonstrating integration with Rust for the ESP32-S2 and ESP32-C3 microcontrollers.

Espressif Systems 303 Jan 4, 2023
Notion Offical API client library for rust

Notion API client library for rust.

Jake Swenson 65 Dec 26, 2022
Rust library for program synthesis of string transformations from input-output examples 馃敭

Synox implements program synthesis of string transformations from input-output examples. Perhaps the most well-known use of string program synthesis in end-user programs is the Flash Fill feature in Excel. These string transformations are learned from input-output examples.

Anish Athalye 21 Apr 27, 2022
Rust for the Windows App SDK

Rust for the Windows App SDK The windows-app crate makes the Windows App SDK (formerly known as Project Reunion) available to Rust developers.

Microsoft 212 Nov 22, 2022