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.
What runs in CodeSplash
- Generalized additive model (smooth terms) Verified in Python and R
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
Let the penalty decide
ReadWith 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:
The second term charges for curvature. A large pulls the curve toward a straight line, and a small one lets it wiggle. REML estimates from the data, so you don't tune it by hand.
The model is additive: .
Make a prediction
PredictPredict 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.
Read the card
In the appF(13.97, 120.22) = 33.93, p < .001
- Deviance explained
- 80.1%
- Adjusted R²
- 0.7820
- Total edf
- 12.785
- Scale (σ²)
- 509.01
Plots
View data
| s(times) | +2 SE | −2 SE | times |
|---|---|---|---|
| 24.473 | 49.111 | −0.1656 | 2.400 |
| 24.199 | 44.382 | 4.016 | 2.958 |
| 23.935 | 41.348 | 6.522 | 3.515 |
| 23.690 | 40.332 | 7.047 | 4.073 |
| 23.473 | 40.744 | 6.202 | 4.630 |
| 23.295 | 41.485 | 5.104 | 5.188 |
| 23.164 | 41.655 | 4.673 | 5.745 |
| 23.090 | 40.832 | 5.348 | 6.303 |
| 23.090 | 39.498 | 6.682 | 6.861 |
| 23.186 | 38.537 | 7.835 | 7.418 |
| 23.398 | 38.330 | 8.466 | 7.976 |
| 23.750 | 38.479 | 9.021 | 8.533 |
| 24.254 | 38.407 | 10.100 | 9.091 |
| 24.862 | 38.586 | 11.138 | 9.648 |
| 25.492 | 39.643 | 11.341 | 10.206 |
| 26.064 | 41.094 | 11.034 | 10.764 |
| 26.470 | 41.761 | 11.178 | 11.321 |
| 26.424 | 41.193 | 11.656 | 11.879 |
| 25.561 | 39.509 | 11.614 | 12.436 |
| 23.515 | 36.723 | 10.308 | 12.994 |
| 19.919 | 32.413 | 7.426 | 13.552 |
| 14.408 | 25.757 | 3.059 | 14.109 |
| 6.664 | 16.198 | −2.869 | 14.667 |
| −3.152 | 5.086 | −11.391 | 15.224 |
| −14.621 | −6.587 | −22.655 | 15.782 |
| −27.247 | −19.263 | −35.230 | 16.339 |
| −40.009 | −31.240 | −48.779 | 16.897 |
| −51.712 | −42.106 | −61.319 | 17.455 |
| −61.902 | −51.938 | −71.866 | 18.012 |
| −70.632 | −59.957 | −81.306 | 18.570 |
| −77.967 | −66.250 | −89.684 | 19.127 |
| −83.967 | −71.691 | −96.243 | 19.685 |
| −88.535 | −76.080 | −100.99 | 20.242 |
| −91.376 | −78.276 | −104.48 | 20.800 |
| −92.184 | −78.260 | −106.11 | 21.358 |
| −90.687 | −76.718 | −104.66 | 21.915 |
| −86.859 | −73.394 | −100.32 | 22.473 |
| −80.779 | −67.660 | −93.897 | 23.030 |
| −72.529 | −59.594 | −85.465 | 23.588 |
| −62.192 | −49.926 | −74.459 | 24.145 |
| −50.071 | −38.812 | −61.329 | 24.703 |
| −36.903 | −25.954 | −47.851 | 25.261 |
| −23.471 | −12.684 | −34.257 | 25.818 |
| −10.294 | 0.2587 | −20.846 | 26.376 |
| 2.444 | 13.484 | −8.595 | 26.933 |
| 14.577 | 26.103 | 3.050 | 27.491 |
| 25.878 | 37.765 | 13.991 | 28.048 |
| 36.077 | 48.968 | 23.186 | 28.606 |
| 44.899 | 59.045 | 30.753 | 29.164 |
| 52.113 | 66.736 | 37.489 | 29.721 |
| 57.677 | 72.109 | 43.246 | 30.279 |
| 61.608 | 75.844 | 47.372 | 30.836 |
| 63.920 | 78.362 | 49.478 | 31.394 |
| 64.628 | 79.478 | 49.777 | 31.952 |
| 63.746 | 78.571 | 48.922 | 32.509 |
| 61.368 | 75.320 | 47.417 | 33.067 |
| 57.888 | 70.741 | 45.034 | 33.624 |
| 53.772 | 66.092 | 41.453 | 34.182 |
| 49.492 | 61.954 | 37.029 | 34.739 |
| 45.502 | 58.154 | 32.850 | 35.297 |
First 60 of 100 rows.
View data
| Fitted | Residual |
|---|---|
| −1.073 | 1.073 |
| −1.172 | −0.1282 |
| −1.463 | −1.237 |
| −1.650 | 1.650 |
| −1.825 | −0.8745 |
| −2.447 | −0.2528 |
| −2.466 | −0.2337 |
| −2.460 | 1.160 |
| −2.228 | −0.4716 |
| −2.024 | −0.6759 |
| −1.573 | 0.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.159 | 0.4595 |
| −6.024 | 3.324 |
| −7.824 | 7.824 |
| −17.838 | 4.538 |
| −17.838 | 12.438 |
| −17.838 | 12.438 |
| −17.838 | 8.538 |
| −17.838 | 1.838 |
| −17.838 | −4.962 |
| −21.056 | 18.356 |
| −32.155 | 9.355 |
| −32.155 | 0.0552 |
| −32.155 | −21.345 |
| −32.155 | −22.745 |
| −36.272 | −3.928 |
| −36.272 | 14.772 |
| −40.564 | 19.064 |
| −40.564 | −10.236 |
| −45.011 | 2.111 |
| −45.011 | 18.211 |
| −49.574 | 28.074 |
| −49.574 | −1.226 |
| −49.574 | −12.126 |
| −54.196 | 48.796 |
| −54.196 | −26.204 |
| −58.817 | −0.1830 |
| −63.381 | −7.619 |
| −63.381 | −27.719 |
| −63.381 | −14.319 |
| −80.061 | 42.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.611 | 45.811 |
| −104.37 | −18.730 |
| −106.61 | 21.012 |
| −106.61 | 34.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
| Term | edf | Ref. df | F | p | Smoothing parameter |
|---|---|---|---|---|---|
| s(times) | 11.785 | 13.968 | 33.934 | < .001 | 25.320 |
Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom.
Parametric terms
| Term | B | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | −25.546 | 1.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
))
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
| Term | edf | Ref. df | F | p | Smoothing parameter |
|---|---|---|---|---|---|
| s(times) | 11.785 | 13.968 | 33.934 | < .001 | 25.320 |
Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom.
Parametric terms
| Term | B | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | −25.546 | 1.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 = 0.782.
The approximate test gives = 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.
Is k big enough?
PredictBasis dimension (k) sets a ceiling of df, and REML decides how much of it to use. This fit set .
Predict first
The crash curve dips and rebounds sharply. Do you expect it to use almost all of its ceiling?
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.
Several curves at once
ReadF(3.70, 104.61) = 12.05, p < .001
- Deviance explained
- 70.9%
- Adjusted R²
- 0.6806
- Total edf
- 11.391
- Scale (σ²)
- 347.52
Plots
View data
| s(Temp) | +2 SE | −2 SE | Temp |
|---|---|---|---|
| −25.815 | −6.571 | −45.060 | 57 |
| −25.439 | −7.039 | −43.839 | 57.404 |
| −25.062 | −7.477 | −42.648 | 57.808 |
| −24.687 | −7.882 | −41.492 | 58.212 |
| −24.312 | −8.249 | −40.376 | 58.616 |
| −23.940 | −8.575 | −39.304 | 59.020 |
| −23.568 | −8.861 | −38.276 | 59.424 |
| −23.199 | −9.104 | −37.295 | 59.828 |
| −22.833 | −9.307 | −36.360 | 60.232 |
| −22.470 | −9.471 | −35.468 | 60.636 |
| −22.110 | −9.601 | −34.618 | 61.040 |
| −21.753 | −9.702 | −33.804 | 61.444 |
| −21.401 | −9.778 | −33.023 | 61.848 |
| −21.053 | −9.835 | −32.270 | 62.253 |
| −20.710 | −9.877 | −31.542 | 62.657 |
| −20.372 | −9.904 | −30.840 | 63.061 |
| −20.041 | −9.915 | −30.167 | 63.465 |
| −19.717 | −9.909 | −29.525 | 63.869 |
| −19.401 | −9.886 | −28.916 | 64.273 |
| −19.093 | −9.847 | −28.340 | 64.677 |
| −18.795 | −9.796 | −27.795 | 65.081 |
| −18.508 | −9.736 | −27.279 | 65.485 |
| −18.231 | −9.676 | −26.786 | 65.889 |
| −17.966 | −9.622 | −26.310 | 66.293 |
| −17.714 | −9.580 | −25.847 | 66.697 |
| −17.472 | −9.551 | −25.394 | 67.101 |
| −17.239 | −9.527 | −24.951 | 67.505 |
| −17.011 | −9.501 | −24.520 | 67.909 |
| −16.785 | −9.467 | −24.103 | 68.313 |
| −16.558 | −9.419 | −23.698 | 68.717 |
| −16.328 | −9.354 | −23.303 | 69.121 |
| −16.091 | −9.270 | −22.912 | 69.525 |
| −15.845 | −9.171 | −22.519 | 69.929 |
| −15.586 | −9.060 | −22.113 | 70.333 |
| −15.312 | −8.940 | −21.684 | 70.737 |
| −15.020 | −8.813 | −21.226 | 71.141 |
| −14.706 | −8.672 | −20.740 | 71.545 |
| −14.368 | −8.507 | −20.229 | 71.949 |
| −14.003 | −8.308 | −19.698 | 72.354 |
| −13.608 | −8.067 | −19.150 | 72.758 |
| −13.180 | −7.777 | −18.584 | 73.162 |
| −12.716 | −7.435 | −17.997 | 73.566 |
| −12.213 | −7.042 | −17.385 | 73.970 |
| −11.669 | −6.600 | −16.737 | 74.374 |
| −11.079 | −6.115 | −16.043 | 74.778 |
| −10.442 | −5.591 | −15.294 | 75.182 |
| −9.759 | −5.026 | −14.493 | 75.586 |
| −9.033 | −4.415 | −13.651 | 75.990 |
| −8.266 | −3.752 | −12.780 | 76.394 |
| −7.462 | −3.031 | −11.892 | 76.798 |
| −6.623 | −2.250 | −10.996 | 77.202 |
| −5.753 | −1.410 | −10.096 | 77.606 |
| −4.855 | −0.5173 | −9.192 | 78.010 |
| −3.931 | 0.4186 | −8.280 | 78.414 |
| −2.984 | 1.386 | −7.354 | 78.818 |
| −2.019 | 2.372 | −6.409 | 79.222 |
| −1.035 | 3.374 | −5.444 | 79.626 |
| −0.0354 | 4.397 | −4.467 | 80.030 |
| 0.9807 | 5.449 | −3.488 | 80.434 |
| 2.013 | 6.539 | −2.514 | 80.838 |
First 60 of 100 rows.
View data
| s(Wind) | +2 SE | −2 SE | Wind |
|---|---|---|---|
| 51.723 | 71.360 | 32.086 | 2.300 |
| 49.902 | 68.371 | 31.434 | 2.486 |
| 48.080 | 65.429 | 30.730 | 2.672 |
| 46.253 | 62.541 | 29.965 | 2.858 |
| 44.421 | 59.713 | 29.128 | 3.043 |
| 42.580 | 56.946 | 28.214 | 3.229 |
| 40.729 | 54.237 | 27.222 | 3.415 |
| 38.867 | 51.580 | 26.154 | 3.601 |
| 36.990 | 48.967 | 25.014 | 3.787 |
| 35.098 | 46.386 | 23.810 | 3.973 |
| 33.188 | 43.829 | 22.547 | 4.159 |
| 31.267 | 41.303 | 21.230 | 4.344 |
| 29.340 | 38.821 | 19.859 | 4.530 |
| 27.416 | 36.394 | 18.439 | 4.716 |
| 25.503 | 34.026 | 16.981 | 4.902 |
| 23.609 | 31.716 | 15.502 | 5.088 |
| 21.740 | 29.453 | 14.027 | 5.274 |
| 19.904 | 27.230 | 12.578 | 5.460 |
| 18.106 | 25.050 | 11.161 | 5.645 |
| 16.350 | 22.925 | 9.775 | 5.831 |
| 14.643 | 20.870 | 8.415 | 6.017 |
| 12.988 | 18.898 | 7.077 | 6.203 |
| 11.390 | 17.021 | 5.759 | 6.389 |
| 9.855 | 15.244 | 4.466 | 6.575 |
| 8.388 | 13.568 | 3.207 | 6.761 |
| 6.992 | 11.984 | 2.001 | 6.946 |
| 5.674 | 10.484 | 0.8647 | 7.132 |
| 4.435 | 9.063 | −0.1927 | 7.318 |
| 3.272 | 7.729 | −1.184 | 7.504 |
| 2.183 | 6.492 | −2.127 | 7.690 |
| 1.163 | 5.363 | −3.037 | 7.876 |
| 0.2101 | 4.344 | −3.924 | 8.062 |
| −0.6788 | 3.431 | −4.789 | 8.247 |
| −1.507 | 2.609 | −5.623 | 8.433 |
| −2.278 | 1.854 | −6.410 | 8.619 |
| −2.994 | 1.143 | −7.131 | 8.805 |
| −3.658 | 0.4539 | −7.771 | 8.991 |
| −4.274 | −0.2122 | −8.337 | 9.177 |
| −4.844 | −0.8382 | −8.850 | 9.363 |
| −5.370 | −1.406 | −9.335 | 9.548 |
| −5.855 | −1.901 | −9.810 | 9.734 |
| −6.302 | −2.318 | −10.286 | 9.920 |
| −6.712 | −2.662 | −10.763 | 10.106 |
| −7.089 | −2.946 | −11.232 | 10.292 |
| −7.435 | −3.191 | −11.680 | 10.478 |
| −7.753 | −3.413 | −12.093 | 10.664 |
| −8.045 | −3.622 | −12.468 | 10.849 |
| −8.313 | −3.806 | −12.819 | 11.035 |
| −8.560 | −3.953 | −13.166 | 11.221 |
| −8.788 | −4.054 | −13.521 | 11.407 |
| −8.999 | −4.109 | −13.889 | 11.593 |
| −9.196 | −4.125 | −14.267 | 11.779 |
| −9.382 | −4.118 | −14.645 | 11.965 |
| −9.557 | −4.107 | −15.007 | 12.151 |
| −9.726 | −4.112 | −15.340 | 12.336 |
| −9.889 | −4.149 | −15.630 | 12.522 |
| −10.048 | −4.212 | −15.883 | 12.708 |
| −10.200 | −4.286 | −16.114 | 12.894 |
| −10.344 | −4.352 | −16.337 | 13.080 |
| −10.480 | −4.396 | −16.563 | 13.266 |
First 60 of 100 rows.
View data
| Fitted | Residual |
|---|---|
| 32.416 | 8.584 |
| 32.228 | 3.772 |
| 23.903 | −11.903 |
| 15.868 | 2.132 |
| 16.797 | 11.203 |
| 24.978 | −1.978 |
| 11.269 | 7.731 |
| 19.072 | −11.072 |
| 41.193 | −34.193 |
| 23.867 | −7.867 |
| 23.528 | −12.528 |
| 20.953 | −6.953 |
| 10.716 | 7.284 |
| 17.525 | −3.525 |
| 18.461 | 15.539 |
| 12.294 | −6.294 |
| 20.178 | 9.822 |
| 18.995 | −7.995 |
| 16.306 | −15.306 |
| 22.392 | −11.392 |
| 18.119 | −14.119 |
| 14.472 | 17.528 |
| 19.086 | 3.914 |
| 37.383 | 7.617 |
| 61.067 | 53.933 |
| 40.933 | −3.933 |
| 36.222 | −7.222 |
| 52.316 | 18.684 |
| 46.975 | −7.975 |
| 42.509 | −19.509 |
| 18.801 | 2.199 |
| 18.968 | 18.032 |
| 13.725 | 6.275 |
| 14.676 | −2.676 |
| 20.808 | −7.808 |
| 89.174 | 45.826 |
| 53.865 | −4.865 |
| 42.886 | −10.886 |
| 81.204 | −17.204 |
| 44.467 | −4.467 |
| 89.817 | −12.817 |
| 87.218 | 9.782 |
| 92.657 | 4.343 |
| 72.659 | 12.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.318 | 13.682 |
| 39.964 | −23.964 |
| 58.821 | 21.179 |
| 58.732 | 49.268 |
| 47.667 | −27.667 |
| 51.606 | 0.3938 |
| 70.245 | 11.755 |
| 64.936 | −14.936 |
| 56.501 | 7.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
| Term | edf | Ref. df | F | p | Smoothing parameter |
|---|---|---|---|---|---|
| s(Temp) | 2.945 | 3.700 | 12.049 | < .001 | 300.13 |
| s(Wind) | 3.446 | 4.277 | 9.717 | < .001 | 161.99 |
Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom.
Parametric terms
| Term | B | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | 46.033 | 4.940 | 9.318 | < .001 | 36.238 | 55.829 |
| month_f: Jun | −9.106 | 8.373 | −1.088 | .279 | −25.709 | 7.497 |
| month_f: Jul | −1.229 | 7.303 | −0.1683 | .867 | −15.710 | 13.251 |
| month_f: Aug | −1.016 | 7.137 | −0.1424 | .887 | −15.168 | 13.135 |
| month_f: Sep | −10.776 | 6.009 | −1.793 | .076 | −22.691 | 1.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
))
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
| Term | edf | Ref. df | F | p | Smoothing parameter |
|---|---|---|---|---|---|
| s(Temp) | 2.945 | 3.700 | 12.049 | < .001 | 300.13 |
| s(Wind) | 3.446 | 4.277 | 9.717 | < .001 | 161.99 |
Approximate significance of smooth terms (Wood 2013); edf = effective degrees of freedom.
Parametric terms
| Term | B | SE | t | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| (Intercept) | 46.033 | 4.940 | 9.318 | < .001 | 36.238 | 55.829 |
| month_f: Jun | −9.106 | 8.373 | −1.088 | .279 | −25.709 | 7.497 |
| month_f: Jul | −1.229 | 7.303 | −0.1683 | .867 | −15.710 | 13.251 |
| month_f: Aug | −1.016 | 7.137 | −0.1424 | .887 | −15.168 | 13.135 |
| month_f: Sep | −10.776 | 6.009 | −1.793 | .076 | −22.691 | 1.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.
Check the residuals anyway
ReflectA 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?
Penalty or fixed df?
ReadFixed df (no penalty) turns off the brake and spends exactly df per smooth, so it's an ordinary regression spline. With , temperature gets 5 df and = 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.
Check your understanding
CheckpointCheck 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.
Fit yours
In the appPick 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.
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)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.
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 .
- Read the plot. A smooth has no single coefficient.
Concepts in this lesson