Skip to content

Instantly share code, notes, and snippets.

@johnjdavisiv
Created December 2, 2020 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnjdavisiv/378863d54889b1b923c89f590ece341e to your computer and use it in GitHub Desktop.
Save johnjdavisiv/378863d54889b1b923c89f590ece341e to your computer and use it in GitHub Desktop.
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