Mathematical Background#
Gauss-Newton optimization#
Consider a least squares problem on the form:
where \(\mathbf{r}\) is a residual function (\(\mathbb{R}^{n_p} \rightarrow \mathbb{R}^{n_r}\)) depending on the parameters \(\mathbf{p} \in \mathbb{R}^{n_p}\) and returning a vector in \(\mathbb{R}^{n_r}\).
The problem is solve using an iterative algorithm based on the Gauss-Newton method. At each iteration, an update \(\Delta \mathbf{p}\) to the current parameters \(\mathbf{p_k}\) is searched to minimize the cost function.
The solution is given by:
where \(\mathbf{r}\) is the full residual vector in \(\mathbb{R}^{n_r}\) evaluated at \(\mathbf{p_k}\) and \(\mathbf{J}\) is the full jacobian matrix in \(\mathbb{M}_{n_r, n_p}(\mathbb{R})\) containing each \(\frac{\partial r_j}{\partial p_l} \forall j \in ( 1, n_r ) \forall l \in ( 1, n_p )\).
The next iteration is performed for \(\mathbf{p_{k+1}} = \mathbf{p_k} + \Delta \mathbf{p}\) until convergence.
See also
The class pysolvegn.Term to represent a least square problem.
Using rJ-type term, this class store two Callable to compute
the residual vector \(\mathbf{r}\) (as a 1D-array with shape (n_residuals,))
and jacobian matrix \(\mathbf{J}\) (as a 2D-array with shape (n_residuals, n_parameters))
from a set of parameters \(\mathbf{p}\) (as a 1D-array with shape (n_parameters,)).
Using gH-type term, this class store two Callable to compute
the Hessian matrix \(\mathbf{H} = \mathbf{J}^T \mathbf{J}\) (as a 2D-array with shape (n_parameters, n_parameters))
and the gradient vector \(\mathbf{g} = \mathbf{J}^T \mathbf{r}\) (as a 1D-array with shape (n_parameters,))
from a set of parameters \(\mathbf{p}\) (as a 1D-array with shape (n_parameters,)).
Demonstration#
Consider a least squares problem of the form:
Developing the residuals \(\mathbf{r}(\mathbf{p})\) around the current parameters \(\mathbf{p_k}\):
where \(\mathbf{J}(\mathbf{p_k}) = \nabla \mathbf{r}(\mathbf{p_k})\) is the Jacobian of the residuals with respect to the parameters, and \(\mathbf{H}_j(\mathbf{p_k})\) is the Hessian of the \(j\)-th residual with respect to the parameters. By convention, the quantities are considered evaluated at \(\mathbf{p_k}\) such that \(\mathbf{r} = \mathbf{r}(\mathbf{p_k})\).
Therefore, for the least squares cost
Using the Taylor expansion above and retaining terms up to second order in \(\Delta \mathbf{p}\):
The gradient of the least squares cost is therefore
and its exact Hessian is
The Gauss-Newton approximation consists in neglecting the second term of the Hessian, giving
The Gauss-Newton step is then obtained by solving
When \(\mathbf{J}^T \mathbf{J}\) is invertible, this can formally be written as
Robust least squares optimization by the Gauss-Newton Method#
Robust cost functions \(\rho : \mathbb{R} \rightarrow \mathbb{R}\) can be used to reduce the influence of outliers. In that case, the standard least squares cost is replaced by a robust cost function that reduces the contribution of residuals with large errors.
Consider a robust least squares problem of the form:
where \(\mathbf{r}_j(\mathbf{p})\) is the \(j\)-th residual function (\(\mathbb{R}^{n_p} \rightarrow \mathbb{R}\)) depending on the parameters \(\mathbf{p} \in \mathbb{R}^{n_p}\).
The update \(\Delta \mathbf{p}\) to the current parameters \(\mathbf{p_k}\) is searched to minimize the cost function and the solution is given by:
Where :
The \(W\) factors are given by the following equations evaluated at \(\mathbf{p_k}\):
See also
The class pysolvegn.Term to represent a least square problem.
In addition to the Callable to compute the operators, this class stores
the robust cost function to use for the optimization problem.
This function returns the values of \(\rho\), \(\rho^{(1)}\)
and \(\rho^{(2)}\) (as a three 1D-array with shape (n_residuals,))
from the squared of the residual vector \(\|\mathbf{r}\|^2\) (as a 1D-array with shape (n_residuals,)).
Demonstration#
Consider a robust least squares problem of the form:
where \(\mathbf{r}_j(\mathbf{p})\) is the \(j\)-th scalar residual and \(\rho\) is the robust cost function.
Developing the residuals \(\mathbf{r}_j(\mathbf{p})\) around the current parameters \(\mathbf{p_k}\) gives:
where \(\mathbf{J}_j(\mathbf{p_k}) = \nabla \mathbf{r}_j(\mathbf{p_k})\) is the Jacobian of the \(j\)-th residual with respect to the parameters, and \(\mathbf{H}_j(\mathbf{p_k})\) is its Hessian. By convention, all quantities are considered evaluated at \(\mathbf{p_k}\), such that \(\mathbf{r}_j = \mathbf{r}_j(\mathbf{p_k})\).
Let \(Z_j = \| \mathbf{r}_j \|^2\) be the squared residual at the current parameters. The robust cost function can then be developed around \(Z_j\):
where \(\delta Z_j\) is the change in the squared residual resulting from the parameter update:
Using the Taylor expansion of the residual and retaining terms up to second order in \(\Delta \mathbf{p}\):
In a similar way, the squared term \(\delta Z_j^2\) can be approximated as:
Substituting these expressions into the Taylor expansion of the robust cost function gives:
By summing over all residuals, the gradient and the Hessian of the robust cost with respect to the parameters is therefore:
The Gauss-Newton approximation consists in neglecting the second-order derivatives of the residuals. The term involving \(r_j \mathbf{H}_j\) is neglected.
Finally, defining a diagonal matrix \(W_J\) and a vector \(W_R\), the Hessian and gradient approximation can be written as:
where:
This system can be expressed as a standard least squares system by introducing a modified Jacobian and a modified residual:
Such that:
Non-positive curvature weights: fallback on \(\rho'\)#
The construction above requires \(\sqrt{W_J}\), so every diagonal element
must be strictly positive. This always holds for a convex loss function, but not for the loss functions that are designed to reject outliers. For these loss functions, \(\rho''\) is negative and dominates \(\rho'\) for large residuals:
Loss |
\(\rho'(Z)\) |
\(W_J(Z) = \rho'(Z) + 2\rho''(Z) Z\) |
\(W_J \leq 0\) when |
|---|---|---|---|
|
\(1\) |
\(1\) |
never |
|
\((1 + Z)^{-1/2}\) |
\((1 + Z)^{-3/2}\) |
never |
|
\(1\) if \(Z \leq 1\), \(Z^{-1/2}\) otherwise |
\(1\) if \(Z \leq 1\), \(0\) otherwise |
\(Z > 1\) |
|
\((1 + Z)^{-1}\) |
\((1 - Z)(1 + Z)^{-2}\) |
\(Z \geq 1\) |
|
\((1 + Z^2)^{-1}\) |
\((1 - 3Z^2)(1 + Z^2)^{-2}\) |
\(Z \geq 1/\sqrt{3}\) |
|
\((1 - Z)^2\) if \(Z \leq 1\), \(0\) otherwise |
\((1 - Z)(1 - 5Z)\) if \(Z \leq 1\), \(0\) otherwise |
\(Z \geq 1/5\) |
A negative \(W_{J,j}\) means that the cost of the \(j\)-th residual is locally concave: the corresponding contribution \(W_{J,j} \mathbf{J}_j^T \mathbf{J}_j\) to the Hessian is negative semi-definite, and the total Hessian may become indefinite (the step is then no longer guaranteed to be a descent direction).
Simply clamping \(W_{J,j}\) to a small value \(\varepsilon\) is not a good solution. The gradient stays exact, but the contribution of the residual to the Hessian becomes \(\varepsilon \mathbf{J}_j^T \mathbf{J}_j \approx 0\). When many residuals are in this regime (e.g. a poor initial guess, or residuals expressed in a unit much larger than the threshold of the loss), the Hessian becomes almost singular and the step explodes.
Instead, the second-order correction of the loss is dropped for these residuals (as in Ceres Solver):
with \(\varepsilon = 10^{-12}\). In the fallback case, the modified residual and Jacobian become:
which is exactly the classical Iteratively Reweighted Least Squares (IRLS) weighting: the residual is treated as a standard least squares residual with the weight \(\rho'(Z_j)\). This choice has three properties:
The gradient is unchanged: in both cases \(\tilde{\mathbf{J}}_j^T \tilde{\mathbf{r}}_j = \rho'(Z_j) \mathbf{J}_j^T \mathbf{r}_j\), so the stationary points of the problem are the same.
The Hessian approximation stays positive semi-definite: each contribution \(W_{J,j} \mathbf{J}_j^T \mathbf{J}_j\) uses \(W_{J,j} \geq 0\). When it is invertible, the step \(\Delta \mathbf{p} = -\mathbf{H}^{-1} \mathbf{g}\) is a descent direction (\(\mathbf{g}^T \Delta \mathbf{p} < 0\)).
The residual keeps a curvature proportional to its influence: an outlier with a small \(\rho'(Z_j)\) contributes little to both the gradient and the Hessian, instead of contributing to the gradient only.
If \(\rho'(Z_j) \leq 0\) too (e.g. "tukey" beyond its threshold, where
\(\rho' = 0\)), then \(W_{J,j} = 0\) and the residual is simply ignored:
\(\tilde{\mathbf{r}}_j = 0\) and \(\tilde{\mathbf{J}}_j = 0\).
Warning
With a redescending loss such as "tukey", if all the residuals are beyond the
threshold, the gradient and the Hessian are both zero and the system is singular.
These loss functions require a good initial guess (e.g. the solution obtained
with "cauchy" or "huber").
Note
The fallback only modifies the Hessian approximation, never the gradient or the
cost. The Levenberg-Marquardt damping (damping="lm" or "lm-diag") remains
useful on top of it to control the step length far from the solution.
Scaling a problem#
All the predefined loss functions have their transition between the quadratic regime (\(\rho(Z) \approx Z\), inliers) and the robust regime (outliers) around \(Z = 1\), that is \(|\mathbf{r}_j| \approx 1\) in the unit of the residuals.
The result of a robust optimization therefore depends on the unit of the residuals. For example, for residuals expressed in millimeters with a noise of a few millimeters, all the residuals are in the robust regime of the loss function: every residual is treated as an outlier and the optimization can fail or converge to a poor solution. The same problem expressed in meters works as expected.
To control the threshold, a soft threshold \(C > 0\) (loss_scale),
expressed in the unit of the residuals, is introduced. The loss function
\(\rho\) is replaced by its scaled version:
The transition is now located at \(Z = C^2\), that is
\(|\mathbf{r}_j| \approx C\). This definition is the same as the
f_scale argument of scipy.optimize.least_squares.
Derivatives#
Denoting \(u_j = Z_j / C^2\) the dimensionless squared residual, the derivatives of the scaled loss function are:
The weights of the robust Gauss-Newton system become:
Both weights are dimensionless and only depend on the ratio \(|\mathbf{r}_j| / C\). The fallback on \(\rho'\) described in the previous section is applied in the same way on \(W_{J,j}\).
Properties#
Small residuals are unchanged. Since all the predefined loss functions satisfy \(\rho(0) = 0\) and \(\rho'(0) = 1\), for \(|\mathbf{r}_j| \ll C\):
\[\rho_C(Z_j) \approx C^2 \frac{Z_j}{C^2} = Z_j\]The inliers are treated as in a standard least squares problem, whatever \(C\).
The linear loss is invariant. For \(\rho(Z) = Z\), \(\rho_C(Z) = Z\) for every \(C\).
Unit invariance. If the residuals are multiplied by a factor \(\alpha\) (change of unit) and \(C\) is multiplied by the same factor, then \(u_j\) is unchanged and the cost is multiplied by \(\alpha^2\):
\[\rho_{\alpha C}(\alpha^2 Z_j) = \alpha^2 \rho_C(Z_j)\]The minimizer is therefore the same: the solution does not depend on the unit of the residuals, as long as \(C\) is expressed in the same unit.
Equivalence with a weighted problem. Since
\[\rho_C\left(\|\mathbf{r}_j\|^2\right) = C^2 \rho\left(\left\|\frac{\mathbf{r}_j}{C}\right\|^2\right)\]a term with the loss \(\rho_C\) and the weight \(w_i\) is equivalent to a term with the loss \(\rho\), the residuals \(\mathbf{r}_i / C\), the Jacobian \(\mathbf{J}_i / C\) and the weight \(w_i C^2\).
loss_scaleperforms this normalization automatically, without modifying the residual functions or the weight.Any loss function can be scaled. The scaling only uses the values of \(\rho\), \(\rho'\) and \(\rho''\), so it applies in the same way to the predefined loss functions and to a custom loss function.
Tip
A good starting value for \(C\) is the expected magnitude of the inlier residuals, e.g. two or three times the standard deviation of the measurement noise. Residuals larger than a few \(C\) are then progressively considered as outliers.
See also
The loss_scale argument of pysolvegn.Term (and
pysolvegn.BatchTerm), which stores the soft threshold \(C\) and
replaces the loss function \(\rho\) (predefined or custom) by \(\rho_C\).
The same \(C\) is used for all the residuals of a term, so terms with
residuals in different units should use different values.
Adding regularization to the Gauss-Newton update#
In many optimization problems, the objective function is composed of several least squares terms. The first term usually corresponds to the data fitting problem, while the remaining terms can be used to regularize the solution.
The resulting objective function can be written as:
where \(i\) indexes the different least squares terms and \(j\) indexes the residuals within each term.
The scalar \(w_i\) is the weight associated with the \(i\)-th term, and \(\rho_i\) is its robust cost function. Each term can therefore have its own residuals, weight, and robust cost function.
By convention, the first term (\(i=0\)) is the main least squares term, which usually contains the data residuals. The remaining terms (\(i \geq 1\)) are considered regularization terms.
Note
A regularization term can be used to introduce additional constraints or prior information into the optimization problem. Its weight \(w_i\) controls its influence relative to the other terms.
For each term, the robust Gauss-Newton approximation described above provides a modified residual \(\tilde{\mathbf{r}}_i\) and a modified Jacobian \(\tilde{\mathbf{J}}_i\).
Since the objective function is the sum of all the terms, their contributions to the gradient and Hessian approximation can be summed directly. The global Gauss-Newton system is therefore:
See also
The class pysolvegn.Term to represent a term in a least square problem.
In addition to the Callable to compute the operators, this class stores
the weight associated to the term.
Changing the parametrization#
Consider a least squares problem of the form:
In some applications, it is convenient to optimize the problem using a different set of parameters than those expected by the residual functions. This can be achieved by introducing a parametrization that maps the input parameters \(\mathbf{p}_{\mathrm{in}}\) to the output parameters \(\mathbf{p}_{\mathrm{out}}\):
where \(\mathbf{p}_{\mathrm{in}} \in \mathbb{R}^{n_{p_{\mathrm{in}}}}\) are the parameters optimized by the Gauss-Newton algorithm, while \(\mathbf{p}_{\mathrm{out}} \in \mathbb{R}^{n_{p_{\mathrm{out}}}}\) are the parameters passed to the residual functions.
The optimization problem can therefore be rewritten directly in terms of the input parameters:
At each iteration, the Gauss-Newton algorithm searches for an update \(\Delta\mathbf{p}_{\mathrm{in}}\) in the space of input parameters. The corresponding output parameters are obtained through the parametrization:
To compute the Jacobian of the residuals with respect to the parameters being optimized, we introduce the Jacobian of the parametrization:
Using the chain rule, the Jacobian of the \(j\)-th residual of the \(i\)-th term with respect to the input parameters is:
Therefore, the parametrization only modifies the Jacobian used by the Gauss-Newton algorithm. The robust weighting described in the previous section is applied in exactly the same way, giving:
while the modified residual remains:
The Gauss-Newton system is consequently solved in the input parameter space:
The important point is that \(\Delta\mathbf{p}_{\mathrm{in}}\) has the dimension of the input parameter space. The parametrization is therefore accounted for through \(\mathbf{J}_P\) when computing the Jacobians.
Once the Gauss-Newton system has been solved, the input parameters are updated as:
The corresponding output parameters are then obtained by applying the parametrization:
This formulation separates the parameters used by the optimization algorithm from those used by the residual functions. The Gauss-Newton algorithm operates entirely in the input parameter space, while the parametrization maps these parameters to the output space required by the optimization terms.
See also
The class pysolvegn.Parametrization represents a parameter
transformation by storing the functions required to compute the output
parameters and the Jacobian of the transformation.
Given the input parameters \(\mathbf{p}_{\mathrm{in}}\) as a 1D-array
with shape (n_parameters,), the parametrization computes the output
parameters \(\mathbf{p}_{\mathrm{out}}\) as a 1D-array with shape
(n_p_outputs,) and the Jacobian \(\mathbf{J}_P\) as a 2D-array
with shape (n_p_outputs, n_parameters)
Solving a batch of independent problems#
Many applications require solving the same least squares problem for a large number of independent datasets (e.g. one fit per pixel, per point or per image). Consider \(K\) independent problems sharing the same terms, indexed by \(k \in (1, K)\):
The residual functions, the robust cost functions \(\rho_i\) and the parametrization \(P\) have the same form for all the problems (\(P\) is strictly identical for all of them), but each problem has its own parameters \(\mathbf{p}_{\mathrm{in},k} \in \mathbb{R}^{n_p}\), its own data (the residuals depend on \(k\)) and possibly its own weights \(w_{i,k}\).
Block-diagonal structure#
These \(K\) problems could be stacked into a single problem with \(K n_p\) parameters. Since the residuals of the problem \(k\) only depend on \(\mathbf{p}_{\mathrm{in},k}\), the stacked Jacobian is block-diagonal, and so is the Gauss-Newton system:
where, for each problem \(k\), the Hessian approximation and the gradient are built exactly as in the previous sections (robust weighting, fallback on \(\rho'\), loss scaling and parametrization):
The global system therefore decouples into \(K\) small independent systems of size \(n_p \times n_p\):
Instead of one system of size \(K n_p\), the batch solver solves \(K\) systems of size \(n_p\) in a single vectorized operation. The cost of an iteration is linear in \(K\), and all the quantities are stored as arrays with a leading batch dimension:
Quantity |
Shape |
|---|---|
Parameters \(\mathbf{p}_{\mathrm{in}}\) |
|
Residuals \(\mathbf{r}_i\) |
|
Jacobians \(\mathbf{J}_i\) |
|
Jacobian of the parametrization \(\mathbf{J}_P\) |
|
Gradients \(\mathbf{g}\) |
|
Hessians \(\mathbf{H}\) |
|
Weights \(w_i\) |
scalar, or |
Independent convergence#
Since the problems are independent, each one converges at its own pace: an easy
problem may converge in a few iterations, while a difficult one requires many more.
The stopping criteria (ftol, atol, gtol, xtol, ptol) are therefore
evaluated for each problem separately, using its own cost \(F_k\), gradient
\(\mathbf{g}_k\) and update \(\Delta \mathbf{p}_{\mathrm{in},k}\). For instance,
the problem \(k\) satisfies ftol when:
The solver maintains the set \(\mathcal{A}^{(n)}\) of the problems still in processing at iteration \(n\) (the active set), with \(m = |\mathcal{A}^{(n)}| \leq K\):
At each iteration, only the \(m\) active problems are evaluated, and their parameters are updated:
This has two consequences:
The converged problems are not modified anymore. Their parameters are frozen at the iteration at which they satisfied a criterion, exactly as if each problem had been solved alone with
pysolvegn.solve().The work decreases during the optimization. The cost of an iteration is proportional to the number \(m\) of active problems, not to \(K\).
A problem can also be stopped without being converged: when its system is singular,
when NaN or Inf values appear in its parameters, or when a global limit is reached
(max_iteration, max_time or the callback), which stops all the remaining
active problems. The solver reports, for each problem, whether it has converged.
Note
The global cost \(\sum_k F_k\) has no particular meaning for independent problems (a single badly fitted problem dominates it). The logged values are therefore averaged over the active problems.
Evaluating a subset of problems#
Because of the active set, the callables of the terms are called with the parameters of the \(m\) active problems only, together with their indices in the batch:
The row \(a\) of every output must only depend on the row \(a\) of the
parameters and on the data of the problem \(k_a\) (selected with the indices,
e.g. observations[indices]). The number \(m\) changes from one call to the
next, so the callables must never assume \(m = K\).
The parametrization \(P\) is the same for all the problems: it does not depend on \(k\), so its callables only receive the parameters of the \(m\) active problems (without indices) and are applied row by row:
The same convention is used for the vector weights: the weights of the active problems are \((w_{i,k_1}, \ldots, w_{i,k_m})\). The weights must be strictly positive: a zero weight would cancel all the contributions of a problem and make its system \(\mathbf{H}_k\) singular.
Note
The loss scale \(C_i\) (loss_scale) of a term is shared by all the
problems of the batch. Problems whose residuals have very different magnitudes
should be normalized in the residual functions (e.g. by dividing by a
per-problem noise level selected with the indices).
See also
The function pysolvegn.solve_batch() solves a batch of independent problems.
The class pysolvegn.BatchTerm represents a term of the batch. Its
Callable take the parameters as a 2D-array with shape (m, n_parameters)
and the indices as a 1D-array with shape (m,), and return the residuals as
a 2D-array with shape (m, n_residuals) and the Jacobians as a 3D-array with
shape (m, n_residuals, n_parameters). Its weight is either a scalar or a
1D-array with shape (K,).
The class pysolvegn.BatchParametrization represents the parameter
transformation \(P\) of the batch. The same transformation is applied to all
the problems: its Callable only take the input parameters as a 2D-array with
shape (m, n_parameters) (no indices) and return the output parameters with shape
(m, n_p_outputs) and the Jacobians \(\mathbf{J}_{P,k}\) with shape
(m, n_p_outputs, n_parameters).