如何从 python pygam.LinearGAM 中提取拦截参数

How to extract intercept parameter from python pygam.LinearGAM

我希望从适合 pygam 的模型中提取适合的参数。这是一个可重现的例子。

from pygam import LinearGAM, s, f
from pygam.datasets import wage
X, y = wage()
gam = LinearGAM(s(0) + s(1) + f(2)).fit(X, y)

以下是我尝试过的一些东西。

#gam.summary() ## This does not show it.
#gam.intercept_ ## This does not exit.
#gam.terms.info ## This does not contain it.
#gam.partial_dependence(-1) ## This raises an error.

这是一个相关的 GitHub 问题,但未出现在最前面的问题已得到解决:https://github.com/dswah/pyGAM/issues/85

TL;DR

  • 默认将截距存储为系数的最后一个,可以通过 gam.coef_[-1].
  • 提取
  • 可以打印 terms 属性来验证此行为。
  • 您可以通过导入 pygam.intercept 并将其包含在您的公式中(例如 gam = LinearGAM(intercept + s(0) + s(1) + f(2)).fit(X, y)
  • 来更加明确

默认行为和条款

默认将截距存储为最后一个系数,可以通过 gam.coef_[-1] 提取。打印 terms 属性来验证这一点。

from pygam import LinearGAM, s, f
from pygam.datasets import wage
X, y = wage()
gam = LinearGAM(s(0) + s(1) + f(2)).fit(X, y)
print(gam.terms)
# s(0) + s(1) + f(2) + intercept
print(gam.coef_[-1])
# 96.31496573750117

明确声明拦截

最好在公式中明确包含截距,这样您就不会依赖截距作为系数的最后一个元素。

from pygam import intercept
gam = LinearGAM(intercept + s(0) + s(1) + f(2)).fit(X, y)
print(gam.terms)
# intercept + s(0) + s(1) + f(2)
print(gam.coef_[0])
# 96.31499924945388