Spline Regression › Formula
Machine Learning from ScratchAll chapters 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 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 of degree with knots at positions is:
Let's break down every piece of this notation:
-
: This is our spline function. It takes an input value and returns a corresponding output value. The function is defined piecewise, meaning it has different formulas for different ranges of .
-
: This represents the degree of the spline. If , we have linear splines (straight line segments). If , we have quadratic splines (parabolic segments). If , we have cubic splines (cubic polynomial segments). Cubic splines are most commonly used because they provide a good balance between flexibility and smoothness.
-
: These are called knots or knot points. They are specific values of where we transition from one polynomial piece to another. Think of them as "break points" where the function changes its behavior. For example, if and , then:
- For all values less than or equal to 3, we use polynomial
- For all values between 3 and 7, we use polynomial
- For all values greater than 7, we use polynomial
-
: Each is a polynomial of degree or less. For example, if (cubic splines), then each might look like:
where are coefficients that we need to determine.
Interval Notation:
The notation , , and uses mathematical interval notation:
- : This means "all values of that are less than or equal to "
- : This means "all values of that are greater than AND less than or equal to "
- : This means "all values of that are greater than "
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.

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:
where:
- : the response variable (the value we want to predict)
- : the intercept term (baseline value when all basis functions are zero)
- : the coefficient for the -th B-spline basis function (weight assigned to basis function )
- : the -th B-spline basis function evaluated at input (building block of the spline)
- : the total number of B-spline basis functions (determined by the number of knots and degree)
- : the input variable or predictor
- : the error term (captures unexplained variation in the response)
The basis functions 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 , B-splines provide a more systematic approach. We can express any spline function as a linear combination of B-spline basis functions:
where:
- : the spline function evaluated at input value (the complete fitted curve)
- : the -th B-spline basis function evaluated at (building block function)
- : the coefficient for the -th basis function (weight determined through regression)
- : the total number of B-spline basis functions used in the model
- : index ranging from 1 to (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:
Let's break down this notation:
-
: This represents the -th zero-degree B-spline function. The subscript tells us which knot interval this function is associated with, and the indicates it's a zero-degree (constant) function.
-
: This is the interval where the function equals 1. Notice the different inequality signs:
- (less than or equal to) on the left means the interval includes the left endpoint
- (less than) on the right means the interval excludes the right endpoint
-
"otherwise": This means the function equals 0 everywhere else.
Example of Zero-degree B-splines:
If we have knots at , then:
- when , and elsewhere
- when , and elsewhere
- when , and elsewhere

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 , 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:
where:
- : the -th B-spline basis function of degree evaluated at (the function we're constructing)
- : the -th B-spline of degree evaluated at (lower-degree basis function)
- : the -th B-spline of degree evaluated at (adjacent lower-degree basis function)
- : the input value where we're evaluating the basis function
- : knot positions (break points in the domain)
- : index identifying which basis function (ranges over all basis functions)
- : 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:
-
: This is a weighting factor that depends on where is located relative to the knots. It's a linear function that:
- Equals 0 when
- Equals 1 when
- Varies linearly between 0 and 1 for values of in between
-
: This is another weighting factor that:
- Equals 1 when
- Equals 0 when
- Varies linearly between 1 and 0 for values of in between
Recursive Construction:
The recursion formula combines two lower-degree B-splines using weighted averages. The weights ensure that:
- The resulting function is smooth and continuous
- The function has compact support (is non-zero only over a small interval)
- The function maintains the desired continuity properties at the knots
Key Properties of B-splines:
-
Compact support: Each B-spline is non-zero only over a small interval, typically spanning knot intervals. This means that for any given , only a few B-splines contribute to the final function value.
-
Partition of unity: The B-splines sum to 1 at every point:
where 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 for all . 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.

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:
where:
- : response vector of dimension (observed values we want to predict)
- : spline basis matrix of dimension (evaluated basis functions at all data points)
- : coefficient vector of dimension (weights for each basis function)
- : error vector of dimension (unexplained variation in responses)
- : number of observations in the dataset
- : 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:
where is the observed response value for the -th observation.
The Spline Basis Matrix:
This is the most important part of the equation. The matrix contains the values of all B-spline basis functions evaluated at all our data points:
- Rows: Each row corresponds to one observation. Row contains the values of all basis functions evaluated at .
- Columns: Each column corresponds to one B-spline basis function. Column contains the values of evaluated at all data points.
- Element : The entry in row , column represents the value of the -th B-spline basis function evaluated at the -th data point.
Example of the Basis Matrix:
If we have 3 observations at and 4 B-spline basis functions, our basis matrix might look like:
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:
This vector contains the coefficients we need to determine through regression, where is the weight assigned to the -th B-spline basis function.
The Error Vector:
This vector contains the error terms (also called residuals), where represents the difference between the observed value and the predicted value for observation .
Matrix Multiplication:
The expression represents matrix multiplication. For each observation , this gives us:
where:
- : the predicted value for observation (the -th element of the product)
- : the value of the -th basis function at the -th data point (element from row , column of )
- : the coefficient for the -th basis function (element of )
This is exactly our spline function evaluated at :
So the matrix equation is saying that for each observation :
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 : This tells us the slope or rate of change of the function
- Second derivative : 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:
where:
- : the second derivative of the spline function with respect to (measures curvature)
- : the first (leftmost) boundary knot (minimum value in the data range)
- : the last (rightmost) boundary knot (maximum value in the data range)
- : the number of interior knots (not including boundary knots)
Let's break this down:
- : The second derivative of the spline function at the left boundary equals zero (no curvature at the left edge)
- : 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:
- Stable extrapolation: The spline won't predict wildly unrealistic values beyond the data range
- Fewer parameters: The constraint reduces the number of free parameters we need to estimate
- Smoother behavior: The linear behavior at boundaries often matches our expectations about how real-world relationships should behave

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:
where:
- : the estimated coefficient vector of dimension (optimal weights for basis functions)
- : the spline basis matrix of dimension (evaluated basis functions)
- : the transpose of with dimension (rows and columns swapped)
- : a matrix representing basis function overlaps (Gram matrix)
- : the inverse of with dimension
- : a vector representing projection of responses onto basis functions
- : the response vector of dimension (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 is non-zero only over a small interval, typically spanning knot intervals (where is the degree). This means that for any given , 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: for all in the domain. This ensures that our spline function behaves predictably and doesn't "blow up" to infinity.
-
Non-negativity: Each basis function satisfies for all and . 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:
- Reduce computational cost: The compact support property means we only need to evaluate a few basis functions for each data point
- Ensure numerical stability: The non-negativity and partition of unity properties prevent numerical issues
- Provide smooth fits: The continuity properties ensure that the resulting function is smooth and well-behaved
- Enable efficient matrix operations: The structure of B-splines makes the matrix well-conditioned and easy to invert