gpt4 book ai didi

r - R中的加权逻辑回归

转载 作者:行者123 更新时间:2023-12-04 10:12:48 24 4
gpt4 key购买 nike

给定成功比例加上样本大小和自变量的样本数据,我正在尝试在 R 中进行逻辑回归。

下面的代码做了我想要的,似乎给出了合理的结果,但看起来不像一个明智的方法;实际上它使数据集的大小加倍

datf <- data.frame(prop  = c(0.125, 0,  0.667, 1,  0.9),
cases = c(8, 1, 3, 3, 10),
x = c(11, 12, 15, 16, 18))

datf2 <- rbind(datf,datf)
datf2$success <- rep(c(1, 0), each=nrow(datf))
datf2$cases <- round(datf2$cases*ifelse(datf2$success,datf2$prop,1-datf2$prop))
fit2 <- glm(success ~ x, weight=cases, data=datf2, family="binomial")

datf$proppredicted <- 1 / (1 + exp(-predict(fit2, datf)))
plot(datf$x, datf$proppredicted, type="l", col="red", ylim=c(0,1))
points(datf$x, datf$prop, cex=sqrt(datf$cases))

生成类似 logistic prediction 的图表

这看起来相当明智。

但我对 datf2 的使用并不满意作为通过复制数据来区分成功和失败的一种方式。这样的事情有必要吗?

作为一个较小的问题,是否有一种更清晰的方法来计算预测的比例?

最佳答案

不需要像那样构建人工数据; glm可以从给定的数据集中拟合您的模型。

> glm(prop ~ x, family=binomial, data=datf, weights=cases)

Call: glm(formula = prop ~ x, family = binomial, data = datf, weights = cases)

Coefficients:
(Intercept) x
-9.3533 0.6714

Degrees of Freedom: 4 Total (i.e. Null); 3 Residual
Null Deviance: 17.3
Residual Deviance: 2.043 AIC: 11.43

您将收到有关“非整数 #successes”的警告,但这是因为 glm很傻。与您构建的数据集上的模型进行比较:
> fit2

Call: glm(formula = success ~ x, family = "binomial", data = datf2,
weights = cases)

Coefficients:
(Intercept) x
-9.3532 0.6713

Degrees of Freedom: 7 Total (i.e. Null); 6 Residual
Null Deviance: 33.65
Residual Deviance: 18.39 AIC: 22.39

回归系数(因此预测值)基本相等。但是,您的残余偏差和 AIC 是可疑的,因为您已经创建了人工数据点。

关于r - R中的加权逻辑回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50078497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com