Skip to content

Instantly share code, notes, and snippets.

@kagaya
Last active June 3, 2018 07:11
Show Gist options
  • Save kagaya/60c4190ac306840daee54115b3c315c3 to your computer and use it in GitHub Desktop.
Save kagaya/60c4190ac306840daee54115b3c315c3 to your computer and use it in GitHub Desktop.
utilities for Harada and Kagaya, https://doi.org/10.1101/330787
library(tidyverse)
library(forcats)
library(rstan)
library(shinystan)
waic <- function(log_likelihood) {
# from https://gist.github.com/MatsuuraKentaro/3f6ae5863e700f5039c19e36a9bdf646
training_error <- - mean(log(colMeans(exp(log_likelihood))))
functional_variance_div_N <- mean(colMeans(log_likelihood^2) - colMeans(log_likelihood)^2)
waic <- training_error + functional_variance_div_N
return(waic)
}
df_quantile_mcmc <- function(x, y_mcmc,
probs=c(2.5, 25, 50, 75, 97.5)/100){
qua <- apply(y_mcmc, 2, quantile, probs=probs)
d_pred <- data.frame(X=x, t(qua))
colnames(d_pred) <- c('X', paste0('p', probs*100))
return(d_pred)
}
check_rhat <- function(fit){
all(summary(fit)$summary[,"Rhat"] <= 1.10, na.rm=T)
}
add_chosen_col_days <- function(d){
d <- d %>% arrange(id, days_to_choice)
x <- paste(d$id, d$days_to_choice, sep="") %>% factor() %>% fct_inorder()
xx <- table(x)
chosen_ind <- names(xx)
chosen_num <- c()
for (i in xx){
chosen_num <- c(chosen_num, 1:i)
}
d$chosen_num <- chosen_num
d
}
add_chosen_col_choice <- function(d){
d <- d %>% arrange(id, choice)
x <- paste(d$id, d$choice, sep="") %>% factor() %>% fct_inorder()
xx <- table(x)
chosen_ind <- names(xx)
chosen_num <- c()
for (i in xx){
chosen_num <- c(chosen_num, 1:i)
}
d$chosen_num <- chosen_num
d
}
add_chosen_col_days <- function(d){
d <- d %>% arrange(id, days_to_choice)
x <- paste(d$id, d$days_to_choice, sep="") %>% factor() %>% fct_inorder()
xx <- table(x)
chosen_ind <- names(xx)
chosen_num <- c()
for (i in xx){
chosen_num <- c(chosen_num, 1:i)
}
d$chosen_num <- chosen_num
d
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment