r-glm2错误 "singular fit encountered"

标签 r glm logistic-regression

我正在尝试不同的方法来进行逻辑回归。 我使用 glm 并收到警告,但仍然得到系数。所以这个公式是有效的。

logit<-glm(flag_compro~.,training, family=binomial("logit"),control = list(maxit = 50))

现在,我正在测试 glm2,因为它说使用与 glm 相同的模型规范,所以我写道:

logit2<-glm2(flag_compro~., training, family=binomial("logit"))

但我收到以下错误:

> logit2<-glm2(flag_compro~., training, family=binomial("logit"))
Error in lm.fit(x = x[good, , drop = FALSE] * w, y = z * w, singular.ok = FALSE,  : 
  singular fit encountered

我认为这与我可能存在多重共线性有关。如果是这样的话,glm2包有办法解决这个问题吗?

最佳答案

glm 函数会默默地删除列以纠正奇异拟合,而 glm2 函数不会执行此操作。一种解决方案是使用 lmglm 函数来拟合数据,查看它删除了哪些列,并在使用“glm2”之前删除这些列。下面是一个简单的可重现示例来演示。

请注意,从 glm 拟合中显式删除这些列也是一个好主意。

df <- data.frame(y = c(200, 1000, 100, 10, 10)
             ,x1 = c(0, 0, 50, 50, 0)
             ,x2 = c(0, 0, 350, 200, 0)
             ,x3 = c(100, 0, 0, 200, 100)
             ,x4 = c(200, 0, 50, 0, 200))
coef(lm(y ~ ., data = df)) # x4 dropped as predictor
coef(glm(y ~ ., data = df)) # x4 dropped as predictor

library(glm2)
glm2(y ~ ., data = df) # gives singular fit error
glm2(y ~ x1 + x2 + x3, data = df) # no singular fit error

summary(lm(x4 ~ x1 + x2 + x3, data = df))$r.squared # x4 is a linear combination of x1-x3

# If making predictions, should also remove columns before fitting with glm
glm_fit <- glm(y ~ ., data = df) 
predict(glm_fit, newdata = df[1:4,]) # gives warning about misleading predictions

glm_fit2 <- glm(y ~ x1 + x2 + x3, data = df)
predict(glm_fit2, newdata = df[1:4,]) # no warning about misleading predictions

关于r-glm2错误 "singular fit encountered",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26599959/

相关文章:

python - 如何在 Python 中创建精确召回曲线图来比较 2 个分类器?

r - ddply聚合列名

r - 使用 n-gram 和 R 进行纠错

r - 将 GLM 相关系数导出到 R 中的 csv

apache-spark - 如何在pyspark的LogisticRegressionWithLBFGS中打印预测概率

python - 如何使用 sklearn 在逻辑回归模型中查找 beta 值

r - 对 R 中的 "sentiment"包感到困惑吗?

r - R 中按列索引子集 - Data.Table 与 dataframe

r - 使用 LIME 预测 R 中的 logit 模型?

r - GLM 模型在交互式代码中运行,但在我使用 knitr 时不运行