Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

write more tests #49

Merged
merged 3 commits into from
Apr 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,68 @@ pub use topology::*;

#[cfg(feature = "serde")]
pub use nnt_serde::*;

#[cfg(test)]
mod tests {
use super::*;
use rand::prelude::*;

#[derive(RandomlyMutable, DivisionReproduction, Clone)]
struct AgentDNA {
network: NeuralNetworkTopology<2, 1>,
}

impl Prunable for AgentDNA {}

impl GenerateRandom for AgentDNA {
fn gen_random(rng: &mut impl Rng) -> Self {
Self {
network: NeuralNetworkTopology::new(0.01, 3, rng),
}
}
}

#[test]
fn basic_test() {
let fitness = |g: &AgentDNA| {
let network = NeuralNetwork::from(&g.network);
let mut fitness = 0.;
let mut rng = rand::thread_rng();

for _ in 0..100 {
let n = rng.gen::<f32>() * 10000.;
let base = rng.gen::<f32>() * 10.;
let expected = n.log(base);

let [answer] = network.predict([n, base]);
network.flush_state();

fitness += 5. / (answer - expected).abs();
}

fitness
};

#[cfg(not(feature = "rayon"))]
let mut rng = rand::thread_rng();

let mut sim = GeneticSim::new(
#[cfg(not(feature = "rayon"))]
Vec::gen_random(&mut rng, 100),
#[cfg(feature = "rayon")]
Vec::gen_random(100),
fitness,
division_pruning_nextgen,
);

for _ in 0..100 {
sim.next_generation();
}

let mut fits: Vec<_> = sim.genomes.iter().map(fitness).collect();

fits.sort_by(|a, b| a.partial_cmp(&b).unwrap());

dbg!(fits);
}
}