The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← CS 230 — Mathematics, Statistics and Data for AI

Weeks 3–5

Derivatives, gradients and optimization steps

Learning objectives

  • Explain and trace the mechanisms in derivatives, gradients and optimization steps.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

A derivative measures local change. In optimization, the gradient collects partial derivatives with respect to model parameters. Subtracting a small positive multiple of the gradient moves locally downhill for a differentiable loss, but a step that is too large can increase loss or diverge. The learning rate has an operational meaning: it determines the size of the parameter update.

For squared loss on one example, L(w) = (wx − y)², the derivative is 2x(wx − y). The chain rule accounts for both the residual and how the prediction changes with w. Omitting x produces the wrong update except in special cases. A numerical finite-difference check compares the derivative with the change in loss under a tiny perturbation; very tiny steps can amplify rounding error.

Automatic differentiation applies differentiation rules to the actual computation graph. It does not determine whether the chosen loss corresponds to the business objective or whether data leaked from the future. Keep training state separate from evaluation. Record initial values and update order, because an accidental in-place modification can change a later calculation. Convergence of training loss is not evidence of good generalization.

Worked reasoning The initial prediction is 2 and residual −4, giving derivative −16. Subtracting 0.1 times −16 raises w to 2.6. The new prediction 5.2 has residual −0.8 and loss 0.64. A rate of 1 instead jumps to w = 17 and loss 784, illustrating that direction alone does not ensure a safe finite step.

Extended teaching and laboratory

For squared loss L(w)=(wx−y)², the chain rule gives dL/dw=2(wx−y)x. The sign points toward local increase; subtracting a positive multiple of it is a descent attempt. A finite learning rate can overshoot, so verify the resulting loss instead of assuming any step against the gradient must improve it.

Derivatives depend on the exact loss definition. Including a factor one-half removes the leading two. State the convention before comparing implementations; otherwise two correct derivations can appear inconsistent.

Worked problem Let x=3, y=12, w=2 and L=(wx−y)². Take a gradient step with learning rate .05, then compare a step with rate .2.

Step-by-step reasoning 1. Initially prediction is 6, residual −6, loss 36, and gradient 2×(−6)×3=−36.

  1. At rate .05, w becomes 3.8. Prediction is 11.4, residual −.6 and loss .36.
  1. At rate .2, w becomes 9.2. Prediction is 27.6, residual 15.6 and loss 243.36, worse than 36.
  1. The derivative supplied local direction, not a blanket guarantee for either finite step. Check the loss and document the update convention.

Local change, shared paths and accumulated quantities

For a real function f, the derivative at a is the limit of [f(a+h)−f(a)]/h as h approaches zero, if that limit exists. It is the slope of the best local linear approximation: f(a+h)=f(a)+f′(a)h+an error small relative to |h|. A difference quotient at one finite h estimates a slope; it is not the limiting definition itself. For f(x)=x², expanding (a+h)² gives quotient 2a+h, whose limit is 2a. At a=3 the tangent approximation is 9+6h. For h=.1 the exact value 9.61 differs from 9.6 by .01.

Differentiation rules combine local changes. Constants differentiate to zero; xⁿ has derivative nxⁿ⁻¹ wherever the expression is differentiable; exp(x) differentiates to itself; ln(x) differentiates to 1/x for x>0. The derivative of af+bg is af′+bg′. The product rule is (fg)′=f′g+fg′, and the quotient rule is (f/g)′=(f′g−fg′)/g² where g is nonzero. These rules require the relevant derivatives to exist. A quotient's denominator or a logarithm's domain cannot be ignored because an algebraic expression looks familiar.

The chain rule multiplies successive local sensitivities. If u=g(x) and y=f(u), then dy/dx=f′(g(x))g′(x). For y=(2x+1)³, the result is 6(2x+1)². At x=1 it equals 54. This is different from the slope with respect to u, which is 3u²=27 at u=3. Omitting the inner factor differentiates a different relationship. At a corner such as |x| at zero, left and right slopes disagree and the ordinary derivative does not exist. Optimization software may choose a subgradient convention; a central difference at the corner does not prove that a conventional choice is an ordinary derivative.

Several inputs: gradient, Jacobian and reverse accumulation

A partial derivative changes one coordinate while holding the others fixed. For a differentiable scalar f(x,y)=x²+xy+2y², the column gradient is [2x+y,x+4y]. At (1,2), f=11 and the gradient is [4,9]. A small displacement δ changes the function approximately by ∇f·δ. With δ=[.01,−.02], the linear prediction is 11−.14=10.86. Direct evaluation gives 10.8607; the difference is the quadratic curvature contribution, not a rounding defect.

The steepest local increase among unit directions under the Euclidean norm follows a nonzero gradient; the steepest decrease follows its negative. This is a statement about a local approximation and the chosen geometry. A finite update θnew=θ−η∇L can overshoot. Different feature scales change the coordinate geometry. Use the course's gradient examples and attention laboratory to compare actual losses before and after updates; a positive learning rate alone does not guarantee improvement.

For a vector-valued g with m outputs and n inputs, define its Jacobian J by J[i,j]=∂gᵢ/∂xⱼ, an m×n matrix. It maps a small input displacement to an approximate output displacement. For a scalar loss L(g(x)), column-gradient convention gives ∇xL=Jᵀ∇gL. The transpose is required by both the component chain rule and dimensions. A vector-valued function has a Jacobian; calling every array derivative a gradient without specifying layout causes avoidable confusion.

Shared computational paths contribute additively. Let u=xy, v=x+y and L=(u+v)²/2. At x=2,y=3, u=6,v=5,L=60.5. The output derivative with respect to u and v is 11 for each. Since ∂u/∂x=3 and ∂v/∂x=1, ∂L/∂x=11×3+11×1=44. Similarly ∂L/∂y=11×2+11×1=33. Keeping only the multiplication path would give 33 and 22, missing the addition branch. A forward pass saves intermediate values; a reverse pass accumulates each node's incoming sensitivity multiplied by its local derivative. Accumulation must add contributions when a node is reused. All gradients for a simultaneous parameter update refer to the same old forward state.

Automatic differentiation executes these rules over the computation that actually ran. It differs from finite differences, which perturb inputs and compare function values, and from symbolically simplifying a formula. None verifies whether the loss represents the application, a feature existed at prediction time, or training data were authorized. Compare analytic gradients with symmetric differences at several non-corner points and sensible step sizes. Very small perturbations can suffer cancellation, while large ones measure curvature rather than a local slope.

Curvature and optimization qualifications

The Hessian H holds second partial derivatives. If second derivatives are continuous nearby, mixed partials agree and H is symmetric. For the quadratic f above, H=[[2,1],[1,4]]. The second-order expansion at a is f(a+δ)≈f(a)+∇f(a)·δ+δᵀH(a)δ/2; it is an exact identity for this quadratic, and generally an approximation with a remainder. The factor one half matters: both off-diagonal terms occur in the matrix product. For δ=[.01,−.02], δᵀHδ/2=.0007, recovering 10.8607 exactly.

At an interior differentiable local minimum of an unconstrained problem, the gradient must be zero. This necessary condition is not sufficient: x²−y² has zero gradient at the origin but rises along one axis and falls along the other, making a saddle. A positive-definite Hessian at a stationary point supplies a strict local-minimum condition under standard smoothness assumptions; an indefinite Hessian indicates a saddle. A semidefinite Hessian may leave the decision unresolved. Boundary optima and nondifferentiable optima need separate reasoning: f(x)=x on [0,1] is minimized at zero even though its derivative there from its smooth extension is one.

Newton's method uses a local quadratic model and solves Hδ=−∇f for an update rather than explicitly forming an inverse. For f at (1,2), solving [[2,1],[1,4]]δ=[−4,−9] gives δ=[−1,−2], reaching the global minimum (0,0) of this positive-definite quadratic. Singular or indefinite Hessians and nonquadratic functions require additional care; an unrestricted Newton step need not decrease the actual loss.

Integration: an accumulation, not a gradient update

A definite integral ∫aᵇr(t)dt accumulates a rate. Divide an interval into narrow pieces and sum rate×width; under suitable integrability conditions these sums approach the integral. Units multiply: jobs/hour times hours gives jobs. For continuous r, F(t)=∫aᵗr(s)ds has derivative r(t); if G′=r on the interval, the fundamental theorem gives ∫aᵇr=G(b)−G(a). The dummy variable s inside an integral is different from its upper endpoint t. An indefinite antiderivative is determined only up to an additive constant; the constant cancels in a definite difference.

Suppose a fictional arrival rate is r(t)=2+3t jobs/hour for 0≤t≤2 hours, with t expressed in hours and coefficients carrying matching units. Accumulation is [2t+(3/2)t²]₀²=10 jobs. The two left-endpoint rectangles of width one give r(0)+r(1)=2+5=7 jobs, an underestimate because this rate increases. Finer partitions improve this particular approximation; one finite grid is not the exact integral. A negative function contributes signed accumulation below zero, and reversing integration limits reverses the sign. Ordinary geometric area uses absolute values where needed; a probability density must instead be nonnegative and integrate to one.

Substitution is the chain rule in reverse. In ∫₀¹2t exp(t²)dt, use u=t², du=2t dt and change bounds to zero and one. The answer is exp(1)−1. Omitting the 2t factor does not perform this change of variables. For continuous functions on a compact rectangle, iterated integration may be taken in either order; more general settings require integrability conditions rather than an unconditional exchange of infinities. On [0,1]×[0,2], integrating h(x,y)=x+y first in y gives 2x+2 and then 3. The same value follows by reversing the order.

A smooth one-to-one change of coordinates in a multiple integral scales volume by the absolute determinant of its Jacobian, under the usual change-of-variables hypotheses. For x=2u,y=3v on a unit square, the determinant is six: the image rectangle has area six, not one. Polar coordinates give area element r dr dθ, not merely dr dθ; the origin and angular seam need appropriate domain treatment. These tools later support normalized continuous distributions and expectations. They do not turn a density's height at a point into a point probability.

Optional changed record: shared gradients, curvature and accumulation

For u=xy, v=x+y and L=(u+v)²/2, change the input to x=1,y=2. Calculate L and both gradients. For the quadratic f, evaluate at a=[1,1] after displacement δ=[.1,−.1], using both direct evaluation and the second-order expansion. Finally replace the arrival rate with r(t)=4+t on [0,2]; compare its exact accumulation with the two left rectangles.

Now u=2,v=3,L=12.5, and the shared upstream derivative is five. The gradients are ∂L/∂x=5(2+1)=15 and ∂L/∂y=5(1+1)=10. Each includes both paths. For f, f(1,1)=4 and gradient [3,5]. The linear change is .3−.5=−.2. Curvature contributes (2×.01+2×1×(−.01)+4×.01)/2=.02. Thus f(1.1,.9)=3.82, which direct substitution 1.21+.99+1.62 confirms. Dropping one half would incorrectly give 3.84. The new arrival accumulation is [4t+t²/2]₀²=10, while two left rectangles give 4+5=9. Different rate paths can have the same accumulated total; a total does not identify the time profile.

Optional criteria: correctly define domains and derivative conventions; include every shared chain path; independently reconcile the quadratic model with direct evaluation; compute accumulation with bounds, units and an approximation comparison. Award one point per fully explained criterion. Existing native loss-step examples and the complete attention/gradient laboratory provide further optional computational practice.

Apply the idea

Let x=3, y=12, w=2 and L=(wx−y)². Take a gradient step with learning rate .05, then compare a step with rate .2.

For L=.5(wx−y)² at the same starting point, calculate the gradient and a .05 update. Explain whether the changed result proves a software bug.

Read the worked reasoning

The gradient is (6−12)×3=−18. The update gives w=2.9, prediction 8.7 and loss .5×3.3²=5.445 under the new definition. The smaller update follows the changed objective scaling; it is not inherently a bug. Compare like loss conventions and adjust the learning rate deliberately.

Check understanding

What does a falling training loss prove?

  1. Correctness of every model assumption
    Feedback

    A wrong objective can also be minimized.

  2. Improvement on that optimization objective, not unseen-data performance
    Feedback

    Optimization and generalization are different questions.

  3. Absence of data leakage
    Feedback

    Leakage can produce misleadingly good training and validation results.

Further reading

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

Read the original on-site preparation chapter and preserved investigation. Work the changed record before opening its full model. Earlier source assignment directions remain in immutable edition4.

My learning →