16

What is the proper way to format a categorical predictor to use in STAN? I cannot seem to input a categorical predictor as a normal factor variable, so what is the quickest way to transform a normal categorical variable such that Stan can accept it?

For example, say I had a a continue predictor and a categorical predictor

your_dataset = data.frame(income = c(62085.59, 60806.33, 60527.27, 67112.64, 57675.92, 58128.44, 60822.47, 55805.80, 63982.99, 64555.45),
country = c("England", "England", "England", "USA", "USA", "USA", "South Africa", "South Africa", "South Africa", "Belgium"))

Which looks like this:

     income      country
1  62085.59      England
2  60806.33      England
3  60527.27      England
4  67112.64          USA
5  57675.92          USA
6  58128.44          USA
7  60822.47 South Africa
8  55805.80 South Africa
9  63982.99 South Africa
10 64555.45      Belgium

How would I prepare this to be entered in rstan?

4

2 回答 2

24

Stan 只输入实数或整数变量是正确的。在这种情况下,您希望将分类预测变量转换为虚拟变量(可能不包括参考类别)。在 R 中,您可以执行类似的操作

dummy_variables <- model.matrix(~ country, data = your_dataset)

看起来像这样

   (Intercept) countryEngland countrySouth Africa countryUSA
1            1              1                   0          0
2            1              1                   0          0
3            1              1                   0          0
4            1              0                   0          1
5            1              0                   0          1
6            1              0                   0          1
7            1              0                   1          0
8            1              0                   1          0
9            1              0                   1          0
10           1              0                   0          0
attr(,"assign")
[1] 0 1 1 1
attr(,"contrasts")
attr(,"contrasts")$country
[1] "contr.treatment"

但是,如果您对其他一些变量有未建模的缺失,则可能无法得出正确数量的观察结果。通过输入整个模型公式,这种方法可以更进一步,例如

X <- model.matrix(outcome ~ predictor1 + predictor2 ..., data = your_dataset)

现在,您有了一个完整的预测变量设计矩阵,可以在带有线性代数的 .stan 程序中使用,例如

data {
  int<lower=1> N;
  int<lower=1> K;
  matrix[N,K]  X;
  vector[N]    y;
}
parameters {
  vector[K] beta;
  real<lower=0> sigma;
}
model {
  y ~ normal(X * beta, sigma); // likelihood
  // priors
}

建议使用设计矩阵,因为它使您的 .stan 程序可重用同一模型的不同变体甚至不同的数据集。

于 2015-03-21T15:48:13.667 回答
5

另一种方法是使用索引变量,在这种情况下,斯坦程序看起来像

data {
  int<lower = 1> N; // observations
  int<lower = 1> J; // levels
  int<lower = 1, upper = J> x[N];
  vector[N] y;      // outcomes
}
parameters {
  vector[J] beta;
  real<lower = 0> sigma;
}
model {
  y ~ normal(beta[x], sigma); // likelihood
  // priors 
}

你会把数据从 R 传递给 Stan

list(N = nrow(my_dataset),
     J = nlevels(my_dataset$x),
     x = as.integer(my_dataset$x),
     y = my_dataset$y)
于 2020-10-19T19:20:04.623 回答