Export a Model to R’s mgcv Format

Convert a fitted whittaker GAM to a dict that mirrors R’s mgcv list structure for cross-language interoperability.

Teams that use both Python and R often need to share fitted models across the language boundary. wk.to_mgcv_dict() converts a fitted whittaker GAM into a JSON-serializable dict whose keys match those of the list returned by R’s mgcv::gam(), making it straightforward to reconstruct or inspect the model on the R side.

Fit a Model

Load the wages dataset and fit a Gamma GAM with two smooth terms.

import json
import numpy as np
import whittaker as wk

# Load dataset and fit Gamma GAM
data = wk.load_dataset("wages")
model = wk.GAM("wage ~ s(age) + s(experience)", family=wk.Gamma()).fit(data)

Export to mgcv Dict

to_mgcv_dict() accepts any fitted GAM and returns a plain Python dict.

d = wk.to_mgcv_dict(model)
list(d.keys())
['coefficients',
 'sp',
 'scale',
 'scale.estimated',
 'gcv.ubre',
 'edf',
 'edf.total',
 'deviance',
 'null.deviance',
 'aic',
 'n',
 'p',
 'converged',
 'iter',
 'method',
 'formula',
 'family',
 'smooth',
 'nsdf',
 'intercept']

Inspect Metadata

The top-level keys mirror mgcv’s return structure. Examine the formula string, family, observation count, and AIC.

d["formula"]
'wage ~ s(age) + s(experience)'
d["family"]
{'family': 'Gamma'}
d["n"]
800
d["aic"]
5881.682264908716

Inspect Smooth Structure

The "smooth" key holds a list of dicts, one per smooth term, matching mgcv’s $smooth list.

[s["term"] for s in d["smooth"]]
[['age'], ['experience']]

Serialize to JSON

The dict is fully JSON-serializable. NumPy arrays are converted with a default handler.

json_str = json.dumps(d, default=lambda x: x.tolist() if hasattr(x, "tolist") else x)
json_str[:200]
'{"coefficients": [3.7108559148950313, 0.03308597228013556, 1.121216091210627, -0.016795838077386698, 0.12874105747190906, -0.00532568942108003, 0.03671596640745752, 1.7328555613005703e-06, -0.01606031'

Round-Trip Back to whittaker

from_mgcv_dict() reconstructs a prediction-ready GAM when the original data is supplied to refit the smooth bases.

# Reconstruct model from dict and predict
model2 = wk.from_mgcv_dict(d, data=data)
model2.predict({"age": np.array([30, 40, 50]), "experience": np.array([5, 10, 15])}).values
array([28.11327006, 47.88873147, 67.12661659])

Interpret

to_mgcv_dict() produces a dict with the same keys as R’s mgcv::gam() return value, making it possible to load a Python-fitted GAM into R for further analysis or reporting. The round-trip through from_mgcv_dict() is useful when you want to reload a model from a stored JSON snapshot without writing a binary file. Use data=None for a lightweight container that carries coefficients and metadata but cannot predict, or supply the original data to get a fully functional model back.