Calculus and Matrix Calculus for ML

Taylor Series and Local Approximation

A shape-aware introduction to Taylor approximations, connecting function values, gradients, and Hessians to local prediction and optimization.

Lesson
39

Goal

Turn derivatives into local predictive models.

The central idea is:

Near an anchor point, a smooth function behaves like a low-degree polynomial whose coefficients are determined by derivatives at that anchor.

A gradient is not merely a direction used by an optimizer. It is the coefficient of the best first-order local model. A Hessian is not merely a curvature table. It supplies the second-order correction that lets the local model bend.

Why Local Models Matter

Suppose evaluating a function is expensive or its formula is complicated. If we already know the function and its derivatives at a point aa, then we can ask a smaller question:

What simple function behaves like the original function for points close to aa?

The answer begins with a constant, then adds increasingly detailed corrections:

known height
+ local slope correction
+ local curvature correction
+ higher-order corrections

This is compression. Instead of carrying the whole function, we carry a local polynomial model.

The model is trustworthy only locally. Moving far from the anchor can make omitted higher-order behavior dominate.

Notation / Symbol Table

SymbolPlain-English nameMeaning
fftarget functionThe function being approximated.
aaanchor pointThe point where values and derivatives are known.
xxtarget pointThe nearby point where we want a prediction.
h=xah=x-adisplacementHow far and in which direction we move from the anchor.
T0(x;a)T_0(x;a)zero-order modelThe constant prediction f(a)f(a).
T1(x;a)T_1(x;a)first-order modelConstant plus slope or gradient correction.
T2(x;a)T_2(x;a)second-order modelFirst-order model plus curvature correction.
Rk(x;a)R_k(x;a)remainderThe approximation error f(x)Tk(x;a)f(x)-T_k(x;a).
Hf(a)H_f(a)Hessian at aaMatrix describing how the gradient changes near aa.

The semicolon in Tk(x;a)T_k(x;a) separates the point being predicted from the fixed anchor used to build the model.

Start With One Variable

For a smooth scalar function f:RRf:\mathbb R\to\mathbb R, write the target point as:

x=a+h.x=a+h.

The displacement hh is the small quantity. The Taylor polynomial through second order is:

f(a+h)f(a)+f(a)h+12f(a)h2.f(a+h) \approx f(a)+f'(a)h+\frac{1}{2}f''(a)h^2.

Equivalently:

T2(x;a)=f(a)+f(a)(xa)+12f(a)(xa)2.T_2(x;a) = f(a)+f'(a)(x-a)+\frac{1}{2}f''(a)(x-a)^2.

Each term has a distinct job:

TermInformation suppliedGeometric job
f(a)f(a)function valuePlaces the model at the correct height.
f(a)hf'(a)hfirst derivativeTilts the model with the correct local slope.
12f(a)h2\frac12 f''(a)h^2second derivativeBends the model with the correct local curvature.

Why The Factorial Appears

The quadratic correction contains 1/2=1/2!1/2=1/2! because differentiating h2h^2 twice produces a factor of 22:

d2dh2(c2h2)=2c2.\frac{d^2}{dh^2}\left(c_2h^2\right)=2c_2.

To make that second derivative equal f(a)f''(a), choose:

c2=f(a)2!.c_2=\frac{f''(a)}{2!}.

The same matching rule gives the degree-kk Taylor polynomial:

Tk(x;a)=j=0kf(j)(a)j!(xa)j.T_k(x;a) = \sum_{j=0}^{k} \frac{f^{(j)}(a)}{j!}(x-a)^j.

The factorial cancels the repeated factors created when a power is differentiated back down.

Worked Example: Approximating The Exponential

Let:

f(x)=exf(x)=e^x

and anchor at a=0a=0. Every derivative of exe^x is exe^x, so at zero:

f(0)=f(0)=f(0)=1.f(0)=f'(0)=f''(0)=1.

The approximations are:

T0(x;0)=1,T_0(x;0)=1, T1(x;0)=1+x,T_1(x;0)=1+x, T2(x;0)=1+x+x22.T_2(x;0)=1+x+\frac{x^2}{2}.

At x=0.1x=0.1:

T1(0.1;0)=1.1,T_1(0.1;0)=1.1, T2(0.1;0)=1.105,T_2(0.1;0)=1.105,

while:

e0.11.105170.e^{0.1}\approx1.105170.

The curvature term repairs most of the first-order error because the displacement is small.

The Remainder Is The Missing Behavior

Define the remainder after a degree-kk approximation by:

Rk(x;a)=f(x)Tk(x;a).R_k(x;a)=f(x)-T_k(x;a).

For a sufficiently smooth function near aa, the local scaling is:

R0=O(h),R1=O(h2),R2=O(h3).R_0=O(|h|), \qquad R_1=O(|h|^2), \qquad R_2=O(|h|^3).

Read O(hp)O(|h|^p) here as a scaling statement: close enough to the anchor, the error is bounded by a constant times hp|h|^p.

This gives a useful experiment. If hh is halved, then locally:

ModelLeading error scaleExpected error factor after halving hh
Constanth\lvert h\rvertabout 1/21/2
First orderh2\lvert h\rvert^2about 1/41/4
Second orderh3\lvert h\rvert^3about 1/81/8

These ratios are asymptotic, not exact promises at arbitrary distances.

Multivariable First-Order Approximation

Now let:

f:RnR,x=a+h.f:\mathbb R^n\to\mathbb R, \qquad x=a+h.

The first-order Taylor model is:

T1(a+h;a)=f(a)+f(a)Th.T_1(a+h;a) = f(a)+\nabla f(a)^T h.

The shape check is:

T11×1=f(a)1×1+f(a)T1×nhn×1.\underbrace{T_1}_{1\times1} = \underbrace{f(a)}_{1\times1} + \underbrace{\nabla f(a)^T}_{1\times n} \underbrace{h}_{n\times1}.

This is the differential from Lesson 38 with a finite but small displacement:

df=f(a)Tdxf(a+h)f(a)f(a)Th.df=\nabla f(a)^Tdx \quad\longrightarrow\quad f(a+h)-f(a)\approx\nabla f(a)^Th.

The approximation is a tangent hyperplane. The gradient supplies its coefficients.

Multivariable Second-Order Approximation

The Hessian supplies the curvature correction:

T2(a+h;a)=f(a)+f(a)Th+12hTHf(a)h.T_2(a+h;a) = f(a) +\nabla f(a)^Th +\frac12h^TH_f(a)h.

The quadratic form is scalar:

hT1×nHf(a)n×nhn×1R.\underbrace{h^T}_{1\times n} \underbrace{H_f(a)}_{n\times n} \underbrace{h}_{n\times1} \in\mathbb R.

The term hTHf(a)hh^TH_f(a)h measures curvature along the actual displacement hh. If hh is not a unit vector, its length contributes twice because hh appears on both sides of the Hessian.

Worked Example: A Quadratic Function

Let:

f(x,y)=x2+xy+2y2.f(x,y)=x^2+xy+2y^2.

Anchor at:

a=[11],a= \begin{bmatrix} 1\\-1 \end{bmatrix},

and use displacement:

h=[0.20.1].h= \begin{bmatrix} 0.2\\0.1 \end{bmatrix}.

First compute the local data:

f(a)=2,f(a)=2, f(x,y)=[2x+yx+4y],f(a)=[13],\nabla f(x,y)= \begin{bmatrix} 2x+y\\x+4y \end{bmatrix}, \qquad \nabla f(a)= \begin{bmatrix} 1\\-3 \end{bmatrix}, Hf=[2114].H_f= \begin{bmatrix} 2&1\\1&4 \end{bmatrix}.

The first-order model predicts:

T1=2+[13][0.20.1]=1.9.T_1=2+ \begin{bmatrix} 1&-3 \end{bmatrix} \begin{bmatrix} 0.2\\0.1 \end{bmatrix} =1.9.

The second-order correction is:

12hTHfh=0.08.\frac12h^TH_fh=0.08.

Therefore:

T2=1.98.T_2=1.98.

The target point is (1.2,0.9)(1.2,-0.9), and direct evaluation also gives:

f(1.2,0.9)=1.98.f(1.2,-0.9)=1.98.

The second-order model is exact because the original function is quadratic. There are no third- or higher-order terms to omit.

A Local Model Is Not A Global Identity

The approximation symbol matters:

f(a+h)Tk(a+h;a).f(a+h)\approx T_k(a+h;a).

Equality holds only in special cases, such as using a second-order model for a quadratic function. For a general function, accuracy depends on:

A high-order polynomial can still be poor far from its anchor. More terms increase local fidelity; they do not make locality disappear.

From Taylor Models To Optimization

Let L(θ)L(\theta) be a loss near current parameters θ\theta. For a proposed update ss, the first-order model is:

L(θ+s)L(θ)+L(θ)Ts.L(\theta+s) \approx L(\theta)+\nabla L(\theta)^Ts.

Choosing:

s=ηL(θ)s=-\eta\nabla L(\theta)

gives the predicted change:

L(θ)Ts=ηL(θ)2,\nabla L(\theta)^Ts = -\eta\lVert\nabla L(\theta)\rVert^2,

which is negative whenever the gradient is nonzero. This is the local-model justification for gradient descent.

The second-order model is:

L(θ+s)L(θ)+L(θ)Ts+12sTHL(θ)s.L(\theta+s) \approx L(\theta) +\nabla L(\theta)^Ts +\frac12s^TH_L(\theta)s.

If the Hessian is invertible and the quadratic model is locally appropriate, setting the model’s gradient with respect to ss to zero gives:

sNewton=HL(θ)1L(θ).s_{\text{Newton}} = -H_L(\theta)^{-1}\nabla L(\theta).

Gradient descent trusts slope and controls distance with a learning rate. Newton’s method also uses curvature to rescale and rotate the proposed step.

Why This Matters For Neural Networks

Neural-network training repeatedly builds implicit local models of a loss landscape:

The Taylor viewpoint unifies these facts: optimization methods differ partly in what local model they build and how much of it they can afford to use.

Connection To Programming

A local quadratic model can be represented without hiding its assumptions:

type Vector = readonly number[];
type Matrix = readonly (readonly number[])[];

const dot = (left: Vector, right: Vector): number =>
  left.reduce((sum, value, index) => sum + value * right[index]!, 0);

const multiplyMatrixVector = (
  matrix: Matrix,
  vector: Vector,
): Vector => matrix.map((row) => dot(row, vector));

const secondOrderTaylor = ({
  valueAtAnchor,
  gradientAtAnchor,
  hessianAtAnchor,
  displacement,
}: Readonly<{
  valueAtAnchor: number;
  gradientAtAnchor: Vector;
  hessianAtAnchor: Matrix;
  displacement: Vector;
}>): number => {
  const linearCorrection = dot(gradientAtAnchor, displacement);
  const curvatureAlongDisplacement = dot(
    displacement,
    multiplyMatrixVector(hessianAtAnchor, displacement),
  );

  return valueAtAnchor + linearCorrection + 0.5 * curvatureAlongDisplacement;
};

The names preserve the mathematical roles. The function receives local information and a displacement; it does not pretend to know the original function globally.

Common Mistakes

Evaluating Derivatives At The Target Instead Of The Anchor

A Taylor model is built from f(a)f(a), f(a)f'(a), and higher derivatives at the fixed anchor aa. Evaluating each coefficient at xx changes the construction.

Forgetting The Displacement

The linear term is not merely f(a)f'(a) or f(a)\nabla f(a). It is the derivative applied to h=xah=x-a.

Dropping The One-Half

The second-order term is 12f(a)h2\frac12f''(a)h^2 in one variable and 12hTHf(a)h\frac12h^TH_f(a)h in several variables.

Treating The Hessian Term As A Matrix Output

For a scalar function, hTHhh^THh is a scalar quadratic form. Shape checking should reduce the full expression to 1×11\times1.

Assuming More Terms Guarantee Global Accuracy

Taylor models organize local derivative information. Their useful region depends on the function and anchor, not just the polynomial degree.

Confusing Approximation Error With Numerical Rounding

Remainder error comes from omitted mathematical terms. Floating-point error comes from numerical representation and computation. They are different sources of error.

Exercises

  1. In plain language, explain the separate jobs of f(a)f(a), f(a)hf'(a)h, and 12f(a)h2\frac12f''(a)h^2. Why is h=xah=x-a the quantity that should be small?

  2. For f(x)=sinxf(x)=\sin x anchored at a=0a=0, derive T1(x;0)T_1(x;0) and T2(x;0)T_2(x;0). Explain why the second-order model is identical to the first-order model even though sinx\sin x is not linear.

  3. For f(x)=lnxf(x)=\ln x anchored at a=1a=1, derive the second-order approximation and use it to estimate ln(1.1)\ln(1.1). Compare the estimate with a calculator value.

  4. Let f(x)=exf(x)=e^x. Compute first-order approximation errors at x=0.2x=0.2 and x=0.1x=0.1 using anchor 00. Does halving the displacement reduce the error by roughly the factor predicted for a first-order model?

  5. Let f(x,y)=x2+3xy+y2f(x,y)=x^2+3xy+y^2. At anchor a=(1,1)a=(1,1) and displacement h=(0.1,0.2)Th=(0.1,-0.2)^T, compute the first- and second-order Taylor predictions. Verify the second-order prediction by direct evaluation.

  6. For a scalar f:RnRf:\mathbb R^n\to\mathbb R, annotate every factor in 12hTHf(a)h\frac12h^TH_f(a)h with its shape. Explain why the result is scalar and why replacing it with Hf(a)hH_f(a)h would change its meaning.

  7. Use the first-order Taylor model to show that the update s=ηL(θ)s=-\eta\nabla L(\theta) predicts a decrease whenever η>0\eta>0 and L(θ)0\nabla L(\theta)\ne0. State why this remains a local prediction rather than a guarantee for arbitrarily large η\eta.

  8. Let L(θ)=12θTAθbTθL(\theta)=\frac12\theta^TA\theta-b^T\theta with symmetric positive-definite AA. Derive the Newton step from the second-order local model and show that one step reaches the exact minimizer when the Hessian is AA everywhere.

  9. Diagnose the claim: “A second-order approximation must always be better than a first-order approximation.” Give a counterexample involving a distant target, a poorly chosen anchor, or a function whose higher derivatives make the local model unreliable.

  10. Implement firstOrderTaylor and secondOrderTaylor in TypeScript for vector inputs. Add dimension checks and test them on the quadratic worked example from this lesson.

Readiness Check

You are ready to move into neural-network layers when you can:

Summary

Next Lesson

Lesson 40 begins the neural-network phase with perceptrons and linear layers. It will turn affine maps into trainable units, connect weights and biases to decision boundaries, and reuse the local derivative machinery developed in Lessons 35–39.