Created
November 21, 2019 10:04
-
-
Save rasmusab/7d449bb328ef2de0c2e8d090358d3f8e to your computer and use it in GitHub Desktop.
BayesCamp 2019 tutorial - Get up to speed with Bayes test script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Prior to the tutorial make sure that the script below runs without error on your R installation. | |
# You first need to install the following packages: | |
# install.packages(c("rstanarm", "prophet", "CausalImpact", "rstan")) | |
library(rstanarm) | |
library(prophet) | |
library(CausalImpact) | |
library(rstan) | |
library(ggridges) | |
# This will test that rstanarm works | |
# Don't be alarmed if you get a warning about "divergent transitions " | |
fit <- stan_lm(mpg ~ wt + qsec + am, data = mtcars, prior = R2(0.75)) | |
plot(fit, prob = 0.8) | |
# This tests that prophet is working | |
history <- data.frame(ds = seq(as.Date('2015-01-01'), as.Date('2016-01-01'), by = 'd'), | |
y = sin(1:366/200) + rnorm(366)/10) | |
m <- prophet(history) | |
future <- make_future_dataframe(m, periods = 365) | |
forecast <- predict(m, future) | |
plot(m, forecast) | |
# This tests that CausalImpact is working | |
# First simulating some data | |
x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 52) | |
y <- 1.2 * x1 + rnorm(52) | |
y[41:52] <- y[41:52] + 10 | |
data <- cbind(y, x1) | |
pre.period <- c(1, 40) | |
post.period <- c(41, 52) | |
# Then running CausalImpact | |
impact <- CausalImpact(data, pre.period, post.period) | |
plot(impact) | |
# This tests that rstan is working | |
stanmodelcode <- " | |
data { | |
int<lower=0> N; | |
real y[N]; | |
} | |
parameters { | |
real mu; | |
} | |
model { | |
mu ~ normal(0, 10); | |
y ~ normal(mu, 1); | |
} | |
" | |
y <- rnorm(20) | |
dat <- list(N = 20, y = y) | |
fit <- stan(model_code = stanmodelcode, data = dat) | |
print(fit) | |
plot(fit) | |
# Test that ggridges works | |
ggplot(iris, aes(x = Sepal.Length, y = Species)) + | |
geom_density_ridges(rel_min_height = 0.005) + | |
scale_y_discrete(expand = c(0.01, 0)) + | |
scale_x_continuous(expand = c(0.01, 0)) + | |
theme_ridges() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment