A quick demo of thin plate regression splines in mgcv
library(mgcv) | |
library(plot3D) | |
#Set up sample data | |
set.seed(42) | |
x <- runif(200, -1,1) | |
y <- runif(200, -1,1) | |
z <- exp(-(x^2 + y^2)) + rnorm(200, 0, 0.15) | |
#Fit 2D thin-plate regression spline | |
fit <- gam(z ~ s(x,y, bs="tp"), method="REML") | |
#Predict over a grid | |
ng = 100 | |
x.pred <- seq(min(x), max(x), length.out = ng) | |
y.pred <- seq(min(y), max(y), length.out = ng) | |
xy <- expand.grid( x = x.pred, y = y.pred) | |
z.pred <- matrix(predict(fit, newdata = xy), | |
nrow = ng, ncol = ng) | |
#Fitted points | |
fitpoints <- predict(fit) | |
#Show points and surface | |
scatter3D(x, y, z, pch = 18, cex = 1.5, | |
theta = 60, phi = 20, | |
xlab = "x", ylab = "y", zlab = "f(x,y)", | |
surf = list(x = x.pred, y = y.pred, z = z.pred, | |
facets = NA, fit = fitpoints), | |
main = "Smoothest possible surface under thin-plate constraints") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment