if (FALSE) {
# Simulate a time-varying coefficient
# (as a Gaussian Process with length scale = 10)
set.seed(1111)
N <- 200
# A function to simulate from a squared exponential Gaussian Process
sim_gp <- function(N, c, alpha, rho) {
Sigma <- alpha ^ 2 *
exp(-0.5 * ((outer(1:N, 1:N, "-") / rho) ^ 2)) +
diag(1e-9, N)
c + mgcv::rmvn(1, mu = rep(0, N), V = Sigma)
}
beta <- sim_gp(alpha = 0.75, rho = 10, c = 0.5, N = N)
plot(
beta, type = 'l', lwd = 3, bty = 'l',
xlab = 'Time', ylab = 'Coefficient', col = 'darkred'
)
# Simulate the predictor as a standard normal
predictor <- rnorm(N, sd = 1)
# Simulate a Gaussian outcome variable
out <- rnorm(N, mean = 4 + beta * predictor, sd = 0.25)
time <- seq_along(predictor)
plot(
out, type = 'l', lwd = 3, bty = 'l',
xlab = 'Time', ylab = 'Outcome', col = 'darkred'
)
# Gather into a data.frame and fit a dynamic coefficient model
data <- data.frame(out, predictor, time)
# Split into training and testing
data_train <- data[1:190, ]
data_test <- data[191:200, ]
# Fit a model using the dynamic function
mod <- mvgam(
out ~
# mis-specify the length scale slightly as this
# won't be known in practice
dynamic(predictor, rho = 8, stationary = TRUE),
family = gaussian(),
data = data_train,
chains = 2,
silent = 2
)
# Inspect the summary
summary(mod)
# Plot the time-varying coefficient estimates
plot(mod, type = 'smooths')
# Extrapolate the coefficient forward in time
plot_mvgam_smooth(mod, smooth = 1, newdata = data)
abline(v = 190, lty = 'dashed', lwd = 2)
# Overlay the true simulated time-varying coefficient
lines(beta, lwd = 2.5, col = 'white')
lines(beta, lwd = 2)
}
Run the code above in your browser using DataLab