Skip to content

GAMs: smooth curves with a built-in brake

A generalized additive model fits a smooth curve for each predictor and lets a penalty decide how much it bends. Learn to read effective degrees of freedom, check the basis size, and interpret the curve itself.

Advanced ~11 min10 steps

What runs in CodeSplash

You will be able to

  • Describe a smooth term as a flexible basis plus a wiggliness penalty
  • Read effective degrees of freedom and check that k is large enough
  • Interpret a smooth from its plot, since it has no single coefficient
  • Decide between a penalized smooth and a fixed-df spline

Read first

01

Let the penalty decide

Read

With a spline, you chose the knots, and each one cost a coefficient. A GAMGeneralized additive modelFits a smooth curve for each predictor, with a penalty on wiggliness whose strength is estimated from the data. starts from many basis functions and adds a brake:

minimize∑i(yi−y^i)2+λ∫f′′(x)2 dx\text{minimize}\quad \sum_i (y_i - \hat y_i)^2 + \lambda \int f''(x)^2\,dx

The second term charges for curvature. A large λ\lambda pulls the curve toward a straight line, and a small one lets it wiggle. REML estimates λ\lambda from the data, so you don't tune it by hand.

The model is additive: y=β0+f1(x1)+f2(x2)+εy = \beta_0 + f_1(x_1) + f_2(x_2) + \varepsilon.

02

Make a prediction

Predict

Predict first

A smooth's complexity is measured in effective degrees of freedomEffective degrees of freedomHow many free parameters a penalized model is really using; a heavily smoothed curve may use about one.. Suppose the penalty flattens a smooth all the way to a straight line. What's its edf?

Make your guess between 0 and 20 df, then reveal.

Reveal

1, since a straight line uses one slope. An edf of 4 is a curve about as complex as four slopes' worth of spline columns. It doesn't have to be a whole number.

03

Read the card

In the app
Generalized additive modelRecorded · Python and R agreeRecorded 2026-11-17 · 26 values compared
R

F(13.97, 120.22) = 33.93, p < .001

Deviance explained
80.1%
Adjusted R²
0.7820
Total edf
12.785
Scale (σ²)
509.01

Plots

Partial effect of timesWhat is a feature's effect on predictions when features are correlated?
View data
s(times)+2 SE−2 SEtimes
24.47349.111−0.16562.400
24.19944.3824.0162.958
23.93541.3486.5223.515
23.69040.3327.0474.073
23.47340.7446.2024.630
23.29541.4855.1045.188
23.16441.6554.6735.745
23.09040.8325.3486.303
23.09039.4986.6826.861
23.18638.5377.8357.418
23.39838.3308.4667.976
23.75038.4799.0218.533
24.25438.40710.1009.091
24.86238.58611.1389.648
25.49239.64311.34110.206
26.06441.09411.03410.764
26.47041.76111.17811.321
26.42441.19311.65611.879
25.56139.50911.61412.436
23.51536.72310.30812.994
19.91932.4137.42613.552
14.40825.7573.05914.109
6.66416.198−2.86914.667
−3.1525.086−11.39115.224
−14.621−6.587−22.65515.782
−27.247−19.263−35.23016.339
−40.009−31.240−48.77916.897
−51.712−42.106−61.31917.455
−61.902−51.938−71.86618.012
−70.632−59.957−81.30618.570
−77.967−66.250−89.68419.127
−83.967−71.691−96.24319.685
−88.535−76.080−100.9920.242
−91.376−78.276−104.4820.800
−92.184−78.260−106.1121.358
−90.687−76.718−104.6621.915
−86.859−73.394−100.3222.473
−80.779−67.660−93.89723.030
−72.529−59.594−85.46523.588
−62.192−49.926−74.45924.145
−50.071−38.812−61.32924.703
−36.903−25.954−47.85125.261
−23.471−12.684−34.25725.818
−10.2940.2587−20.84626.376
2.44413.484−8.59526.933
14.57726.1033.05027.491
25.87837.76513.99128.048
36.07748.96823.18628.606
44.89959.04530.75329.164
52.11366.73637.48929.721
57.67772.10943.24630.279
61.60875.84447.37230.836
63.92078.36249.47831.394
64.62879.47849.77731.952
63.74678.57148.92232.509
61.36875.32047.41733.067
57.88870.74145.03433.624
53.77266.09241.45334.182
49.49261.95437.02934.739
45.50258.15432.85035.297

First 60 of 100 rows.

Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
FittedResidual
−1.0731.073
−1.172−0.1282
−1.463−1.237
−1.6501.650
−1.825−0.8745
−2.447−0.2528
−2.466−0.2337
−2.4601.160
−2.228−0.4716
−2.024−0.6759
−1.5730.2733
−1.573−1.127
−0.7391−1.961
−0.2840−2.416
−0.0602−5.340
0.3612−3.061
0.7219−6.122
0.9533−0.9533
−3.1590.4595
−6.0243.324
−7.8247.824
−17.8384.538
−17.83812.438
−17.83812.438
−17.8388.538
−17.8381.838
−17.838−4.962
−21.05618.356
−32.1559.355
−32.1550.0552
−32.155−21.345
−32.155−22.745
−36.272−3.928
−36.27214.772
−40.56419.064
−40.564−10.236
−45.0112.111
−45.01118.211
−49.57428.074
−49.574−1.226
−49.574−12.126
−54.19648.796
−54.196−26.204
−58.817−0.1830
−63.381−7.619
−63.381−27.719
−63.381−14.319
−80.06142.561
−80.061−5.539
−80.061−43.039
−80.061−21.839
−83.747−15.353
−83.747−20.653
−96.611−15.889
−96.61145.811
−104.37−18.730
−106.6121.012
−106.6134.312
−108.69−18.514
−113.79−9.310

First 60 of 133 rows.

Assumptions

  • Basis dimension large enough — The most complex smooth uses 62% of its k − 1 = 19 df.
  • Normal residuals — Shapiro–Wilk W = 0.976, p = .019.

Smooth terms

TermedfRef. dfFpSmoothing parameter
s(times)11.78513.96833.934< .00125.320

Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom.

Parametric terms

TermBSEtp95% CI low95% CI high
(Intercept)−25.5461.956−13.058< .001−29.419−21.673
  • Penalized cubic regression splines, smoothness by REML with k = 20 (mgcv::gam).
The exact R script · R R version 4.5.1 (2025-06-13)
# Generalized additive model (smooth terms)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.gam 1.0.1 · spec 56321aef4661c153
# Dataset: s1_mcycle (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(mgcv))

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_mcycle.parquet", col_select = c("accel", "times")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("accel", "times")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("accel", "times"))  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome <- "accel"
smooth_cols <- c("times")
predictors <- c()
k <- as.integer(20)  # basis dimension of each smooth
fixed <- FALSE  # TRUE: unpenalized regression splines (fx = TRUE)
conf <- 0.95
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than coefficients: the linear terms plus k - 1 per smooth (one is absorbed by its centering).
cs_check_rows(nrow(df), length(cs_design_labels(df, predictors)) + length(smooth_cols) * (k - 1) + 1, "A generalized additive model")
for (col in c(outcome, smooth_cols, predictors)) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation
for (x in smooth_cols) {
  nu <- length(unique(df[[x]]))
  if (nu < k) cs_error("CS_E_INVALID_OPTION", option = "The basis dimension k", allowed = sprintf("at most %d, the number of distinct values of %s", nu, x), value = k)
}
# mgcv's formula parser drops backticks, so the model runs on safe column names (labels keep the originals).
dat <- data.frame(.cs_y = df[[outcome]])
p_names <- if (length(predictors)) paste0(".cs_p", seq_along(predictors)) else character(0)
s_names <- paste0(".cs_s", seq_along(smooth_cols))
for (i in seq_along(predictors)) dat[[p_names[i]]] <- df[[predictors[i]]]
for (i in seq_along(smooth_cols)) dat[[s_names[i]]] <- df[[smooth_cols[i]]]
rhs <- c(if (length(predictors)) p_names else "1",
         sprintf("s(%s, bs = \"cr\", k = %d, fx = %s)", s_names, k, if (fixed) "TRUE" else "FALSE"))
fml <- stats::as.formula(paste(".cs_y ~", paste(rhs, collapse = " + ")))
# REML with tight convergence so the smoothing parameters agree to ~1e-9.
fit <- gam(fml, data = dat, method = "REML", control = gam.control(epsilon = 1e-12, newton = list(conv.tol = 1e-12)))
X <- predict(fit, type = "lpmatrix")
y <- df[[outcome]]
n <- length(y)
edf_total <- sum(fit$edf)
rdf <- n - edf_total
Vp <- fit$Vp
beta <- unname(coef(fit))
values <- list()

# %% Parametric terms (t tests on the residual df)
terms_p <- cs_design_labels(df, predictors)
if (length(terms_p) != fit$nsdf) cs_error("CS_E_COLLINEAR")
q <- qt(1 - (1 - conf) / 2, rdf)
coefs <- list()
for (j in seq_len(fit$nsdf)) {
  b <- beta[j]; se <- sqrt(Vp[j, j]); t <- b / se; p <- 2 * pt(abs(t), rdf, lower.tail = FALSE)
  term <- terms_p[j]
  coefs[[j]] <- list(term = term, estimate = b, se = se, t = t, p = p, ci_low = b - q * se, ci_high = b + q * se)
  values[[sprintf("coef[%s]", term)]] <- b; values[[sprintf("se[%s]", term)]] <- se; values[[sprintf("t[%s]", term)]] <- t
  values[[sprintf("p[%s]", term)]] <- p; values[[sprintf("ci_low[%s]", term)]] <- b - q * se; values[[sprintf("ci_high[%s]", term)]] <- b + q * se
}

# %% Smooth terms (summary.gam's testStat, on the full model matrix)
s_rows <- list()
for (i in seq_along(fit$smooth)) {
  sm <- fit$smooth[[i]]
  idx <- sm$first.para:sm$last.para
  label <- sprintf("s(%s)", smooth_cols[i])
  edf_i <- sum(fit$edf[idx])
  edf1_i <- sum(fit$edf1[idx])
  if (abs(edf1_i - round(edf1_i)) < 1e-9) edf1_i <- round(edf1_i)  # whole-number edf (fixed smooths): integer-rank branch in both engines
  res <- mgcv:::testStat(beta[idx], X[, idx, drop = FALSE], Vp[idx, idx, drop = FALSE], min(length(idx), edf1_i), type = 0, res.df = rdf)
  F <- res$stat / res$rank
  sp <- if (fixed) NULL else unname(fit$sp[i])
  s_rows[[i]] <- list(term = label, edf = edf_i, ref_df = res$rank, f = F, p = res$pval, sp = sp)
  values[[sprintf("edf[%s]", label)]] <- edf_i; values[[sprintf("ref_df[%s]", label)]] <- res$rank
  values[[sprintf("s_f[%s]", label)]] <- F; values[[sprintf("s_p[%s]", label)]] <- res$pval
  if (!fixed) values[[sprintf("sp[%s]", label)]] <- sp
}
fitted_v <- unname(fitted(fit))
resid <- y - fitted_v
r2_adj <- 1 - var(resid) * (n - 1) / (var(y - mean(y)) * rdf)
dev_expl <- 1 - sum(resid^2) / sum((y - mean(y))^2)
max_share <- max(vapply(s_rows, function(r) r$edf / (k - 1), 0))
values <- c(values, list(n = n, k_param = fit$nsdf, edf_total = edf_total, residual_df = rdf, r2_adj = r2_adj, dev_expl = dev_expl,
                         scale = fit$sig2, focal_f = s_rows[[1]]$f, focal_df = s_rows[[1]]$ref_df, focal_p = s_rows[[1]]$p,
                         max_edf_share = max_share, fixed_df = fixed, missing_share = if (n_input > 0) n_dropped / n_input else 0))
if (!fixed) values$reml <- unname(fit$gcv.ubre)

# %% Assumptions
assumptions <- list(list(key = "basis", label = "Basis dimension large enough", status = if (!fixed && max_share > 0.9) "warn" else "pass", statistic = max_share,
                         detail = if (!fixed && max_share > 0.9) sprintf("A smooth uses %.0f%% of its k − 1 = %d df: increase k and refit.", 100 * max_share, k - 1L)
                                  else sprintf("The most complex smooth uses %.0f%% of its k − 1 = %d df.", 100 * max_share, k - 1L)))
if (n >= 3 && n <= 5000) {
  sw <- shapiro.test(resid)
  values$sw_p_resid <- sw$p.value
  assumptions[[2]] <- list(key = "normality", label = "Normal residuals", status = if (sw$p.value >= 0.05) "pass" else if (n < 300) "warn" else "info",
                           statistic = unname(sw$statistic), p = sw$p.value, detail = sprintf("Shapiro–Wilk W = %.3f, %s.", sw$statistic, cs_fmt_p(sw$p.value)))
}

# %% Result
charts <- list()
for (i in seq_along(fit$smooth)) {
  sm <- fit$smooth[[i]]
  idx <- sm$first.para:sm$last.para
  x <- smooth_cols[i]
  grid <- seq(min(df[[x]]), max(df[[x]]), length.out = 100)
  Xg <- PredictMat(sm, setNames(data.frame(grid), s_names[i]))
  f <- as.vector(Xg %*% beta[idx])
  sef <- sqrt(pmax(rowSums((Xg %*% Vp[idx, idx]) * Xg), 0))
  charts[[i]] <- cs_chart(paste0("smooth_", x), "ale-plot", sprintf("Partial effect of %s", x), list(
    x = cs_col(x, grid), effect = cs_col(sprintf("s(%s)", x), f), low = cs_col("−2 SE", f - 2 * sef), high = cs_col("+2 SE", f + 2 * sef)))
}
charts[[length(charts) + 1]] <- cs_chart("residuals", "residual-panel", "Residual diagnostics", list(fitted = cs_col("Fitted", fitted_v), residual = cs_col("Residual", resid)))
pct <- sprintf("%.0f%%", conf * 100)
s0 <- s_rows[[1]]
summary <- paste0(sprintf("Additive model of %s (n = %d): deviance explained %.1f%%, adjusted R² = %.3f. ", outcome, n, 100 * dev_expl, r2_adj),
                  paste(vapply(s_rows, function(r) sprintf("%s: edf = %.2f, F = %.2f, %s", r$term, r$edf, r$f, cs_fmt_p(r$p)), ""), collapse = "; "), ".")
cs_publish(list(
  method = "regression.gam",
  methodVersion = "1.0.1",
  title = "Generalized additive model",
  engine = cs_engine_info("mgcv", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("F(%.2f, %.2f) = %.2f, %s", s0$ref_df, rdf, s0$f, cs_fmt_p(s0$p)),
  statistics = list(list(key = "dev_expl", label = "Deviance explained", value = dev_expl, format = "percent"),
                    list(key = "r2_adj", label = "Adjusted R²", value = r2_adj), list(key = "edf_total", label = "Total edf", value = edf_total),
                    list(key = "scale", label = "Scale (σ²)", value = fit$sig2)),
  tables = list(
    list(key = "smooths", title = "Smooth terms", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "edf", label = "edf", type = "number"), list(key = "ref_df", label = "Ref. df", type = "number"),
      list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue"), list(key = "sp", label = "Smoothing parameter", type = "number")),
      rows = s_rows, note = "Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom."),
    list(key = "parametric", title = "Parametric terms", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"), list(key = "se", label = "SE", type = "number"),
      list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
      list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")), rows = coefs)
  ),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("%s with k = %d (mgcv::gam).", if (fixed) "Unpenalized cubic regression splines (fixed df)" else "Penalized cubic regression splines, smoothness by REML", k)),
  charts = charts,
  values = values
))
Python

F(13.97, 120.22) = 33.93, p < .001

Deviance explained
80.1%
Adjusted R²
0.7820
Total edf
12.785
Scale (σ²)
509.01

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Basis dimension large enough — The most complex smooth uses 62% of its k − 1 = 19 df.
  • Normal residuals — Shapiro–Wilk W = 0.976, p = .019.

Smooth terms

TermedfRef. dfFpSmoothing parameter
s(times)11.78513.96833.934< .00125.320

Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom.

Parametric terms

TermBSEtp95% CI low95% CI high
(Intercept)−25.5461.956−13.058< .001−29.419−21.673
  • Penalized cubic regression splines, smoothness by REML with k = 20; twin of mgcv::gam.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generalized additive model (smooth terms)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.gam 1.0.1 · spec 56321aef4661c153
# Dataset: s1_mcycle (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import gam as csgam  # twin of mgcv::gam(bs = "cr", method = "REML") — pygam uses other bases and criteria
from codesplash.stats import regression as csreg

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_mcycle.parquet", columns=["accel", "times"])
n_input = len(df)
df = df.dropna(subset=["accel", "times"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["accel", "times"])  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome = "accel"
smooth_cols = ["times"]
predictors = []
k = int(20)  # basis dimension of each smooth
fixed = False  # True: unpenalized regression splines (mgcv fx = TRUE)
conf = 0.95
y = df[outcome].to_numpy(dtype=float)
Xp = csreg.design_matrix(df, predictors)  # intercept + linear terms
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than coefficients: the linear terms plus k − 1 per smooth (one is absorbed by its centering).
cs.check_rows(len(df), Xp.shape[1] + len(smooth_cols) * (k - 1) + 1, "A generalized additive model")
for col in [outcome] + smooth_cols + predictors:
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation
for x in smooth_cols:
    nu = df[x].nunique()
    if nu < k:
        cs.cs_error("CS_E_INVALID_OPTION", option="The basis dimension k", allowed=f"at most {nu}, the number of distinct values of {x}", value=k)
smooths = [csgam.cr_smooth(df[x].to_numpy(dtype=float), k, f"s({x})", fixed) for x in smooth_cols]
fit = csgam.fit_gam(y, Xp.to_numpy(), smooths)
X = np.column_stack([Xp.to_numpy()] + [s.X for s in smooths])
n = len(y)
edf_total = float(fit.edf.sum())
rdf = n - edf_total
values = {}

# %% Parametric terms (t tests on the residual df)
coefs = []
q = stats.t.ppf(1 - (1 - conf) / 2, rdf)
for j, term in enumerate(Xp.columns):
    b = float(fit.beta[j])
    se = float(np.sqrt(fit.Vp[j, j]))
    t = b / se
    p = float(2 * stats.t.sf(abs(t), rdf))
    coefs.append({"term": term, "estimate": b, "se": se, "t": t, "p": p, "ci_low": b - q * se, "ci_high": b + q * se})
    values.update({f"coef[{term}]": b, f"se[{term}]": se, f"t[{term}]": t, f"p[{term}]": p, f"ci_low[{term}]": b - q * se, f"ci_high[{term}]": b + q * se})

# %% Smooth terms (mgcv's testStat on the full model matrix)
s_rows = []
for i, (s, (a, b_)) in enumerate(zip(smooths, fit.blocks)):
    edf_i = float(fit.edf[a:b_].sum())
    edf1_i = float(fit.edf1[a:b_].sum())
    if abs(edf1_i - round(edf1_i)) < 1e-9:
        edf1_i = float(round(edf1_i))  # whole-number edf (fixed smooths): integer-rank branch in both engines
    stat, pv, rank = csgam.test_stat(fit.beta[a:b_], X[:, a:b_], fit.Vp[a:b_, a:b_], min(b_ - a, edf1_i), rdf)
    F = stat / rank
    s_rows.append({"term": s.label, "edf": edf_i, "ref_df": rank, "f": F, "p": pv, "sp": None if s.fixed else float(fit.sp[i])})
    values.update({f"edf[{s.label}]": edf_i, f"ref_df[{s.label}]": rank, f"s_f[{s.label}]": F, f"s_p[{s.label}]": pv})
    if not s.fixed:
        values[f"sp[{s.label}]"] = float(fit.sp[i])
resid = y - fit.fitted
r2_adj = 1 - np.var(resid, ddof=1) * (n - 1) / (np.var(y - y.mean(), ddof=1) * rdf)
dev_expl = 1 - float(resid @ resid) / float(np.sum((y - y.mean()) ** 2))
max_share = max(r["edf"] / (k - 1) for r in s_rows)
values.update({"n": n, "k_param": Xp.shape[1], "edf_total": edf_total, "residual_df": rdf, "r2_adj": float(r2_adj), "dev_expl": dev_expl,
               "scale": fit.scale, "focal_f": s_rows[0]["f"], "focal_df": s_rows[0]["ref_df"], "focal_p": s_rows[0]["p"],
               "max_edf_share": max_share, "fixed_df": fixed, "missing_share": n_dropped / n_input if n_input else 0.0})
if not fixed:
    values["reml"] = fit.reml

# %% Assumptions
assumptions = [{"key": "basis", "label": "Basis dimension large enough", "status": "warn" if (not fixed and max_share > 0.9) else "pass", "statistic": max_share,
                "detail": (f"A smooth uses {max_share:.0%} of its k − 1 = {k - 1} df: increase k and refit." if (not fixed and max_share > 0.9)
                           else f"The most complex smooth uses {max_share:.0%} of its k − 1 = {k - 1} df.")}]
if 3 <= n <= 5000:
    sw = stats.shapiro(resid)
    values["sw_p_resid"] = float(sw.pvalue)
    assumptions.append({"key": "normality", "label": "Normal residuals", "status": "pass" if sw.pvalue >= 0.05 else ("warn" if n < 300 else "info"),
                        "statistic": float(sw.statistic), "p": float(sw.pvalue), "detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}."})
if not fit.converged:
    warnings.append("A smoothing parameter ran to its limit (the smooth is either a straight line or as wiggly as k allows).")

# %% Result
charts = []
for s, (a, b_), xname in zip(smooths, fit.blocks, smooth_cols):
    grid = np.linspace(df[xname].min(), df[xname].max(), 100)
    Xg = csgam.cr_basis(grid, s.knots) @ s.Z
    f = Xg @ fit.beta[a:b_]
    sef = np.sqrt(np.maximum(np.sum((Xg @ fit.Vp[a:b_, a:b_]) * Xg, axis=1), 0.0))
    charts.append(cs.chart(f"smooth_{xname}", "ale-plot", f"Partial effect of {xname}", {
        "x": cs.col(xname, grid), "effect": cs.col(s.label, f), "low": cs.col("−2 SE", f - 2 * sef), "high": cs.col("+2 SE", f + 2 * sef)}))
charts.append(cs.chart("residuals", "residual-panel", "Residual diagnostics", {"fitted": cs.col("Fitted", fit.fitted), "residual": cs.col("Residual", resid)}))
pct = f"{conf:.0%}"
s0 = s_rows[0]
summary = (f"Additive model of {outcome} (n = {n}): deviance explained {dev_expl:.1%}, adjusted R² = {r2_adj:.3f}. "
           + "; ".join(f"{r['term']}: edf = {r['edf']:.2f}, F = {r['f']:.2f}, {cs.fmt_p(r['p'])}" for r in s_rows) + ".")
cs.publish({
    "method": "regression.gam",
    "methodVersion": "1.0.1",
    "title": "Generalized additive model",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"F({s0['ref_df']:.2f}, {rdf:.2f}) = {s0['f']:.2f}, {cs.fmt_p(s0['p'])}",
    "statistics": [{"key": "dev_expl", "label": "Deviance explained", "value": dev_expl, "format": "percent"},
                   {"key": "r2_adj", "label": "Adjusted R²", "value": float(r2_adj)}, {"key": "edf_total", "label": "Total edf", "value": edf_total},
                   {"key": "scale", "label": "Scale (σ²)", "value": fit.scale}],
    "tables": [
        {"key": "smooths", "title": "Smooth terms", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "edf", "label": "edf", "type": "number"}, {"key": "ref_df", "label": "Ref. df", "type": "number"},
            {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}, {"key": "sp", "label": "Smoothing parameter", "type": "number"}],
         "rows": s_rows, "note": "Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom."},
        {"key": "parametric", "title": "Parametric terms", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
            {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
            {"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}], "rows": coefs},
    ],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [("Unpenalized cubic regression splines (fixed df)" if fixed else "Penalized cubic regression splines, smoothness by REML") + f" with k = {k}; twin of mgcv::gam."],
    "charts": charts,
    "values": values,
})

This is head acceleration after a simulated motorcycle crash, against time, in 133 readings. The curve explains 80% of the deviance, with adjusted R2R^2 = 0.782.

The approximate test gives FF = 33.9, p < .001. That only says the curve isn't flat. Its plot is the result: a smooth has no single coefficient to quote.

04

Is k big enough?

Predict

Basis dimension (k) sets a ceiling of k−1k - 1 df, and REML decides how much of it to use. This fit set k=20k = 20.

Predict first

The crash curve dips and rebounds sharply. Do you expect it to use almost all of its ceiling?

Near the ceiling, so raise kWell below it, so k is fineCan't tell from the card
Reveal

It uses 62% of the ceiling, so there's room to spare. A share close to 100% means k may be limiting the curve: raise it and refit. Raising k further here wouldn't add wiggle for its own sake, because the penalty still applies.

05

Several curves at once

Read
Generalized additive modelRecorded · Python and R agreeRecorded 2026-11-17 · 55 values compared
R

F(3.70, 104.61) = 12.05, p < .001

Deviance explained
70.9%
Adjusted R²
0.6806
Total edf
11.391
Scale (σ²)
347.52

Plots

Partial effect of TempWhat is a feature's effect on predictions when features are correlated?
View data
s(Temp)+2 SE−2 SETemp
−25.815−6.571−45.06057
−25.439−7.039−43.83957.404
−25.062−7.477−42.64857.808
−24.687−7.882−41.49258.212
−24.312−8.249−40.37658.616
−23.940−8.575−39.30459.020
−23.568−8.861−38.27659.424
−23.199−9.104−37.29559.828
−22.833−9.307−36.36060.232
−22.470−9.471−35.46860.636
−22.110−9.601−34.61861.040
−21.753−9.702−33.80461.444
−21.401−9.778−33.02361.848
−21.053−9.835−32.27062.253
−20.710−9.877−31.54262.657
−20.372−9.904−30.84063.061
−20.041−9.915−30.16763.465
−19.717−9.909−29.52563.869
−19.401−9.886−28.91664.273
−19.093−9.847−28.34064.677
−18.795−9.796−27.79565.081
−18.508−9.736−27.27965.485
−18.231−9.676−26.78665.889
−17.966−9.622−26.31066.293
−17.714−9.580−25.84766.697
−17.472−9.551−25.39467.101
−17.239−9.527−24.95167.505
−17.011−9.501−24.52067.909
−16.785−9.467−24.10368.313
−16.558−9.419−23.69868.717
−16.328−9.354−23.30369.121
−16.091−9.270−22.91269.525
−15.845−9.171−22.51969.929
−15.586−9.060−22.11370.333
−15.312−8.940−21.68470.737
−15.020−8.813−21.22671.141
−14.706−8.672−20.74071.545
−14.368−8.507−20.22971.949
−14.003−8.308−19.69872.354
−13.608−8.067−19.15072.758
−13.180−7.777−18.58473.162
−12.716−7.435−17.99773.566
−12.213−7.042−17.38573.970
−11.669−6.600−16.73774.374
−11.079−6.115−16.04374.778
−10.442−5.591−15.29475.182
−9.759−5.026−14.49375.586
−9.033−4.415−13.65175.990
−8.266−3.752−12.78076.394
−7.462−3.031−11.89276.798
−6.623−2.250−10.99677.202
−5.753−1.410−10.09677.606
−4.855−0.5173−9.19278.010
−3.9310.4186−8.28078.414
−2.9841.386−7.35478.818
−2.0192.372−6.40979.222
−1.0353.374−5.44479.626
−0.03544.397−4.46780.030
0.98075.449−3.48880.434
2.0136.539−2.51480.838

First 60 of 100 rows.

Partial effect of WindWhat is a feature's effect on predictions when features are correlated?
View data
s(Wind)+2 SE−2 SEWind
51.72371.36032.0862.300
49.90268.37131.4342.486
48.08065.42930.7302.672
46.25362.54129.9652.858
44.42159.71329.1283.043
42.58056.94628.2143.229
40.72954.23727.2223.415
38.86751.58026.1543.601
36.99048.96725.0143.787
35.09846.38623.8103.973
33.18843.82922.5474.159
31.26741.30321.2304.344
29.34038.82119.8594.530
27.41636.39418.4394.716
25.50334.02616.9814.902
23.60931.71615.5025.088
21.74029.45314.0275.274
19.90427.23012.5785.460
18.10625.05011.1615.645
16.35022.9259.7755.831
14.64320.8708.4156.017
12.98818.8987.0776.203
11.39017.0215.7596.389
9.85515.2444.4666.575
8.38813.5683.2076.761
6.99211.9842.0016.946
5.67410.4840.86477.132
4.4359.063−0.19277.318
3.2727.729−1.1847.504
2.1836.492−2.1277.690
1.1635.363−3.0377.876
0.21014.344−3.9248.062
−0.67883.431−4.7898.247
−1.5072.609−5.6238.433
−2.2781.854−6.4108.619
−2.9941.143−7.1318.805
−3.6580.4539−7.7718.991
−4.274−0.2122−8.3379.177
−4.844−0.8382−8.8509.363
−5.370−1.406−9.3359.548
−5.855−1.901−9.8109.734
−6.302−2.318−10.2869.920
−6.712−2.662−10.76310.106
−7.089−2.946−11.23210.292
−7.435−3.191−11.68010.478
−7.753−3.413−12.09310.664
−8.045−3.622−12.46810.849
−8.313−3.806−12.81911.035
−8.560−3.953−13.16611.221
−8.788−4.054−13.52111.407
−8.999−4.109−13.88911.593
−9.196−4.125−14.26711.779
−9.382−4.118−14.64511.965
−9.557−4.107−15.00712.151
−9.726−4.112−15.34012.336
−9.889−4.149−15.63012.522
−10.048−4.212−15.88312.708
−10.200−4.286−16.11412.894
−10.344−4.352−16.33713.080
−10.480−4.396−16.56313.266

First 60 of 100 rows.

Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
FittedResidual
32.4168.584
32.2283.772
23.903−11.903
15.8682.132
16.79711.203
24.978−1.978
11.2697.731
19.072−11.072
41.193−34.193
23.867−7.867
23.528−12.528
20.953−6.953
10.7167.284
17.525−3.525
18.46115.539
12.294−6.294
20.1789.822
18.995−7.995
16.306−15.306
22.392−11.392
18.119−14.119
14.47217.528
19.0863.914
37.3837.617
61.06753.933
40.933−3.933
36.222−7.222
52.31618.684
46.975−7.975
42.509−19.509
18.8012.199
18.96818.032
13.7256.275
14.676−2.676
20.808−7.808
89.17445.826
53.865−4.865
42.886−10.886
81.204−17.204
44.467−4.467
89.817−12.817
87.2189.782
92.6574.343
72.65912.341
20.444−10.444
36.154−9.154
33.688−26.688
54.568−6.568
42.762−7.762
67.529−6.529
87.233−8.233
49.31813.682
39.964−23.964
58.82121.179
58.73249.268
47.667−27.667
51.6060.3938
70.24511.755
64.936−14.936
56.5017.499

First 60 of 116 rows.

Assumptions

  • Basis dimension large enough — The most complex smooth uses 38% of its k − 1 = 9 df.
  • Normal residuals — Shapiro–Wilk W = 0.930, p < .001.

Smooth terms

TermedfRef. dfFpSmoothing parameter
s(Temp)2.9453.70012.049< .001300.13
s(Wind)3.4464.2779.717< .001161.99

Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom.

Parametric terms

TermBSEtp95% CI low95% CI high
(Intercept)46.0334.9409.318< .00136.23855.829
month_f: Jun−9.1068.373−1.088.279−25.7097.497
month_f: Jul−1.2297.303−0.1683.867−15.71013.251
month_f: Aug−1.0167.137−0.1424.887−15.16813.135
month_f: Sep−10.7766.009−1.793.076−22.6911.138
  • 37 of 153 rows were left out because a value was missing.
  • Penalized cubic regression splines, smoothness by REML with k = 10 (mgcv::gam).
The exact R script · R R version 4.5.1 (2025-06-13)
# Generalized additive model (smooth terms)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.gam 1.0.1 · spec f1b04ff567790fc0
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(mgcv))

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/airquality.parquet", col_select = c("Ozone", "Temp", "Wind", "month_f")))
n_input <- nrow(df)
df[["month_f"]] <- factor(df[["month_f"]], levels = c("May", "Jun", "Jul", "Aug", "Sep"))  # stored level order
df <- df[stats::complete.cases(df[c("Ozone", "Temp", "Wind", "month_f")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("Ozone", "Temp", "Wind", "month_f"))  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome <- "Ozone"
smooth_cols <- c("Temp", "Wind")
predictors <- c("month_f")
k <- as.integer(10)  # basis dimension of each smooth
fixed <- FALSE  # TRUE: unpenalized regression splines (fx = TRUE)
conf <- 0.95
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than coefficients: the linear terms plus k - 1 per smooth (one is absorbed by its centering).
cs_check_rows(nrow(df), length(cs_design_labels(df, predictors)) + length(smooth_cols) * (k - 1) + 1, "A generalized additive model")
for (col in c(outcome, smooth_cols, predictors)) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation
for (x in smooth_cols) {
  nu <- length(unique(df[[x]]))
  if (nu < k) cs_error("CS_E_INVALID_OPTION", option = "The basis dimension k", allowed = sprintf("at most %d, the number of distinct values of %s", nu, x), value = k)
}
# mgcv's formula parser drops backticks, so the model runs on safe column names (labels keep the originals).
dat <- data.frame(.cs_y = df[[outcome]])
p_names <- if (length(predictors)) paste0(".cs_p", seq_along(predictors)) else character(0)
s_names <- paste0(".cs_s", seq_along(smooth_cols))
for (i in seq_along(predictors)) dat[[p_names[i]]] <- df[[predictors[i]]]
for (i in seq_along(smooth_cols)) dat[[s_names[i]]] <- df[[smooth_cols[i]]]
rhs <- c(if (length(predictors)) p_names else "1",
         sprintf("s(%s, bs = \"cr\", k = %d, fx = %s)", s_names, k, if (fixed) "TRUE" else "FALSE"))
fml <- stats::as.formula(paste(".cs_y ~", paste(rhs, collapse = " + ")))
# REML with tight convergence so the smoothing parameters agree to ~1e-9.
fit <- gam(fml, data = dat, method = "REML", control = gam.control(epsilon = 1e-12, newton = list(conv.tol = 1e-12)))
X <- predict(fit, type = "lpmatrix")
y <- df[[outcome]]
n <- length(y)
edf_total <- sum(fit$edf)
rdf <- n - edf_total
Vp <- fit$Vp
beta <- unname(coef(fit))
values <- list()

# %% Parametric terms (t tests on the residual df)
terms_p <- cs_design_labels(df, predictors)
if (length(terms_p) != fit$nsdf) cs_error("CS_E_COLLINEAR")
q <- qt(1 - (1 - conf) / 2, rdf)
coefs <- list()
for (j in seq_len(fit$nsdf)) {
  b <- beta[j]; se <- sqrt(Vp[j, j]); t <- b / se; p <- 2 * pt(abs(t), rdf, lower.tail = FALSE)
  term <- terms_p[j]
  coefs[[j]] <- list(term = term, estimate = b, se = se, t = t, p = p, ci_low = b - q * se, ci_high = b + q * se)
  values[[sprintf("coef[%s]", term)]] <- b; values[[sprintf("se[%s]", term)]] <- se; values[[sprintf("t[%s]", term)]] <- t
  values[[sprintf("p[%s]", term)]] <- p; values[[sprintf("ci_low[%s]", term)]] <- b - q * se; values[[sprintf("ci_high[%s]", term)]] <- b + q * se
}

# %% Smooth terms (summary.gam's testStat, on the full model matrix)
s_rows <- list()
for (i in seq_along(fit$smooth)) {
  sm <- fit$smooth[[i]]
  idx <- sm$first.para:sm$last.para
  label <- sprintf("s(%s)", smooth_cols[i])
  edf_i <- sum(fit$edf[idx])
  edf1_i <- sum(fit$edf1[idx])
  if (abs(edf1_i - round(edf1_i)) < 1e-9) edf1_i <- round(edf1_i)  # whole-number edf (fixed smooths): integer-rank branch in both engines
  res <- mgcv:::testStat(beta[idx], X[, idx, drop = FALSE], Vp[idx, idx, drop = FALSE], min(length(idx), edf1_i), type = 0, res.df = rdf)
  F <- res$stat / res$rank
  sp <- if (fixed) NULL else unname(fit$sp[i])
  s_rows[[i]] <- list(term = label, edf = edf_i, ref_df = res$rank, f = F, p = res$pval, sp = sp)
  values[[sprintf("edf[%s]", label)]] <- edf_i; values[[sprintf("ref_df[%s]", label)]] <- res$rank
  values[[sprintf("s_f[%s]", label)]] <- F; values[[sprintf("s_p[%s]", label)]] <- res$pval
  if (!fixed) values[[sprintf("sp[%s]", label)]] <- sp
}
fitted_v <- unname(fitted(fit))
resid <- y - fitted_v
r2_adj <- 1 - var(resid) * (n - 1) / (var(y - mean(y)) * rdf)
dev_expl <- 1 - sum(resid^2) / sum((y - mean(y))^2)
max_share <- max(vapply(s_rows, function(r) r$edf / (k - 1), 0))
values <- c(values, list(n = n, k_param = fit$nsdf, edf_total = edf_total, residual_df = rdf, r2_adj = r2_adj, dev_expl = dev_expl,
                         scale = fit$sig2, focal_f = s_rows[[1]]$f, focal_df = s_rows[[1]]$ref_df, focal_p = s_rows[[1]]$p,
                         max_edf_share = max_share, fixed_df = fixed, missing_share = if (n_input > 0) n_dropped / n_input else 0))
if (!fixed) values$reml <- unname(fit$gcv.ubre)

# %% Assumptions
assumptions <- list(list(key = "basis", label = "Basis dimension large enough", status = if (!fixed && max_share > 0.9) "warn" else "pass", statistic = max_share,
                         detail = if (!fixed && max_share > 0.9) sprintf("A smooth uses %.0f%% of its k − 1 = %d df: increase k and refit.", 100 * max_share, k - 1L)
                                  else sprintf("The most complex smooth uses %.0f%% of its k − 1 = %d df.", 100 * max_share, k - 1L)))
if (n >= 3 && n <= 5000) {
  sw <- shapiro.test(resid)
  values$sw_p_resid <- sw$p.value
  assumptions[[2]] <- list(key = "normality", label = "Normal residuals", status = if (sw$p.value >= 0.05) "pass" else if (n < 300) "warn" else "info",
                           statistic = unname(sw$statistic), p = sw$p.value, detail = sprintf("Shapiro–Wilk W = %.3f, %s.", sw$statistic, cs_fmt_p(sw$p.value)))
}

# %% Result
charts <- list()
for (i in seq_along(fit$smooth)) {
  sm <- fit$smooth[[i]]
  idx <- sm$first.para:sm$last.para
  x <- smooth_cols[i]
  grid <- seq(min(df[[x]]), max(df[[x]]), length.out = 100)
  Xg <- PredictMat(sm, setNames(data.frame(grid), s_names[i]))
  f <- as.vector(Xg %*% beta[idx])
  sef <- sqrt(pmax(rowSums((Xg %*% Vp[idx, idx]) * Xg), 0))
  charts[[i]] <- cs_chart(paste0("smooth_", x), "ale-plot", sprintf("Partial effect of %s", x), list(
    x = cs_col(x, grid), effect = cs_col(sprintf("s(%s)", x), f), low = cs_col("−2 SE", f - 2 * sef), high = cs_col("+2 SE", f + 2 * sef)))
}
charts[[length(charts) + 1]] <- cs_chart("residuals", "residual-panel", "Residual diagnostics", list(fitted = cs_col("Fitted", fitted_v), residual = cs_col("Residual", resid)))
pct <- sprintf("%.0f%%", conf * 100)
s0 <- s_rows[[1]]
summary <- paste0(sprintf("Additive model of %s (n = %d): deviance explained %.1f%%, adjusted R² = %.3f. ", outcome, n, 100 * dev_expl, r2_adj),
                  paste(vapply(s_rows, function(r) sprintf("%s: edf = %.2f, F = %.2f, %s", r$term, r$edf, r$f, cs_fmt_p(r$p)), ""), collapse = "; "), ".")
cs_publish(list(
  method = "regression.gam",
  methodVersion = "1.0.1",
  title = "Generalized additive model",
  engine = cs_engine_info("mgcv", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("F(%.2f, %.2f) = %.2f, %s", s0$ref_df, rdf, s0$f, cs_fmt_p(s0$p)),
  statistics = list(list(key = "dev_expl", label = "Deviance explained", value = dev_expl, format = "percent"),
                    list(key = "r2_adj", label = "Adjusted R²", value = r2_adj), list(key = "edf_total", label = "Total edf", value = edf_total),
                    list(key = "scale", label = "Scale (σ²)", value = fit$sig2)),
  tables = list(
    list(key = "smooths", title = "Smooth terms", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "edf", label = "edf", type = "number"), list(key = "ref_df", label = "Ref. df", type = "number"),
      list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue"), list(key = "sp", label = "Smoothing parameter", type = "number")),
      rows = s_rows, note = "Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom."),
    list(key = "parametric", title = "Parametric terms", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"), list(key = "se", label = "SE", type = "number"),
      list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
      list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")), rows = coefs)
  ),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("%s with k = %d (mgcv::gam).", if (fixed) "Unpenalized cubic regression splines (fixed df)" else "Penalized cubic regression splines, smoothness by REML", k)),
  charts = charts,
  values = values
))
Python

F(3.70, 104.61) = 12.05, p < .001

Deviance explained
70.9%
Adjusted R²
0.6806
Total edf
11.391
Scale (σ²)
347.52

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Basis dimension large enough — The most complex smooth uses 38% of its k − 1 = 9 df.
  • Normal residuals — Shapiro–Wilk W = 0.930, p < .001.

Smooth terms

TermedfRef. dfFpSmoothing parameter
s(Temp)2.9453.70012.049< .001300.13
s(Wind)3.4464.2779.717< .001161.99

Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom.

Parametric terms

TermBSEtp95% CI low95% CI high
(Intercept)46.0334.9409.318< .00136.23855.829
month_f: Jun−9.1068.373−1.088.279−25.7097.497
month_f: Jul−1.2297.303−0.1683.867−15.71013.251
month_f: Aug−1.0167.137−0.1424.887−15.16813.135
month_f: Sep−10.7766.009−1.793.076−22.6911.138
  • 37 of 153 rows were left out because a value was missing.
  • Penalized cubic regression splines, smoothness by REML with k = 10; twin of mgcv::gam.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generalized additive model (smooth terms)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.gam 1.0.1 · spec f1b04ff567790fc0
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import gam as csgam  # twin of mgcv::gam(bs = "cr", method = "REML") — pygam uses other bases and criteria
from codesplash.stats import regression as csreg

# %% Data
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=["Ozone", "Temp", "Wind", "month_f"])
n_input = len(df)
df["month_f"] = pd.Categorical(df["month_f"], categories=["May", "Jun", "Jul", "Aug", "Sep"])  # stored level order
df = df.dropna(subset=["Ozone", "Temp", "Wind", "month_f"])  # listwise deletion over the analysis columns
df["month_f"] = df["month_f"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Ozone", "Temp", "Wind", "month_f"])  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome = "Ozone"
smooth_cols = ["Temp", "Wind"]
predictors = ["month_f"]
k = int(10)  # basis dimension of each smooth
fixed = False  # True: unpenalized regression splines (mgcv fx = TRUE)
conf = 0.95
y = df[outcome].to_numpy(dtype=float)
Xp = csreg.design_matrix(df, predictors)  # intercept + linear terms
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than coefficients: the linear terms plus k − 1 per smooth (one is absorbed by its centering).
cs.check_rows(len(df), Xp.shape[1] + len(smooth_cols) * (k - 1) + 1, "A generalized additive model")
for col in [outcome] + smooth_cols + predictors:
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation
for x in smooth_cols:
    nu = df[x].nunique()
    if nu < k:
        cs.cs_error("CS_E_INVALID_OPTION", option="The basis dimension k", allowed=f"at most {nu}, the number of distinct values of {x}", value=k)
smooths = [csgam.cr_smooth(df[x].to_numpy(dtype=float), k, f"s({x})", fixed) for x in smooth_cols]
fit = csgam.fit_gam(y, Xp.to_numpy(), smooths)
X = np.column_stack([Xp.to_numpy()] + [s.X for s in smooths])
n = len(y)
edf_total = float(fit.edf.sum())
rdf = n - edf_total
values = {}

# %% Parametric terms (t tests on the residual df)
coefs = []
q = stats.t.ppf(1 - (1 - conf) / 2, rdf)
for j, term in enumerate(Xp.columns):
    b = float(fit.beta[j])
    se = float(np.sqrt(fit.Vp[j, j]))
    t = b / se
    p = float(2 * stats.t.sf(abs(t), rdf))
    coefs.append({"term": term, "estimate": b, "se": se, "t": t, "p": p, "ci_low": b - q * se, "ci_high": b + q * se})
    values.update({f"coef[{term}]": b, f"se[{term}]": se, f"t[{term}]": t, f"p[{term}]": p, f"ci_low[{term}]": b - q * se, f"ci_high[{term}]": b + q * se})

# %% Smooth terms (mgcv's testStat on the full model matrix)
s_rows = []
for i, (s, (a, b_)) in enumerate(zip(smooths, fit.blocks)):
    edf_i = float(fit.edf[a:b_].sum())
    edf1_i = float(fit.edf1[a:b_].sum())
    if abs(edf1_i - round(edf1_i)) < 1e-9:
        edf1_i = float(round(edf1_i))  # whole-number edf (fixed smooths): integer-rank branch in both engines
    stat, pv, rank = csgam.test_stat(fit.beta[a:b_], X[:, a:b_], fit.Vp[a:b_, a:b_], min(b_ - a, edf1_i), rdf)
    F = stat / rank
    s_rows.append({"term": s.label, "edf": edf_i, "ref_df": rank, "f": F, "p": pv, "sp": None if s.fixed else float(fit.sp[i])})
    values.update({f"edf[{s.label}]": edf_i, f"ref_df[{s.label}]": rank, f"s_f[{s.label}]": F, f"s_p[{s.label}]": pv})
    if not s.fixed:
        values[f"sp[{s.label}]"] = float(fit.sp[i])
resid = y - fit.fitted
r2_adj = 1 - np.var(resid, ddof=1) * (n - 1) / (np.var(y - y.mean(), ddof=1) * rdf)
dev_expl = 1 - float(resid @ resid) / float(np.sum((y - y.mean()) ** 2))
max_share = max(r["edf"] / (k - 1) for r in s_rows)
values.update({"n": n, "k_param": Xp.shape[1], "edf_total": edf_total, "residual_df": rdf, "r2_adj": float(r2_adj), "dev_expl": dev_expl,
               "scale": fit.scale, "focal_f": s_rows[0]["f"], "focal_df": s_rows[0]["ref_df"], "focal_p": s_rows[0]["p"],
               "max_edf_share": max_share, "fixed_df": fixed, "missing_share": n_dropped / n_input if n_input else 0.0})
if not fixed:
    values["reml"] = fit.reml

# %% Assumptions
assumptions = [{"key": "basis", "label": "Basis dimension large enough", "status": "warn" if (not fixed and max_share > 0.9) else "pass", "statistic": max_share,
                "detail": (f"A smooth uses {max_share:.0%} of its k − 1 = {k - 1} df: increase k and refit." if (not fixed and max_share > 0.9)
                           else f"The most complex smooth uses {max_share:.0%} of its k − 1 = {k - 1} df.")}]
if 3 <= n <= 5000:
    sw = stats.shapiro(resid)
    values["sw_p_resid"] = float(sw.pvalue)
    assumptions.append({"key": "normality", "label": "Normal residuals", "status": "pass" if sw.pvalue >= 0.05 else ("warn" if n < 300 else "info"),
                        "statistic": float(sw.statistic), "p": float(sw.pvalue), "detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}."})
if not fit.converged:
    warnings.append("A smoothing parameter ran to its limit (the smooth is either a straight line or as wiggly as k allows).")

# %% Result
charts = []
for s, (a, b_), xname in zip(smooths, fit.blocks, smooth_cols):
    grid = np.linspace(df[xname].min(), df[xname].max(), 100)
    Xg = csgam.cr_basis(grid, s.knots) @ s.Z
    f = Xg @ fit.beta[a:b_]
    sef = np.sqrt(np.maximum(np.sum((Xg @ fit.Vp[a:b_, a:b_]) * Xg, axis=1), 0.0))
    charts.append(cs.chart(f"smooth_{xname}", "ale-plot", f"Partial effect of {xname}", {
        "x": cs.col(xname, grid), "effect": cs.col(s.label, f), "low": cs.col("−2 SE", f - 2 * sef), "high": cs.col("+2 SE", f + 2 * sef)}))
charts.append(cs.chart("residuals", "residual-panel", "Residual diagnostics", {"fitted": cs.col("Fitted", fit.fitted), "residual": cs.col("Residual", resid)}))
pct = f"{conf:.0%}"
s0 = s_rows[0]
summary = (f"Additive model of {outcome} (n = {n}): deviance explained {dev_expl:.1%}, adjusted R² = {r2_adj:.3f}. "
           + "; ".join(f"{r['term']}: edf = {r['edf']:.2f}, F = {r['f']:.2f}, {cs.fmt_p(r['p'])}" for r in s_rows) + ".")
cs.publish({
    "method": "regression.gam",
    "methodVersion": "1.0.1",
    "title": "Generalized additive model",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"F({s0['ref_df']:.2f}, {rdf:.2f}) = {s0['f']:.2f}, {cs.fmt_p(s0['p'])}",
    "statistics": [{"key": "dev_expl", "label": "Deviance explained", "value": dev_expl, "format": "percent"},
                   {"key": "r2_adj", "label": "Adjusted R²", "value": float(r2_adj)}, {"key": "edf_total", "label": "Total edf", "value": edf_total},
                   {"key": "scale", "label": "Scale (σ²)", "value": fit.scale}],
    "tables": [
        {"key": "smooths", "title": "Smooth terms", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "edf", "label": "edf", "type": "number"}, {"key": "ref_df", "label": "Ref. df", "type": "number"},
            {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}, {"key": "sp", "label": "Smoothing parameter", "type": "number"}],
         "rows": s_rows, "note": "Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom."},
        {"key": "parametric", "title": "Parametric terms", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
            {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
            {"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}], "rows": coefs},
    ],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [("Unpenalized cubic regression splines (fixed df)" if fixed else "Penalized cubic regression splines, smoothness by REML") + f" with k = {k}; twin of mgcv::gam."],
    "charts": charts,
    "values": values,
})

Ozone gets one smooth for temperature, one for wind, and a linear term for month. Together they explain 71% of the deviance, using 11.4 effective df in total.

Each curve is drawn with the other terms held fixed. "Additive" also means no interaction: this model can't let the temperature curve change with wind.

Notice that 24% of the rows were dropped for missing values. A flexible curve doesn't repair that.

06

Check the residuals anyway

Reflect

A flexible mean doesn't fix a wrong error model. For the ozone fit, the residuals' Shapiro–Wilk test gives p < .001. This GAM assumes normal errors with constant spread.

Open the residual panel on the card. Does the spread grow with the fitted value? What would you try next for an outcome that's bounded at zero and skewed, as ozone is?

07

Penalty or fixed df?

Read

Fixed df (no penalty) turns off the brake and spends exactly k−1k - 1 df per smooth, so it's an ordinary regression spline. With k=6k = 6, temperature gets 5 df and FF = 24.2.

Fixed df suits a curve whose complexity you set in advance, as in a pre-registered analysis. The penalty suits exploring a shape. Since smoothness is estimated from the same data, the penalized p-values are approximate. Report the curve and its band, not only the p-value.

08

Check your understanding

Checkpoint

Check yourself

A smooth reports edf = 1.02. What should you conclude?

Show the answer

Answer: a

An edf near 1 is a straight line. A k problem shows up the other way, with edf close to k − 1.

Check yourself

With k = 10, a smooth reports edf = 8.9. What do you do?

Show the answer

Answer: b

k is a limit, not a target. If edf sits near k − 1, the basis may be constraining the curve. If it barely changes after you raise k, the first fit was fine.

Check yourself

What's the best way to report a smooth term?

Show the answer

Answer: b

A smooth has no single slope. The shape, and how sure you are of it, is the finding.

09

Fit yours

In the app

Pick an Outcome, put curved predictors in Smooth terms and the rest in Linear terms. Start with the default Basis dimension (k), then check how close each smooth gets to its ceiling.

Python
import pandas as pd
from statsmodels.gam.api import BSplines, GLMGam

df = pd.read_csv("s1_mcycle.csv")
basis = BSplines(df[["times"]], df=[20], degree=[3])

# Try several penalties and keep the one with the lowest AIC
fits = [GLMGam.from_formula("accel ~ 1", data=df, smoother=basis, alpha=[a]).fit()
        for a in [0.1, 1, 10, 100, 1000, 10000]]
fit = min(fits, key=lambda f: f.aic)
print(fit.summary())
print("deviance explained:", 1 - fit.deviance / fit.null_deviance)
R
library(mgcv)

df <- read.csv("s1_mcycle.csv")
fit <- gam(accel ~ s(times, k = 20, bs = "cr"), data = df, method = "REML")
summary(fit)
gam.check(fit)
plot(fit, shade = TRUE)

The statsmodels script uses a different basis and picks its penalty from a short list by AIC, so its numbers differ from mgcv's. The CodeSplash card matches mgcv in both engines.

10

Recap

Recap
  • A GAM fits a smooth per predictor, and a penalty controls how much each bends.
  • Effective df says how complex the curve became: 1 is a straight line.
  • k is a ceiling, so raise it if edf gets close to k−1k - 1.
  • Read the plot. A smooth has no single coefficient.

Concepts in this lesson