使用rstanarm

时间:2017-07-11 14:30:51

标签: r stan rstan rstanarm

根据这篇文章,我试图获得边际效应:http://andrewgelman.com/2016/01/14/rstanarm-and-more/

td <- readRDS("some data")

CHAINS <- 1
CORES <- 1
SEED <- 42
ITERATIONS <- 2000
MAX_TREEDEPTH <- 9

md <- td[,.(y,x1,x2)] # selection the columns i need. y is binary


glm1 <- stan_glm(y~x1+x2,
                 data = md,
                 family = binomial(link="logit"),
                 prior = NULL,
                 prior_intercept = NULL,
                 chains = CHAINS,
                 cores = CORES,
                 seed = SEED,
                 iter = ITERATIONS,
                 control=list(max_treedepth=MAX_TREEDEPTH)
)

# launch_shinystan(glm1) 


tmp <- posterior_predict(glm1,newdata=md[,.(x1,x2)])

问题

运行此代码后,我收到以下错误: 我收到y未找到的错误,这实际上意味着我还需要在y中传递newdata,根据?posterior_predict情况不应该这样。

推理

我需要tmp <- posterior_predict(glm1,newdata=md[,.(x1,x2)])因为根据上面的帖子(据我所知),为了计算x1的边际效应(如果我假设x1是二进制的)将是

temp <- md
temp[,x1:=0]
temp[,x2:=mean(x2)]
number_0 <- posterior_predict(glm1,newdata=temp)

temp <- md
temp[,x1:=1]
temp[,x2:=mean(x2)]
number_1 <- posterior_predict(glm1,newdata=temp)

marginal_effect_x1 <- number_1 - number_0

1 个答案:

答案 0 :(得分:3)

对于二元logit模型,连续变量的边际效应是相对于该变量的成功概率的导数,其中链规则是逻辑密度(在预测变量的某些值处评估,通常是预测值的观测值乘以所讨论变量的系数。在你的情况下,那将是 df <- as.data.frame(glm1) ME <- df$x2 * dlogis(posterior_linpred(glm1)) 由于这取决于预测变量的观测值,因此通常对数据进行平均 AME <- rowMeans(ME) 对于二元预测变量,只需x1 = 0x1 = 1成功的概率中减去成功概率 nd <- md nd$x1 <- 0 p0 <- posterior_linpred(glm1, newdata = nd, transform = TRUE) nd$x1 <- 1 p1 <- posterior_linpred(glm1, newdata = nd, transform = TRUE) ME <- p1 - p0 AME <- rowMeans(ME)