Skip to content

Instantly share code, notes, and snippets.

@ito4303
Last active March 6, 2019 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ito4303/a6af80ed5edff73fcca902d54dab9c5d to your computer and use it in GitHub Desktop.
Save ito4303/a6af80ed5edff73fcca902d54dab9c5d to your computer and use it in GitHub Desktop.
Dealing with rounded data in Stan
---
title: "Rounding"
output: html_notebook
---
```{r}
library(rstan)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
```
# Model
https://mc-stan.org/docs/2_18/stan-users-guide/bayesian-measurement-error-model.html
```{stan, output.var=rounding}
data {
int<lower=0> N;
vector[N] y;
}
parameters {
real mu;
real<lower=0> sigma_sq;
vector<lower=-0.5, upper=0.5>[N] y_err;
}
transformed parameters {
real<lower=0> sigma;
vector[N] z;
sigma = sqrt(sigma_sq);
z = y + y_err;
}
model {
target += -2 * log(sigma);
z ~ normal(mu, sigma);
}
```
# Run Stan
```{r}
set.seed(12)
y <- rnorm(20, 10, 2)
y_r <- round(y, 0)
N <- length(y)
fit <- sampling(rounding, data = list(N = N, y = y_r))
print(fit)
plot(fit, pars = "y_err")
```
```{r}
df <- data.frame(Y = rep(y, 2),
Y2 = c(y_r, get_posterior_mean(fit, pars = "z")[, "mean-all chains"]),
Var = rep(c("Rounded", "Estimated"), each = length(y)))
ggplot(df) +
geom_point(aes(x = Y, y = Y2, colour = Var)) +
geom_abline(aes(slope = 1, intercept = 0), colour = "gray") +
labs(x = "True", y = "Rounded and estimated") +
coord_fixed()
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment