Gauss–Newton and Levenberg–Marquardt: what changes?

Environment

Python 3.14.6, NumPy 2.5.4, SciPy 1.18.1, Matplotlib 3.11.2.

This article is a rewrite of a post from around 2013–2016, with calculations performed in the environment described above.

Overview

Gauss–Newton and Levenberg–Marquardt are iterative methods for nonlinear least squares. Both linearize the residuals, but the latter adds damping to control the update. We derive their update equations and compare scalar steps, two-variable iterations, and exponential curve fitting in Python. We abbreviate the methods as GN and LM.

Setup

Run the code in Jupyter Notebook from top to bottom.

Imports and plotting setup
import platform
from pathlib import Path
from pprint import pprint

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy
from IPython.display import Math, display
from matplotlib.ticker import FuncFormatter, MaxNLocator, NullFormatter
from matplotlib_inline.backend_inline import set_matplotlib_formats
from scipy.optimize import least_squares

%matplotlib inline
# Prefer SVG and embed PNG in the notebook for viewer compatibility.
set_matplotlib_formats("svg", "png")

print("Environment: wa-src(3.14.6)")
print("Python:", platform.python_version())
print("OS:", platform.system(), platform.release())
print("NumPy:", np.__version__)
print("SciPy:", scipy.__version__)
print("Matplotlib:", matplotlib.__version__)
assert platform.python_version() == "3.14.6"


def sig3(value):
    """Display three significant digits, retaining trailing zeros."""
    return f"{float(value):#.3g}"


np.set_printoptions(formatter={"float_kind": sig3})
plt.rcParams.update({"font.size": 11, "axes.grid": True, "grid.alpha": 0.250,
                     "svg.fonttype": "none", "svg.hashsalt": "104"})
output_dir = Path("104_nb_files")
output_dir.mkdir(exist_ok=True)
colors = {"GN": "#c85a2a", "LM": "#176c9e"}


def save_figure(fig, filename, integer_x=False):
    """Format ticks, save the SVG, and display it in the notebook."""
    for ax in fig.axes:
        ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: sig3(x)))
        ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: sig3(x)))
        ax.xaxis.set_minor_formatter(NullFormatter())
        ax.yaxis.set_minor_formatter(NullFormatter())
        if integer_x:
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: f"{x:.0f}"))
    fig.savefig(output_dir / filename, format="svg", bbox_inches="tight",
                metadata={"Date": None})
    plt.show()
    plt.close(fig)
Environment: wa-src(3.14.6)
Python: 3.14.6
OS: Darwin 25.5.0
NumPy: 2.5.4
SciPy: 1.18.1
Matplotlib: 3.11.2

1. The nonlinear least-squares problem

Approximate observations $y_i$ by a model $f(t_i;\mathbf{x})$. Let $\mathbf{x}\in\mathbb{R}^n$ contain the unknown parameters and $m$ be the number of observations. Define each residual as the model value minus the observation.

$$ r_i(\mathbf{x})=f(t_i;\mathbf{x})-y_i,\qquad \mathbf{r}(\mathbf{x})=\begin{bmatrix}r_1(\mathbf{x})&\cdots&r_m(\mathbf{x})\end{bmatrix}^{\mathsf T}. $$

The objective is half the sum of squared residuals. The factor $1/2$ simplifies differentiation without changing the minimizer.

$$ F(\mathbf{x})=\frac12\sum_{i=1}^m r_i(\mathbf{x})^2 =\frac12\mathbf{r}(\mathbf{x})^{\mathsf T}\mathbf{r}(\mathbf{x}). $$

The Jacobian $\mathbf{J}\in\mathbb{R}^{m\times n}$ has entries $J_{ij}=\partial r_i/\partial x_j$. Differentiating component by component gives

$$ \begin{aligned} \frac{\partial F}{\partial x_j} &=\frac12\sum_i 2r_i\frac{\partial r_i}{\partial x_j} =\sum_i J_{ij}r_i,\\ \mathbf{g}=\nabla F&=\mathbf{J}^{\mathsf T}\mathbf{r},\\ \frac{\partial^2 F}{\partial x_k\partial x_j} &=\sum_i\left(\frac{\partial r_i}{\partial x_k}\frac{\partial r_i}{\partial x_j} +r_i\frac{\partial^2 r_i}{\partial x_k\partial x_j}\right),\\ \nabla^2 F&=\mathbf{J}^{\mathsf T}\mathbf{J}+\sum_i r_i\nabla^2 r_i. \end{aligned} $$

Newton’s method uses the entire Hessian. GN omits the final sum of residuals multiplied by their second derivatives.

2. Deriving Gauss–Newton

Let $\mathbf{p}$ be the change from the current point $\mathbf{x}$. For sufficiently smooth residuals, the first-order Taylor expansion has the form below. From now on, evaluate $\mathbf{r}$ and $\mathbf{J}$ at the current point.

$$ \mathbf{r}(\mathbf{x}+\mathbf{p}) =\mathbf{r}+\mathbf{J}\mathbf{p}+O(\|\mathbf{p}\|^2). $$

Drop terms of order two and higher from the residual expansion to form a local quadratic $q$.

$$ \begin{aligned} q(\mathbf{p}) &=\frac12\|\mathbf{r}+\mathbf{J}\mathbf{p}\|^2\\ &=\frac12(\mathbf{r}+\mathbf{J}\mathbf{p})^{\mathsf T} (\mathbf{r}+\mathbf{J}\mathbf{p})\\ &=\frac12\mathbf{r}^{\mathsf T}\mathbf{r} +\frac12\mathbf{r}^{\mathsf T}\mathbf{J}\mathbf{p} +\frac12\mathbf{p}^{\mathsf T}\mathbf{J}^{\mathsf T}\mathbf{r} +\frac12\mathbf{p}^{\mathsf T}\mathbf{J}^{\mathsf T}\mathbf{J}\mathbf{p}\\ &=F(\mathbf{x})+\mathbf{g}^{\mathsf T}\mathbf{p} +\frac12\mathbf{p}^{\mathsf T}\mathbf{J}^{\mathsf T}\mathbf{J}\mathbf{p}. \end{aligned} $$

The two middle scalar terms are equal because transposing a scalar does not change it. Differentiate with respect to $\mathbf{p}$ and set the result to zero.

$$ \begin{aligned} \nabla_{\mathbf{p}}q&=\mathbf{J}^{\mathsf T}\mathbf{r} +\mathbf{J}^{\mathsf T}\mathbf{J}\mathbf{p}=\mathbf{0},\\ \mathbf{J}^{\mathsf T}\mathbf{J}\mathbf{p}_{\mathrm{GN}} &=-\mathbf{J}^{\mathsf T}\mathbf{r},\\ \mathbf{x}_{k+1}&=\mathbf{x}_k+\mathbf{p}_{\mathrm{GN}}. \end{aligned} $$

If $\mathbf{J}$ has full column rank, the update is unique. Near a small-residual solution, the omitted term is often small, although its size also depends on the residuals’ second derivatives. With zero residual at the solution, a full-column-rank Jacobian, and sufficient smoothness, GN converges quadratically from a sufficiently close starting point.

Reducing $q$ does not necessarily reduce the true objective $F$. The GN implementation here takes the full update. Other versions shorten the update with a line search.

3. Deriving Levenberg–Marquardt

LM adds a penalty on the update size. First consider the form using the identity matrix $\mathbf{I}$.

$$ \begin{aligned} q_\lambda(\mathbf{p}) &=q(\mathbf{p})+\frac{\lambda}{2}\|\mathbf{p}\|^2,\qquad\lambda\gt 0,\\ \nabla_{\mathbf{p}}q_\lambda &=\mathbf{J}^{\mathsf T}\mathbf{r}+\mathbf{J}^{\mathsf T}\mathbf{J}\mathbf{p} +\lambda\mathbf{p}=\mathbf{0}. \end{aligned} $$

This gives the following update equation.

$$ (\mathbf{J}^{\mathsf T}\mathbf{J}+\lambda\mathbf{I})\mathbf{p}_{\mathrm{LM}} =-\mathbf{J}^{\mathsf T}\mathbf{r}. $$

For every $\mathbf{v}\ne\mathbf{0}$,

$$ \mathbf{v}^{\mathsf T}(\mathbf{J}^{\mathsf T}\mathbf{J}+\lambda\mathbf{I})\mathbf{v} =\|\mathbf{J}\mathbf{v}\|^2+\lambda\|\mathbf{v}\|^2\gt 0 $$

Thus the linear system has a unique solution even if $\mathbf{J}$ is rank deficient. This does not make the original parameters uniquely identifiable from the data.

If $\mathbf{J}$ has full column rank, the LM update approaches the GN update as $\lambda\to0$. On the other hand, writing $\mathbf{H}=\mathbf{J}^{\mathsf T}\mathbf{J}$ gives

$$ \begin{aligned} \mathbf{p}_{\mathrm{LM}} &=-(\mathbf{H}+\lambda\mathbf{I})^{-1}\mathbf{g}\\ &=-\frac1\lambda\left(\mathbf{I}+\frac{\mathbf{H}}\lambda\right)^{-1}\mathbf{g} \approx-\frac1\lambda\mathbf{g}. \end{aligned} $$

The last approximation holds when $\lambda$ is much larger than the largest eigenvalue of $\mathbf{H}$. The direction then approaches steepest descent. In general, the LM update is not a scalar multiple of the GN update.

4. Computing a scalar update

Take $r(x)=x^2-1$ and $F(x)=r(x)^2/2$, starting from $x_0=0.100$. The residual and derivative are $r(x_0)=-0.990$ and $J(x_0)=2x_0=0.200$.

$$ \begin{aligned} p_{\mathrm{GN}} &=-\frac{Jr}{J^2} =-\frac{0.200\times(-0.990)}{0.200^2}=4.95,\\ x_1^{\mathrm{GN}}&=0.100+4.95=5.05,\\ p_{\mathrm{LM}} &=-\frac{Jr}{J^2+\lambda} =\frac{0.198}{0.0400+1.00}\approx0.190,\\ x_1^{\mathrm{LM}}&\approx0.290. \end{aligned} $$

Here $\lambda=1.00$. The starting value is $F(x_0)\approx0.490$, whereas the GN candidate gives $F\approx3.00\times10^2$ and the LM candidate gives $F\approx0.419$. GN makes the linearized residual zero, but the actual residual grows. Evaluating the true objective at the candidate points shows what happens when the linear approximation is poor.

x0 = 0.100
r0, J0 = x0**2 - 1, 2 * x0
step_gn = -J0 * r0 / J0**2
step_lm = -J0 * r0 / (J0**2 + 1.00)
points = {"start": x0, "GN": x0 + step_gn, "LM": x0 + step_lm}
pprint({name: {"x": sig3(x), "F": sig3((x**2 - 1)**2 / 2)}
        for name, x in points.items()}, sort_dicts=False)
display(Math(r"p_{\mathrm{GN}}=-\frac{Jr}{J^2},\qquad "
             r"p_{\mathrm{LM}}=-\frac{Jr}{J^2+\lambda}"))

grid = np.linspace(-0.300, 5.40, 500)
linear_r = r0 + J0 * (grid - x0)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
axes[0].plot(grid, grid**2 - 1, label="Actual residual")
axes[0].plot(grid, linear_r, "--", label="Linearized residual")
axes[0].axhline(0, color="0.600", linewidth=1)
axes[0].set(xlabel="x", ylabel="Residual", title="Residual linearization")
axes[1].plot(grid, (grid**2 - 1)**2 / 2, label="Actual F")
axes[1].plot(grid, linear_r**2 / 2, "--", label="Local model q")
axes[1].set(xlabel="Candidate x", ylabel="Objective / model",
            title="One candidate step", yscale="symlog", ylim=(-0.0100, 500))
for name, x in points.items():
    color = colors.get(name, "#333333")
    axes[0].scatter(x, x**2 - 1, s=55, color=color, zorder=3, label=name)
    axes[1].scatter(x, (x**2 - 1)**2 / 2, s=55, color=color, zorder=3, label=name)
for ax in axes:
    ax.legend(fontsize=9)
save_figure(fig, "01_scalar_step.svg")
{'start': {'x': '0.100', 'F': '0.490'},
 'GN': {'x': '5.05', 'F': '300.'},
 'LM': {'x': '0.290', 'F': '0.419'}}

$$ \displaystyle p_{\mathrm{GN}}=-\frac{Jr}{J^2},\qquad p_{\mathrm{LM}}=-\frac{Jr}{J^2+\lambda} $$

5. Implementing adaptive damping

One calculation with a fixed $\lambda$ does not tell us whether a candidate is suitable. Compare the actual reduction with the reduction predicted by the linearized model.

$$ \begin{aligned} \mathrm{pred} &=q(\mathbf{0})-q(\mathbf{p}) =-\mathbf{g}^{\mathsf T}\mathbf{p}-\frac12\|\mathbf{J}\mathbf{p}\|^2,\\ \mathrm{ared}&=F(\mathbf{x})-F(\mathbf{x}+\mathbf{p}),\\ \rho&=\frac{\mathrm{ared}}{\mathrm{pred}}. \end{aligned} $$

The denominator uses $q$ without its damping term. Our simple LM implementation accepts a candidate if $\mathrm{pred}\gt 0$ and $\rho\gt 1.00\times10^{-4}$. After rejection, it keeps the current point, multiplies $\lambda$ by 10, and retries. After acceptance, it divides $\lambda$ by 3 if $\rho\gt 0.750$, doubles it if $\rho\lt 0.250$, and otherwise leaves it unchanged. These constants are choices for this example, not unique requirements of LM.

Compute the update from the following augmented least-squares problem.

$$ \min_{\mathbf{p}}\frac12\left\| \begin{bmatrix}\mathbf{J}\\\sqrt{\lambda}\mathbf{I}\end{bmatrix}\mathbf{p} -\begin{bmatrix}-\mathbf{r}\\\mathbf{0}\end{bmatrix} \right\|^2 =\min_{\mathbf{p}}\left\{\frac12\|\mathbf{J}\mathbf{p}+\mathbf{r}\|^2 +\frac{\lambda}{2}\|\mathbf{p}\|^2\right\}. $$

This avoids forming an inverse or $\mathbf{J}^{\mathsf T}\mathbf{J}$. For full column rank, the 2-norm condition number satisfies $\kappa_2(\mathbf{J}^{\mathsf T}\mathbf{J})=\kappa_2(\mathbf{J})^2$, so we solve the augmented problem directly with lstsq.

The stopping conditions are a gradient infinity norm at most $1.00\times10^{-8}$ or an accepted update norm at most $1.00\times10^{-10}(1+\|\mathbf{x}\|)$. Reaching the trial limit and encountering nonfinite values are reported separately. A small update alone does not guarantee arrival at a minimizer.

def solve_ls(fun, jac, x0, method, lam0=1.00e-3, max_trials=200):
    """Run full-step GN or a simple LM method with adaptive damping."""
    if method not in {"GN", "LM"}:
        raise ValueError("method must be GN or LM")
    x = np.array(x0, dtype=float, copy=True)
    r = fun(x)
    value = float(r @ r / 2)
    lam = lam0
    path, costs, history = [x.copy()], [value], []
    status = "Trial limit reached"

    for trial in range(max_trials):
        J = jac(x)
        g = J.T @ r
        if np.linalg.norm(g, ord=np.inf) <= 1.00e-8:
            status = "Gradient tolerance satisfied"
            break

        # Solve least squares directly without inverting the normal equations.
        damping = lam if method == "LM" else 0
        A = np.vstack([J, np.sqrt(damping) * np.eye(x.size)])
        b = np.concatenate([-r, np.zeros(x.size)])
        step = np.linalg.lstsq(A, b, rcond=None)[0]
        J_step = J @ step
        predicted = float(-g @ step - J_step @ J_step / 2)

        # Reject nonfinite candidates; GN stops at that point.
        with np.errstate(over="ignore", invalid="ignore"):
            r_trial = fun(x + step)
            trial_value = float(r_trial @ r_trial / 2)
        finite = np.isfinite(trial_value)
        rho = (value - trial_value) / predicted if finite and predicted > 0 else -np.inf
        accepted = bool(finite and (method == "GN" or rho > 1.00e-4))
        history.append({"trial": trial + 1, "lambda": damping, "rho": rho,
                        "accepted": accepted, "candidate_F": trial_value})

        if accepted:
            x, r, value = x + step, r_trial, trial_value
            path.append(x.copy())
        costs.append(value)  # For a rejected trial, record the unchanged current value.

        if method == "LM":
            if not accepted:
                lam *= 10
            elif rho > 0.750:
                lam = max(lam / 3, 1.00e-15)
            elif rho < 0.250:
                lam *= 2
        elif not finite:
            status = "Stopped due to nonfinite values"
            break

        if accepted and np.linalg.norm(step) <= 1.00e-10 * (1 + np.linalg.norm(x)):
            status = "Step tolerance satisfied"
            break

    return {"x": x, "F": value, "path": np.array(path),
            "costs": np.array(costs), "history": history, "status": status}

6. Comparing iterations in two variables

Write half the Rosenbrock function as a least-squares problem.

$$ \mathbf{x}=\begin{bmatrix}u\\v\end{bmatrix},\quad \mathbf{r}(\mathbf{x})=\begin{bmatrix}10(v-u^2)\\1-u\end{bmatrix},\quad \mathbf{J}(\mathbf{x})=\begin{bmatrix}-20u&10\\-1&0\end{bmatrix},\quad F=\frac12\{100(v-u^2)^2+(1-u)^2\}. $$

The solution is $(u,v)=(1,1)$. At the starting point $(-1.20,1.00)$,

$$ \mathbf{r}_0=\begin{bmatrix}-4.40\\2.20\end{bmatrix},\quad \mathbf{J}_0=\begin{bmatrix}24&10\\-1&0\end{bmatrix}. $$

The Jacobian in this example is square and invertible, so the GN update follows directly from $\mathbf{J}_0\mathbf{p}=-\mathbf{r}_0$.

$$ \begin{aligned} -p_u&=-2.20\quad\Rightarrow\quad p_u=2.20,\\ 24p_u+10p_v&=4.40\quad\Rightarrow\quad p_v=\frac{4.40-24\times2.20}{10}=-4.84,\\ \mathbf{x}_1&=\begin{bmatrix}-1.20\\1.00\end{bmatrix} +\begin{bmatrix}2.20\\-4.84\end{bmatrix} =\begin{bmatrix}1.00\\-3.84\end{bmatrix}. \end{aligned} $$

The objective increases from $12.1$ to $1.17\times10^3$. The next update has $p_u=0$ and $10p_v=48.4$, reaching $(1,1)$. GN solves this example in two steps despite the large temporary increase.

def rosen_residual(x):
    u, v = x
    return np.array([10 * (v - u**2), 1 - u])


def rosen_jacobian(x):
    u, _ = x
    return np.array([[-20 * u, 10], [-1, 0]], dtype=float)


def result_summary(result):
    """Collect arrays and decimals in a readable output dictionary."""
    return {"x": [sig3(v) for v in result["x"]], "F": sig3(result["F"]),
            "trials": len(result["history"]), "accepted": len(result["path"]) - 1,
            "status": result["status"]}


start = np.array([-1.20, 1.00])
results = {method: solve_ls(rosen_residual, rosen_jacobian, start, method)
           for method in ["GN", "LM"]}
pprint({name: result_summary(result) for name, result in results.items()}, sort_dicts=False)

# Check the known solution and decreasing objective values at accepted LM points.
for result in results.values():
    np.testing.assert_allclose(result["x"], [1, 1], atol=1.00e-6)
assert np.all(np.diff(results["LM"]["costs"]) <= 0)
assert results["GN"]["costs"][1] > results["GN"]["costs"][0]
{'GN': {'x': ['1.00', '1.00'],
        'F': '1.21e-28',
        'trials': 2,
        'accepted': 2,
        'status': 'Gradient tolerance satisfied'},
 'LM': {'x': ['1.00', '1.00'],
        'F': '1.94e-16',
        'trials': 25,
        'accepted': 19,
        'status': 'Gradient tolerance satisfied'}}

Paths and objective values

GN moves far from the valley before reaching the solution. The simple LM implementation accepts 19 of its 25 trials and rejects six. The path plot contains accepted points only; the objective plot counts all trials, including rejections. Iteration count alone is not a complete efficiency measure, but LM does not finish in fewer updates in this example.

fig, axes = plt.subplots(1, 2, figsize=(11, 4.50), layout="constrained")
for ax, (bottom, top), title in zip(
    axes, [(-4.20, 2.00), (-0.200, 1.60)], ["Full paths", "Valley detail"]
):
    u, v = np.meshgrid(np.linspace(-1.60, 1.40, 300), np.linspace(bottom, top, 350))
    values = (100 * (v - u**2)**2 + (1 - u)**2) / 2
    ax.contour(u, v, values, levels=np.logspace(-2, 3, 12),
               colors="0.700", linewidths=0.700)
    for name, result in results.items():
        path = result["path"]
        ax.plot(path[:, 0], path[:, 1], ".-", color=colors[name], label=name)
    ax.scatter(*start, marker="s", color="black", s=45, label="Start", zorder=4)
    ax.scatter(1, 1, marker="*", color="#39823a", s=130, label="Solution", zorder=4)
    ax.set(xlim=(-1.60, 1.40), ylim=(bottom, top), xlabel="u", ylabel="v", title=title)
    ax.legend(fontsize=9)
save_figure(fig, "02_rosenbrock_paths.svg")
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
for name, result in results.items():
    axes[0].semilogy(np.arange(result["costs"].size), result["costs"],
                     ".-", color=colors[name], label=name)
    # The right panel shows distance to the solution against accepted step count.
    distances = np.linalg.norm(result["path"] - np.array([1, 1]), axis=1)
    axes[1].semilogy(np.arange(distances.size), distances,
                     ".-", color=colors[name], label=name)
axes[0].set(xlabel="Trial (including rejections)", ylabel="F", title="Objective history")
axes[1].set(xlabel="Accepted update", ylabel="Distance to (1, 1)", title="Parameter error")
for ax in axes:
    ax.legend()
save_figure(fig, "03_convergence.svg", integer_x=True)

Rejection and damping

The next figure shows the $\lambda$ and $\rho$ used for each candidate. Red markers indicate rejection. A negative $\rho$ means that the objective increased despite a predicted reduction. After rejection, increase $\lambda$ and compute another candidate from the same current point.

history = results["LM"]["history"]
trials = np.array([h["trial"] for h in history])
dampings = np.array([h["lambda"] for h in history])
ratios = np.array([h["rho"] for h in history])
rejected = np.array([not h["accepted"] for h in history])
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
axes[0].semilogy(trials, dampings, ".-", color=colors["LM"])
axes[0].scatter(trials[rejected], dampings[rejected], color="#b52828", marker="x", s=70,
                label="Rejected", zorder=3)
axes[0].set(xlabel="Trial", ylabel=r"$\lambda$ used", title="Damping adjustment")
axes[1].plot(trials, ratios, ".-", color=colors["LM"])
axes[1].scatter(trials[rejected], ratios[rejected], color="#b52828", marker="x", s=70,
                label="Rejected", zorder=3)
axes[1].axhline(0, color="0.500", linewidth=1)
axes[1].axhline(1, color="0.500", linestyle="--", linewidth=1)
axes[1].set(xlabel="Trial", ylabel=r"$\rho$", yscale="symlog", title="Actual / predicted decrease")
for ax in axes:
    ax.legend()
save_figure(fig, "04_damping_history.svg", integer_x=True)

7. Conditioning and parameter scales

Assume $m\ge n$, and let $\sigma_{\max}$ and $\sigma_{\min}$ be the largest and smallest singular values of $\mathbf{J}$. Then

$$ \kappa_2(\mathbf{J}^{\mathsf T}\mathbf{J}+\lambda\mathbf{I}) =\frac{\sigma_{\max}^2+\lambda}{\sigma_{\min}^2+\lambda}. $$

The next figure varies only $\lambda$ at the initial Rosenbrock point. Increasing it brings the condition number closer to one and reduces the update size. Updates that are too small, however, slow progress.

J = rosen_jacobian(start)
r = rosen_residual(start)
singular_values = np.linalg.svd(J, compute_uv=False)
lambda_grid = np.logspace(-4, 5, 200)
step_sizes = []
for damping in lambda_grid:
    A = np.vstack([J, np.sqrt(damping) * np.eye(2)])
    b = np.concatenate([-r, np.zeros(2)])
    step_sizes.append(np.linalg.norm(np.linalg.lstsq(A, b, rcond=None)[0]))
condition = (singular_values[0]**2 + lambda_grid) / (singular_values[-1]**2 + lambda_grid)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
axes[0].loglog(lambda_grid, condition)
axes[0].set(xlabel=r"$\lambda$", ylabel="Condition number", title="Condition of damped system")
axes[1].loglog(lambda_grid, step_sizes)
axes[1].set(xlabel=r"$\lambda$", ylabel="Step norm", title="Size of the candidate step")
save_figure(fig, "05_conditioning.svg")

If parameters have different units, applying the same penalty makes the update depend on the chosen units. Another form uses a positive diagonal matrix $\mathbf{D}$:

$$ q_\lambda=q+\frac\lambda2\|\mathbf{D}\mathbf{p}\|^2 \quad\Rightarrow\quad (\mathbf{J}^{\mathsf T}\mathbf{J}+\lambda\mathbf{D}^{\mathsf T}\mathbf{D})\mathbf{p}=-\mathbf{g} $$

One choice for $\mathbf{D}$ uses the Jacobian’s column norms, with a positive lower bound for zero entries. For large $\lambda$, this form approaches the direction $-(\mathbf{D}^{\mathsf T}\mathbf{D})^{-1}\mathbf{g}$.

LM corresponds to minimizing $q$ within a trust region $\|\mathbf{D}\mathbf{p}\|\le\Delta$. Here $\Delta$ is the allowed update radius, while $\lambda$ corresponds to the strength of the constraint. Damping rules and scaling choices vary between implementations. The Ceres Solver documentation also discusses this form.

The damping term controls the update at each iteration. This differs from ridge regularization, which adds a fixed $\lambda\|\mathbf{x}\|^2/2$ to the original objective. Neither GN nor LM guarantees a global minimum for a general nonlinear problem.

8. Fitting an exponential curve

Next consider $y_i\approx a e^{-b t_i}$. With $\mathbf{x}=(a,b)^{\mathsf T}$, the residual and each Jacobian row are as follows.

$$ \begin{aligned} r_i&=a e^{-bt_i}-y_i,\\ \frac{\partial r_i}{\partial a}&=e^{-bt_i},\\ \frac{\partial r_i}{\partial b}&=a e^{-bt_i}(-t_i)=-a t_i e^{-bt_i},\\ \mathbf{J}_{i,:}&=\begin{bmatrix}e^{-bt_i}&-a t_i e^{-bt_i}\end{bmatrix}. \end{aligned} $$

Generate 40 points with $a=2.50$ and $b=1.30$, and add Gaussian noise with standard deviation $0.0500$. Fix the random seed at 104. Use two starting points: $(1.00,0.500)$ and $(0.100,4.00)$.

rng = np.random.default_rng(104)
t = np.linspace(0, 4, 40)
y = 2.50 * np.exp(-1.30 * t) + rng.normal(0, 0.0500, t.size)


def exp_model(x, times):
    a, b = x
    return a * np.exp(-b * times)


def exp_residual(x):
    return exp_model(x, t) - y


def exp_jacobian(x):
    a, b = x
    decay = np.exp(-b * t)
    return np.column_stack([decay, -a * t * decay])


# Check the analytic Jacobian with central differences.
check_point = np.array([1.00, 0.500])
h = 1.00e-6
directions = h * np.eye(2)
finite_difference = np.column_stack([
    (exp_residual(check_point + d) - exp_residual(check_point - d)) / (2 * h)
    for d in directions
])
np.testing.assert_allclose(exp_jacobian(check_point), finite_difference,
                           rtol=1.00e-7, atol=1.00e-9)

initials = {"near": [1.00, 0.500], "far": [0.100, 4.00]}
fits = {(case, method): solve_ls(exp_residual, exp_jacobian, initial, method)
        for case, initial in initials.items() for method in ["GN", "LM"]}
pprint({f"{case} / {method}": result_summary(result)
        for (case, method), result in fits.items()}, sort_dicts=False)
{'near / GN': {'x': ['2.50', '1.27'],
               'F': '0.0406',
               'trials': 6,
               'accepted': 6,
               'status': 'Gradient tolerance satisfied'},
 'near / LM': {'x': ['2.50', '1.27'],
               'F': '0.0406',
               'trials': 6,
               'accepted': 6,
               'status': 'Gradient tolerance satisfied'},
 'far / GN': {'x': ['0.100', '4.00'],
              'F': '13.1',
              'trials': 1,
              'accepted': 0,
              'status': 'Stopped due to nonfinite values'},
 'far / LM': {'x': ['2.50', '1.27'],
              'F': '0.0406',
              'trials': 11,
              'accepted': 8,
              'status': 'Gradient tolerance satisfied'}}

Both methods reach the same solution from the closer starting point. From the farther point, GN’s first candidate produces nonfinite exponential values and the implementation stops. LM rejects candidates and continues, obtaining $a\approx2.50$, $b\approx1.27$, and $F\approx0.0406$. The curve labeled “far / GN stopped” shows the retained initial values at termination, not a successful fit.

dense_t = np.linspace(0, 4, 250)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
axes[0].scatter(t, y, s=20, color="0.400", label="Data")
axes[0].plot(dense_t, 2.50 * np.exp(-1.30 * dense_t), "--", color="black", label="True curve")
for method, style in [("GN", ":"), ("LM", "-")]:
    x_fit = fits[("far", method)]["x"]
    label = "far / GN stopped" if method == "GN" else "far / LM"
    axes[0].plot(dense_t, exp_model(x_fit, dense_t), style, color=colors[method], label=label)
    axes[1].plot(t, exp_residual(x_fit), "." + style, color=colors[method], label=label)
axes[0].set(xlabel="t", ylabel="y", title="Exponential fit from far start")
axes[1].axhline(0, color="0.500", linewidth=1)
axes[1].set(xlabel="t", ylabel="Model - observation", title="Residuals")
for ax in axes:
    ax.legend(fontsize=9)
save_figure(fig, "06_exponential_fit.svg")

fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
for ax, case in zip(axes, initials):
    for method, style in [("GN", ":"), ("LM", "-")]:
        result = fits[(case, method)]
        # Use open circles for GN so overlapping curves remain distinguishable.
        ax.semilogy(
            np.arange(result["costs"].size), result["costs"], linestyle=style,
            marker="o" if method == "GN" else ".", markersize=6 if method == "GN" else 3,
            markerfacecolor="none" if method == "GN" else colors[method],
            color=colors[method], label=method, zorder=3 if method == "GN" else 2,
        )
        if result["status"] == "Stopped due to nonfinite values":
            last_trial = result["costs"].size - 1
            ax.scatter(last_trial, result["F"], marker="x", s=60, color=colors[method], zorder=4)
            ax.annotate("GN stopped", (last_trial, result["F"]), xytext=(12, -18),
                        textcoords="offset points", color=colors[method], fontsize=9)
    ax.set(xlabel="Trial (including rejections)", ylabel="F", title=f"Initial point: {case}")
    ax.legend()
save_figure(fig, "07_initial_values.svg", integer_x=True)

Checking against SciPy’s LM method

Pass the residual vector, not its sum of squares, to scipy.optimize.least_squares. Its method="lm" uses MINPACK, with damping and stopping rules different from our simple implementation. We explicitly set x_scale=1 to avoid relying on the default.

SciPy’s LM interface does not support bounds, sparse Jacobians, or problems with $m\lt n$. It supports only linear loss. These are restrictions of this particular interface. For bounds, choose a method such as method="trf". See the SciPy documentation.

reference = least_squares(
    exp_residual, initials["far"], jac=exp_jacobian, method="lm", x_scale=1,
    ftol=1.00e-12, xtol=1.00e-12, gtol=1.00e-12,
)
pprint({"x": [sig3(v) for v in reference.x], "F": sig3(reference.cost),
        "nfev": reference.nfev, "success": bool(reference.success)}, sort_dicts=False)

# Compare solutions and gradients for the same objective, not iteration counts.
assert reference.success
for key in [("near", "GN"), ("near", "LM"), ("far", "LM")]:
    np.testing.assert_allclose(fits[key]["x"], reference.x, atol=1.00e-6)
    gradient = exp_jacobian(fits[key]["x"]).T @ exp_residual(fits[key]["x"])
    assert np.linalg.norm(gradient, ord=np.inf) < 1.00e-7
for case in initials:
    assert np.all(np.diff(fits[(case, "LM")]["costs"]) <= 0)
assert fits[("far", "GN")]["status"] == "Stopped due to nonfinite values"

display(Math(r"\widehat{\mathbf{x}}=\begin{bmatrix}"
             + sig3(reference.x[0]) + r"\\" + sig3(reference.x[1])
             + r"\end{bmatrix},\qquad F(\widehat{\mathbf{x}})=" + sig3(reference.cost)))
print("Checked the known solution, Jacobian, accepted objective values, and agreement with SciPy.")
{'x': ['2.50', '1.27'], 'F': '0.0406', 'nfev': 10, 'success': True}

$$ \displaystyle \widehat{\mathbf{x}}=\begin{bmatrix}2.50\\1.27\end{bmatrix},\qquad F(\widehat{\mathbf{x}})=0.0406 $$

Checked the known solution, Jacobian, accepted objective values, and agreement with SciPy.

Conclusion

We derived the GN and LM updates and used numerical examples to examine damping, update sizes, and candidate acceptance or rejection.

GN solves a least-squares problem formed by linearizing the residuals. LM penalizes the update and adjusts damping using the actual reduction. GN can make progress with few updates near a solution, while LM’s rejection and retry mechanism helps when a candidate moves far from the current point. Check the objective value and termination reason as well as the final parameter estimates.