Brute force, isotonic regression and gradient checks
| Problem | Minimise a function of a few variables by exhaustive search over a grid; fit a monotone sequence to data by least squares; approximate a gradient by finite differences and check an analytic gradient against it |
| Devised by | Miriam Ayer, H. Daniel Brunk, George Ewing, W. T. Reid and Edward Silverman (1955), the pool-adjacent-violators algorithm; Richard Barlow, David Bartholomew, John Bremner and H. Daniel Brunk (1972), isotonic regression |
| Accuracy | Brute force: the grid spacing, or the local minimiser’s tolerance after polishing. Isotonic regression: exact, to rounding. Forward differences: about relative |
| Cost | Brute force: evaluations for points on each of axes. Isotonic regression: . Finite-difference gradient: evaluations |
| Read first | Direct search: the Nelder-Mead and Powell methods |
| API | brute, BruteResult; isotonic_regression, IsotonicResult; approx_fprime, check_grad |
Overview
Three small tools from scipy.optimize:
bruteevaluates the objective at every point of a rectangular grid and returns the best one, optionally polished by a local method. In one to three dimensions it is the most reliable way to find a global minimum of an inexpensive function. It is also the easiest to trust, since it looks everywhere. Beyond about four dimensions the grid grows too fast.isotonic_regressionfinds the non-decreasing (or non-increasing) sequence closest to the data in weighted least squares. It is used for dose-response curves, for calibrating classifier scores into probabilities, and wherever a relationship is known to be monotone but its shape is not.approx_fprimeandcheck_gradcompute forward-difference gradients. Their main use is to catch errors in hand-coded gradients before handing them to a gradient-based optimiser.
Where it is used
Simple tools that are often exactly what is needed.
- Brute force. A coarse search over a grid of a few parameters finds a good starting point for a local optimiser, and verifies that a result is not stuck in a poor local minimum.
- Isotonic regression. Fitting a monotone curve, such as a calibration curve (the response of a sensor must increase with the input), dose-response relationships and probability calibration of classifiers.
- Gradient checks. Comparing analytic derivatives with finite differences to find bugs in model code.
History
Isotonic regression was introduced by Miriam Ayer, H. Daniel Brunk and colleagues (1955) for estimating monotone probabilities from bioassays. Their pool-adjacent-violators algorithm (PAVA) is still the method of choice. Richard Barlow, David Bartholomew, John Bremner and Brunk’s book (1972) developed the theory of order-restricted inference. Grid search is as old as numerical computation. Checking derivatives by finite differences has been standard practice since at least the 1960s, when optimisation codes first asked their users for gradients.
The idea
Brute force. With equally spaced points from to on each axis, the best grid point is within half a grid spacing of the global minimiser. This holds provided the basin of the global minimum is wider than the spacing. A local method started from it (Nelder-Mead here, fmin in SciPy) then converges to the minimiser itself.
Isotonic regression. The problem has a solution that is constant on blocks of consecutive indices, each block taking the weighted mean of its data. PAVA builds the blocks from left to right. Each new observation starts its own block. While the last block’s mean is not above the one before it, the two violate the order and are pooled into one block with the combined weighted mean. Each observation is pooled at most once, so the cost is .
Forward differences. has truncation error and rounding error about . The two balance at , SciPy’s default, and the gradient is then accurate to about relative. check_grad returns the Euclidean distance between the analytic and finite-difference gradients. That distance is of the order of times the curvature when the gradient is right, and of the order of the gradient itself when it is wrong.
Implementation
/// Minimises `f` by evaluating it at every point of the grid with `ns` equally spaced points
/// from `lo` to `hi` (both included) on each axis (SciPy's `brute` with `(lo, hi)` ranges and
/// `Ns = ns`, SciPy's default 20). With `finish`, the best grid point is polished by Nelder-Mead,
/// as SciPy's default `finish = fmin`, and kept only if the polished point is better.
pub fn brute(f: impl Fn(&[f64]) -> f64, ranges: &[(f64, f64)], ns: usize, finish: bool) -> Result<BruteResult, ErrorsJSL> {
if ranges.is_empty() || ns < 2 || ranges.iter().any(|(a, b)| !a.is_finite() || !b.is_finite()) {
return Err(ErrorsJSL::InvalidInputRange("brute: need at least one finite range and two points per axis"));
}
let d = ranges.len();
let total = ns.checked_pow(d as u32).filter(|&t| t <= 100_000_000).ok_or(ErrorsJSL::InvalidInputRange("brute: grid too large"))?;
let grid: Vec<Vec<f64>> = ranges.iter().map(|&(a, b)| (0..ns).map(|i| if i + 1 == ns { b } else { a + (b - a) * i as f64 / (ns - 1) as f64 }).collect()).collect();
let mut values = Vec::with_capacity(total);
let mut point = vec![0.0; d];
let (mut best, mut best_x) = (f64::INFINITY, vec![f64::NAN; d]);
for flat in 0..total {
let mut r = flat;
for k in (0..d).rev() {
point[k] = grid[k][r % ns];
r /= ns;
}
let v = f(&point);
// The first of equal minima, as NumPy's argmin.
if v < best || best_x[0].is_nan() {
best = v;
best_x.clone_from(&point);
}
values.push(v);
}
if finish {
let mut nm = NelderMeadMethod::new();
nm.set_tolerance(Some(1e-14));
nm.set_max_iterations(Some(5000));
if let Ok(r) = nm.gradient_free_minimize(&Wrapped(&f), best_x.clone())
&& r.objective_value < best
{
best = r.objective_value;
best_x = r.parameters;
}
}
Ok(BruteResult { x: best_x, fun: best, grid, values })
}
/// The weighted least-squares fit of `y` by a non-decreasing (or, with `increasing = false`,
/// non-increasing) sequence, `min Σ wᵢ (xᵢ − yᵢ)²` subject to `x₁ ≤ x₂ ≤ … ≤ xₙ` (SciPy's
/// `isotonic_regression`). The pool-adjacent-violators algorithm merges each new observation
/// with the blocks before it while their weighted means are out of order; every block's value
/// is its weighted mean, in O(n) time. `weights` default to one and must be positive.
pub fn isotonic_regression(y: &[f64], weights: Option<&[f64]>, increasing: bool) -> Result<IsotonicResult, ErrorsJSL> {
let n = y.len();
let w: Vec<f64> = match weights {
Some(w) if w.len() != n => return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), n))),
Some(w) if w.iter().any(|v| v.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) || !v.is_finite()) => {
return Err(ErrorsJSL::InvalidInputRange("isotonic_regression: weights must be positive and finite"));
}
Some(w) => w.to_vec(),
None => vec![1.0; n],
};
let sign = if increasing { 1.0 } else { -1.0 };
// Blocks as (weighted mean, weight, start).
let mut blocks: Vec<(f64, f64, usize)> = Vec::with_capacity(n);
for i in 0..n {
let (mut mean, mut weight, mut start) = (sign * y[i], w[i], i);
while let Some(&(m, wt, s)) = blocks.last() {
if m < mean {
break;
}
mean = (m * wt + mean * weight) / (wt + weight);
weight += wt;
start = s;
blocks.pop();
}
blocks.push((mean, weight, start));
}
let mut x = vec![0.0; n];
let mut starts: Vec<usize> = blocks.iter().map(|b| b.2).collect();
starts.push(n);
for (k, b) in blocks.iter().enumerate() {
x[starts[k]..starts[k + 1]].fill(sign * b.0);
}
Ok(IsotonicResult { x, weights: blocks.iter().map(|b| b.1).collect(), blocks: starts })
}
/// The Euclidean norm of the difference between an analytic gradient `grad(x)` and the
/// forward-difference gradient of `f` (SciPy's `check_grad`): about `√ε` times the size of the
/// second derivatives when `grad` is right, of the order of the gradient itself when it is wrong.
pub fn check_grad(f: impl Fn(&[f64]) -> f64, grad: impl Fn(&[f64]) -> Vec<f64>, x: &[f64], epsilon: f64) -> f64 {
let g = grad(x);
let a = approx_fprime(f, x, epsilon);
g.iter().zip(&a).map(|(u, v)| (u - v) * (u - v)).sum::<f64>().sqrt()
}
brutereturns every grid value (values, last axis fastest) as well as the minimiser, like SciPy’sfull_output. The finishing Nelder-Mead runs to a much tighter tolerance than SciPy’sfmin(xtol = 1e-4), and its result is kept only if it improves on the grid point.isotonic_regressionreturns the block boundaries and block weights as SciPy does. A decreasing fit is the increasing fit of , negated.- The finite-difference step is the representable , as in SciPy.
In practice
The references are from SciPy 1.17.1, written by book/generator/data/make_calc28_refs.py:
Table 5.16. Brute force, isotonic regression and finite-difference gradients against `scipy.optimize`.
| Problem | Result | Difference from SciPy | Notes |
|---|---|---|---|
isotonic_regression, increasing | 60 points, 14 blocks | 2e-15 (values), 7e-15 (weights) | identical blocks |
isotonic_regression, decreasing | 60 points, 1 block | 9e-16 (values), 0 (weights) | identical blocks |
approx_fprime, Rosenbrock in 4-D | 4 components | 0 | relative; same steps as SciPy |
check_grad, Rosenbrock in 4-D | 1.615402e-5 | 9e-10 | relative |
brute, Himmelblau, 20 × 20 grid | (2.894737, 1.842105) | 0 | same grid point and value |
brute, then Nelder-Mead | (3.0000000103, 2.0000000129) | 4e-5 | SciPy’s fmin stops at xtol = 10⁻⁴; the library is 1e-8 from (3, 2) |
The isotonic fits have the same blocks as SciPy’s, with values equal to rounding. The finite-difference gradient is bit-for-bit SciPy’s. check_grad returns a difference of two nearly equal gradients, so it agrees only to relative. That is far more than its purpose needs. On Himmelblau’s function the grid search picks the same grid point as SciPy. After polishing, the library’s point is from the minimiser , SciPy’s .
Figure 5.14. Weighted isotonic regression of 60 points. The fit is a staircase of 14 blocks, each at the weighted mean of its data; the long last step pools the points that fall back after index 30.
Strengths
- Brute force with a finish is robust for small problems with several local minima, and gives a picture of the whole landscape for free.
- PAVA is exact and linear in time.
check_gradcatches wrong gradients immediately: a correct one gives about relative difference, a wrong one about 1.
Weaknesses
- The grid has points: 20 per axis is million evaluations in five dimensions.
- A minimum in a basin narrower than the grid spacing can be missed entirely.
- Forward differences give only half the digits; for accurate derivatives, see numerical differentiation.
Exercises
- Show that the isotonic regression of a sequence that is already non-decreasing is the sequence itself, and that of a non-increasing sequence is its weighted mean.
- Show that in the solution each block’s value is its weighted mean. (Hint: fix the blocks and minimise over a common value.)
- With at , find the step that minimises the error of the forward difference in double precision, and the resulting error.
- How many evaluations does
brutewith and a Nelder-Mead finish need in two dimensions, roughly?
Hints and answers
- No pair violates the order, so no blocks are pooled. In a non-increasing sequence every new point violates the order with everything before it, so all points pool into one block.
- Within a block of fixed extent the constraint is inactive, and is minimised by .
- The error is , minimised at with error .
- 400 grid points, plus typically 100–200 for Nelder-Mead in two dimensions.
Further reading
- M. Ayer, H. D. Brunk, G. M. Ewing, W. T. Reid and E. Silverman, “An empirical distribution function for sampling with incomplete information”, Annals of Mathematical Statistics 26 (1955) 641–647.
- R. E. Barlow, D. J. Bartholomew, J. M. Bremner and H. D. Brunk, Statistical Inference under Order Restrictions, Wiley (1972).
- J. de Leeuw, K. Hornik and P. Mair, “Isotone optimization in R: pool-adjacent-violators algorithm (PAVA) and active set methods”, Journal of Statistical Software 32 (2009) 1–24.
- J. Nocedal and S. J. Wright, Numerical Optimization, 2nd ed., Springer (2006), section 8.1 on finite-difference derivatives.