Cla*_*nry 5 r prediction predict glm bayesglm
使用bayesglm时,我在预测功能方面遇到了一些问题.我读过一些帖子,说当样本数据的数量超过样本数据时,可能会出现这个问题,但是我使用相同的数据来拟合和预测函数.预测与常规glm一起工作正常,但不适用于bayesglm.例:
control <- y ~ x1 + x2
# this works fine:
glmObject <- glm(control, myData, family = binomial())
predicted1 <- predict.glm(glmObject , myData, type = "response")
# this gives an error:
bayesglmObject <- bayesglm(control, myData, family = binomial())
predicted2 <- predict.bayesglm(bayesglmObject , myData, type = "response")
Error in X[, piv, drop = FALSE] : subscript out of bounds
# Edit... I just discovered this works.
# Should I be concerned about using these results?
# Not sure why is fails when I specify the dataset
predicted3 <- predict(bayesglmObject, type = "response")
Run Code Online (Sandbox Code Playgroud)
无法弄清楚如何用bayesglm对象进行预测.有任何想法吗?谢谢!
原因之一可能与 bayesglm 命令中参数“drop.unused.levels”的默认设置有关。默认情况下,此参数设置为 TRUE。因此,如果存在未使用的级别,它会在模型构建过程中被丢弃。但是,预测函数仍然使用原始数据以及因子变量中存在未使用的级别。这会导致用于模型构建的数据和用于预测的数据之间存在级别差异(即使它是相同的数据名 - 在您的情况下为 myData)。我在下面给出了一个例子:
n <- 100
x1 <- rnorm (n)
x2 <- as.factor(sample(c(1,2,3),n,replace = TRUE))
# Replacing 3 with 2 makes the level = 3 as unused
x2[x2==3] <- 2
y <- as.factor(sample(c(1,2),n,replace = TRUE))
myData <- data.frame(x1 = x1, x2 = x2, y = y)
control <- y ~ x1 + x2
# this works fine:
glmObject <- glm(control, myData, family = binomial())
predicted1 <- predict.glm(glmObject , myData, type = "response")
# this gives an error - this uses default drop.unused.levels = TRUE
bayesglmObject <- bayesglm(control, myData, family = binomial())
predicted2 <- predict.bayesglm(bayesglmObject , myData, type = "response")
Error in X[, piv, drop = FALSE] : subscript out of bounds
# this works fine - value of drop.unused.levels is set to FALSE
bayesglmObject <- bayesglm(control, myData, family = binomial(),drop.unused.levels = FALSE)
predicted2 <- predict.bayesglm(bayesglmObject , myData, type = "response")
Run Code Online (Sandbox Code Playgroud)
我认为更好的方法是使用 droplevels 预先从数据帧中删除未使用的级别,并将其用于模型构建和预测。