Search code examples
pythongampygam

How to extract intercept parameter from python pygam.LinearGAM


I am looking to extract the fitted parameter from a model fit with pygam. Here is a reproducible example.

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)

Here are few things I have tried.

#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.

Here is a relevant GitHub issue that does not appear top have been implemented: https://github.com/dswah/pyGAM/issues/85


Solution

  • TL;DR

    • The default stores the intercept as last of the coefficients and can be extracted via gam.coef_[-1].
    • The terms attribute can be printed to verify this behavior.
    • You can be more explicit by importing pygam.intercept and including it in your formula (e.g. gam = LinearGAM(intercept + s(0) + s(1) + f(2)).fit(X, y))

    Default Behavior and Terms

    The default stores the intercept as last of the coefficients and can be extracted via gam.coef_[-1]. Print the terms attribute to verify this.

    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
    

    Explicitly declaring the intercept

    It is a good idea to explicitly include the intercept in your formula so that you are not relying on the intercept being the last element of the coefficients.

    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