[英]How to represent a categorical predictor rstan?
格式化要在 STAN 中使用的分類預測器的正確方法是什么? 我似乎無法輸入分類預測變量作為正常因子變量,那么轉換正常分類變量以使 Stan 可以接受的最快方法是什么?
例如,假設我有一個繼續預測變量和一個分類預測變量
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"))
看起來像這樣:
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
我將如何准備將其輸入rstan
?
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 程序可重復使用相同模型甚至不同數據集的不同變體。
另一種方法是使用索引變量,在這種情況下,Stan 程序看起來像
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.