Skip to content
Prev 779 / 7419 Next

multivariate smoothing and gradient estimation

On Wed, 2009-09-16 at 14:10 -0700, Chris Martin wrote:
Depending upon how many observations you have (i.e. not very large
numbers) you could estimate this model using mgcv::gam which allows
multivariate smooths. You can then compute the derivatives for this
smooth using finite differences using the predict.gam method as a basis
from which to work (using type = "lpmatrix").

The trick is to get the bits from the model that you need. This code
snippet uses data from the semiPar package. I produced the script as I
was reading the text that semiPar is support for. Simon Wood, author of
the mgcv package, kindly helped me with the code to compute the
derivatives:

## Example from Ruppert, Wand and Carroll 2003 pp 156-8
## Semiparametric regression
## Cambridge University Press
##
## Data for the strontium example are in package SemiPar, support
## software for the book above.
require(SemiPar)
require(mgcv)
# '`
require(nlme)

## load the Strontium data
data(fossil)

mod1 <- gamm(strontium.ratio ~ s(age), data = fossil)

## Compute derivatives ###############################################
## where to evaluate derivatives
x.age <- with(fossil, seq(min(age), max(age), length = 200))
newd <- data.frame(age = x.age)
X0 <- predict(mod1$gam, newd, type = "lpmatrix")
eps <- 1e-7 ## finite difference interval
x.age <- x.age + eps ## shift the evaluation points
newd <- data.frame(age = x.age)
X1 <- predict(mod1$gam, newd, type = "lpmatrix")
Xp <- (X1 - X0) / eps ## maps coefficients to (fd approx.) derivatives
colnames(Xp)

Xi <- Xp*0
Xi[, 2:10] <- Xp[,2:10] ## Xi\%*\%coef(b) = smooth deriv i
## you'll need to change 2:10 in the above to match the cols for your 
## smoother
## ith smooth derivative
df <- Xi %*% coef(mod1$gam)
## cheap diag(Xi\%*\%b$Vp\%*\%t(Xi))^.5
df.sd <- rowSums(Xi %*% mod1$gam$Vp * Xi)^.5 ## SE of deriv

I haven't used this approach to compute the derivatives of a
multivariate smooth, but it should work as long as you can identify the
columns of X0 and X1 that arise from predict.gam.

HTH

G