High-level interfaces¶
The SciPy-style entry points, and where to start. They take the objective in its most natural
form (residuals, or a scalar), choose a method by name and pass that method’s settings
through: least_squares() forwards its other keyword arguments, and minimize()
forwards options. The method-specific solvers they run document every
setting.
- piazzi.least_squares(fun, x0, *, loss='linear', f_scale=1.0, method='lm', has_aux=False, curvature='irls', manifold=None, **kwargs)[source]¶
Minimise a sum of squared residuals, like
scipy.optimize.least_squares().Minimises
0.5 * sum(f_scale^2 * rho((r / f_scale)^2))withr = fun(x). This builds the normal equations withpiazzi.least_squares_system()and solves them withpiazzi.gauss_newton(), using the residuals alone, without the Jacobian, for value-only evaluations. With amanifoldsuch aspiazzi.SE3,x0is a point on it (a(4, 4)pose) and every iterate stays on it.- Parameters:
fun (
Callable) –fun(x) -> r, or(r, aux)withhas_aux=True, whereris a tensor of residuals of any shape andxhas the shape ofx0.x0 (
torch.Tensor) – starting point, of any shape, or a point onmanifold.
- Keyword Arguments:
loss (
strorCallable, optional) – a name frompiazzi.LOSSESor a callablerho(z), as inpiazzi.least_squares_system(). Default:"linear"f_scale (
float, optional) – soft margin between inlier and outlier residuals, in the units ofr. Default:1.0method (
str, optional) –"lm"(Levenberg-Marquardt) or"gn"(Gauss-Newton). Default:"lm"has_aux (
bool, optional) – whetherfunalso returns an auxiliary output (any tree of tensors), returned detached inresult.auxandinfo.aux. Default:Falsecurvature (
str, optional) –"irls"or"scipy", as inpiazzi.least_squares_system(). Default:"irls"manifold (
piazzi.Manifold, optional) – keepsxon a manifold (seepiazzi.Manifold). Default:None**kwargs – other keyword arguments of
piazzi.gauss_newton(), such asmax_iter,step_tol,max_step,damping,linear_solver,callbackorverbose.
- Returns:
OptimizeResult – as for
piazzi.gauss_newton().result.funis the cost, not the residuals.
See also
piazzi.gauss_newton(): the method this runs (method="lm"or"gn"), which documents the other keyword arguments.piazzi.least_squares_system(): the normal equations this builds fromfun.piazzi.scipy.least_squares(): the same problem with SciPy’s solvers.
Example:
>>> t = torch.linspace(0, 4, 40) >>> y = 2.5 * torch.exp(-1.3 * t) >>> y[::10] += 2.0 # outliers >>> def residuals(theta): ... return theta[0] * torch.exp(-theta[1] * t) - y >>> res = piazzi.least_squares(residuals, torch.tensor([1.0, 0.5]), loss="cauchy", f_scale=0.1) >>> res.x tensor([2.5026, 1.3005])
- piazzi.minimize(fun, x0, method='lbfgs', *, has_aux=False, manifold=None, callback=None, verbose=False, options=None)[source]¶
Minimise a scalar function of a tensor, like
scipy.optimize.minimize().Gradients come from autograd. As in SciPy,
methodnames the solver and its settings go inoptions.piazzi.scipy.minimize()has the same calling convention and runs SciPy’s methods, so you can swap backends to compare them.methodcan also be atorch.optim.Optimizersubclass, such astorch.optim.LBFGSortorch.optim.Adam.optionsthen holds its constructor arguments (lr,line_search_fn, …) plus piazzi’smax_iter(default100),step_tol(stop once a step is below it in max-norm; off by default, since some optimisers, such as Rprop, skip steps) and, for LBFGS,max_eval. Each iteration is one optimiser step,callbackis called after each, and every evaluation computes the value and gradient together.torch.optim.LBFGSruns one L-BFGS iteration per step, withmax_iter,max_eval(defaultmax_iter * 5 // 4) and itstolerance_gradandtolerance_changetests applied to the whole run, so it follows the same path as a single upstreamstepcall. The point its line search accepts is not evaluated twice.result.rawis the optimiser.- Parameters:
fun (
Callable) –fun(x) -> loss, or(loss, aux)withhas_aux=True, wherelossis a scalar tensor differentiable with respect toxandxhas the shape ofx0.x0 (
torch.Tensor) – starting point, of any shape, or a point onmanifold.method (
strortype, optional) – a name frompiazzi.MINIMIZE_METHODS(case insensitive;"lbfgs", that ispiazzi.lbfgs(), or"torchmin-bfgs","torchmin-trust-exact", … for the methods ofpiazzi.torchmin.minimize(), which needs pytorch-minimize), or atorch.optim.Optimizersubclass (the class, not an instance). Default:"lbfgs"
- Keyword Arguments:
has_aux (
bool, optional) – whetherfunalso returns an auxiliary output (any tree of tensors), returned detached inresult.auxandinfo.aux. Default:Falsemanifold (
piazzi.Manifold, optional) – keepsxon a manifold such aspiazzi.SE3; seepiazzi.lbfgs(). Not supported withtorch.optim.Optimizermethods. Default:Nonecallback (
Callable, optional) – called with anpiazzi.IterationInfoafter every iteration; returningTruestops the run. Default:Noneverbose (
boolorint, optional) – print a table of the run’s progress withpiazzi.print_progress()before callingcallback:Trueprints every iteration and an integerkeveryk-th one. Default:Falseoptions (
dict, optional) – settings for the method, for example{"max_iter": 500, "step_tol": 1e-8}. Default:None
- Returns:
OptimizeResult – the method’s result; see
piazzi.lbfgs().
See also
piazzi.lbfgs(): the default method, which documents itsoptions.piazzi.scipy.minimize(): the same problem with SciPy’s methods.
Example:
>>> def rosenbrock(x): ... return (100 * (x[1:] - x[:-1] ** 2) ** 2 + (1 - x[:-1]) ** 2).sum() >>> x0 = torch.tensor([-1.2, 1.0], dtype=torch.float64) >>> piazzi.minimize(rosenbrock, x0).x tensor([1.0000, 1.0000], dtype=torch.float64) >>> res = piazzi.minimize(rosenbrock, x0, method=torch.optim.LBFGS, options={"line_search_fn": "strong_wolfe"}) >>> res.x tensor([1.0000, 1.0000], dtype=torch.float64)
- piazzi.finite_difference(fun, *, eps=None, scheme='central', manifold=None)[source]¶
Make a black-box function look differentiable, so that any solver can use it.
Use this when
fun(x) -> Tensorcannot be differentiated by autograd: a non-differentiable renderer or simulator, a library working on NumPy arrays, a measurement. The returned function gives the same values asfunand has finite-difference derivatives, in forward mode (torch.func.jacfwd(), whichpiazzi.least_squares()uses) and in reverse mode (backward, whichpiazzi.minimize()uses), so solvers,manifold=and robust losses work unchanged.Every Jacobian costs
n("forward") or2n("central") extra calls offunfornparameters, which is why this is a last resort: prefer autograd where it works. The solver’sn_fun_gradcounts only its own evaluations, so read the total from then_evalsattribute of the returned function, which counts every call offun.funis called without gradient tracking, on a copy of its argument, and its result is copied. It must return a tensor (has_auxis not supported) and be deterministic: noise larger than the step ruins the differences. It runs on the device and in the dtype ofx, and so do the differences. Prefer float64: in float32 the default step is large (about5e-3) and a central difference is accurate to roughly1e-3relative error at best.The numerics follow the numerical Jacobian of
torch.autograd.gradcheck(central differences, one coordinate at a time), with the step relative to the coordinate:eps * max(|x_i|, 1).With
manifold=M, pass the same manifold to the solver. The solver differentiatesfun(M.plus(x, delta))atdelta = 0; the wrapper then recovers the tangent coordinatesdeltaof each direction and evaluatesfun(M.plus(x, +-h * delta)), sofunonly ever sees points on the manifold (a valid rotation matrix, say), a Jacobian costs2 * tangent_sizecalls, and the stephisepsin tangent coordinates (not scaled by|x|). Withoutmanifold=, the differences are taken in ambient space along the tangent directions, sofunis evaluated at points that leave the manifold byO(eps^2).- Parameters:
fun (
Callable) – the black-box functionfun(x) -> Tensorof a tensorx.- Keyword Arguments:
eps (
float, optional) – relative step. Default:finfo.eps ** (1/3)for"central"(about6e-6in float64) andfinfo.eps ** (1/2)for"forward", the steps that balance truncation and rounding error.scheme (
str, optional) –"central"(errorO(eps^2),2ncalls) or"forward"(errorO(eps),ncalls, reusing the value atxthat the solver has just computed). Default:"central"manifold (
piazzi.Manifold, optional) – thepiazzi.Manifoldthat the solver is given, if any, as above. Default:None
- Returns:
Callable –
fd_fun(x) -> Tensorwith the values offunand finite-difference derivatives. Itsn_evalsattribute counts the calls offunso far, the finite-difference ones included.
Example:
>>> def simulate(x): # a stand-in for code that autograd cannot see through ... y = x.detach().numpy() ... return torch.from_numpy(y**2 + y[::-1]) >>> fd_fun = piazzi.finite_difference(simulate) >>> target = torch.tensor([5.0, 8.0, 7.0], dtype=torch.float64) >>> res = piazzi.least_squares(lambda x: fd_fun(x) - target, torch.ones(3, dtype=torch.float64)) >>> torch.allclose(fd_fun(res.x), target, atol=1e-6) True >>> fd_fun.n_evals > res.n_system # every difference calls simulate True
- piazzi.MINIMIZE_METHODS: dict[str, Callable[..., OptimizeResult]]¶
Scalar minimisers available to
minimize()by name (currently"lbfgs"). To add one, register a callablemethod(fun, x0, *, has_aux, callback, **options)under a lower-case name.minimize()passesmanifold=only when one is given, so a method that doesn’t support manifolds need not accept it.