Skip to main content

Next-Generation GAMs for Python

AI / Agents

Skills
llms.txt
llms-full.txt

Developers

Richard Iannone

Maintainer

Community

Contributing guide
Code of conduct
Security policy
Full license MIT

Meta

Requires: Python >=3.10
Provides-Extra: pd, pl, pa, formula, altair, tables, fast, all, dev, docs
Site Tags
Package Info

Whittaker fits generalized additive models in Python: regressions in which each effect is a smooth curve learned from the data, with its smoothness chosen automatically. It brings the depth of R’s mgcv to Pandas, Polars, and any Narwhals DataFrame, with an interactive chart for every fit.

18smooth bases
18response families
39User Guide chapters
51cookbook recipes
2,800+tests

A model, one term at a time

A GAM is a formula of smooth terms, fitted in one call. Step through this one, on four decades of CO₂ readings from Mauna Loa, to see what each term adds, with the new lines of code highlighted.

Data

Start with a data frame. This one, one of Whittaker’s built-in datasets, has a reading for every month from 1958 to 1997: a rising trend with a yearly cycle on top.

import altair as alt
import whittaker as wk

co2 = wk.load_dataset("co2", as_frame=True)

chart = alt.Chart(co2).encode(x=alt.X("t:Q", title=None, axis=alt.Axis(format="d")))
data = chart.mark_line(color="#c4bccb").encode(
    y=alt.Y("co2:Q", title="CO₂ (ppm)", scale=alt.Scale(zero=False))
)

data.properties(width="container", height=280)

Trend

s(t) is a smooth function of time, with no shape assumed. Its wiggliness is penalized, and the penalty’s weight is chosen from the data, so the curve follows the trend and not the noise.

import altair as alt
import whittaker as wk

co2 = wk.load_dataset("co2", as_frame=True)

model = wk.GAM("co2 ~ s(t)").fit(co2)
co2["fit"] = model.predict(co2).values

chart = alt.Chart(co2).encode(x=alt.X("t:Q", title=None, axis=alt.Axis(format="d")))
data = chart.mark_line(color="#c4bccb").encode(
    y=alt.Y("co2:Q", title="CO₂ (ppm)", scale=alt.Scale(zero=False))
)
fit = chart.mark_line(color="#b8405f", strokeWidth=1.5).encode(y="fit:Q")

(data + fit).properties(width="container", height=280)

Season

Add a second smooth, of the month. A cyclic basis (bs="cc") makes December meet January, and the two terms are fitted together: now the curve tracks every season.

import altair as alt
import whittaker as wk

co2 = wk.load_dataset("co2", as_frame=True)

model = wk.GAM("co2 ~ s(t) + s(month, bs='cc', k=12)").fit(co2)
co2["fit"] = model.predict(co2).values

chart = alt.Chart(co2).encode(x=alt.X("t:Q", title=None, axis=alt.Axis(format="d")))
data = chart.mark_line(color="#c4bccb").encode(
    y=alt.Y("co2:Q", title="CO₂ (ppm)", scale=alt.Scale(zero=False))
)
fit = chart.mark_line(color="#b8405f", strokeWidth=1.5).encode(y="fit:Q")

(data + fit).properties(width="container", height=280)

Effects

Each term can be seen on its own. model.plot() draws every smooth’s partial effect, with its confidence band and its effective degrees of freedom.

import whittaker as wk

co2 = wk.load_dataset("co2", as_frame=True)

model = wk.GAM("co2 ~ s(t) + s(month, bs='cc', k=12)").fit(co2)

model.plot()

Summary

model.summary() gives the model’s numbers: each smooth’s effective degrees of freedom and significance test, the deviance explained, and the AIC.

import whittaker as wk

co2 = wk.load_dataset("co2", as_frame=True)

model = wk.GAM("co2 ~ s(t) + s(month, bs='cc', k=12)").fit(co2)

model.summary()
GAM fit summary
============================================================
Formula:    co2 ~ s(t) + s(month, bs='cc', k=12)
Family:     Gaussian(link='identity')
Inference:  GCV
Observations: 504
Coefficients: 20

Parametric coefficients:
  Term                       Estimate    Std.Err    t value    p-value
  ------------------------ ---------- ---------- ---------- ----------
  (Intercept)                349.3071     0.0172  20367.634    < 1e-16

Approximate significance of smooth terms:
  Term                        EDF Ref.df     Chi.sq    p-value
  ------------------------ ------ ------ ---------- ----------
  s(t)                       1.77      2 1411871.594    < 1e-16
  s(month, bs='cc', k=12)    8.02      9  17900.530    < 1e-16

Total EDF:  10.79
Scale est:  0.143054
Deviance:   70.5564
Null dev:   205200.9698
Dev. expl:  100.0%
GCV score:  0.146183
AIC:        461.03
BIC:        506.58

Check

wk.check() asks whether the model can be trusted: the residuals against the fit, their quantiles and histogram, and the observed values against the fitted ones.

import whittaker as wk

co2 = wk.load_dataset("co2", as_frame=True)

model = wk.GAM("co2 ~ s(t) + s(month, bs='cc', k=12)").fit(co2)

wk.check(model)

Quick start Smooth terms Model diagnostics

Every kind of smooth

Thin plate and cubic splines, P-splines, cyclic and adaptive smooths, Gaussian processes, random effects, tensor products for surfaces, and smooths held to a shape (increasing, decreasing, convex, or concave). Each tile here is a real fit, so select one to read about it.

Smooth terms Shape constraints

Four ways to draw a band

The head’s acceleration in a simulated motorcycle crash spreads out after the impact. Each of these models puts a 90% band around it in its own way.

How the charts are drawn
import numpy as np
import pandas as pd

mcycle = wk.load_dataset("mcycle", as_frame=True)
grid = pd.DataFrame({"times": np.linspace(0, 57, 200)})


# The data, and a curve with a band around it
def show(middle, lower, upper):
    band = grid.assign(middle=middle, lower=lower, upper=upper)
    x = alt.X("times:Q", title="Time after impact (ms)")
    return (
        alt.Chart(band).mark_area(color="#d36983", opacity=0.18).encode(x=x, y="lower:Q", y2="upper:Q")
        + alt.Chart(mcycle).mark_circle(color="#9a8aa8", size=22).encode(
            x=x, y=alt.Y("accel:Q", title="Acceleration (g)")
        )
        + alt.Chart(band).mark_line(color="#b8405f", strokeWidth=2).encode(x=x, y="middle:Q")
    ).properties(width="container", height=300)

Mean

A GAM’s prediction interval has one width everywhere, so it is too wide before the impact and too narrow after it.

model = wk.GAM("accel ~ s(times, k=20)").fit(mcycle, method="REML")
pred = model.predict(grid, interval="prediction", level=0.9)

show(pred.values, pred.lower, pred.upper)

Location and scale

A GAMLSS model gives the spread its own smooth, alongside the mean’s, and the band follows the spread as it changes.

model = wk.GAMLSS(
    formulas={"mu": "accel ~ s(times, k=20)", "sigma": "accel ~ s(times)"},
    family=wk.GaussianLS(),
).fit(mcycle)
pred = model.predict(grid).values

show(pred["mu"], pred["mu"] - 1.645 * pred["sigma"], pred["mu"] + 1.645 * pred["sigma"])

Quantiles

Quantile regression fits the 5th, 50th and 95th percentiles directly, with no distribution assumed for the noise.

model = wk.QuantileGAM("accel ~ s(times, k=15)", quantiles=[0.05, 0.5, 0.95]).fit(mcycle)
pred = model.predict(grid)

show(pred[0.5].values, pred[0.05].values, pred[0.95].values)

Conformal

Conformal prediction wraps any model in an interval with guaranteed coverage, from the model’s errors on data it wasn’t fitted to.

model = wk.conformal_fit("accel ~ s(times, k=20)", mcycle, method="cv+", level=0.9, seed=1)
pred = model.predict(grid)

show(pred.values, pred.lower, pred.upper)

Distributional regression Quantile regression Conformal prediction

And when you need more

Families for any response

Counts, proportions, positive and skewed values, survival times, ordered and unordered categories, and zero-inflated data, each with its own links.

Response families →

Bayesian inference

Variational inference for a fast posterior, or NUTS sampling with R-hat, effective sample sizes, and divergences, then LOO, WAIC, and stacking.

MCMC sampling →

Large datasets

BigGAM fits millions of rows by discretizing them, and PolarsGAM and DuckDBGAM stream data that doesn’t fit in memory.

Large datasets →

Causal inference

Average and conditional treatment effects by double machine learning, with smooths for the nuisance models, and mediation analysis.

Causal inference →

Streaming and functional data

Update a model as data arrives, tracking drift with decay, or regress a scalar on a whole curve.

Streaming and online fitting →

Derivatives and comparisons

Derivatives and marginal effects with simultaneous bands, ANOVA, and side-by-side comparisons of models.

Derivatives and marginal effects →

scikit-learn

GAMRegressor and GAMClassifier go into pipelines, grid searches, and cross-validation like any other estimator.

scikit-learn integration →

Save, load, and share with R

Save a fitted model to a compact file, and convert it to and from mgcv’s form for R.

Saving and loading models →

Formulas in code

Build models from terms in code as well as from formula strings, and get their model matrices for your own work.

Programmatic formulas →

Get started

Install Whittaker from PyPI:

pip install whittaker

Then fit your first models in the Quick start, learn how GAMs work in Understanding GAMs, or find a recipe for a task in the Cookbook.