从GAM平滑对象确定导数

时间:2013-01-08 02:14:03

标签: r mgcv

我有一个非常简单的时间序列数据集,包括单个变量的年平均值(" AVERAGE")。我希望调查变化率(一阶导数)和加速度(二阶导数)以及相关的标准误差"趋势"时间序列的组成部分。我已经获得了"趋势"使用MGCV的GAM和PREDICT功能简单如下:

A <- gam(AVERAGE ~ s(YEAR), data=DF, na.action=na.omit)
B <- predict(A, type="response", se.fit=TRUE)

我通过2种不同的方法确定了导数,应用了高DoF三次平滑样条,并通过第一和第二差异(轻微平滑)和自举来近似误差,两者都产生了可比较的结果。

我注意到&#34; gam.fit3&#34;函数有助于确定二阶导数,但不直接调用。我还注意到使用&#34; predict.gam&#34;类型&#34; lpmatrix&#34;促进光滑的衍生物。我想使用&#34; GAM&#34;直接起作用计算第一和第二衍生物,但不足以计算或提取这些衍生物。我试图在&#34; Predict.gam&#34;结束时重新配置伍德的例子。一个变量的帮助页面但没有成功。让我走向正确方向的任何帮助都会非常棒。谢谢菲尔。

1 个答案:

答案 0 :(得分:5)

来自predict.gam的示例使用finite differences来近似平滑术语的导数

以下是针对单个预测变量模型执行此操作的示例。这比帮助中的例子更直接。

A <- gam(AVERAGE ~ s(YEAR), data=DF, na.action=na.omit)
# new data for prediction
newDF <- with(DF, data.frame(YEAR = unique(YEAR)))
# prediction of smoothed estimates at each unique year value
# with standard error    
B <- predict(A,  newDF, type="response", se.fit=TRUE)


# finite difference approach to derivatives following
# example from ?predict.gam

eps <- 1e-7
X0 <- predict(A, newDF, type = 'lpmatrix')


newDFeps_p <- newDF + eps

X1 <- predict(A, newDFeps_p, type = 'lpmatrix')

# finite difference approximation of first derivative
# the design matrix
Xp <- (X0 - X1) / eps

# first derivative
fd_d1 <- Xp %*% coef(A)

# second derivative
newDFeps_m <- newDF - eps

X_1 <- predict(A, newDFeps_m, type = 'lpmatrix')
# design matrix for second derivative
Xpp <- (X1 + X_1 - 2*X0)  / eps^2
# second derivative
fd_d2 <- Xpp %*% coef(A)

如果您使用引导捆绑来获得置信区间,您应该能够获得这些近似值的置信区间。