Skip to content

DRegression models · regression.gam

Generalized additive model (smooth terms)

How does a numeric outcome depend on predictors whose effects may be curved?

Gaussian additive model as mgcv::gam(method = "REML"): up to four smooth terms (penalized cubic regression splines, basis dimension k, smoothness chosen by REML) plus linear terms for other numeric or categorical predictors. Effective degrees of freedom and approximate F tests for each smooth (Wood 2013), parametric coefficients with t tests, adjusted R², deviance explained and the estimated partial effect of each smooth with ±2 SE bands. "Fixed df" fits unpenalized regression splines with k − 1 df each instead.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Airquality two smooths”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Airquality two smoothsairquality · outcome: Ozone · predictors: month_f · smooths: Temp, Wind
  • Mcycle k20s1_mcycle · outcome: accel · smooths: times
  • Airquality fixed dfairquality · outcome: Ozone · predictors: Solar.R · smooths: Temp
  • Dietox smooth weeks1_dietox · outcome: weight · predictors: copper, vitamin E · smooths: week
  • Degenerate constantairquality · outcome: Ozone · predictors: month_f · smooths: Temp, Wind
  • Degenerate n3airquality · outcome: Ozone · predictors: month_f · smooths: Temp, Wind
  • Degenerate single levelairquality · outcome: Ozone · predictors: month_f · smooths: Temp, Wind

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Non-linear: GAM or polynomial terms · Statistics Guide · D — Predict an outcome
  • Linearity · Statistics Guide · Step 2 — Check assumptions
  • Generalized models · Statistics Guide · Step 3 — If assumptions are violated
  • Regression (linear, logistic, Poisson) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Outcomenumeric · 1 column
The numeric variable you are analyzing.
Smooth termsnumeric · 1–4 columns
Numeric predictors whose effect is estimated as a smooth curve (needs at least k distinct values).
Linear termsnumeric / categorical / boolean · 0–10 columns · 2–30 levels
Predictors with a straight-line (numeric) or dummy (categorical) effect.

Choices you make

statistics

Basis dimension (k)default 10

Knots per smooth (the upper limit of its complexity, k − 1 df); REML decides how much of it is used.

Fixed df (no penalty)default off

Unpenalized regression splines with exactly k − 1 df per smooth (mgcv's fx = TRUE).

hypothesis

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Basis dimension large enough

    A smooth whose edf is close to k − 1 may need a larger k.

  • Normal residuals

What it reports

  • Tests: First smooth term (approximate F test)
n
How many independent units the analysis used; it sets precision and power.
k_param
How many coefficients the model estimated, counting the intercept.
edf_total
How many free parameters a penalized model is really using; a heavily smoothed curve may use about one.
residual_df
How much independent information is left to estimate variability after fitting the model.
r2_adj
R² penalized for the number of predictors, so adding useless ones lowers it.
dev_expl
Twice the gap in log-likelihood between a model and a perfect fit; GLMs' analog of the residual sum of squares.
scale
Stretches or shrinks a fitted distribution without changing its form, so larger means more spread.
focal_f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
focal_df
How much independent information is left to estimate variability after fitting the model.
focal_p
How surprising your data would be if the null hypothesis were true, as a probability.
max_edf_share
How many free parameters a penalized model is really using; a heavily smoothed curve may use about one.
fixed_df
How much independent information is left to estimate variability after fitting the model.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: edf[<smooth>], ref_df[…], s_f[…], s_p[…], sp[…], coef[<term>], se[…], t[…], p[…], ci_low[…], ci_high[…], reml, sw_p_resid

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses mgcv, nanoparquet, codesplashr.

Default traps between the two languages

  • Python has no mgcv: the Python engine has its own cubic regression spline basis (the same knot placement, penalty, penalty scaling and sum-to-zero constraint), Gaussian REML criterion and summary tests, so bases, coefficients and edf agree to ~1e-10 and smoothing parameters to ~1e-9 (both optimizers converged tightly).
  • Smooth-term p-values have an absolute floor of 2e-6 (s_p[*], focal_p). mgcv::psum.chisq at its default accuracy errs by up to 1.7e-6 (400 random mixtures), and Python's own inversion of the characteristic function doesn't reproduce that error; R at tol = 1e-12 gives Python's values. On airquality-two-smooths Python gives 2.04e-7 and 6.64e-7 where R gives 0 and 9.56e-7. All of these report as p < .001.
  • Smooth-term tests use the full model matrix in both engines; mgcv's summary.gam sub-samples 1,000 rows when n > 1,000 (seeded with R's own generator), so for larger data the printed summary differs slightly.
  • An edf1 within 1e-9 of a whole number is rounded in both engines (fixed-df smooths), so the test takes the same integer-rank branch.
  • On 640 simulated fits, 6 differ in the REML score by more than 1e-6 (very uneven knots at k = 20, or two real minima). None is in the fixtures.
Python

The exact script CodeSplash ran for example “Airquality two smooths” · 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,
})
R

The exact script CodeSplash ran for example “Airquality two smooths” · 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
))

Sources

  • Wood, S. N. (2017). Generalized Additive Models: An Introduction with R (2nd ed.). CRC Press.
  • Wood, S. N. (2011). Fast stable restricted maximum likelihood and marginal likelihood estimation of semiparametric generalized linear models. JRSS B, 73, 3–36.
  • Wood, S. N. (2013). On p-values for smooth components of an extended generalized additive model. Biometrika, 100, 221–228.
  • Davies, R. B. (1980). Algorithm AS 155: The distribution of a linear combination of χ² random variables. Applied Statistics, 29, 323–333.

From the CodeSplash method registry · regression.gam v1.0.1.