5 个版本 (破坏性)
| 0.5.1 | 2024 年 4 月 16 日 | 
|---|---|
| 0.5.0 |  | 
| 0.4.0 | 2024 年 2 月 27 日 | 
| 0.3.0 | 2024 年 2 月 23 日 | 
| 0.0.0 |  | 
#80 在 机器学习
每月 <618 次下载
44KB
929 行
neat
使用 genetic-rs 实现的 NEAT 算法。
特性
- rayon - 在 NeuralNetwork结构上使用并行化,并将rayon特性添加到genetic-rs重新导出。
- serde - 添加 NNTSerde 结构并允许序列化 NeuralNetworkTopology
- crossover - 在 NeuralNetworkTopology上实现CrossoverReproduction 特性,并将crossover特性添加到genetic-rs重新导出。
你喜欢这个仓库并想支持它吗?如果是这样,留下一个 ⭐
如何使用
在处理此 crate 时,您需要在代理的 DNA 中使用 NeuralNetworkTopology 结构,并在最终想要测试其性能时使用 NeuralNetwork::from。此 crate 的其余部分也随此 crate 一起重新导出。
以下是一个使用此 crate 的示例
use neat::*;
#[derive(Clone, RandomlyMutable, DivisionReproduction)]
struct MyAgentDNA {
    network: NeuralNetworkTopology<1, 2>,
}
impl GenerateRandom for MyAgentDNA {
    fn gen_random(rng: &mut impl rand::Rng) -> Self {
        Self {
            network: NeuralNetworkTopology::new(0.01, 3, rng),
        }
    }
}
struct MyAgent {
    network: NeuralNetwork<1, 2>,
    // ... other state
}
impl From<&MyAgentDNA> for MyAgent {
    fn from(value: &MyAgentDNA) -> Self {
        Self {
            network: NeuralNetwork::from(&value.network),
        }
    }
}
fn fitness(dna: &MyAgentDNA) -> f32 {
    // agent will simply try to predict whether a number is greater than 0.5
    let mut agent = MyAgent::from(dna);
    let mut rng = rand::thread_rng();
    let mut fitness = 0;
    // use repeated tests to avoid situational bias and some local maximums, overall providing more accurate score
    for _ in 0..10 {
        let n = rng.gen::<f32>();
        let above = n > 0.5;
        let res = agent.network.predict([n]);
        let resi = res.iter().max_index();
        if resi == 0 ^ above {
            // agent did not guess correctly, punish slightly (too much will hinder exploration)
            fitness -= 0.5;
            continue;
        }
        // agent guessed correctly, they become more fit.
        fitness += 3.;
    }
    fitness
}
fn main() {
    let mut rng = rand::thread_rng();
    let mut sim = GeneticSim::new(
        Vec::gen_random(&mut rng, 100),
        fitness,
        division_pruning_nextgen,
    );
    // simulate 100 generations
    for _ in 0..100 {
        sim.next_generation();
    }
    // display fitness results
    let fits: Vec<_> = sim.entities
        .iter()
        .map(fitness)
        .collect();
    dbg!(&fits, fits.iter().max());
}
许可证
此 crate 适用于 MIT 许可证
依赖项
~0.7–1.5MB
~32K SLoC