#genetic #generics #implemented #bbte #algorithm #varan-tavers #optim

bbte_optim_tzim1773_genetic

VaranTavers使用泛型实现的遗传(类似)算法

1 个不稳定版本

0.1.0 2019年11月1日

#72 in #genetic

GPL-3.0-or-later

790KB
276

包含 (WOFF字体,190KB) doc/FiraSans-Medium.woff,(WOFF字体,185KB) doc/FiraSans-Regular.woff,(WOFF字体,94KB) doc/SourceSerifPro-Bold.ttf.woff,(WOFF字体,89KB) doc/SourceSerifPro-Regular.ttf.woff,(WOFF字体,56KB) doc/SourceCodePro-Regular.woff,(WOFF字体,56KB) doc/SourceCodePro-Semibold.woff 和更多.

bbte_optim_tzim1773_genetic

VaranTavers使用泛型实现的遗传(类似)算法

这个库仅适用于个人使用,所以它可能比其他可用的选项要差,但是你可以尝试一下,也许会很有趣。

此库可在crates.io上找到,您可以使用以下方式将其包含在基于cargo的项目中

[dependencies]                                                                    
bbte_optim_tzim1773_genetic = "0.1.0"

此项目可能涉及接口更改,使用"^0.1.0"符号时请用户小心。

使用示例

(我们尝试最大化函数:5 - x^2)

use rand::prelude::*;
use bbte_optim_tzim1773_genetic::Genetic;

fn main() {
    let agent = || {
        let mut rng = thread_rng();
        rng.gen_range(-5.0, 5.0)
    };
    
    let fit = |a: &f64| 5.0 - a * a;
    
    let muta = |a: &f64| {
        let mut rng = thread_rng();
        *a + rng.gen_range(-0.01, 0.01)
    };
    
    let off = |a: &f64, b: &f64| (*a + *b) / 2.0;
    
    let test: Genetic<f64> = Genetic {
        population: 100,
        max_generation: 20,
        pc: 0.5,
        pm: 0.4,
        get_random_agent: &agent,
        f_fitness: &fit,
        f_mutate: &muta,
        f_offspring: &off,
    };
    
    let simul = test.run();
    let best = test.get_best(&simul);
    
    println!("{}", simul[best]); // should be a number close to 0
}

遗传算法定义为

pub struct Genetic<'a, T> {
    /// Population size: with increased size comes increased accuracy but decreased speed
    pub population: usize,
    /// Max generation: with increased generation comes increased accuracy but decreased speed
    /// Depends on the complexity of the task. Bigger tasks require more generations.
    pub max_generation: usize,
    /// Probability of crossover ((never) 0.0 <= pc <= 1.0 (always))
    pub pc: f64,
    /// Probability of mutation ((never) 0.0 <= pm <= 1.0 (always))
    pub pm: f64,
    /// Function that returns one agent which is used in the 0th generation
    /// You can start from a given point, or use a random generator like the rand crate
    pub get_random_agent: &'a dyn Fn()->T,
    /// Function that evaluates an agent and returns it's fitness (this algorithm maximises this function)
    pub f_fitness: &'a dyn Fn(&T) -> f64,
    /// Function that mutates an agent and returns the mutated version of it
    pub f_mutate: &'a dyn Fn(&T) -> T,
    /// Function that crossovers two agents and creates an offspring
    pub f_offspring: &'a dyn Fn(&T, &T) -> T,

}

依赖项