diff --git a/examples/optim.rs b/examples/optim.rs new file mode 100644 index 00000000..13964c05 --- /dev/null +++ b/examples/optim.rs @@ -0,0 +1,39 @@ +#[macro_use] +extern crate peroxide; +use peroxide::fuga::*; + +fn main() { + // To prepare noise + let normal = Normal(0f64, 0.1f64); + let normal2 = Normal(0f64, 100f64); + + // Noise to domain + let mut x = seq(0., 99., 1f64); + x = zip_with(|a, b| (a + b).abs(), &x, &normal.sample(x.len())); + + // Noise to image + let mut y = x.fmap(|t| t.powi(2)); + y = zip_with(|a, b| a + b, &y, &normal2.sample(y.len())); + + // Initial parameter + let n_init = vec![1f64]; + let data = hstack!(x.clone(), y.clone()); + + // Optimizer setting + let mut opt = Optimizer::new(data, quad); + let p = opt.set_init_param(n_init) + .set_max_iter(50) + .set_method(LevenbergMarquardt) + .optimize(); + p.print(); // Optimized parameter + opt.get_error().print(); // Optimized RMSE +} + +fn quad(x: &Vec, n: Vec) -> Option> { + Some( + x.clone().into_iter() + .map(|t| AD1(t, 0f64)) + .map(|t| t.pow(n[0])) + .collect() + ) +} diff --git a/src/numerical/optimize.rs b/src/numerical/optimize.rs index 3cc0431f..5b43c154 100644 --- a/src/numerical/optimize.rs +++ b/src/numerical/optimize.rs @@ -73,12 +73,10 @@ //! p.print(); // Optimized parameter //! opt.get_error().print(); // Optimized RMSE //! -//! // To prepare plotting -//! let z = quad(&x, p.to_ad_vec()).unwrap().to_f64_vec(); -//! //! // Plot //! //#[cfg(feature = "plot")] //! //{ +//! // let z = quad(&x, p.to_ad_vec()).unwrap().to_f64_vec(); //! // let mut plt = Plot2D::new(); //! // plt.set_domain(x) //! // .insert_image(y) // plot data @@ -94,7 +92,7 @@ //! fn quad(x: &Vec, n: Vec) -> Option> { //! Some( //! x.clone().into_iter() -//! .map(|t| AD::from(t)) +//! .map(|t| AD1(t, 0f64)) //! .map(|t| t.pow(n[0])) //! .collect() //! )