######***###### standard parameterization ######***######
# generate data
set.seed(0)
n <- 101
x <- seq(0, 1, length.out = n)
knots <- seq(0, 0.95, by = 0.05)
eta <- 1 + 2 * x + sin(2 * pi * x)
y <- eta + rnorm(n, sd = 0.5)
# cubic thin plate spline basis
X <- basis.tps(x, knots, intercept = TRUE)
# cubic thin plate spline penalty
Q <- penalty.tps(knots)
# pad Q with zeros (for intercept and linear effect)
Q <- rbind(0, 0, cbind(0, 0, Q))
# define smoothing parameter
lambda <- 1e-5
# estimate coefficients
coefs <- psolve(crossprod(X) + n * lambda * Q) %*% crossprod(X, y)
# estimate eta
yhat <- X %*% coefs
# check rmse
sqrt(mean((eta - yhat)^2))
# plot results
plot(x, y)
lines(x, yhat)
######***###### ridge parameterization ######***######
# generate data
set.seed(0)
n <- 101
x <- seq(0, 1, length.out = n)
knots <- seq(0, 0.95, by = 0.05)
eta <- 1 + 2 * x + sin(2 * pi * x)
y <- eta + rnorm(n, sd = 0.5)
# cubic thin plate spline basis
X <- basis.tps(x, knots, intercept = TRUE, ridge = TRUE)
# cubic thin plate spline penalty (ridge)
Q <- diag(rep(c(0, 1), times = c(2, ncol(X) - 2)))
# define smoothing parameter
lambda <- 1e-5
# estimate coefficients
coefs <- psolve(crossprod(X) + n * lambda * Q) %*% crossprod(X, y)
# estimate eta
yhat <- X %*% coefs
# check rmse
sqrt(mean((eta - yhat)^2))
# plot results
plot(x, y)
lines(x, yhat)
Run the code above in your browser using DataLab