rust-cv / levenberg-marquardt

Provides abstractions to run Levenberg-Marquardt optimization
MIT License
49 stars 15 forks source link

Add a simpler, easier to use interface for simpler problems #20

Open koute opened 9 months ago

koute commented 9 months ago

The default interface for this crate is somewhat tricky to use, especially if you want to just run Levenberg-Marquardt to pick coefficients for a simple equation with only one input and one output, so I've come up with a little helper for my own use to make things a little bit more convenient, and I thought it might be worth upstreaming it.

Here's how it's used: (assuming y = f(ws, x), where ws are the coefficients we want to calculate)

use levenberg_marquardt::Equation;

struct Problem;

impl Equation<2, f64> for Problem {
    fn equation(&self, ws: &[f64; 2], x: f64) -> f64 {
        ws[0] * 2.0 * x + ws[1] * 0.5 * x.powi(2)
    }

    fn derivatives(&self, ws: &[f64; 2], x: f64) -> [f64; 2] {
        [
            2.0 * x,
            0.5 * x.powi(2),
        ]
    }
}

let ws = [1.33, 0.66];
let xs = [1.0, 10.0, 100.0];
let ys = xs.map(|x| Problem.equation(&ws, x));
let ([w0, w1], _) = Problem.least_squares_fit(&xs, &ys, [1.5, 1.0]);
assert_relative_eq!(w0, 1.33);
assert_relative_eq!(w1, 0.66);

As you can see it's dead simple to use and it doesn't require any nalgebra acrobatics as it only uses plain old slices and arrays to pass data.

Feel free to close this PR if you feel this is unnecessary.