library(tidyverse)
library(tidybayes)
library(cmdstanr)
model_code = '
data{
int N;
vector[N] x;
vector[N] y;
}
parameters{
real alpha;
real beta;
real<lower=0> sigma;
}
model{
alpha ~ normal(0,1);
beta ~ normal(0,1);
sigma ~ cauchy(0,1);
y ~ normal(alpha + beta*x, sigma);
}
generated quantities{
real yppc[N] = normal_rng(alpha + beta*x, sigma);
}
'
fl = write_stan_file(model_code)
model = cmdstan_model(fl)
N = 10
x = rnorm(N)
y = 2*x + 1 + rnorm(N, 0, 0.45)
model_data = list(N=N, x=x, y=y)
fit = model$sample(model_data, parallel_chains=4)
library(tidyverse)
library(tidybayes)
library(cmdstanr)
model_code = '
data{
int N;
vector[N] x;
vector[N] y;
}
parameters{
real alpha;
real beta;
real<lower=0> sigma;
}
model{
alpha ~ normal(0,1);
beta ~ normal(0,1);
sigma ~ cauchy(0,1);
y ~ normal(alpha + beta*x, sigma);
}
generated quantities{
real yppc[N] = normal_rng(alpha + beta*x, sigma);
}
'
fl = write_stan_file(model_code)
model = cmdstan_model(fl)
N = 10
x = rnorm(N)
y = 2*x + 1 + rnorm(N, 0, 0.45)
model_data = list(N=N, x=x, y=y)
fit = model$sample(model_data, parallel_chains=4)
beta = as.numeric(fit$draws('beta'))
alpha = as.numeric(fit$draws('alpha'))
sigma = as.numeric(fit$draws('sigma'))
beta = as.numeric(fit$draws('beta'))
alpha = as.numeric(fit$draws('alpha'))
sigma = as.numeric(fit$draws('sigma'))
prediction = alpha + beta*3
hist(prediction)
prediction = alpha + beta*3
hist(prediction)
mean(prediction)
>>>7.281336
mean(prediction)
>>>7.281336