Spline Regression › Formula

Michael BrenndoerferJune 18, 202525 min read
Machine Learning from ScratchAll chapters
Part 4 of 9Regression Models
Chapter 33Spline Regression › Formula
Reading section 2 of 8 · Formula · 25 minSection 2 of 8 · 25 min

Book contents

Section 2 of 8 · 25 min read

Spline Regression › FormulaOne section · Sections in this chapter2 / 8 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

The spline regression model extends linear regression by using piecewise polynomial basis functions instead of simple polynomial terms. We'll start with the most intuitive form and progressively build to the complete mathematical framework, explaining every piece of notation along the way.

Basic Spline Concept

Let's begin by understanding what a spline function is. A spline function S(x)S(x) is a special type of function that is constructed by joining together multiple polynomial pieces. Think of it like connecting different curved segments to create one smooth, continuous curve.

The mathematical definition of a spline function S(x)S(x) of degree dd with knots at positions t1,t2,…,tkt_1, t_2, \ldots, t_k is:

S(x)={P1(x)if x≤t1P2(x)if t1<x≤t2⋮⋮Pk+1(x)if x>tkS(x) = \begin{cases} P_1(x) & \text{if } x \leq t_1 \\ P_2(x) & \text{if } t_1 < x \leq t_2 \\ \vdots & \vdots \\ P_{k+1}(x) & \text{if } x > t_k \end{cases}

Let's break down every piece of this notation:

  • S(x)S(x): This is our spline function. It takes an input value xx and returns a corresponding output value. The function is defined piecewise, meaning it has different formulas for different ranges of xx.

  • dd: This represents the degree of the spline. If d=1d = 1, we have linear splines (straight line segments). If d=2d = 2, we have quadratic splines (parabolic segments). If d=3d = 3, we have cubic splines (cubic polynomial segments). Cubic splines are most commonly used because they provide a good balance between flexibility and smoothness.

  • t1,t2,…,tkt_1, t_2, \ldots, t_k: These are called knots or knot points. They are specific values of xx where we transition from one polynomial piece to another. Think of them as "break points" where the function changes its behavior. For example, if t1=3t_1 = 3 and t2=7t_2 = 7, then:

    • For all xx values less than or equal to 3, we use polynomial P1(x)P_1(x)
    • For all xx values between 3 and 7, we use polynomial P2(x)P_2(x)
    • For all xx values greater than 7, we use polynomial P3(x)P_3(x)
  • Pi(x)P_i(x): Each Pi(x)P_i(x) is a polynomial of degree dd or less. For example, if d=3d = 3 (cubic splines), then each Pi(x)P_i(x) might look like:

    Pi(x)=ai+bix+cix2+dix3P_i(x) = a_i + b_i x + c_i x^2 + d_i x^3

    where ai,bi,ci,dia_i, b_i, c_i, d_i are coefficients that we need to determine.

Interval Notation:

The notation x≤t1x \leq t_1, t1<x≤t2t_1 < x \leq t_2, and x>tkx > t_k uses mathematical interval notation:

  • x≤t1x \leq t_1: This means "all values of xx that are less than or equal to t1t_1"
  • t1<x≤t2t_1 < x \leq t_2: This means "all values of xx that are greater than t1t_1 AND less than or equal to t2t_2"
  • x>tkx > t_k: This means "all values of xx that are greater than tkt_k"

The key insight is that we're not fitting a single polynomial across the entire range, but rather different polynomials in different regions, connected at the knot points. This allows us to capture local patterns in the data while maintaining smoothness across the entire function.

Out[4]:
Visualization
Visualization of spline regression showing three cubic polynomial segments connected at knots, forming a smooth continuous function.
Illustration of piecewise polynomial construction in spline regression. The spline function (thick black line) is composed of three separate cubic polynomial pieces (shown in different colors), each defined over a different region. The polynomials connect smoothly at the knot points (vertical dashed red lines at x=3 and x=7).

This visualization demonstrates the fundamental concept of spline regression: instead of using a single complex polynomial across the entire range, we use simpler polynomials in different regions. Each colored segment represents a different cubic polynomial, and these pieces connect smoothly at the knots (red dashed lines). The complete spline function is the combination of all these pieces, creating a flexible curve that can adapt to local patterns in the data.

Cubic Spline Regression Model

The most common form is cubic spline regression, where we use cubic polynomials in each segment. The cubic spline regression model can be written as:

y=β0+∑j=1pβjBj(x)+ϵy = \beta_0 + \sum_{j=1}^{p} \beta_j B_j(x) + \epsilon

where:

  • yy: the response variable (the value we want to predict)
  • β0\beta_0: the intercept term (baseline value when all basis functions are zero)
  • βj\beta_j: the coefficient for the jj-th B-spline basis function (weight assigned to basis function jj)
  • Bj(x)B_j(x): the jj-th B-spline basis function evaluated at input xx (building block of the spline)
  • pp: the total number of B-spline basis functions (determined by the number of knots and degree)
  • xx: the input variable or predictor
  • ϵ\epsilon: the error term (captures unexplained variation in the response)

The basis functions Bj(x)B_j(x) are constructed to ensure continuity and smoothness at the knot points.

B-spline Basis Functions

The most elegant way to construct spline basis functions is through B-splines (Basis splines). B-splines are special functions that serve as the "building blocks" for constructing any spline function. Think of them as standardized, reusable components that we can combine in different ways to create the spline we want.

Why B-splines?

Instead of directly working with the piecewise polynomials Pi(x)P_i(x), B-splines provide a more systematic approach. We can express any spline function as a linear combination of B-spline basis functions:

S(x)=∑j=1pβjBj(x)S(x) = \sum_{j=1}^{p} \beta_j B_j(x)

where:

  • S(x)S(x): the spline function evaluated at input value xx (the complete fitted curve)
  • Bj(x)B_j(x): the jj-th B-spline basis function evaluated at xx (building block function)
  • βj\beta_j: the coefficient for the jj-th basis function (weight determined through regression)
  • pp: the total number of B-spline basis functions used in the model
  • jj: index ranging from 1 to pp (identifies which basis function)

Recursive Construction:

B-splines are constructed recursively, starting from simple step functions and building up to more complex, smooth functions. Let's understand this step by step.

Zero-degree B-splines (Step Functions):

The foundation of B-splines starts with zero-degree B-splines, which are essentially step functions:

Bi,0(x)={1if ti≤x<ti+10otherwiseB_{i,0}(x) = \begin{cases} 1 & \text{if } t_i \leq x < t_{i+1} \\ 0 & \text{otherwise} \end{cases}

Let's break down this notation:

  • Bi,0(x)B_{i,0}(x): This represents the ii-th zero-degree B-spline function. The subscript ii tells us which knot interval this function is associated with, and the 00 indicates it's a zero-degree (constant) function.

  • ti≤x<ti+1t_i \leq x < t_{i+1}: This is the interval where the function equals 1. Notice the different inequality signs:

    • ≤\leq (less than or equal to) on the left means the interval includes the left endpoint tit_i
    • << (less than) on the right means the interval excludes the right endpoint ti+1t_{i+1}
  • "otherwise": This means the function equals 0 everywhere else.

Example of Zero-degree B-splines:

If we have knots at t0=0,t1=2,t2=5,t3=8t_0 = 0, t_1 = 2, t_2 = 5, t_3 = 8, then:

  • B0,0(x)=1B_{0,0}(x) = 1 when 0≤x<20 \leq x < 2, and 00 elsewhere
  • B1,0(x)=1B_{1,0}(x) = 1 when 2≤x<52 \leq x < 5, and 00 elsewhere
  • B2,0(x)=1B_{2,0}(x) = 1 when 5≤x<85 \leq x < 8, and 00 elsewhere
Out[5]:
Visualization
Three step functions showing zero-degree B-spline basis functions, each active over non-overlapping intervals defined by knots.
Zero-degree B-spline basis functions (step functions) with knots at positions 0, 2, 5, and 8. Each basis function equals 1 over its designated interval and 0 elsewhere. These step functions form the foundation for constructing higher-degree B-splines through the Cox-de Boor recursion formula. Notice how the functions partition the domain without overlapping.

This visualization shows the three zero-degree B-spline basis functions from our example. Each function is a simple step function that equals 1 over its designated interval and 0 everywhere else. These are the "building blocks" from which we construct smoother, higher-degree B-splines. Notice that at any point xx, at most one of these functions is non-zero, which is the foundation of the "compact support" property. The Cox-de Boor recursion formula combines these step functions to create smooth, higher-degree basis functions.

Higher-degree B-splines (Cox-de Boor Recursion):

To create smooth, higher-degree B-splines, we use the Cox-de Boor recursion formula:

Bi,d(x)=x−titi+d−tiBi,d−1(x)+ti+d+1−xti+d+1−ti+1Bi+1,d−1(x)B_{i,d}(x) = \frac{x - t_i}{t_{i+d} - t_i} B_{i,d-1}(x) + \frac{t_{i+d+1} - x}{t_{i+d+1} - t_{i+1}} B_{i+1,d-1}(x)

where:

  • Bi,d(x)B_{i,d}(x): the ii-th B-spline basis function of degree dd evaluated at xx (the function we're constructing)
  • Bi,d−1(x)B_{i,d-1}(x): the ii-th B-spline of degree d−1d-1 evaluated at xx (lower-degree basis function)
  • Bi+1,d−1(x)B_{i+1,d-1}(x): the (i+1)(i+1)-th B-spline of degree d−1d-1 evaluated at xx (adjacent lower-degree basis function)
  • xx: the input value where we're evaluating the basis function
  • ti,ti+1,…,ti+d+1t_i, t_{i+1}, \ldots, t_{i+d+1}: knot positions (break points in the domain)
  • ii: index identifying which basis function (ranges over all basis functions)
  • dd: degree of the spline (0 for step functions, 1 for linear, 2 for quadratic, 3 for cubic)

This formula looks complex, but let's understand what each part means:

  • x−titi+d−ti\frac{x - t_i}{t_{i+d} - t_i}: This is a weighting factor that depends on where xx is located relative to the knots. It's a linear function that:

    • Equals 0 when x=tix = t_i
    • Equals 1 when x=ti+dx = t_{i+d}
    • Varies linearly between 0 and 1 for values of xx in between
  • ti+d+1−xti+d+1−ti+1\frac{t_{i+d+1} - x}{t_{i+d+1} - t_{i+1}}: This is another weighting factor that:

    • Equals 1 when x=ti+1x = t_{i+1}
    • Equals 0 when x=ti+d+1x = t_{i+d+1}
    • Varies linearly between 1 and 0 for values of xx in between

Recursive Construction:

The recursion formula combines two lower-degree B-splines using weighted averages. The weights ensure that:

  1. The resulting function is smooth and continuous
  2. The function has compact support (is non-zero only over a small interval)
  3. The function maintains the desired continuity properties at the knots

Key Properties of B-splines:

  • Compact support: Each B-spline Bi,d(x)B_{i,d}(x) is non-zero only over a small interval, typically spanning d+1d+1 knot intervals. This means that for any given xx, only a few B-splines contribute to the final function value.

  • Partition of unity: The B-splines sum to 1 at every point:

    ∑j=1pBj(x)=1 for all x\sum_{j=1}^{p} B_j(x) = 1 \text{ for all } x

    where pp is the total number of basis functions. This ensures that our spline function behaves predictably and doesn't "blow up" to infinity.

  • Non-negativity: Each B-spline satisfies Bj(x)≥0B_j(x) \geq 0 for all xx. This property helps ensure numerical stability.

  • Continuity: B-splines automatically ensure the desired level of continuity at the knots. For example, cubic B-splines ensure that the function, its first derivative, and second derivative are all continuous.

Out[6]:
Visualization
Three-panel comparison showing linear splines with corners (top), quadratic splines with smooth first derivatives (middle), and cubic splines with smooth second derivatives (bottom).
Comparison of spline continuity across different degrees. Linear splines (top) have C⁰ continuity with visible corners at knots. Quadratic splines (middle) have C¹ continuity with smooth first derivatives but visible changes in curvature. Cubic splines (bottom) have C² continuity with smooth second derivatives, creating the smoothest transitions. The knots are marked with vertical dashed lines, and the degree of smoothness increases from top to bottom.

This visualization demonstrates why cubic splines are the most commonly used: they provide C² continuity, meaning the function itself, its first derivative (slope), and its second derivative (curvature) are all continuous at the knots. Linear splines (C⁰) show visible corners at knots where the slope changes abruptly. Quadratic splines (C¹) have smooth slopes but visible changes in curvature. Cubic splines (C²) provide the smoothest transitions with no visible discontinuities in the function, slope, or curvature. This smoothness makes cubic splines ideal for modeling natural phenomena and physical relationships.

Matrix Formulation

Now that we understand how B-splines work, let's see how we can express the spline regression model in matrix form. This will show us how to compute spline regression using linear algebra.

The spline regression model can be written in matrix form as:

y=Bβ+ϵ\mathbf{y} = \mathbf{B}\boldsymbol{\beta} + \boldsymbol{\epsilon}

where:

  • y\mathbf{y}: response vector of dimension n×1n \times 1 (observed values we want to predict)
  • B\mathbf{B}: spline basis matrix of dimension n×pn \times p (evaluated basis functions at all data points)
  • β\boldsymbol{\beta}: coefficient vector of dimension p×1p \times 1 (weights for each basis function)
  • ϵ\boldsymbol{\epsilon}: error vector of dimension n×1n \times 1 (unexplained variation in responses)
  • nn: number of observations in the dataset
  • pp: number of B-spline basis functions

This equation looks very similar to the standard linear regression equation, but with an important difference: instead of using simple polynomial terms, we're using B-spline basis functions. Let's break down each component:

The Response Vector:

A column vector containing all our observed response values:

y=[y1y2⋮yn]\mathbf{y} = \begin{bmatrix} y_1 \\ y_2 \\ \vdots \\ y_n \end{bmatrix}

where yiy_i is the observed response value for the ii-th observation.

The Spline Basis Matrix:

B=[B1(x1)B2(x1)⋯Bp(x1)B1(x2)B2(x2)⋯Bp(x2)⋮⋮⋱⋮B1(xn)B2(xn)⋯Bp(xn)]\mathbf{B} = \begin{bmatrix} B_1(x_1) & B_2(x_1) & \cdots & B_p(x_1) \\ B_1(x_2) & B_2(x_2) & \cdots & B_p(x_2) \\ \vdots & \vdots & \ddots & \vdots \\ B_1(x_n) & B_2(x_n) & \cdots & B_p(x_n) \end{bmatrix}

This is the most important part of the equation. The matrix B\mathbf{B} contains the values of all B-spline basis functions evaluated at all our data points:

  • Rows: Each row corresponds to one observation. Row ii contains the values of all basis functions evaluated at xix_i.
  • Columns: Each column corresponds to one B-spline basis function. Column jj contains the values of Bj(x)B_j(x) evaluated at all data points.
  • Element Bj(xi)B_j(x_i): The entry in row ii, column jj represents the value of the jj-th B-spline basis function evaluated at the ii-th data point.

Example of the Basis Matrix:

If we have 3 observations at x1=1,x2=3,x3=5x_1 = 1, x_2 = 3, x_3 = 5 and 4 B-spline basis functions, our basis matrix might look like:

B=[B1(1)B2(1)B3(1)B4(1)B1(3)B2(3)B3(3)B4(3)B1(5)B2(5)B3(5)B4(5)]=[0.80.20.00.00.10.70.20.00.00.20.60.2]\mathbf{B} = \begin{bmatrix} B_1(1) & B_2(1) & B_3(1) & B_4(1) \\ B_1(3) & B_2(3) & B_3(3) & B_4(3) \\ B_1(5) & B_2(5) & B_3(5) & B_4(5) \end{bmatrix} = \begin{bmatrix} 0.8 & 0.2 & 0.0 & 0.0 \\ 0.1 & 0.7 & 0.2 & 0.0 \\ 0.0 & 0.2 & 0.6 & 0.2 \end{bmatrix}

Notice how each row sums to approximately 1 (due to the partition of unity property), and most entries are 0 (due to the compact support property).

The Coefficient Vector:

β=[β1β2⋮βp]\boldsymbol{\beta} = \begin{bmatrix} \beta_1 \\ \beta_2 \\ \vdots \\ \beta_p \end{bmatrix}

This vector contains the coefficients we need to determine through regression, where βj\beta_j is the weight assigned to the jj-th B-spline basis function.

The Error Vector:

ϵ=[ϵ1ϵ2⋮ϵn]\boldsymbol{\epsilon} = \begin{bmatrix} \epsilon_1 \\ \epsilon_2 \\ \vdots \\ \epsilon_n \end{bmatrix}

This vector contains the error terms (also called residuals), where ϵi\epsilon_i represents the difference between the observed value yiy_i and the predicted value for observation ii.

Matrix Multiplication:

The expression Bβ\mathbf{B}\boldsymbol{\beta} represents matrix multiplication. For each observation ii, this gives us:

(Bβ)i=∑j=1pBj(xi)βj=B1(xi)β1+B2(xi)β2+⋯+Bp(xi)βp(\mathbf{B}\boldsymbol{\beta})_i = \sum_{j=1}^{p} B_j(x_i)\beta_j = B_1(x_i)\beta_1 + B_2(x_i)\beta_2 + \cdots + B_p(x_i)\beta_p

where:

  • (Bβ)i(\mathbf{B}\boldsymbol{\beta})_i: the predicted value for observation ii (the ii-th element of the product)
  • Bj(xi)B_j(x_i): the value of the jj-th basis function at the ii-th data point (element from row ii, column jj of B\mathbf{B})
  • βj\beta_j: the coefficient for the jj-th basis function (element jj of β\boldsymbol{\beta})

This is exactly our spline function evaluated at xix_i:

S(xi)=∑j=1pβjBj(xi)S(x_i) = \sum_{j=1}^{p} \beta_j B_j(x_i)

So the matrix equation y=Bβ+ϵ\mathbf{y} = \mathbf{B}\boldsymbol{\beta} + \boldsymbol{\epsilon} is saying that for each observation ii:

yi=S(xi)+ϵiy_i = S(x_i) + \epsilon_i

In other words, the observed value equals the spline function value plus some random error.

Natural Cubic Splines

For better behavior at the boundaries (the edges of our data), we often use natural cubic splines. These impose additional constraints that help prevent the spline from behaving erratically when we try to predict values outside the range of our training data.

The Problem with Regular Cubic Splines: Regular cubic splines can sometimes extrapolate (predict beyond the data range) in ways that don't make physical sense. For example, if we're modeling temperature over time, a regular cubic spline might predict temperatures that are impossibly high or low when we try to forecast into the future.

The Natural Cubic Spline Solution: Natural cubic splines solve this problem by imposing boundary conditions that make the spline behave more reasonably at the edges. Specifically, natural cubic splines require that the second derivative is zero at the boundary knots.

Derivatives:

Before we can understand the constraint, let's recall what derivatives mean:

  • First derivative S′(x)S'(x): This tells us the slope or rate of change of the function
  • Second derivative S′′(x)S''(x): This tells us how the slope is changing, or the "curvature" of the function

The Natural Cubic Spline Constraint:

The natural cubic spline constraint can be written as:

S′′(t0)=S′′(tk+1)=0S''(t_0) = S''(t_{k+1}) = 0

where:

  • S′′(x)S''(x): the second derivative of the spline function with respect to xx (measures curvature)
  • t0t_0: the first (leftmost) boundary knot (minimum value in the data range)
  • tk+1t_{k+1}: the last (rightmost) boundary knot (maximum value in the data range)
  • kk: the number of interior knots (not including boundary knots)

Let's break this down:

  • S′′(t0)=0S''(t_0) = 0: The second derivative of the spline function at the left boundary equals zero (no curvature at the left edge)
  • S′′(tk+1)=0S''(t_{k+1}) = 0: The second derivative of the spline function at the right boundary equals zero (no curvature at the right edge)

What This Constraint Means:

When the second derivative equals zero, it means there's no curvature at that point. In other words, the function becomes linear (straight line) at the boundaries. This prevents the spline from "curving away" dramatically from the data, making extrapolation more stable and reasonable.

Benefits of Natural Cubic Splines:

  1. Stable extrapolation: The spline won't predict wildly unrealistic values beyond the data range
  2. Fewer parameters: The constraint reduces the number of free parameters we need to estimate
  3. Smoother behavior: The linear behavior at boundaries often matches our expectations about how real-world relationships should behave
Out[7]:
Visualization
Comparison showing standard cubic splines curving dramatically in extrapolation zones versus natural cubic splines maintaining linear behavior at boundaries.
Comparison of boundary behavior between standard cubic splines and natural cubic splines. The shaded regions indicate extrapolation zones beyond the training data range (x < 1 and x > 9). Standard splines (blue) can curve dramatically when extrapolating, potentially producing unrealistic predictions. Natural splines (orange) enforce linear behavior at boundaries (zero second derivative). The difference is most pronounced in the extrapolation regions, while both methods fit the interior data similarly.

This visualization clearly demonstrates the practical importance of natural cubic splines when extrapolation is necessary. In the shaded extrapolation zones, the standard spline exhibits dramatic curvature that may produce unrealistic predictions, while the natural spline maintains linear behavior due to the zero second derivative constraint at the boundaries. Both methods fit the interior training data similarly, but their boundary conditions lead to vastly different extrapolation behavior. This makes natural cubic splines the preferred choice for applications requiring predictions beyond the training data range, such as forecasting or physical modeling where linear extrapolation is more defensible than arbitrary polynomial behavior.

Mathematical Properties

The spline regression model maintains several important mathematical properties that make it both theoretically sound and computationally efficient.

The Least Squares Solution:

Just like in regular linear regression, we can find the optimal coefficients using the normal equation:

β^=(BTB)−1BTy\hat{\boldsymbol{\beta}} = (\mathbf{B}^T\mathbf{B})^{-1}\mathbf{B}^T\mathbf{y}

where:

  • β^\hat{\boldsymbol{\beta}}: the estimated coefficient vector of dimension p×1p \times 1 (optimal weights for basis functions)
  • B\mathbf{B}: the spline basis matrix of dimension n×pn \times p (evaluated basis functions)
  • BT\mathbf{B}^T: the transpose of B\mathbf{B} with dimension p×np \times n (rows and columns swapped)
  • BTB\mathbf{B}^T\mathbf{B}: a p×pp \times p matrix representing basis function overlaps (Gram matrix)
  • (BTB)−1(\mathbf{B}^T\mathbf{B})^{-1}: the inverse of BTB\mathbf{B}^T\mathbf{B} with dimension p×pp \times p
  • BTy\mathbf{B}^T\mathbf{y}: a p×1p \times 1 vector representing projection of responses onto basis functions
  • y\mathbf{y}: the response vector of dimension n×1n \times 1 (observed values)

Key Properties of B-spline Basis Functions:

The B-spline basis functions have several mathematical properties that make them particularly well-suited for regression:

  • Compact support: Each basis function Bj(x)B_j(x) is non-zero only over a small interval, typically spanning d+1d+1 knot intervals (where dd is the degree). This means that for any given xx, only a few basis functions contribute to the final function value, making computations efficient.

  • Partition of unity: The basis functions sum to 1 at every point: ∑j=1pBj(x)=1\sum_{j=1}^{p} B_j(x) = 1 for all xx in the domain. This ensures that our spline function behaves predictably and doesn't "blow up" to infinity.

  • Non-negativity: Each basis function satisfies Bj(x)≥0B_j(x) \geq 0 for all xx and jj. This property helps ensure numerical stability and prevents oscillations in the fitted function.

  • Continuity: The basis functions automatically ensure the desired level of continuity at the knots. For example, cubic B-splines ensure that the function, its first derivative, and second derivative are all continuous, creating smooth transitions between polynomial pieces.

Computational Advantages:

These properties make B-splines particularly well-suited for regression problems because they:

  1. Reduce computational cost: The compact support property means we only need to evaluate a few basis functions for each data point
  2. Ensure numerical stability: The non-negativity and partition of unity properties prevent numerical issues
  3. Provide smooth fits: The continuity properties ensure that the resulting function is smooth and well-behaved
  4. Enable efficient matrix operations: The structure of B-splines makes the matrix BTB\mathbf{B}^T\mathbf{B} well-conditioned and easy to invert