{
  "id": "calculus-optimization",
  "module": "math-ml",
  "level": 2,
  "minutes": 35,
  "audiences": [
    "beginner",
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "Calculus and Optimization: Derivatives, Gradients, the Chain Rule and Gradient Descent",
      "description": "Calculus and optimisation for machine learning: derivatives and partial derivatives, the geometry of the gradient, the chain rule, backpropagation and automatic differentiation, gradient descent and the learning rate, condition number and convergence on quadratics, momentum, stochastic gradient descent (Robbins–Monro), Adam and AdamW, and convex versus non-convex losses. Based on original papers and official documentation, with runnable NumPy and PyTorch code.",
      "updated": "2026-11-10",
      "takeaways": [
        "The gradient is the vector of partial derivatives and points in the direction of steepest increase; gradient descent updates parameters along the negative gradient, w ← w − α∇f(w), where α is the learning rate.",
        "The chain rule writes the derivative of a composite function as a product of local derivatives. Backpropagation (Rumelhart, Hinton and Williams, 1986) uses it to compute every parameter's gradient layer by layer from the output backwards; Baydin et al. (2015) note that it is a special case of reverse-mode automatic differentiation.",
        "On a quadratic, gradient descent converges at rate max|1−αλᵢ|, governed by the ratio of the Hessian's largest and smallest eigenvalues (the condition number κ); any learning rate above 2/λ_max diverges. Momentum improves the dependence on the same problem from κ to roughly √κ.",
        "Stochastic gradient descent replaces the full gradient with a mini-batch gradient; it goes back to the stochastic approximation method of Robbins and Monro (1951), and Bottou et al. (2016) review its central role in large-scale machine learning.",
        "Adam adapts each parameter's step using exponential moving averages of the gradient's first and second moments; AdamW decouples weight decay from the gradient update, and Loshchilov and Hutter (2017) show that for Adam, L2 regularisation and weight decay are not equivalent."
      ],
      "faq": [
        {
          "q": "Why does the gradient point in the direction of steepest increase?",
          "a": "The directional derivative along a unit vector u is ∇f·u = ‖∇f‖cosθ, where θ is the angle between u and the gradient. It is largest, ‖∇f‖, at θ = 0 — along the gradient — and most negative at θ = π, which is why gradient descent steps along the negative gradient."
        },
        {
          "q": "How should I choose the learning rate?",
          "a": "In theory, under a quadratic approximation the learning rate must be below 2/λ_max (λ_max being the Hessian's largest eigenvalue), and the optimum is 2/(λ_min+λ_max). In practice the Hessian is unknown, so you run a learning-rate sweep on a log scale (1e-4, 3e-4, 1e-3, …), train briefly with each, pick the value whose loss falls fastest without diverging, and combine it with warm-up and decay schedules."
        },
        {
          "q": "Neural-network losses are non-convex. Why does gradient descent still work?",
          "a": "Non-convex functions can have many local minima and saddle points, and gradient descent does not guarantee a global optimum. In practice, gradient methods usually find well-generalising solutions for large networks; the visualisations of Li et al. (2017) show that architectural choices such as skip connections make the loss surface smoother and easier to train. This is an empirical observation, not a general theorem."
        },
        {
          "q": "How does automatic differentiation differ from numerical differentiation?",
          "a": "Numerical differentiation approximates derivatives with (f(x+h)−f(x−h))/2h, needs two extra function evaluations per parameter and suffers from truncation and round-off error, so it is only suitable for gradient checking. Automatic differentiation records operations as the program runs and applies the chain rule exactly; in reverse mode, one backward pass yields the gradient of a scalar loss with respect to all parameters."
        },
        {
          "q": "Why does a PyTorch training loop call zero_grad every step?",
          "a": "The official PyTorch tutorial explains that backward accumulates gradients into the .grad attribute of leaf tensors. Without zeroing, this step's gradient is added to the previous one. In this lesson's example, calling backward twice on the same loss changes w.grad from −0.354894 to −0.709788 — exactly doubled."
        }
      ],
      "sources": [
        {
          "title": "Robbins & Monro (1951), A Stochastic Approximation Method, The Annals of Mathematical Statistics",
          "url": "https://projecteuclid.org/euclid.aoms/1177729586"
        },
        {
          "title": "Polyak (1964), Some methods of speeding up the convergence of iteration methods",
          "url": "https://doi.org/10.1016/0041-5553(64)90137-5"
        },
        {
          "title": "Rumelhart, Hinton & Williams (1986), Learning representations by back-propagating errors, Nature",
          "url": "https://doi.org/10.1038/323533a0"
        },
        {
          "title": "Baydin et al. (2015), Automatic differentiation in machine learning: a survey",
          "url": "https://arxiv.org/abs/1502.05767"
        },
        {
          "title": "Bottou, Curtis & Nocedal (2016), Optimization Methods for Large-Scale Machine Learning",
          "url": "https://arxiv.org/abs/1606.04838"
        },
        {
          "title": "Kingma & Ba (2014), Adam: A Method for Stochastic Optimization",
          "url": "https://arxiv.org/abs/1412.6980"
        },
        {
          "title": "Loshchilov & Hutter (2017), Decoupled Weight Decay Regularization (AdamW)",
          "url": "https://arxiv.org/abs/1711.05101"
        },
        {
          "title": "Li et al. (2017), Visualizing the Loss Landscape of Neural Nets",
          "url": "https://arxiv.org/abs/1712.09913"
        },
        {
          "title": "Goh (2017), Why Momentum Really Works, Distill",
          "url": "https://distill.pub/2017/momentum/"
        },
        {
          "title": "PyTorch tutorial: Automatic Differentiation with torch.autograd",
          "url": "https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html"
        },
        {
          "title": "PyTorch documentation: torch.optim",
          "url": "https://docs.pytorch.org/docs/stable/optim.html"
        },
        {
          "title": "Dive into Deep Learning: 2.4 Calculus, 2.5 Automatic Differentiation",
          "url": "https://d2l.ai/chapter_preliminaries/calculus.html"
        },
        {
          "title": "Dive into Deep Learning: 12 Optimization Algorithms",
          "url": "https://d2l.ai/chapter_optimization/index.html"
        },
        {
          "title": "Deisenroth, Faisal, Ong: Mathematics for Machine Learning (official free edition)",
          "url": "https://mml-book.github.io/"
        },
        {
          "title": "karpathy/micrograd (an autodiff engine in about a hundred lines)",
          "url": "https://github.com/karpathy/micrograd"
        },
        {
          "title": "3Blue1Brown: Essence of Calculus",
          "url": "https://www.3blue1brown.com/?topic=calculus"
        },
        {
          "title": "Khan Academy: Multivariable calculus",
          "url": "https://www.khanacademy.org/math/multivariable-calculus"
        }
      ],
      "url": "https://aimap.page/en/learn/math-ml/calculus-optimization/",
      "markdown": "**Overview**: Training a neural network means solving an optimisation problem: finding the parameters that minimise a loss function. This lesson starts from derivatives, partial derivatives and gradients, shows how the chain rule becomes backpropagation and automatic differentiation, then analyses the learning rate and condition number of gradient descent, momentum, stochastic gradient descent, and the two mainstream optimisers Adam and AdamW. Every numerical claim comes with a runnable check.\n\nThis lesson belongs to the [Calculus and Optimization](/learn/unit/u12-calculus) unit; the prerequisite is [Python and NumPy setup](/learn/python-numpy-setup), and the eigenvalue section of [Linear Algebra](/learn/linear-algebra) is recommended first. Continue with [PyTorch autograd and the training loop](/learn/pytorch-autograd) and [Neural Network Basics](/learn/neural-networks). Related algorithm cards: [SGD](/learn/algorithms/sgd), [Backpropagation](/learn/algorithms/backprop), [Adam](/learn/algorithms/adam), [AdamW](/learn/algorithms/adamw), [Weight initialisation](/learn/algorithms/weight-init).\n\n## Derivatives, partial derivatives and gradients\n\nThe derivative of a one-variable function, f′(x) = lim(h→0) [f(x+h) − f(x)]/h, is its rate of change at x. For a multivariable function f(x₁, …, xₙ), differentiating with respect to each variable gives the **partial derivatives** ∂f/∂xᵢ; stacking them gives the **gradient**:\n\n```text\n∇f(x) = ( ∂f/∂x₁, …, ∂f/∂xₙ )ᵀ\n```\n\nThe directional derivative along a unit vector u is ∇f·u = ‖∇f‖cos θ. The gradient is therefore the direction of steepest increase, and the negative gradient the direction of steepest decrease.\n\nFor example, f(x, y) = x²y + sin y has ∂f/∂x = 2xy and ∂f/∂y = x² + cos y. At (1.5, −0.7) the analytic gradient is (−2.1, 3.014842), which matches the central difference [f(x+h) − f(x−h)]/2h (see the example below). Central differences are routinely used for **gradient checking** of hand-written or custom derivative code.\n\nThe matrix of second derivatives, the **Hessian** Hᵢⱼ = ∂²f/∂xᵢ∂xⱼ, describes curvature. It is real and symmetric, and its eigenvalues determine how gradient descent converges; see the section on the condition number.\n\n## The chain rule, backpropagation and automatic differentiation\n\nIf L = g(h(w)), then dL/dw = g′(h(w))·h′(w). A neural network is a composition of many functions, and the chain rule writes the derivative of the loss with respect to any parameter as a product of local derivatives along the path.\n\nFor a single neuron L = (σ(wx+b) − t)², with z = wx + b and s = σ(z):\n\n```text\n∂L/∂w = 2(s − t) · s(1 − s) · x\n```\n\nThe three factors are ∂L/∂s, ∂s/∂z and ∂z/∂w respectively.\n\nWith x = 2, t = 1, w = 0.3, b = −0.1, the chain rule gives −0.354894, the same value as numerical differentiation and PyTorch autograd.\n\n- **Backpropagation**: the algorithm published by Rumelhart, Hinton and Williams (1986) in Nature repeatedly adjusts connection weights to minimise the difference between the network's actual and desired outputs, and in the process hidden units come to represent important features of the task ([Rumelhart et al., 1986](https://doi.org/10.1038/323533a0)).\n- **Automatic differentiation**: the survey by Baydin et al. (2015) defines automatic differentiation as a family of techniques for computing derivatives of programs exactly, more general than backpropagation, which is a special case of reverse-mode AD ([Baydin et al., 2015](https://arxiv.org/abs/1502.05767)). Reverse mode's advantage is that, for a scalar loss, one backward sweep yields the gradient with respect to all parameters, at a cost of the same order as one forward evaluation.\n- **PyTorch autograd**: the official tutorial explains that autograd records tensors and executed operations in a directed acyclic graph (DAG) of Function objects, with input tensors as leaves and outputs as roots; calling `.backward()` computes gradients by the chain rule and **accumulates** them into each leaf tensor's `.grad` attribute ([PyTorch tutorial](https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html)). This is why training loops call `zero_grad()` every step.\n\nTo see the mechanism in source code, read [micrograd](https://github.com/karpathy/micrograd), a scalar reverse-mode autodiff engine in about a hundred lines of Python.\n\n## Gradient descent and the learning rate\n\nGradient descent updates\n\n```text\nw_{t+1} = w_t − α ∇f(w_t)\n```\n\nwhere the learning rate α sets the step size. Fitting y = 3x + 0.5 (plus a little noise) on 200 examples with mean squared error, 50 steps each, this lesson's demo measured:\n\n| Learning rate | a after 50 steps | b after 50 steps | MSE | Behaviour |\n|---|---|---|---|---|\n| 0.05 | 2.5253 | 0.5451 | 0.08824 | Converging, not yet there |\n| 0.5 | 2.9873 | 0.4921 | 0.01042 | Close to the true values |\n| 1.2 | about −4.9×10⁶ | about −4.0×10⁷ | about 1.6×10¹⁵ | Diverges |\n\nA learning rate that is too small converges slowly; one that is too large makes the parameters bounce across the valley with growing amplitude. The next section explains this quantitatively.\n\n## Condition number and convergence speed\n\nConsider the quadratic f(w) = ½wᵀAw with symmetric positive definite A and eigenvalues λ₁ ≤ … ≤ λₙ. In eigenvector coordinates, gradient descent shrinks each direction independently by a factor 1 − αλᵢ, so the overall rate is\n\n```text\nrate(α) = max{ |1 − αλ₁|, |1 − αλₙ| }\n```\n\nGoh (2017) derives the following in Distill ([Goh, 2017](https://distill.pub/2017/momentum/)):\n\n- The optimal learning rate is α* = 2/(λ₁ + λₙ), giving rate (κ − 1)/(κ + 1), where the **condition number** is κ = λₙ/λ₁;\n- the larger κ, the slower gradient descent; with κ = 1 it converges in one step;\n- as soon as some direction has |1 − αλᵢ| > 1, i.e. α > 2/λₙ, the iteration diverges.\n\nWith λ = (1, 100), κ = 100, and 100 iterations, the demo measured:\n\n| Learning rate α | Rate | ‖w‖ after 100 steps |\n|---|---|---|\n| 0.005 | 0.9950 | 0.6058 |\n| 2/101 ≈ 0.0198 (optimal) | 0.9802 | 0.1914 |\n| 0.0201 (just above 2/100) | 1.0100 | 2.708 (diverging) |\n\nEven with the optimal learning rate, gradient descent is slow on an ill-conditioned problem, and a learning rate only slightly above 2/λₘₐₓ diverges.\n\n## Momentum\n\nMomentum (the heavy-ball method, Polyak 1964) adds a \"velocity\" term to the update ([Polyak, 1964](https://doi.org/10.1016/0041-5553(64)90137-5)):\n\n```text\nz_{t+1} = β z_t + ∇f(w_t)\nw_{t+1} = w_t − α z_{t+1}\n```\n\nGoh (2017) gives the optimal parameters on a quadratic, α = [2/(√λ₁ + √λₙ)]² and β = [(√κ − 1)/(√κ + 1)]², which improve the rate from (κ − 1)/(κ + 1) to (√κ − 1)/(√κ + 1) — described in the article as up to a quadratic speed-up. On the κ = 100 problem above, after 100 steps the demo measured ‖w‖ = 0.1914 for optimal gradient descent and 3.5×10⁻⁷ for optimal momentum.\n\n## Stochastic gradient descent\n\nMachine-learning losses are usually averages over many examples, f(w) = (1/N)Σᵢ ℓᵢ(w). Computing the full gradient every step is too expensive, so **stochastic gradient descent (SGD)** uses the gradient on a mini-batch as an unbiased estimate.\n\nIts theoretical origin is the stochastic approximation method of Robbins and Monro (1951), which iteratively finds a root when only noisy function values can be observed ([Robbins & Monro, 1951](https://doi.org/10.1214/aoms/1177729586)). The classical convergence conditions require step sizes with Σₜ αₜ = ∞ and Σₜ αₜ² < ∞, the theoretical basis for decaying learning rates. The review by Bottou, Curtis and Nocedal (2016) argues that large-scale machine learning is a setting where the stochastic gradient method plays a central role while conventional gradient-based nonlinear optimisation techniques typically falter, and discusses two lines of improvement: reducing noise in stochastic directions and using second-order information ([Bottou et al., 2016](https://arxiv.org/abs/1606.04838)).\n\n## Adam and AdamW\n\n**Adam** (Kingma and Ba, 2014) keeps, for each parameter, exponential moving averages of the gradient's first moment m and second moment v, with bias correction ([Kingma & Ba, 2014](https://arxiv.org/abs/1412.6980)):\n\n```text\nm_t = β₁ m_{t−1} + (1 − β₁) g_t\nv_t = β₂ v_{t−1} + (1 − β₂) g_t²\nm̂_t = m_t / (1 − β₁ᵗ)\nv̂_t = v_t / (1 − β₂ᵗ)\nw_t = w_{t−1} − α · m̂_t / (√v̂_t + ε)\n```\n\nThe paper's default hyperparameters are α = 0.001, β₁ = 0.9, β₂ = 0.999, ε = 10⁻⁸, and the abstract notes that the method is invariant to diagonal rescaling of the gradients. In this lesson's demo the two gradient components differ by a factor of 100 (0.1 and −10), yet Adam's first update is 0.001 in magnitude for both, opposite to the gradient — the step size is set by α, not by the gradient's absolute scale.\n\n**AdamW** (Loshchilov and Hutter, 2017) points out that L2 regularisation and weight decay are equivalent for standard SGD (after rescaling by the learning rate) but not for adaptive methods such as Adam. They decouple weight decay from the loss-based gradient step, which makes the optimal weight-decay factor independent of the learning rate and substantially improves Adam's generalisation ([Loshchilov & Hutter, 2017](https://arxiv.org/abs/1711.05101)). PyTorch provides both `Adam` and `AdamW` in `torch.optim` ([PyTorch documentation](https://docs.pytorch.org/docs/stable/optim.html)).\n\n| Method | State per parameter | Main effect | Source |\n|---|---|---|---|\n| SGD | None | Mini-batch estimate of the full gradient | Robbins & Monro, 1951 |\n| Momentum | One velocity | Counters ill-conditioning, speeds convergence | Polyak, 1964 |\n| Adam | First and second moments | Per-parameter adaptive steps | Kingma & Ba, 2014 |\n| AdamW | Same as Adam | Decoupled weight decay | Loshchilov & Hutter, 2017 |\n\n## Convex and non-convex losses\n\nFor a convex function every local minimum is global, and gradient descent with a suitable learning rate is guaranteed to converge; the losses of linear and logistic regression are convex. Neural-network losses are non-convex, with many local minima and saddle points. Li et al. (2017) introduce \"filter normalisation\" to visualise loss surfaces and compare how architectures and training parameters shape the surface and its minimisers — for instance, skip connections produce losses that are easier to train ([Li et al., 2017](https://arxiv.org/abs/1712.09913)). These are empirical findings; why non-convex optimisation works so well in deep learning remains an open research question.\n\n## Runnable example\n\nThe NumPy script below reproduces every numerical claim in this lesson (run under Python 3.13 and NumPy 2.5 with a fixed seed):\n\n```python\nimport numpy as np\nrng = np.random.default_rng(0)\n\n# 1) Partial derivatives and gradient check: f(x, y) = x^2 * y + sin(y)\nf = lambda p: p[0] ** 2 * p[1] + np.sin(p[1])\ngrad_f = lambda p: np.array([2 * p[0] * p[1], p[0] ** 2 + np.cos(p[1])])\np, h = np.array([1.5, -0.7]), 1e-5\nnum = np.array([(f(p + h * e) - f(p - h * e)) / (2 * h) for e in np.eye(2)])\nprint(\"analytic =\", np.round(grad_f(p), 6), \" numeric =\", np.round(num, 6))\n\n# 2) Chain rule: L = (sigmoid(w*x + b) - t)^2\nx, t, w, b = 2.0, 1.0, 0.3, -0.1\ns = 1 / (1 + np.exp(-(w * x + b)))\nprint(\"dL/dw =\", round(2 * (s - t) * s * (1 - s) * x, 6))\n\n# 3) Gradient descent for y = a x + b with three learning rates\nX = rng.uniform(-1, 1, 200); Y = 3.0 * X + 0.5 + 0.1 * rng.standard_normal(200)\nfor lr in (0.05, 0.5, 1.2):\n    a = bb = 0.0\n    for _ in range(50):\n        r = a * X + bb - Y\n        a, bb = a - lr * 2 * (r * X).mean(), bb - lr * 2 * r.mean()\n    print(f\"lr={lr} a={a:.4f} b={bb:.4f} mse={((a * X + bb - Y) ** 2).mean():.4g}\")\n\n# 4) Condition number: f = 0.5 * (1 * x1^2 + 100 * x2^2)\nlam = np.array([1.0, 100.0]); kappa = lam.max() / lam.min()\ndef run(alpha, beta=0.0, steps=100):\n    w_, z = np.array([1.0, 1.0]), np.zeros(2)\n    for _ in range(steps):\n        z = beta * z + lam * w_\n        w_ = w_ - alpha * z\n    return np.linalg.norm(w_)\nfor alpha in (0.005, 2 / (lam.min() + lam.max()), 0.0201):\n    print(f\"alpha={alpha:.5f} rate={np.abs(1 - alpha * lam).max():.4f} |w|={run(alpha):.3e}\")\n\n# 5) Momentum with the optimal parameters from Goh (2017)\na_m = (2 / (np.sqrt(lam.min()) + np.sqrt(lam.max()))) ** 2\nb_m = ((np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)) ** 2\nprint(f\"momentum alpha={a_m:.4f} beta={b_m:.4f} |w|={run(a_m, b_m):.3e}\")\n\n# 6) First Adam step (Kingma & Ba default hyperparameters)\ng = np.array([0.1, -10.0]); b1, b2, lr, eps = 0.9, 0.999, 1e-3, 1e-8\nm, v = (1 - b1) * g, (1 - b2) * g ** 2\nprint(\"Adam step =\", lr * (m / (1 - b1)) / (np.sqrt(v / (1 - b2)) + eps))\n```\n\nKey points from the measured output: analytic and numerical gradients are both `[-2.1, 3.014842]`; the chain rule gives `dL/dw = -0.354894`; the learning-rate results are in the table above; the condition-number and momentum figures are in those two sections (optimal momentum parameters α = 0.0331, β = 0.6694); the first Adam step is `[0.001, -0.001]`.\n\nChecking the same chain rule with PyTorch autograd, and observing gradient accumulation (measured on PyTorch 2.x CPU):\n\n```python\nimport torch\nx, t = torch.tensor(2.0), torch.tensor(1.0)\nw = torch.tensor(0.3, requires_grad=True)\nb = torch.tensor(-0.1, requires_grad=True)\nL = (torch.sigmoid(w * x + b) - t) ** 2\nL.backward()\nprint(w.grad.item(), b.grad.item())   # -0.354894, -0.177447\nL = (torch.sigmoid(w * x + b) - t) ** 2\nL.backward()                          # not zeroed, so gradients accumulate\nprint(w.grad.item())                  # -0.709788\n```\n\n## Exercises\n\n1. **Unit project**: write gradient descent by hand to fit y = ax + b, try at least three learning rates and plot the loss curves; use the condition-number section to explain which one diverges and why. Then standardise the input feature, rerun, and compare convergence speed.\n2. Read and retype [micrograd](https://github.com/karpathy/micrograd), train a small multilayer perceptron with it, and check its gradients with central differences.\n3. In the interactive figures of [Distill: Why Momentum Really Works](https://distill.pub/2017/momentum/), adjust the step size and momentum and observe when gradient descent oscillates or diverges.\n4. In PyTorch, train the same model with `torch.optim.SGD` (with momentum), `Adam` and `AdamW`, record training and validation loss, and compare the effect of weight decay.\n\n## Suggested order of study\n\nStart with [3Blue1Brown's Essence of Calculus](https://www.3blue1brown.com/?topic=calculus) for intuition about derivatives and the chain rule, and practise partial derivatives and gradients in [Khan Academy Multivariable Calculus](https://www.khanacademy.org/math/multivariable-calculus). Then read [D2L sections 2.4–2.5](https://d2l.ai/chapter_preliminaries/calculus.html) to put the ideas into code; for systematic study use chapters 5 (vector calculus) and 7 (continuous optimisation) of [Mathematics for Machine Learning](https://mml-book.github.io/), and see [D2L chapter 12](https://d2l.ai/chapter_optimization/index.html) for optimiser details. Then continue with [PyTorch autograd and the training loop](/learn/pytorch-autograd)."
    },
    "zh-hans": {
      "title": "微积分与优化：导数、梯度、链式法则与梯度下降",
      "description": "面向机器学习的微积分与优化：导数与偏导、梯度的几何含义，链式法则与反向传播、自动微分，梯度下降与学习率，二次函数上的条件数与收敛速度，动量法、随机梯度下降（Robbins–Monro）、Adam 与 AdamW，以及凸与非凸损失。依据原始论文与官方文档，附可运行的 NumPy 与 PyTorch 示例。",
      "updated": "2026-11-10",
      "takeaways": [
        "梯度是由各偏导组成的向量，指向函数值增长最快的方向；梯度下降沿负梯度方向更新参数：w ← w − α∇f(w)，α 为学习率。",
        "链式法则把复合函数的导数写成各层局部导数的乘积。反向传播（Rumelhart、Hinton、Williams，1986）按此从输出往回逐层计算每个参数的梯度；Baydin 等（2015）指出它是反向模式自动微分的特例。",
        "在二次函数上，梯度下降的收敛速度为 max|1−αλᵢ|，由 Hessian 最大与最小特征值之比（条件数 κ）决定；学习率超过 2/λ_max 就会发散。动量法在同一问题上把依赖关系从 κ 改善为约 √κ。",
        "随机梯度下降用小批量梯度代替全量梯度，源头是 Robbins 与 Monro（1951）的随机逼近方法；Bottou 等（2016）总结了它在大规模机器学习中的核心地位。",
        "Adam 用梯度一阶矩与二阶矩的指数滑动平均自适应调整每个参数的步长；AdamW 把权重衰减从梯度更新中解耦，Loshchilov 与 Hutter（2017）证明对 Adam 而言 L2 正则与权重衰减并不等价。"
      ],
      "faq": [
        {
          "q": "梯度为什么指向函数增长最快的方向？",
          "a": "沿单位方向 u 的方向导数等于 ∇f·u = ‖∇f‖cosθ，θ 为 u 与梯度的夹角。θ=0 时取最大值 ‖∇f‖，即沿梯度方向增长最快；θ=π 时下降最快，这就是梯度下降取负梯度方向的原因。"
        },
        {
          "q": "学习率应该怎么选？",
          "a": "从理论上看，二次近似下学习率需小于 2/λ_max（λ_max 为 Hessian 最大特征值），最优值为 2/(λ_min+λ_max)。实践中 Hessian 未知，通常做学习率扫描：按对数间隔（如 1e-4、3e-4、1e-3……）各训练一小段，选损失下降最快且不发散的值，再配合预热与衰减调度。"
        },
        {
          "q": "神经网络的损失是非凸的，梯度下降为什么还有效？",
          "a": "非凸函数可能有多个局部极小与鞍点，梯度下降不保证找到全局最优。实践中，大网络通过梯度方法通常能找到泛化良好的解；Li 等（2017）的可视化显示，残差连接等结构会让损失曲面更平滑、更易训练。这是经验观察，不是普遍定理。"
        },
        {
          "q": "自动微分和数值差分有什么区别？",
          "a": "数值差分用 (f(x+h)−f(x−h))/2h 近似导数，每个参数都要多算两次函数，且有截断与舍入误差，只适合用来检查梯度。自动微分在程序执行时记录运算，按链式法则精确求导；反向模式一次反向传播即可得到标量损失对全部参数的梯度。"
        },
        {
          "q": "为什么 PyTorch 训练循环里每步都要 zero_grad？",
          "a": "PyTorch 官方教程说明：调用 backward 时梯度会累加到叶子张量的 .grad 属性上。不清零的话，本步梯度会叠加上一步的梯度。本课示例对同一损失连续两次 backward，w.grad 从 −0.354894 变为 −0.709788，正好翻倍。"
        }
      ],
      "sources": [
        {
          "title": "Robbins、Monro（1951），A Stochastic Approximation Method，The Annals of Mathematical Statistics",
          "url": "https://projecteuclid.org/euclid.aoms/1177729586"
        },
        {
          "title": "Polyak（1964），Some methods of speeding up the convergence of iteration methods",
          "url": "https://doi.org/10.1016/0041-5553(64)90137-5"
        },
        {
          "title": "Rumelhart、Hinton、Williams（1986），Learning representations by back-propagating errors，Nature",
          "url": "https://doi.org/10.1038/323533a0"
        },
        {
          "title": "Baydin 等（2015），Automatic differentiation in machine learning: a survey",
          "url": "https://arxiv.org/abs/1502.05767"
        },
        {
          "title": "Bottou、Curtis、Nocedal（2016），Optimization Methods for Large-Scale Machine Learning",
          "url": "https://arxiv.org/abs/1606.04838"
        },
        {
          "title": "Kingma、Ba（2014），Adam: A Method for Stochastic Optimization",
          "url": "https://arxiv.org/abs/1412.6980"
        },
        {
          "title": "Loshchilov、Hutter（2017），Decoupled Weight Decay Regularization（AdamW）",
          "url": "https://arxiv.org/abs/1711.05101"
        },
        {
          "title": "Li 等（2017），Visualizing the Loss Landscape of Neural Nets",
          "url": "https://arxiv.org/abs/1712.09913"
        },
        {
          "title": "Goh（2017），Why Momentum Really Works，Distill",
          "url": "https://distill.pub/2017/momentum/"
        },
        {
          "title": "PyTorch 官方教程：Automatic Differentiation with torch.autograd",
          "url": "https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html"
        },
        {
          "title": "PyTorch 文档：torch.optim",
          "url": "https://docs.pytorch.org/docs/stable/optim.html"
        },
        {
          "title": "Dive into Deep Learning：2.4 Calculus、2.5 Automatic Differentiation",
          "url": "https://d2l.ai/chapter_preliminaries/calculus.html"
        },
        {
          "title": "Dive into Deep Learning：12 Optimization Algorithms",
          "url": "https://d2l.ai/chapter_optimization/index.html"
        },
        {
          "title": "Deisenroth、Faisal、Ong：Mathematics for Machine Learning（官方免费版）",
          "url": "https://mml-book.github.io/"
        },
        {
          "title": "karpathy/micrograd（约百行的自动微分引擎）",
          "url": "https://github.com/karpathy/micrograd"
        },
        {
          "title": "3Blue1Brown：Essence of Calculus（微积分的本质）",
          "url": "https://www.3blue1brown.com/?topic=calculus"
        },
        {
          "title": "Khan Academy：Multivariable calculus",
          "url": "https://www.khanacademy.org/math/multivariable-calculus"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/math-ml/calculus-optimization/",
      "markdown": "**概要**：训练神经网络就是求解一个优化问题：找到使损失函数最小的参数。本课从导数、偏导与梯度出发，说明链式法则如何变成反向传播与自动微分，再分析梯度下降的学习率与条件数、动量法、随机梯度下降，以及 Adam 与 AdamW 两种主流优化器。每个结论都附有可运行的数值验证。\n\n本课属于[微积分与优化](/learn/unit/u12-calculus)单元，前置为 [Python 与 NumPy 环境](/learn/python-numpy-setup)，建议先学[线性代数](/learn/linear-algebra)中的特征值部分。后续可接 [PyTorch 自动求导与训练循环](/learn/pytorch-autograd)与[神经网络基础](/learn/neural-networks)。相关算法卡：[随机梯度下降](/learn/algorithms/sgd)、[反向传播](/learn/algorithms/backprop)、[Adam](/learn/algorithms/adam)、[AdamW](/learn/algorithms/adamw)、[权重初始化](/learn/algorithms/weight-init)。\n\n## 导数、偏导与梯度\n\n一元函数的导数 f′(x) = lim(h→0) [f(x+h) − f(x)]/h 描述函数在 x 处的变化率。多元函数 f(x₁, …, xₙ) 对每个变量分别求导得到**偏导** ∂f/∂xᵢ，把全部偏导排成向量就是**梯度**：\n\n```text\n∇f(x) = ( ∂f/∂x₁, …, ∂f/∂xₙ )ᵀ\n```\n\n沿单位方向 u 的方向导数为 ∇f·u = ‖∇f‖cos θ。因此梯度方向是函数值增长最快的方向，负梯度方向下降最快。\n\n例如 f(x, y) = x²y + sin y，有 ∂f/∂x = 2xy、∂f/∂y = x² + cos y。在点 (1.5, −0.7) 处，解析梯度为 (−2.1, 3.014842)，与中心差分 [f(x+h) − f(x−h)]/2h 的结果一致（见下文示例）。中心差分常用于**梯度检查**，用来验证手写或自定义的求导代码。\n\n二阶导数组成的矩阵称为 **Hessian** Hᵢⱼ = ∂²f/∂xᵢ∂xⱼ，刻画曲面的弯曲程度。它是实对称矩阵，其特征值决定了梯度下降的收敛行为，见后文“条件数”一节。\n\n## 链式法则、反向传播与自动微分\n\n若 L = g(h(w))，则 dL/dw = g′(h(w))·h′(w)。神经网络是很多层函数的复合，链式法则把损失对某个参数的导数写成沿路径各层局部导数的乘积。\n\n以单个神经元 L = (σ(wx+b) − t)² 为例，令 z = wx + b、s = σ(z)：\n\n```text\n∂L/∂w = 2(s − t) · s(1 − s) · x\n```\n\n其中三项依次为 ∂L/∂s、∂s/∂z 与 ∂z/∂w。\n\n取 x = 2，t = 1，w = 0.3，b = −0.1，按链式法则手算得 −0.354894，与数值差分和 PyTorch autograd 的结果相同。\n\n- **反向传播**：Rumelhart、Hinton 与 Williams（1986）在 Nature 发表的算法反复调整连接权重，使网络实际输出与期望输出之间的差距最小，隐藏单元在此过程中学会表示任务的重要特征（[Rumelhart 等，1986](https://doi.org/10.1038/323533a0)）。\n- **自动微分**：Baydin 等（2015）的综述把自动微分定义为一族精确计算程序导数的技术，比反向传播更一般；反向传播是反向模式自动微分的特例（[Baydin 等，2015](https://arxiv.org/abs/1502.05767)）。反向模式的优点是：对标量损失，一次反向遍历即可得到全部参数的梯度，代价与一次前向计算同一量级。\n- **PyTorch autograd**：官方教程说明，autograd 把张量与执行过的运算记录为由 Function 对象组成的有向无环图（DAG），叶子是输入张量，根是输出张量；调用 `.backward()` 后，按链式法则计算梯度并**累加**到叶子张量的 `.grad` 属性中（[PyTorch 教程](https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html)）。这也是训练循环每步都要 `zero_grad()` 的原因。\n\n想从源码层面理解，可以阅读 [micrograd](https://github.com/karpathy/micrograd)：它用约百行 Python 实现了标量反向模式自动微分。\n\n## 梯度下降与学习率\n\n梯度下降的更新规则为\n\n```text\nw_{t+1} = w_t − α ∇f(w_t)\n```\n\n学习率 α 控制步长。用 200 个样本拟合 y = 3x + 0.5（加少量噪声），损失为均方误差，各训练 50 步，本课示例的实测结果如下：\n\n| 学习率 | 50 步后的 a | 50 步后的 b | 均方误差 | 行为 |\n|---|---|---|---|---|\n| 0.05 | 2.5253 | 0.5451 | 0.08824 | 收敛，但尚未到位 |\n| 0.5 | 2.9873 | 0.4921 | 0.01042 | 收敛到接近真值 |\n| 1.2 | 约 −4.9×10⁶ | 约 −4.0×10⁷ | 约 1.6×10¹⁵ | 发散 |\n\n学习率过小时收敛慢，过大时参数在谷底两侧来回跳动并越跳越远。下一节给出这一现象的定量解释。\n\n## 条件数与收敛速度\n\n考虑二次函数 f(w) = ½wᵀAw，A 为对称正定矩阵，特征值 λ₁ ≤ … ≤ λₙ。在特征向量坐标下，梯度下降在每个方向上各自以因子 1 − αλᵢ 收缩，因此整体收敛速度为\n\n```text\nrate(α) = max{ |1 − αλ₁|, |1 − αλₙ| }\n```\n\nGoh（2017）在 Distill 中推导了以下结论（[Goh，2017](https://distill.pub/2017/momentum/)）：\n\n- 最优学习率 α* = 2/(λ₁ + λₙ)，此时速度为 (κ − 1)/(κ + 1)，其中**条件数** κ = λₙ/λ₁；\n- κ 越大，梯度下降越慢；κ = 1 时一步即可收敛；\n- 只要某个方向满足 |1 − αλᵢ| > 1，即 α > 2/λₙ，迭代就会发散。\n\n本课示例取 λ = (1, 100)、κ = 100，各迭代 100 步：\n\n| 学习率 α | 收敛因子 | 100 步后 ‖w‖ |\n|---|---|---|\n| 0.005 | 0.9950 | 0.6058 |\n| 2/101 ≈ 0.0198（最优） | 0.9802 | 0.1914 |\n| 0.0201（略大于 2/100） | 1.0100 | 2.708（发散） |\n\n这说明：即使用了最优学习率，病态问题上的梯度下降依然很慢；而学习率只要略超过 2/λₘₐₓ 就会发散。\n\n## 动量法\n\n动量法（heavy ball，Polyak，1964）在更新中加入“速度”项（[Polyak，1964](https://doi.org/10.1016/0041-5553(64)90137-5)）：\n\n```text\nz_{t+1} = β z_t + ∇f(w_t)\nw_{t+1} = w_t − α z_{t+1}\n```\n\nGoh（2017）给出了二次函数上的最优参数 α = [2/(√λ₁ + √λₙ)]²、β = [(√κ − 1)/(√κ + 1)]²，收敛速度从 (κ − 1)/(κ + 1) 改善为 (√κ − 1)/(√κ + 1)，文中称之为“最多二次方的加速”。在上面 κ = 100 的问题上，本课示例实测 100 步后，最优梯度下降的 ‖w‖ 为 0.1914，最优动量法为 3.5×10⁻⁷。\n\n## 随机梯度下降\n\n机器学习的损失通常是对大量样本的平均 f(w) = (1/N)Σᵢ ℓᵢ(w)。每步计算全量梯度代价太高，**随机梯度下降（SGD）**改用一个小批量样本的梯度作为无偏估计。\n\n它的理论源头是 Robbins 与 Monro（1951）的随机逼近方法：在只能观测到带噪声函数值的情况下迭代求根（[Robbins 与 Monro，1951](https://doi.org/10.1214/aoms/1177729586)）。经典收敛条件要求步长序列满足 Σₜ αₜ = ∞ 且 Σₜ αₜ² < ∞，这正是“学习率逐步衰减”的理论依据。Bottou、Curtis 与 Nocedal（2016）的综述指出，大规模机器学习是随机梯度方法占核心地位、而传统基于梯度的非线性优化方法往往表现不佳的场景，并讨论了降低随机方向噪声和利用二阶信息两条改进路线（[Bottou 等，2016](https://arxiv.org/abs/1606.04838)）。\n\n## Adam 与 AdamW\n\n**Adam**（Kingma 与 Ba，2014）对每个参数维护梯度的一阶矩 m 与二阶矩 v 的指数滑动平均，并做偏差修正（[Kingma 与 Ba，2014](https://arxiv.org/abs/1412.6980)）：\n\n```text\nm_t = β₁ m_{t−1} + (1 − β₁) g_t\nv_t = β₂ v_{t−1} + (1 − β₂) g_t²\nm̂_t = m_t / (1 − β₁ᵗ)\nv̂_t = v_t / (1 − β₂ᵗ)\nw_t = w_{t−1} − α · m̂_t / (√v̂_t + ε)\n```\n\n论文给出的默认超参为 α = 0.001，β₁ = 0.9，β₂ = 0.999，ε = 10⁻⁸。摘要指出该方法对梯度的对角缩放保持不变。本课示例中，两个分量梯度相差 100 倍（0.1 与 −10），Adam 第一步的更新却都是 0.001，大小相同、方向与梯度相反——步长由 α 决定，而不是由梯度的绝对大小决定。\n\n**AdamW**（Loshchilov 与 Hutter，2017）指出：对标准 SGD 而言，L2 正则与权重衰减（按学习率换算后）等价；但对 Adam 这类自适应方法并不等价。他们提出把权重衰减从基于损失的梯度更新中解耦，使最优权重衰减系数与学习率的选择相互独立，并显著改善 Adam 的泛化表现（[Loshchilov 与 Hutter，2017](https://arxiv.org/abs/1711.05101)）。PyTorch 在 `torch.optim` 中分别提供 `Adam` 与 `AdamW`（[PyTorch 文档](https://docs.pytorch.org/docs/stable/optim.html)）。\n\n| 方法 | 每参数状态 | 主要作用 | 出处 |\n|---|---|---|---|\n| SGD | 无 | 用小批量梯度近似全量梯度 | Robbins 与 Monro，1951 |\n| 动量法 | 速度 1 份 | 缓解病态曲率，加速收敛 | Polyak，1964 |\n| Adam | 一阶矩、二阶矩各 1 份 | 按参数自适应步长 | Kingma 与 Ba，2014 |\n| AdamW | 同 Adam | 解耦权重衰减 | Loshchilov 与 Hutter，2017 |\n\n## 凸与非凸\n\n凸函数的任意局部极小值都是全局极小值，梯度下降在合适学习率下有收敛保证，线性回归、逻辑回归的损失都属于此类。神经网络的损失是非凸的，存在多个局部极小与鞍点。Li 等（2017）提出“滤波器归一化”方法可视化损失曲面，比较了不同网络结构与训练参数对曲面形状和极小值附近形态的影响，例如残差连接让损失曲面更易训练（[Li 等，2017](https://arxiv.org/abs/1712.09913)）。这些是经验结论；非凸优化在深度学习中为何普遍有效，目前仍是开放的研究问题。\n\n## 可运行示例\n\n以下 NumPy 脚本覆盖本课全部数值结论（Python 3.13、NumPy 2.5 实测，随机种子固定）：\n\n```python\nimport numpy as np\nrng = np.random.default_rng(0)\n\n# 1) 偏导与梯度检查：f(x, y) = x^2 * y + sin(y)\nf = lambda p: p[0] ** 2 * p[1] + np.sin(p[1])\ngrad_f = lambda p: np.array([2 * p[0] * p[1], p[0] ** 2 + np.cos(p[1])])\np, h = np.array([1.5, -0.7]), 1e-5\nnum = np.array([(f(p + h * e) - f(p - h * e)) / (2 * h) for e in np.eye(2)])\nprint(\"analytic =\", np.round(grad_f(p), 6), \" numeric =\", np.round(num, 6))\n\n# 2) 链式法则：L = (sigmoid(w*x + b) - t)^2\nx, t, w, b = 2.0, 1.0, 0.3, -0.1\ns = 1 / (1 + np.exp(-(w * x + b)))\nprint(\"dL/dw =\", round(2 * (s - t) * s * (1 - s) * x, 6))\n\n# 3) 梯度下降拟合 y = a x + b，三种学习率\nX = rng.uniform(-1, 1, 200); Y = 3.0 * X + 0.5 + 0.1 * rng.standard_normal(200)\nfor lr in (0.05, 0.5, 1.2):\n    a = bb = 0.0\n    for _ in range(50):\n        r = a * X + bb - Y\n        a, bb = a - lr * 2 * (r * X).mean(), bb - lr * 2 * r.mean()\n    print(f\"lr={lr} a={a:.4f} b={bb:.4f} mse={((a * X + bb - Y) ** 2).mean():.4g}\")\n\n# 4) 条件数：f = 0.5 * (1 * x1^2 + 100 * x2^2)\nlam = np.array([1.0, 100.0]); kappa = lam.max() / lam.min()\ndef run(alpha, beta=0.0, steps=100):\n    w_, z = np.array([1.0, 1.0]), np.zeros(2)\n    for _ in range(steps):\n        z = beta * z + lam * w_\n        w_ = w_ - alpha * z\n    return np.linalg.norm(w_)\nfor alpha in (0.005, 2 / (lam.min() + lam.max()), 0.0201):\n    print(f\"alpha={alpha:.5f} rate={np.abs(1 - alpha * lam).max():.4f} |w|={run(alpha):.3e}\")\n\n# 5) 动量法（Goh 2017 给出的最优参数）\na_m = (2 / (np.sqrt(lam.min()) + np.sqrt(lam.max()))) ** 2\nb_m = ((np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)) ** 2\nprint(f\"momentum alpha={a_m:.4f} beta={b_m:.4f} |w|={run(a_m, b_m):.3e}\")\n\n# 6) Adam 第一步（Kingma & Ba 默认超参）\ng = np.array([0.1, -10.0]); b1, b2, lr, eps = 0.9, 0.999, 1e-3, 1e-8\nm, v = (1 - b1) * g, (1 - b2) * g ** 2\nprint(\"Adam step =\", lr * (m / (1 - b1)) / (np.sqrt(v / (1 - b2)) + eps))\n```\n\n实测输出要点：解析梯度与数值梯度均为 `[-2.1, 3.014842]`；链式法则得 `dL/dw = -0.354894`；三种学习率的结果见上文表格；条件数实验与动量实验的数值见“条件数”与“动量法”两节（动量法最优参数为 α=0.0331、β=0.6694）；Adam 第一步为 `[0.001, -0.001]`。\n\n用 PyTorch autograd 验证同一个链式法则，并观察梯度累加（PyTorch 2.x CPU 实测）：\n\n```python\nimport torch\nx, t = torch.tensor(2.0), torch.tensor(1.0)\nw = torch.tensor(0.3, requires_grad=True)\nb = torch.tensor(-0.1, requires_grad=True)\nL = (torch.sigmoid(w * x + b) - t) ** 2\nL.backward()\nprint(w.grad.item(), b.grad.item())   # -0.354894, -0.177447\nL = (torch.sigmoid(w * x + b) - t) ** 2\nL.backward()                          # 未清零，梯度累加\nprint(w.grad.item())                  # -0.709788\n```\n\n## 动手练习\n\n1. **单元项目**：手写梯度下降拟合 y = ax + b，至少尝试三种学习率，画出损失曲线；用“条件数”一节的结论解释哪一个发散、为什么。再对输入特征做标准化后重跑，比较收敛速度。\n2. 阅读并手敲 [micrograd](https://github.com/karpathy/micrograd)，用它训练一个小型多层感知机，并用中心差分检查梯度。\n3. 在 [Distill：Why Momentum Really Works](https://distill.pub/2017/momentum/) 的交互图中调节学习率与动量，观察梯度下降何时震荡、何时发散。\n4. 在 PyTorch 中对同一模型分别使用 `torch.optim.SGD`（带动量）、`Adam` 与 `AdamW`，记录训练损失与验证损失，比较权重衰减的作用。\n\n## 推荐学习顺序\n\n先看 [3Blue1Brown《微积分的本质》](https://www.3blue1brown.com/?topic=calculus)建立导数与链式法则的直觉，在 [Khan Academy 多元微积分](https://www.khanacademy.org/math/multivariable-calculus)练习偏导与梯度；再读 [D2L 2.4–2.5 节](https://d2l.ai/chapter_preliminaries/calculus.html)把概念落到代码，系统学习用 [Mathematics for Machine Learning](https://mml-book.github.io/) 第 5 章（向量微积分）与第 7 章（连续优化），优化器细节见 [D2L 第 12 章](https://d2l.ai/chapter_optimization/index.html)。之后进入 [PyTorch 自动求导与训练循环](/learn/pytorch-autograd)。"
    }
  }
}