I am trying to fit a restricted cubic spline (natural cubic spline) with 4 knots to toy data, attempting to follow Hastie, Tibshirani, Friedman 2nd ed. 5.2.1 p.144-146, Eqs 5.4 and 5.5. Data: Is basically a transposed ‘S’ shape. R-code is:
n <© 100
x <- (1:n)/n
true <- ((exp(1.2*x)+1.5*sin(7*x))-1)/3
noise <- rnorm(n, 0, 0.15)
y <- true + noise
plot(x,y)
I set knots at: {.2, .4, .6, .8} and am fitting using the non-linear NLS() function in R, but I can’t get the S-shape of the data no matter what I try.
My equations is wrong ? Or I am completely off-base in my approach? Any suggestions?
(Book-excerpt, my equation, and data-plot posted below)
A natural cubic spline with $K$ knots is represented by $K$ basis functions. One can start from a basis for cubic splines, and derive the reduced basis by imposing the boundary constraints. For example, starting from the truncated power series basis described in section 5.2, we arrive at where $$d_k=\frac{(X-\xi_k)^3_+ - (X-\xi_K)^3_+}{\xi_K - \xi_k} \enspace .$$ Each of these basis functions can be seend to have zero second and third derivative for $X\geq \xi_K$. $$y = \beta_0 + \beta_1 x + \beta_2\left(\left[\frac{(x-k_1)^3_+ - (x-k_4)^3_+}{k_4 - k_1}\right] - \left[\frac{(x-k_3)^3_+ - (x-k_4)^3_+}{k_4 - k_3}\right] \right) + \beta_3\left(\left[\frac{(x-k_2)^3_+ - (x-k_4)^3_+}{k_4 - k_2}\right] - \left[\frac{(x-k_3)^3_+ - (x-k_4)^3_+}{k_4 - k_3}\right] \right)$$
Can I ask a simpler question: Sites/books say: for my natural cubic spline approach (i.e. restricted cubic spline) w/ 4 knots, I need 4 basis functions. Is it Beta_0, Beta_1*x, and '4 more' ? Or is indeed just 4 betas (conceptually, as I have above) ? Thank you.
Thank you for your guidance.
I am fitting the spline, along with many other modeling co-variates, i.e. explanatory variables. So, a simple canned package for the spline alone is not sufficient.
The actual shape I expect, when I fit to my modeling data, is a very positive skewed distributional form (I was trying to fit the fancy shaped example data, with an inflection, thinking it would be a good test of my coding of the spline functional-form).
I thought about snitching the functional form and calibrated-parameterization (from your Python above or from R) - but its a cubic-spline, not a natural cubic spline.
I get how my ftn is linear to the LHS of first knot. I guess next step is for me to see that various terms cancel, and indeed I'd be linear to the RHS of the right-most knot too. Also look for a 4-term basis that is said to be 'stable'.