Newton's method, trust regions and Gauss-Newton
Derive Newton's method by minimizing the complete quadratic model and prove its local quadratic convergence and affine invariance. Study globalization by damped line search or trust regions, and exploit nonlinear least-squares structure with Gauss-Newton and Levenberg-Marquardt.
After this lesson you can
- Derive the Newton step and decrement and prove affine invariance.
- Prove local quadratic convergence when the Hessian is Lipschitz and nonsingular at the optimum.
- Implement damped Newton with backtracking and recognize its damped and quadratic phases.
- Solve the trust-region subproblem with the Cauchy point and dogleg method, adjusting the radius using the reduction ratio.
- Implement Gauss-Newton and Levenberg-Marquardt for curve fitting and relate them to Newton.
Before you start
- 06Armijo backtracking line searchConvergence orders and ratesStrong convexitySecond-order optimality conditionsGradient descent dynamics on quadraticsDescent direction
- 03Jacobian matrixHessian matrix
- 02Cholesky decomposition
- 09Cholesky in finite precision: stability and jitterNewton's method for nonlinear systems
Motivation: use curvature to arrive in a handful of iterations
Lesson 7’s gradient descent uses one piece of information: which way the function decreases. A step to be chosen or searched determines how far to move, tying speed to the condition number. On Rosenbrock, with Armijo backtracking from , gradient descent needs over thirteen thousand iterations to bring the gradient norm below (the cell below counts them). Damped Newton takes about twenty. For logistic regression with five variables and four hundred examples, seven steps exhaust machine precision.
The difference is which information is used. The gradient gives a direction in which decreases; the Hessian gives curvature in every direction, exactly what is missing to decide how far to move. In a parabola , gradient divided by curvature gives the exact minimum from any point. In multiple dimensions Newton’s method performs this division in each Hessian eigenvector direction at once: gradient descent with a different step, inverse curvature, in each direction.
This idea underlies much of what you will use:
- Logistic regression and generalized linear models are fitted with Newton (in statistics, IRLS: iteratively reweighted least squares). With few variables and lots of data, seven passes through the data beat thousands of gradient steps.
- The Laplace approximation in probabilistic models uses the Hessian at the mode, the same object Newton constructs.
- Interior-point methods apply Newton to a succession of barrier problems.
- Bundle adjustment, SLAM and physical-model calibration are nonlinear least-squares problems solved by Gauss-Newton and Levenberg-Marquardt, the last two sections.
- Large-scale optimizers (quasi-Newton and inexact Newton, later Adam and preconditioners) try to obtain part of this effect without its cost: per iteration.
The lesson proceeds through the Newton step as minimizer of a quadratic model, affine invariance, local quadratic convergence with proof, globalization (damped line search and trust regions), what to do when the Hessian is not positive definite, and the special structure of least squares. It ends with cost and code.
Intuition: jump to the model’s minimum
Around , the second-order Taylor polynomial is the best quadratic approximation to . Newton minimizes it completely and jumps to the paraboloid’s minimum. In the figure, blue level curves are that paraboloid at the current iterate and pass through it; the purple circle marks its stationary point, the next iterate.
Three things the figure shows, formalized in the rest of the lesson:
- With a convex model, the step reaches the model’s minimum, not necessarily that of . The farther from the optimum, the worse the model. In the convex function the jump from lands almost ninety units away because the Hessian there is nearly singular (smallest eigenvalue ), dividing by a tiny number in that direction.
- With a nonconvex model, the model’s “minimum” does not exist. A dome’s stationary point is a maximum, and a saddle’s is not an extremum. Newton seeks zeros of the gradient, not minima.
- Two remedies both limit step length: shorten it along the Newton direction (line search), or first decide how much to trust the model and then choose direction (trust region).
Definition
The model gradient is , zero at ; since the model is strictly convex, so that stationary point is its unique minimum. Substituting, and . Four frequently used facts follow:
- What is gained. : the squared decrement is twice the model’s predicted reduction. Near optimum it also estimates and is the natural stopping criterion: .
- Descent direction. if (descent direction). This holds only if .
- It is a norm. : step size measured in the curvature’s own metric. Thus it is independent of variable scaling (proved next).
- It is Newton for equations. Minimizing requires solving . Newton’s method for equation systems (numerical methods lesson) uses , and here is the gradient’s Jacobian: the same algorithm. It inherits its blindness: it solves without distinguishing minima, maxima and saddles.
If is quadratic, with , the model is exact and Newton reaches the minimum, , in one step from any point, regardless of . Compare gradient descent on quadratics, which needs on the order of steps.
Affine invariance: why Newton ignores ill-conditioning
Gradient descent depends on coordinates. Stretch a variable tenfold and the function does not change, but the Hessian eigenvalues do, along with the largest stable step and iteration count. Newton does not notice. This distinguishes it from the first-order repertoire.
Proof
By the chain rule, and . Writing and using ,
which is the first claim. For the decrement, . The final claim follows by induction: .
∎The figure uses damped Newton, not pure. No contradiction: Armijo backtracking only looks at values and directional derivative , both preserved: and . You prove this in the final proof exercise.
Consequences, from most practical to deepest:
- The Hessian condition number does not govern Newton. Stretching, rotating or scaling variables does not change iterations (in exact arithmetic; floating-point linear solves do lose digits, as any solve does). Feature normalization is unnecessary for Newton to converge, although useful for accurate solves.
- The decrement is intrinsic, independent of coordinates. Thus is a reliable stopping criterion and gradient norm is not: changes with .
- Gradient descent is Newton with the wrong Hessian. In coordinates GD takes , i.e. . Reparameterization is preconditioning with . Newton corresponds to ideal preconditioner . The chapter on second-order methods and large-scale preconditioners (lesson 14, Adam in 20, geometry in 26) seeks to approach that at reasonable cost.
- What is not invariant is Euclidean analysis and regions. Constants and of the next theorem change with , although the algorithm does not. A trust region’s Euclidean ball is not invariant either: use a scaled norm . A complete affine-invariant analysis exists for Nesterov and Nemirovski’s self-concordant functions, returning in interior-point methods.
Local quadratic convergence
Now the property justifying the method: near a nondegenerate minimum, error is squared at every step.
Proof
Let satisfy , where .
The Hessian is invertible and bounded. Since , the smallest eigenvalue of is at least (an eigenvalue moves by at most the perturbation norm). Thus and .
Step error. Since , the fundamental theorem of calculus on the segment connecting to (inside the ball) gives . Then
The bound. By Lipschitz continuity, , and , so the integral has norm at most . With the inverse Hessian bound, .
Induction. If , then : the new iterate stays in the ball and the bound applies again. Let . Then and , so .
∎Three observations about what this says and does not say:
- It is very fast, with a practical effect. With , and , below machine precision. The quadratic phase’s iteration count grows as , almost constant: six or seven steps suffice for double precision.
- Radius is a guarantee, not a limit. It is conservative. For Newton gives and converges iff (cubically, too), whereas the theorem, with and , guarantees radius . The actual convergence region may be much larger, with a complicated boundary (even fractal, already in one variable).
- If is singular, this is lost. For , : linear convergence at rate . The minimum is degenerate and its Hessian is , exactly what the theorem excludes.
Damped Newton: phases and global behavior
The theorem is local: it requires starting inside a ball. Outside it, pure Newton can make three mistakes, all in one variable:
- Move away. For , and , so . If iterates grow without bound although is smooth and convex; with they oscillate between and .
- Leave the domain, as in .
- Cycle. For , and . From the sequence is forever.
The minimal remedy is that of any descent method: accept the step only if it improves sufficiently; otherwise shorten it.
Always start with because this makes Newton what it is: if the full step is acceptable, take it. The first question is when it is accepted; the answer explains the two phases.
Proof
With an -Lipschitz Hessian, the second-order Taylor polynomial has error at most (Taylor remainder): . For , . Also , i.e. . Then
Armijo with requires , which holds if , the hypothesis.
∎The full result for strongly convex functions is proved in Boyd and Vandenberghe (Convex Optimization, section 9.5.3): with and -Lipschitz , constants exist depending on , , an upper Hessian bound, and and , such that
- Damped phase: if , then , generally with ;
- Quadratic phase: if , then and , continuing thereafter.
Total iterations are bounded by : one term depends on starting distance, the other is almost constant. The proposition above explains the second phase (why is accepted); see it in the digits figure: shaded rows are the damped phase, then and digits double. Boyd and Vandenberghe’s and are not affine invariant although the algorithm is: self-concordant analysis gives a bound with universal constants.
Indefinite Hessians: modify the Hessian or trust the model
Everything above assumes . For nonconvex functions that can fail, breaking three things. The quadratic model has no minimum, so the Newton step points toward a maximum or saddle. The direction may not descend: can be positive (always so if and ), making Armijo backtracking inappropriate: for small , rises along and the condition always fails, so the loop either never terminates or accepts a long step that may even raise (with Armijo’s right side exceeds ). Iterates may also converge to a critical point that is not a minimum, as in figure 1 with Himmelblau.
There are two solution families. The first fixes the Hessian.
Modify the Hessian
Replace by with as small as possible while positive definite. The standard method uses Cholesky as a test (Nocedal and Wright algorithm 3.3): try factoring , with if all diagonals are positive and otherwise; on failure double and repeat. The step is and always descends, since . Code inverts nothing: one Cholesky factorization and two triangular substitutions, with shift like the Cholesky stability “jitter”. This is implemented in the next cell and called “Hessian correction” in figure 1.
What matters is the form of . With it is Newton. As , and : a gradient step of size . The shift interpolates between Newton and gradient descent, step length shrinking as grows. This is exactly the same set of steps described by trust regions and Levenberg-Marquardt. A finer alternative replaces Hessian eigenvalues by (as in Dauphin et al.’s 2014 “saddle-free” Newton, seen in lesson 23) and uses the negative-curvature direction to escape.
Trust the model only as far as possible
The second family changes the approach. Instead of fixing direction and searching for length, first decide how much to trust the model, then choose the best step within that radius. This is the trust region.
Trust regions
The quadratic model approximates well near and poorly far away. Declare a radius within which to trust it, solve the model there and adjust the radius based on the result.
Compare line search: it chooses direction first, then distance; a trust region first chooses how far to move, , then the best direction under that limit. This solves the ascent-direction problem: a nonconvex model does have a minimum inside a ball.
What the subproblem solution satisfies
Proof
For any , is convex because , and its gradient vanishes at . Hence minimizes on all : . By complementary slackness, , so for all with .
∎Two readings. If and the Newton step fits in the ball, and is the Newton step: near the optimum, where the step is short, the region does not interfere. Otherwise the step is on the boundary and is for giving . This is the preceding section’s shift family with . Decomposing into eigenvectors of with eigenvalues , decreases with , so each radius has a unique . As shrinks the step rotates from Newton toward steepest descent: for large . There is a “hard case” when is orthogonal to the eigenvector of smallest eigenvalue and the radius exceeds the limit of as : no in the family reaches the boundary, and the solution is plus the multiple of the eigenvector that reaches ; the figure’s code explicitly handles it.
The Cauchy point and dogleg
Solving the exact subproblem costs several factorizations. Two cheap approximations suffice to guarantee convergence.
The Cauchy point minimizes the model on the steepest-descent segment inside the region: , with if and otherwise. It is a gradient step with optimal bounded length.
Proof
Three cases. If , and . If and , reduction is . If and , then and reduction is . All cases satisfy the bound.
∎That bound suffices for global convergence (below). Dogleg improves on the Cauchy point when by following a two-segment path: from to the model minimum along , , then to Newton step . The step is the path’s point touching the boundary: if , it is ; if , it is the first-leg intersection, ; otherwise the second-leg intersection with the circle, obtained from a quadratic equation. Along the path increases and decreases (Nocedal and Wright, lemma 4.2), so dogleg always improves on the Cauchy point. It needs one factorization per iteration. If is not positive definite, dogleg is undefined; use the Cauchy point or exact method.
Convergence
Global. Suppose is bounded below on the level set of , is Lipschitz in a neighborhood, and each step attains at least fraction of Cauchy decrease (and ). Then with , , and with , (Nocedal and Wright, theorem 4.6 for and 4.5 for ). Neither convexity nor is needed, distinguishing it from line search. If also and the subproblem is solved exactly, limit points satisfy (Conn, Gould and Toint, 2000).
Local. Near a minimum with , the Newton step fits inside the region and ratio approaches , so the radius grows and the method behaves like pure Newton: quadratic convergence. Nocedal and Wright (theorem 4.9) prove this under usual hypotheses: global and fast.
Cost and scale. Dogleg costs one factorization per iteration; the exact subproblem costs two to four. For large , approximate it with truncated conjugate gradients (Steihaug–Toint), using only Hessian-vector products and forming the basis of inexact Newton in lesson 14.
Variables with different scales. The Euclidean ball is not invariant under changing units. When variables have very different scales use a scaled norm , with diagonal .
Nonlinear least squares: Gauss-Newton and Levenberg-Marquardt
Many problems have form , with residuals (model minus data) and : curve fitting, calibration, bundle adjustment, inverse kinematics, the correction step of the iterated extended Kalman filter (iterated EKF). This form has structure. With the Jacobian of ,
(Obtain this by differentiating again.) The Hessian splits into two terms, the first known from first derivatives alone and the second from each residual’s second derivatives. The second, , vanishes when residuals are small or models nearly linear.
Three properties. It needs only first derivatives. always, so with full rank descends: , with the orthogonal projector onto ‘s columns, nonzero if . In practice use QR factorization of , not forming (which squares the condition number; see numerical least squares).
What is lost by discarding S?
Proof
The iteration is . Its derivative at is , because the term differentiating the inverse multiplies . With , . First-order expansion of at gives the formula, and the fixed-point local convergence criterion (Ostrowski’s theorem) says attracts if and repels if . Eigenvalues of are real because it is similar to symmetric . If , near , since ; the Gauss-Newton step then differs from Newton by and Newton’s quadratic convergence proof applies with that perturbation.
∎Strict local minimality (, i.e. ) only guarantees eigenvalues of exceed ; it does not prevent one exceeding . A strict minimum can repel Gauss-Newton when optimal residual is large and the model curves in the same direction. With noise size , and the rate grow with , as the figure shows.
Levenberg-Marquardt: Gauss-Newton with a trust region
Pure Gauss-Newton has no globalization: if is nearly singular the step is huge, and if it does not converge. The remedy is in the previous section.
This is Gauss-Newton with a trust region. By subproblem optimality, with (so for all ), the LM vector with exactly solves subject to , with the constraint multiplier: each corresponds to a . With diagonal , it corresponds to elliptical region , making Marquardt’s version invariant to separate parameter rescalings. The extremes are expected: gives Gauss-Newton and gives gradient step . Moreover is invertible even if lacks full rank (Tikhonov regularization), and inverse kinematics with “damped least squares” (DLS) is LM with fixed .
Cost per iteration and when it pays off
A Newton iteration needs the gradient, Hessian (an matrix to assemble and store, bytes in double precision) and an linear solve: Cholesky costs floating-point operations (flop count) and two substitutions cost . If Hessian-vector products (HVPs) replace assembly, each costs about two or three gradient evaluations.
import numpy as np
def humano(b):
for u in ["B", "KB", "MB", "GB", "TB", "PB", "EB"]:
if b < 1000:
return f"{b:.3g} {u}"
b /= 1000
return f"{b:.3g} ZB"
print(f"{'n':>10} {'memoria de H':>12} {'flops de Cholesky':>18} {'a 1 TFLOP/s':>14}")
for n in [1e2, 1e3, 1e4, 1e5, 1.24e8, 7e9]:
memoria = 8 * n * n # bytes en doble precisión
flops = n**3 / 3
seg = flops / 1e12
t = f"{seg:.3g} s" if seg < 3600 else f"{seg / 3.156e7:.3g} años"
print(f"{n:10.3g} {humano(memoria):>12} {flops:18.3g} {t:>14}")With in the hundreds or low thousands, an iteration is a blink and Newton wins decisively. At storage already requires 80 GB. With hundreds of millions of parameters in a language model (the row is small GPT-2), no computer can store the Hessian; with it would be about 400 exabytes. Deep learning therefore uses inexact Newton, limited-memory quasi-Newton, diagonal (Adam) or block preconditioners, not Newton.
It pays off when:
- is small (hundreds to a few thousand) and high accuracy is needed: few cheap iterations. Logistic regression, distribution fitting, classical statistical models.
- The Hessian is sparse or structured. In bundle adjustment the approximate Hessian has block arrow structure, and the Schur complement reduces the large system to one the size of the cameras.
- Evaluating and its gradient is expensive (a pass over many data points): few passes matter more than many cheap passes. With data and parameters, Hessian assembly costs once per iteration.
- They are inner steps of another algorithm (interior-point, augmented Lagrangian methods).
Implementation from scratch
First, damped Newton with shifted Cholesky, without inverting any matrix. Apply it to regularized logistic regression (Newton is IRLS) and Rosenbrock, recording decrement to see the quadratic phase. For Rosenbrock the cell also counts gradient descent with Armijo.
import numpy as np
from scipy.linalg import solve_triangular
def newton_modificado(H, g, beta=1e-3):
"""Dirección de Newton con Cholesky desplazado: d = -(H + tau I)^{-1} g, sin invertir nada."""
n = len(g)
mindiag = H.diagonal().min()
tau = 0.0 if mindiag > 0 else -mindiag + beta
while True:
try:
L = np.linalg.cholesky(H + tau * np.eye(n))
break
except np.linalg.LinAlgError:
tau = max(2 * tau, beta)
y = solve_triangular(L, -g, lower=True) # L y = -g
d = solve_triangular(L.T, y, lower=False) # L^T d = y
return d, tau
def newton(f, grad, hess, x0, amortiguado=True, alpha=1e-4, beta=0.5, tol=1e-13, max_iter=100):
x = np.array(x0, dtype=float)
hist = []
for k in range(max_iter):
g, H = grad(x), hess(x)
d, tau = newton_modificado(H, g)
lam2 = -g @ d # decremento de Newton al cuadrado
if lam2 / 2 <= tol: # ½λ² estima f(x) - f*: parada afín invariante
hist.append((f(x), lam2 / 2, 1.0, tau))
break
t = 1.0
if amortiguado: # retroceso de Armijo sobre la dirección de Newton
while f(x + t * d) > f(x) + alpha * t * (g @ d) and t > 1e-12:
t *= beta
hist.append((f(x), lam2 / 2, t, tau))
x = x + t * d
return x, hist
# 1) regresión logística regularizada: Newton es aquí IRLS
rng = np.random.default_rng(0)
n, d = 400, 5
X = rng.normal(size=(n, d))
y = (X @ rng.normal(size=d) + 0.7 * rng.normal(size=n) > 0).astype(float)
lam = 1e-3
def f_log(w):
z = X @ w
return np.mean(np.logaddexp(0, z) - y * z) + 0.5 * lam * w @ w
def g_log(w):
return X.T @ (1 / (1 + np.exp(-(X @ w))) - y) / n + lam * w
def h_log(w):
s = 1 / (1 + np.exp(-(X @ w)))
return (X.T * (s * (1 - s))) @ X / n + lam * np.eye(d)
w, hist = newton(f_log, g_log, h_log, np.zeros(d))
print("logística: pasos dados =", len(hist) - 1)
print(" k f - f* ½λ² t")
fstar = hist[-1][0]
for k, (fk, dec, t, tau) in enumerate(hist):
print(f"{k:2d} {fk - fstar:10.3e} {dec:10.3e} {t:.3f}")
dec = np.array([h[1] for h in hist])
cifras = -np.log10(dec[dec > 1e-15])
print("cifras de ½λ² por iteración:", np.round(cifras, 1))
print("cociente entre cifras sucesivas:", np.round(cifras[1:] / cifras[:-1], 2))
# 2) Rosenbrock: fase amortiguada y fase cuadrática
def f_r(x): return (1 - x[0])**2 + 100 * (x[1] - x[0]**2)**2
def g_r(x): return np.array([-2 * (1 - x[0]) - 400 * x[0] * (x[1] - x[0]**2), 200 * (x[1] - x[0]**2)])
def h_r(x): return np.array([[2 - 400 * x[1] + 1200 * x[0]**2, -400 * x[0]], [-400 * x[0], 200.0]])
x, hist = newton(f_r, g_r, h_r, [-1.2, 1.0])
print("\nRosenbrock, Newton amortiguado: pasos dados =", len(hist) - 1, " x =", x)
print(" k f ½λ² t")
for k, (fk, dec, t, tau) in enumerate(hist):
print(f"{k:2d} {fk:9.2e} {dec:9.2e} {t:.4f}")
# 3) descenso por gradiente con Armijo desde el mismo punto (en Python puro, para que sea rápido)
def f2(a, b): return (1 - a)**2 + 100 * (b - a * a)**2
a, b, k = -1.2, 1.0, 0
while k < 30000:
ga, gb = -2 * (1 - a) - 400 * a * (b - a * a), 200 * (b - a * a)
gn2 = ga * ga + gb * gb
if gn2 ** 0.5 < 1e-6:
break
t, fx = 1.0, f2(a, b)
while f2(a - t * ga, b - t * gb) > fx - 1e-4 * t * gn2:
t *= 0.5
a, b, k = a - t * ga, b - t * gb, k + 1
print(f"\nRosenbrock, descenso por gradiente con Armijo: {k} iteraciones hasta |grad| < 1e-6")Notice three code decisions. The stopping criterion is , estimating independent of units. Backtracking uses directional derivative , equal to if no shift occurred. np.linalg.inv is never called: two triangular substitutions use the Cholesky factor.
In logistic regression falls from to in six steps with throughout, and the ratio between digits of in successive steps rises toward (, , ). Rosenbrock has an irregular damped phase (21 steps total, with , or interspersed through iteration 13), then roughly five quadratic steps in which goes from to , , , and . Gradient descent needs 13,756 iterations, over six hundred times more. Curiously, pure Newton from converges in six or seven steps (depending on stopping criterion), fewer than damped Newton: Armijo’s monotonicity costs steps in a curved valley, and this lucky full step is unreliable (change the start and it may stop working, as the digits figure shows).
Now a trust region with dogleg, also from scratch, and comparison with the library. When the Hessian is not positive definite use the Cauchy point, as theory says.
import numpy as np
from scipy.optimize import minimize
def f_r(x): return (1 - x[0])**2 + 100 * (x[1] - x[0]**2)**2
def g_r(x): return np.array([-2 * (1 - x[0]) - 400 * x[0] * (x[1] - x[0]**2), 200 * (x[1] - x[0]**2)])
def h_r(x): return np.array([[2 - 400 * x[1] + 1200 * x[0]**2, -400 * x[0]], [-400 * x[0], 200.0]])
def punto_cauchy(g, B, delta):
gBg = g @ B @ g
tau = 1.0 if gBg <= 0 else min(np.linalg.norm(g)**3 / (delta * gBg), 1.0)
return -tau * delta / np.linalg.norm(g) * g
def dogleg(g, B, delta):
"""Poligonal 0 -> pU -> pB, cortada en la frontera. Exige B definida positiva."""
pB = -np.linalg.solve(B, g)
if np.linalg.norm(pB) <= delta:
return pB
pU = -(g @ g) / (g @ B @ g) * g
if np.linalg.norm(pU) >= delta:
return -delta * g / np.linalg.norm(g)
d = pB - pU # ‖pU + s d‖² = Δ², raíz en [0, 1]
a, b, c = d @ d, 2 * pU @ d, pU @ pU - delta**2
s = (-b + np.sqrt(b * b - 4 * a * c)) / (2 * a)
return pU + s * d
def region_confianza(f, grad, hess, x0, delta0=1.0, delta_max=10.0, eta=0.15, tol=1e-9, max_iter=200):
x, delta = np.array(x0, dtype=float), delta0
hist = []
for k in range(max_iter):
g, B = grad(x), hess(x)
if np.linalg.norm(g) < tol:
break
definida = np.linalg.eigvalsh(B)[0] > 0
p = dogleg(g, B, delta) if definida else punto_cauchy(g, B, delta)
predicha = -(g @ p + 0.5 * p @ B @ p) # m(0) - m(p)
real = f(x) - f(x + p)
rho = real / predicha
hist.append((f(x), delta, rho))
if rho < 0.25:
delta *= 0.25
elif rho > 0.75 and np.isclose(np.linalg.norm(p), delta):
delta = min(2 * delta, delta_max)
if rho > eta:
x = x + p
return x, hist
x, hist = region_confianza(f_r, g_r, h_r, [-1.2, 1.0])
rechazos = sum(1 for _, _, r in hist if r <= 0.15)
print(f"dogleg propio: {len(hist)} iteraciones ({rechazos} rechazadas), x = {x}")
for k, (fk, dl, rho) in list(enumerate(hist))[:6]:
print(f" k={k} f={fk:9.3e} Δ={dl:7.4f} ρ={rho:6.3f}")
# comparación con SciPy desde el mismo punto
x0 = np.array([-1.2, 1.0])
print("\nmétodo iter f(x*)")
for metodo in ["Newton-CG", "dogleg", "trust-ncg", "trust-exact"]:
r = minimize(f_r, x0, jac=g_r, hess=h_r, method=metodo, tol=1e-9)
print(f"{metodo:14s} {r.nit:4d} {r.fun:.1e}")
r = minimize(f_r, x0, jac=g_r, method="BFGS", tol=1e-9)
print(f"{'BFGS':14s} {r.nit:4d} {r.fun:.1e} (sin hessiano)")The first iteration accepts the Newton step (), the second is rejected with (the model predicted a decrease but rose) and the radius is quartered; later the radius rises again when and the step touches the boundary. This is the trust-region figure’s mechanism in code. With the library (method='trust-exact', 'dogleg', 'trust-ncg' and 'Newton-CG' with analytic Hessian), dogleg and trust-exact need 25 and 26 iterations, like our dogleg (25), trust-ncg 30, Newton-CG (which uses line search) 85 and BFGS without Hessian 34; trust-ncg and Newton-CG accept a Hessian-vector product (hessp) instead of the Hessian, needed at scale.
Finally, nonlinear least squares: Gauss-Newton and Levenberg-Marquardt from scratch, with exponential model and Michaelis–Menten , compared with scipy.optimize.least_squares (methods 'lm', MINPACK, and 'trf', trust region). The cell also calculates theorem rate and compares it to the measured rate.
import numpy as np
from scipy.optimize import least_squares
def gauss_newton(r, J, x0, max_iter=100, tol=1e-10):
x = np.array(x0, dtype=float)
hist = [x.copy()]
for _ in range(max_iter):
Jx, rx = J(x), r(x)
g = Jx.T @ rx
if np.linalg.norm(g) < tol:
break
try:
p = np.linalg.solve(Jx.T @ Jx, -g) # ecuaciones normales de min ‖r + J p‖²
except np.linalg.LinAlgError: # JᵀJ singular: GN no sabe qué hacer
break
x = x + p
hist.append(x.copy())
if not np.all(np.isfinite(x)) or np.abs(x).max() > 1e8:
break
return x, hist
def levenberg_marquardt(r, J, x0, mu0=1e-3, max_iter=200, tol=1e-10):
x = np.array(x0, dtype=float)
mu, nu = None, 2.0
hist = [x.copy()]
for _ in range(max_iter):
Jx, rx = J(x), r(x)
A, g = Jx.T @ Jx, Jx.T @ rx
if np.linalg.norm(g) < tol:
break
if mu is None:
mu = mu0 * A.diagonal().max()
while True:
p = np.linalg.solve(A + mu * np.eye(len(x)), -g)
xn = x + p
reduccion_real = 0.5 * rx @ rx - 0.5 * r(xn) @ r(xn)
reduccion_pred = 0.5 * p @ (mu * p - g) # ganancia del modelo lineal
if reduccion_pred < 1e-300: # ya no hay nada que ganar
return x, hist
rho = reduccion_real / reduccion_pred
if rho > 0:
x, nu = xn, 2.0
mu *= max(1 / 3, 1 - (2 * rho - 1) ** 3)
break
mu, nu = mu * nu, 2 * nu # rechazado: más amortiguamiento
hist.append(x.copy())
return x, hist
t = np.linspace(0.3, 4.5, 12)
def problema(nombre, sigma):
z = np.random.default_rng(3).normal(size=t.size)
if nombre == "exponencial":
xv = np.array([2.0, 0.6]); y = lambda x: x[0] * np.exp(-x[1] * t)
J = lambda x: np.column_stack([np.exp(-x[1] * t), -x[0] * t * np.exp(-x[1] * t)])
def S(x, rx): # Σ r_i ∇²r_i, el término que GN ignora
e = np.exp(-x[1] * t)
return np.array([[0, np.sum(rx * -t * e)], [np.sum(rx * -t * e), np.sum(rx * x[0] * t**2 * e)]])
x0 = [1.0, 2.0]
else:
xv = np.array([1.0, 1.0]); y = lambda x: x[0] * t / (x[1] + t)
J = lambda x: np.column_stack([t / (x[1] + t), -x[0] * t / (x[1] + t) ** 2])
def S(x, rx):
c = -t / (x[1] + t) ** 2
return np.array([[0, np.sum(rx * c)], [np.sum(rx * c), np.sum(rx * 2 * x[0] * t / (x[1] + t) ** 3)]])
x0 = [0.5, 3.0]
datos = y(xv) + sigma * z
return (lambda x: y(x) - datos), J, S, x0
casos = [("exponencial", 0.0), ("exponencial", 0.5), ("Michaelis-Menten", 0.0), ("Michaelis-Menten", 0.2)]
for nombre, sigma in casos:
r, J, S, x0 = problema(nombre, sigma)
xl, hl = levenberg_marquardt(r, J, x0)
rs = r(xl)
rho = max(abs(np.linalg.eigvals(np.linalg.solve(J(xl).T @ J(xl), S(xl, rs)))))
sp = {m: least_squares(r, x0, method=m, ftol=1e-15, xtol=1e-15, gtol=1e-15) for m in ("lm", "trf")}
dif = max(np.abs(sp[m].x - xl).max() for m in sp)
print(f"{nombre}, σ={sigma}: ‖r*‖ = {np.linalg.norm(rs):.3f}, x* = {np.round(xl, 4)}")
print(f" LM propio: {len(hl)-1} iteraciones; SciPy lm: {sp['lm'].nfev} evaluaciones, trf: {sp['trf'].nfev}; diferencia máxima {dif:.1e}")
xg, hg = gauss_newton(r, J, xl + np.array([0.15, -0.15])) # GN cerca del óptimo
e = [np.linalg.norm(h - xl) for h in hg]
print(" GN cerca del óptimo, errores:", " ".join(f"{v:.0e}" for v in e[:9]))
print(f" tasa predicha ρ((JᵀJ)⁻¹S) = {rho:.3f}" + (f", cociente medido entre errores sucesivos = {e[7] / e[6]:.3f}" if rho > 0.01 and len(e) > 8 else ""))
xg2, hg2 = gauss_newton(r, J, x0, max_iter=60) # GN desde el arranque lejano
ok = np.all(np.isfinite(xg2)) and np.linalg.norm(xg2 - xl) < 1e-6
print(f" GN puro desde {x0}: {'converge en ' + str(len(hg2) - 1) + ' iteraciones' if ok else 'no llega al mínimo'}")Without noise the optimal residual is zero and Gauss-Newton near the minimum behaves like Newton: errors fall as , doubling digits. With noise ( in the exponential model, large residual) the theorem predicts asymptotic rate , matching measured to three digits: going from to takes about sixty iterations instead of five. With in Michaelis–Menten, versus . From distant starts (last line in each case), pure Gauss-Newton misses the minimum in noiseless problems, while LM reaches it in all cases. Both SciPy implementations and ours agree on the minimum within or less; 'trf' mainly exists for bounds and large sparse problems.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How do you express to use what you know about ?
Step 1 of 4. How are gradients and Hessians of and related?
levenberg_marquardt(residual, jac, x0, max_iter=200, tol=1e-10, mu0=1e-3), minimizing and returning (x, pasos_aceptados). Initialize with times the largest diagonal entry of , solve , calculate gain ratio and update as in Nielsen: if , accept and ; otherwise reject, , . Stop when . Do not call scipy.import numpy as np
def levenberg_marquardt(residual, jac, x0, max_iter=200, tol=1e-10, mu0=1e-3):
"""Minimiza 0.5*||residual(x)||^2. Devuelve (x, pasos_aceptados)."""
x = np.array(x0, dtype=float)
# tu código: mu inicial = mu0 * max(diag(J^T J)); en cada iteración resuelve (J^T J + mu I) p = -J^T r,
# calcula la ganancia rho = reducción real / reducción predicha, acepta si rho > 0 y actualiza mu
return x, 0dogleg(g, B, delta), returning the dogleg step for subject to . If is positive definite: return Newton step if it fits; otherwise, if with , return intersection ; otherwise return the point on with . If is not positive definite, return the Cauchy point. Solve the quadratic equation by hand; do not call an optimizer.import numpy as np
def dogleg(g, B, delta):
"""Paso dogleg para min g.p + 0.5 p.B.p con ||p|| <= delta. Si B no es definida positiva, devuelve el punto de Cauchy."""
g = np.asarray(g, dtype=float)
B = np.asarray(B, dtype=float)
# tu código: pB (paso de Newton), pU (mínimo a lo largo de -g) y los tres casos
return np.zeros_like(g)Summary
- Newton step minimizes the second-order Taylor model, is its predicted decrease and is an intrinsic (affine-invariant) measure of distance to optimum. On a quadratic it arrives in one step.
- With -Lipschitz and , within radius . Six or seven iterations exhaust double precision. A singular Hessian at optimum loses this and convergence is linear.
- Pure Newton can move away, leave the domain, cycle or converge to a maximum or saddle. Damped Newton (Armijo backtracking starting at ) has a damped phase with guaranteed minimum decrease per iteration, and a quadratic one with accepted once .
- With an indefinite Hessian, modify it ( with Cholesky) or use a trust region: solve with , exactly (conditions , , complementary slackness) or with the Cauchy point or dogleg; actual-to-predicted reduction ratio decides acceptance and whether radius expands or shrinks. It converges globally even without convexity.
- For least squares, . Gauss-Newton discards : quadratic if optimal residual is zero and linear at rate otherwise. Levenberg-Marquardt, , is the trust region for that model and globalizes by adapting with .
- Cost: per iteration and memory. It pays with small , sparse structure or expensive evaluations; at scale use quasi-Newton and inexact Newton, in the next lesson.