ceres_nls: Non-linear least squares with Ceres Solver

View source: R/ceres_nls.R

ceres_nlsR Documentation

Non-linear least squares with Ceres Solver

Description

Minimises \frac{1}{2}\sum_i \rho(r_i(\theta)^2) over the parameters \theta, optionally within bounds, where the residuals r_i are computed by an R function and \rho is an optional robust loss function.

Usage

ceres_nls(fn, par, ..., jac = NULL, lower = -Inf, upper = Inf,
          loss = c("linear", "huber", "soft_l1", "cauchy", "arctan", "tukey"),
          loss_scale = 1, vcov = TRUE, control = ceres_control())

## S3 method for class 'ceres_nls'
coef(object, ...)
## S3 method for class 'ceres_nls'
residuals(object, ...)
## S3 method for class 'ceres_nls'
vcov(object, ...)
## S3 method for class 'ceres_nls'
deviance(object, ...)
## S3 method for class 'ceres_nls'
df.residual(object, ...)
## S3 method for class 'ceres_nls'
print(x, digits = max(3L, getOption("digits") - 3L), ...)
## S3 method for class 'ceres_nls'
summary(object, ...)
## S3 method for class 'summary.ceres_nls'
print(x, digits = max(3L, getOption("digits") - 3L), ...)

Arguments

fn

a function fn(par, ...) returning the numeric vector of residuals. Its length must not change between calls. Non-finite values during the solve make Ceres reject that step.

par

a numeric vector of starting values. Its names are passed on to fn and jac and used in the results.

...

further arguments passed to fn and jac. For the methods, ignored.

jac

an optional function jac(par, ...) returning the Jacobian of the residuals, a numeric matrix with one row per residual and one column per parameter. If NULL, finite differences are used, which never evaluate fn outside the bounds.

lower, upper

bounds on the parameters: a single value, a vector with one value per parameter, or a vector named by some of the parameters, in which case the others are unbounded. A parameter with equal lower and upper bounds is fixed at that value and is not counted as an estimate.

loss

the loss function \rho, applied to each residual. With "linear" this is ordinary least squares. The others reduce the influence of outliers, see ‘Details’.

loss_scale

a positive number, the scale of the loss function: roughly the size of residual above which it starts to reduce the influence of an observation. It is in the units of the residuals, so the default of 1 is rarely right for your data. Ignored with loss = "linear".

vcov

if TRUE, compute the covariance matrix of the estimates. It is not available with a robust loss, see ‘Details’.

control

options for the solver, from ceres_control.

object, x

an object of class "ceres_nls", or "summary.ceres_nls" for its print method.

digits

the number of significant digits to print.

Details

With scale a and s = r^2, the loss functions are those of Ceres Solver:

"huber" s for s \le a^2, otherwise 2a\sqrt{s} - a^2
"soft_l1" 2a^2(\sqrt{1 + s/a^2} - 1)
"cauchy" a^2\log(1 + s/a^2)
"arctan" a\arctan(s/a)
"tukey" \frac{a^2}{3}(1 - (1 - s/a^2)^3) for s \le a^2, otherwise a^2/3

With a parameter at a bound, Ceres Solver alone can stop while the other parameters are far from their optimum, and report convergence. So parameters pushed against a bound are held there and the others solved again, in stages, releasing any that the gradient pulls back inside. max_iter applies to each stage. A bounded fit is reported as converged only if a Gauss-Newton step in the free parameters is predicted to reduce the objective by a negligible amount, relative to the objective. This takes more calls of fn than an unbounded fit.

The covariance matrix is \hat\sigma^2 (J^\top J)^{-1} with \hat\sigma^2 the residual sum of squares divided by the residual degrees of freedom, as in nls. That variance estimate assumes the linear loss, so with a robust loss vcov is NULL and a message says so. It is also NULL, with a warning, if the Jacobian is rank deficient, and has a warning if a parameter ends up at a bound, where the usual standard errors are not valid.

fn and jac are always called on the main R thread, one at a time. Each point costs one call of fn, plus one call of jac or up to 2 * length(par) further calls of fn for the finite differences, when Ceres needs the Jacobian there. An error or interrupt in fn or jac stops the solve and is passed on to the caller, and Ceres may also print a line about the failed evaluation. If the solver does not converge, or an interrupt arrives between calls of fn and jac, there is a warning and the result has the best point found so far.

For more accurate estimates, or fewer calls of fn, change function_tol and parameter_tol in ceres_control.

Value

ceres_nls() returns a list of class "ceres_nls" with

par

the estimates.

residuals

the residuals at the estimates.

jacobian

the Jacobian of the residuals at the estimates.

vcov

the covariance matrix of the estimates, or NULL.

cost

the objective at the estimates, including the loss function.

initial_cost

the objective at par.

rss

the residual sum of squares, without the loss function.

converged

TRUE if Ceres reports convergence.

status, message

the termination type and message from Ceres.

iterations

the number of iterations.

n_evals

the number of calls of fn and jac.

time

the time spent in the solver, in seconds.

trace

a data frame with one row per iteration, with the stage it belongs to. Only bounded fits can have more than one stage.

at_bound

a logical vector, TRUE for estimated parameters at a bound.

fixed

a logical vector, TRUE for parameters with equal bounds.

loss, loss_scale, n, call

the loss function and its scale, the number of residuals and the call.

See Also

ceres_control, nls. For large problems, where calling R for every evaluation is too slow, write the residuals in C++: see CxxFlags.

Examples

set.seed(1)
x <- seq(0, 5, length.out = 100)
y <- exp(0.3 * x + 0.1) + rnorm(100, sd = 0.2)
y[c(20, 60)] <- y[c(20, 60)] + 10
resid_exp <- function(p, x, y) y - exp(p[["m"]] * x + p[["c"]])

## ordinary least squares is pulled away by the two outliers
fit <- ceres_nls(resid_exp, c(m = 0, c = 0), x = x, y = y)
summary(fit)

## a robust loss, with m constrained to be positive
robust <- ceres_nls(resid_exp, c(m = 0.2, c = 0), x = x, y = y,
                    lower = c(m = 0), loss = "cauchy", loss_scale = 0.5,
                    vcov = FALSE)
coef(robust)

ceres documentation built on Nov. 28, 2026, 1:07 a.m.