lib_jsl_optimization/finite_differences.rs
1//! Forward-difference gradients and gradient checking (SciPy's `optimize.approx_fprime` and
2//! `optimize.check_grad`).
3//!
4//! See the book entry [Brute force, isotonic regression and gradient checks](https://jwkunz.github.io/lib_jsl/book/optimization/brute-isotonic.html).
5
6// ANCHOR: approx_fprime
7/// The forward-difference gradient `(f(x + hεᵢ) − f(x))/h` of `f` at `x` (SciPy's `approx_fprime`),
8/// with step `epsilon` (SciPy's default is `√ε ≈ 1.49·10⁻⁸`); the step actually used is the
9/// representable `(xᵢ + h) − xᵢ`. Its error is about `h|f''|/2 + 2ε|f|/h`, smallest near the default.
10pub fn approx_fprime(f: impl Fn(&[f64]) -> f64, x: &[f64], epsilon: f64) -> Vec<f64> {
11 let fx = f(x);
12 let mut xh = x.to_vec();
13 (0..x.len())
14 .map(|i| {
15 xh[i] = x[i] + epsilon;
16 let dx = xh[i] - x[i];
17 let g = (f(&xh) - fx) / dx;
18 xh[i] = x[i];
19 g
20 })
21 .collect()
22}
23// ANCHOR_END: approx_fprime
24
25// ANCHOR: check_grad
26/// The Euclidean norm of the difference between an analytic gradient `grad(x)` and the
27/// forward-difference gradient of `f` (SciPy's `check_grad`): about `√ε` times the size of the
28/// second derivatives when `grad` is right, of the order of the gradient itself when it is wrong.
29pub fn check_grad(f: impl Fn(&[f64]) -> f64, grad: impl Fn(&[f64]) -> Vec<f64>, x: &[f64], epsilon: f64) -> f64 {
30 let g = grad(x);
31 let a = approx_fprime(f, x, epsilon);
32 g.iter().zip(&a).map(|(u, v)| (u - v) * (u - v)).sum::<f64>().sqrt()
33}
34// ANCHOR_END: check_grad
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 #[test]
41 fn rosenbrock_gradient_checks() {
42 let f = |x: &[f64]| (1.0 - x[0]).powi(2) + 100.0 * (x[1] - x[0] * x[0]).powi(2);
43 let g = |x: &[f64]| vec![-2.0 * (1.0 - x[0]) - 400.0 * x[0] * (x[1] - x[0] * x[0]), 200.0 * (x[1] - x[0] * x[0])];
44 let h = f64::EPSILON.sqrt();
45 let x = [-1.2, 1.0];
46 assert!(check_grad(f, g, &x, h) < 1e-4);
47 let wrong = |x: &[f64]| vec![g(x)[0], 0.0];
48 assert!(check_grad(f, wrong, &x, h) > 50.0);
49 let a = approx_fprime(f, &x, h);
50 assert!((a[0] - g(&x)[0]).abs() < 1e-4 * g(&x)[0].abs());
51 }
52}