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.
A real result
Example “Airquality two smooths”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
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).
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.
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.
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,
})
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.