Hello, all! I’ve been futzing around with state space models recently and have been trying to figure out their proper implementation.
So, consider, for example, the Nile dataset.
library(fpp2)
library(forecast)
#from base
fitNile <- StructTS(Nile, "level")
cat("Transitional variance:", fitNile$coef["level"],
"\n", "Observational variance:", fitNile$coef["epsilon"],
"\n", "Initial level:", fitNile$model0$a, "\n")
autoplot(Nile) +
geom_line(y=fitted(fitNile), col="red", lty=2) +
ggtitle("Fit model from State Space Model")
Works great! Now, I’m trying to figure out the proper implementation in brms. Using
library(brms)
library(tidybayes)
#n.b. tidybayes is amazing - from
#https://github.com/mjskay/tidybayes
Nile_df <- as.data.frame(Nile) %>%
mutate(t = 1871:1970) %>%
mutate(x_cent = x-mean(x)) #centering helps
#not sure if this works - trying
#to find a better example....
nile_brms <- brm(x_cent ~ 1,
autocor = cor_bsts(~ t),
data = Nile_df)
seems to produce OK parameter estimates (although still not quite at good convergence). But, I only get a fitted mean
#plot
nile_results <- Nile_df %>%
add_fitted_samples(nile_brms)
#show the fit and CIs
ggplot(nile_results, aes(x=t)) +
stat_lineribbon(aes(y = estimate+mean(x)), .prob = c(.99, .95, .8, .5)) +
geom_line(aes(y = x)) +
scale_fill_brewer()
shows this quite well.
Thoughts - have any of you done something similar>