Week 07 · Splines and additive models
Build a curve from piecewise terms and inspect its slope on each side of a knot.
← Week 6 · Subject contents · Week 8 →
Build a curve from piecewise terms and inspect its slope on each side of a knot.
Work through the problem
The hinge h(x) = max(0,x−k) is zero up to knot k and grows linearly afterwards. In y = a + bx + ch(x), the left slope is b, the right slope is b+c, and the line stays continuous at k.
Take y = 2+x+3 max(0,x−2). At x = 1 the prediction is 3. At x = 4 it is 12. Adding another predictor as a separate term, such as −2z, creates an additive model whose z contribution stays inspectable. Interactions require explicit additional terms.
Run the Python lab
import numpy as np
x = np.arange(6)
z = np.array([0,1,0,1,0,1])
design = np.c_[np.ones(len(x)),x,np.maximum(0,x-2),z]
y = design @ [2,1,3,-2]
coef = np.linalg.lstsq(design,y,rcond=None)[0]
print("Intercept, slopes, z coefficient:", coef.round(2))
assert np.allclose(coef,[2,1,3,-2])
Output from the lab
Intercept, slopes, z coefficient: [ 2. 1. 3. -2.]
Practice
- What is the slope to the right of knot 2?
Check your reasoning
- 1 + 3 = 4.