请注意,为了执行您想要的操作,您可以使用 predict 函数为数据集中的每个观察提取线性预测。然后,您可以简单地使用适当的概率分布函数来获得预测概率。例如,在逻辑回归的情况下,使用 plogis。换句话说,如果 mod 是你的模型适合 glm:
plogis(predict(mod))
将返回数据集中每个观察的预测概率,假设您估计了一个逻辑模型。如果您需要计算不在数据集中的点的预测概率,请参阅预测的新数据选项。请注意,预测还可以提供每个点的标准误差。查看 predict.glm 的文档以获取更多信息(使用 help(predict)):
predict(mod, type="response")
改编自杰森摩根:predict probability using R
此外,对于逻辑回归,函数用法如下:
predict(object, newdata = NULL,
type = c("link", "response", "terms"),
se.fit = FALSE, dispersion = NULL, terms = NULL,
na.action = na.pass, ...)
您可以尝试将可用的 R 实现为:
predict(budworm.lg, data.frame(ldose = ld,
sex = factor(rep("M", length(ld)), levels = levels(sex))),
type = "response")
对于数据库Venables 和 Ripley (2002, pp. 190-2.)。具体可以使用如下代码:
require(graphics)
## example from Venables and Ripley (2002, pp. 190-2.)
ldose <- rep(0:5, 2)
numdead <- c(1, 4, 9, 13, 18, 20, 0, 2, 6, 10, 12, 16)
sex <- factor(rep(c("M", "F"), c(6, 6)))
SF <- cbind(numdead, numalive = 20-numdead)
budworm.lg
budworm.lg <- glm(SF ~ sex*ldose, family = binomial)
summary(budworm.lg)
plot(c(1,32), c(0,1), type = "n", xlab = "dose",
ylab = "prob", log = "x")
text(2^ldose, numdead/20, as.character(sex))
ld <- seq(0, 5, 0.1)
lines(2^ld, predict(budworm.lg, data.frame(ldose = ld,
sex = factor(rep("M", length(ld)), levels = levels(sex))),
type = "response"))
lines(2^ld, predict(budworm.lg, data.frame(ldose = ld,
sex = factor(rep("F", length(ld)), levels = levels(sex))),
type = "response"))