在glm函数的优化算法的每个步骤中是否有一种方法可以获得系数?

11

在R中执行逻辑回归时,可以使用coefficients()函数,在优化算法收敛(或未收敛)后获得系数:

library(MASS)
data(menarche)
glm.out = glm(cbind(Menarche, Total-Menarche) ~ Age,
               family=binomial(logit), data=menarche)
coefficients(glm.out)
## (Intercept)         Age 
## -21.226395    1.631968

有没有一种方法可以获取优化算法每个步骤的系数以跟踪其步骤?

1个回答

10

glm.fit的内部结构已经改变(请参见@John的评论),因此请使用此替代方法。它不依赖于内部结构的行位置,而是在glm.fit中截获每个cat实例并将消息添加到迭代消息中,因此尽管它仍然依赖于内部结构,但应该更加稳定。在R 4.1和4.2中对我有效。

library(MASS)
data(menarche)

trace(glm.fit, quote(cat <- function(...) {
  base::cat(...)
  if (...length() >= 3 && identical(..3, " Iterations - ")) print(coefold)
}))
glm.out = glm(cbind(Menarche, Total-Menarche) ~ Age,
                     family=binomial(logit), data=menarche,
                     control = glm.control(trace = TRUE))
untrace(glm.fit)

之前的解决方案

使用值为所示的control=参数会导致偏差打印,使用trace语句将导致系数值打印:

trace(glm.fit, quote(print(coefold)), at = list(c(22, 4, 8, 4, 19, 3)))
glm.out = glm(cbind(Menarche, Total-Menarche) ~ Age,
                     family=binomial(logit), data=menarche,
                     control = glm.control(trace = TRUE))

输出结果将类似于:

Tracing glm.fit(x = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  .... step 22,4,8,4,19,3 
NULL
Deviance = 27.23412 Iterations - 1
Tracing glm.fit(x = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  .... step 22,4,8,4,19,3 
[1] -20.673652   1.589536
Deviance = 26.7041 Iterations - 2
Tracing glm.fit(x = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  .... step 22,4,8,4,19,3 
[1] -21.206854   1.630468
Deviance = 26.70345 Iterations - 3
Tracing glm.fit(x = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  .... step 22,4,8,4,19,3 
[1] -21.226370   1.631966
Deviance = 26.70345 Iterations - 4

要删除痕迹,请使用:

untrace(glm.fit)

请注意,在trace调用中,coefold是在glm.fit源代码中内部使用的变量名称,并且使用的数字是指源代码中的语句编号,因此如果glm.fit源代码发生更改,则这些数字可能需要更改。我正在使用“R版本3.2.2 Patched(2015-10-19 r69550)”。


如果glm.fit源代码发生更改,则两者都可能需要更改:我认为在4.1左右可能已经发生了这种情况,因为该命令开始返回错误。 - John
1
已经修复了。 - G. Grothendieck
太棒了!谢谢。如果可以的话,我会再次点赞的。 - John

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接