ベイジアン一変量線形回帰 $y = \beta_0 + \beta_1 x + \varepsilon$ でStan (具体的には rstan) を使用しています。そして、Coda パッケージを使用して、$\beta$ の結果の軌跡と分布を視覚化しようとしています。ただし、これによりエラーが発生しますError in plot.new() : figure margins too large。 traceplotそしてdensplotうまくいくようです。問題はplot.mcmc、素敵なパネル出力を生成するはずの にあるようです。予想される出力の例は、こちらのスライド「Traceplots and Density Plots」にあります。
mtcarsデータセット を使用した最小限の (非) 動作例を次に示します。
library(rstan)
library(coda)
stanmodel <- "
data { // Data block: Exogenously given information
int<lower=1> N; // Sample size
vector<lower=1>[N] y; // Response or output.
// [N] means this is a vector of length N
vector<lower=0, upper=1>[N] x; // The single regressor; either 0 or 1
}
parameters { // Parameter block: Unobserved variables to be estimated
vector[2] beta; // Regression coefficients
real<lower=0> sigma; // Standard deviation of the error term
}
model { // Model block: Connects data to parameters
vector[N] yhat; // Regression estimate for y
yhat <- beta[1] + x*beta[2];
// Priors
beta ~ normal(0, 10);
// To plot in R: plot(function (x) {dnorm(x, 0, 10)}, -30, 30)
sigma ~ cauchy(0, 5); // With sigma bounded at 0, this is half-cauchy
// http://en.wikipedia.org/wiki/Cauchy_distribution
// To plot in R: plot(function (x) {dcauchy(x, 0, 5)}, 0, 10)
// Likelihood
y ~ normal(yhat, sigma); // yhat is the estimator, plus the N(0, sigma^2) error
// Note that Stan uses standard deviation
}
"
# Designate data
nobs <- nrow(mtcars)
y <- mtcars$mpg
x <- mtcars$am # Simple regression version doesn't include constant
data <- list(
N = nobs, # Sample size or number of observations
y = y, # The response or output
x = x # The single variable regressor, transmission type
)
# Set a seed for the random number generator
set.seed(123456)
# Run the model
bayes = stan(
model_code = stanmodel,
data = data, # Use the model and data we just defined
iter = 12000, # We're going to take 12,000 draws from the posterior,
warmup = 2000, # But throw away the first 2,000
thin = 10, # And only keep every tenth draw.
chains = 3 # But we'll do these 12,000 draws 4 times.
)
# Use the coda library to visualize parameter trajectories and distributions
param_samples <-
as.data.frame(bayes)[,c('beta[1]', 'beta[2]')]
plot(as.mcmc(param_samples))