Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

ModelSpec, ColumnTransformer, patsy and formulaic

ModelSpec builds model matrices, as do sklearn’s ColumnTransformer, patsy and formulaic. The two formula libraries parse a string such as 'Sales ~ Price * ShelveLoc' in the spirit of R’s model formulae. A ColumnTransformer lists a transformer and the columns it applies to, for each block of columns. ModelSpec takes a list of Python objects: column names, tuples for interactions, and features that wrap any sklearn transformer.

This page compares them on flexibility and extensibility: what it takes to add a new kind of term, to nest one feature inside another, to interact terms, and to work inside sklearn. Reproducing R’s formula semantics is not a goal of ModelSpec, so some defaults differ on purpose; those are collected at the end.

At a glance

ModelSpecColumnTransformerpatsyformulaic
any sklearn transformer as a termdirectlydirectlywith a stateful-transform wrapperwith a stateful-transform wrapper
interacting terms (e.g. a spline with a categorical)a tupleno: PolynomialFeatures multiplies every pair of columns* and :* and :
a feature of other features (e.g. PCA of a polynomial and dummies)yesyes, nesting Pipelines and ColumnTransformersnono
categorical columnscoded from their dtypean encoder you name, for columns you list or select by dtypecoded from their dtypecoded from their dtype
a model fitted elsewhere as a termyes, with FrozenEstimatorwith a FunctionTransformer around ityes, a function calling ityes, a function calling it
building a specificationPython lists of objectslists of (name, transformer, columns)formula stringsformula strings
sklearn transformer (Pipeline, refit in each CV fold)yesyesneeds a wrapper estimatorneeds a wrapper estimator
tuning a term’s parameters by GridSearchCVyes (modelspec__terms__0__df)yes (columntransformer__spline__n_knots)needs a wrapper estimatorneeds a wrapper estimator
pickling a fitted specificationyesyesnoyes
sparse model matricesyes (sparse_output=True)yes (sparse_threshold)noyes (output='sparse')
input other than pandas (e.g. polars)yes; output in the same backendyes; output by set_outputnoyes
patsy 1.0.3, formulaic 1.2.2, scikit-learn 1.9.1, pandas 3.1.0

The modelmatrix helpers are accessed as mm.poly, mm.ns, etc. rather than imported by name. Formula strings are evaluated in the calling namespace, so importing modelmatrix’s bs would silently replace patsy’s bs inside patsy.dmatrix('bs(Price, df=5)', ...).

Terms are Python objects

Any sklearn transformer can be used as a term with derived_feature, with no registration or wrapper. Its state is fit when the ModelSpec is fit, and reused on new data.

Loading...

Because terms are objects, a list of them can be built with ordinary Python, for example a natural spline for every numeric column:

(400, 25)

The inputs of a feature may themselves be features, which are encoded first. Here a PCA is fit to an orthogonal polynomial in Price, Income and the one-hot encoding of ShelveLoc, and its scores are interacted with US:

Loading...

Fitting a ModelSpec fits copies of the encoders of its terms, so the same terms can be used in several specifications, and a fitted specification can be fit again. A model fit elsewhere, on other data, can be a term too: wrapped in sklearn’s FrozenEstimator, it is used as is and never refit. Here a nearest-neighbour fit to the first 200 stores supplies a column for the others:

Loading...

The same in patsy and formulaic

Both formula libraries support stateful transforms, but an sklearn transformer needs a wrapper written against each library’s protocol.

((400, 10), (400, 10), (400, 10))

With the wrapper, a learned feature can be interacted with a categorical in either library. Nesting is a different matter: inside a function call, C(ShelveLoc) is a box holding the labels rather than its dummy columns, so the PCA above cannot be written this way.

patsy: PatsyError
formulaic: FactorEvaluationError

Working inside scikit-learn

A ModelSpec is an sklearn transformer, so it can be the first step of a Pipeline, and refit on each fold of a cross-validation. Here the regression fits its own intercept, so the model matrix has none:

array([0.54 , 0.458, 0.618, 0.581, 0.55 ])

Tuning the parameters of terms

The parameters of each term are parameters of the ModelSpec, so GridSearchCV can tune them as it tunes those of any sklearn estimator. A term’s parameter is named by the position of the term in terms:

keythe parameter of
'terms__<i>__<parameter>'the term at position i, e.g. 'terms__0__df'
'terms__<i>__<j>__<parameter>'part j of the interaction at position i
'terms__<name>__<parameter>'the term given that name, e.g. ns('Price', df=4, name='price')

get_params() lists them:

{'terms__0__df': 4, 'terms__2__1__degree': 2}

In a Pipeline each key is prefixed by the name of its step, here 'modelspec__'. Both parameters are tuned below. A term made by ns(), bs(), poly() or pca() is made again with its new parameters, so its name, and the names of its columns, follow:

({'modelspec__terms__0__df': 1, 'modelspec__terms__2__1__degree': 1}, 'ns(Price, df=1)', 'poly(Income, degree=1)')

The parameters of other terms, e.g. a derived_feature of any transformer or contrast(), are those of their encoder ('terms__<i>__n_knots' for a SplineTransformer, 'terms__<i>__method' for contrast()). Setting a parameter does not change terms: it is replaced by a copy, in which a term used in several places, e.g. also in an interaction, is changed in all of them.

So can terms itself, to choose among specifications:

2

get_feature_names_out names the columns, which also enables set_output, here giving a data frame from an np.ndarray:

Loading...

Compared with scikit-learn’s ColumnTransformer

A ColumnTransformer fits as naturally into sklearn as a ModelSpec: it is a transformer, and the parameters of its transformers can be tuned. The same model matrix, a spline in Price, ShelveLoc and Income, is written below both ways; they give the same columns, and tuning the number of knots of the spline gives the same results.

ModelSpec          {'modelspec__terms__0__n_knots': 3} [0.5483 0.5409 0.5457]
ColumnTransformer  {'columntransformer__spline__n_knots': 3} [0.5483 0.5409 0.5457]

The categorical ShelveLoc needs its own encoder in the ColumnTransformer, chosen by name or, as here, by dtype; a ModelSpec codes it from its dtype.

(400, 10)

Interactions are where the two differ most. In a ModelSpec a tuple interacts any terms, here the spline with ShelveLoc. A ColumnTransformer has no way to multiply one block of columns by another: PolynomialFeatures(interaction_only=True) multiplies every pair of its input columns, including pairs of spline columns and of dummy columns.

ModelSpec         23 columns
ColumnTransformer 45 columns

A fitted ModelSpec can be pickled, with all of its encoders, as can formulaic’s ModelSpec; patsy’s DesignInfo cannot.

ModelSpec: pickled
patsy: NotImplementedError
formulaic: pickled

Sparse model matrices

With sparse_output=True, a ModelSpec returns a scipy.sparse.csr_matrix. Categorical encodings and their interactions are built sparse throughout, so a categorical with many levels never forms its dense columns; formulaic’s output='sparse' does the same. Here a categorical with 5,000 levels and 50,000 rows, whose dense model matrix would take 2 GB:

ModelSpec csr_matrix (50000, 9998) 199,974 nonzero
formulaic ModelMatrix (50000, 9998) 199,974 nonzero

Other dataframes

Dataframes of the backends supported by narwhals, such as polars or pyarrow, can be given to a ModelSpec, and the model matrix is returned in the same backend. A polars Enum carries the order of its levels, so ordinal() can score it. formulaic accepts them too; patsy expects pandas or numpy.

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[18], line 3
      1 import polars as pl
      2 
----> 3 P = pl.from_pandas(Carseats).with_columns(
      4     pl.col('ShelveLoc').cast(pl.String).cast(pl.Enum(['Bad', 'Medium', 'Good'])))
      5 design = MS(['Price', 'US', mm.ordinal('ShelveLoc')], intercept=True).fit(P)
      6 design.transform(P.head())

File /opt/hostedtoolcache/Python/3.12.15/x64/lib/python3.12/site-packages/polars/convert/general.py:725, in from_pandas(data, schema_overrides, rechunk, nan_to_null, include_index)
    722     return wrap_s(pandas_to_pyseries("", data, nan_to_null=nan_to_null))
    723 elif isinstance(data, pd.DataFrame):
    724     return wrap_df(
--> 725         pandas_to_pydf(
    726             data,
    727             schema_overrides=schema_overrides,
    728             rechunk=rechunk,
    729             nan_to_null=nan_to_null,
    730             include_index=include_index,
    731         )
    732     )
    733 else:
    734     msg = f"expected pandas DataFrame or Series, got {qualified_type_name(data)!r}"

File /opt/hostedtoolcache/Python/3.12.15/x64/lib/python3.12/site-packages/polars/_utils/construction/dataframe.py:1164, in pandas_to_pydf(data, schema, schema_overrides, strict, rechunk, nan_to_null, include_index)
   1158 if not _PYARROW_AVAILABLE:
   1159     msg = (
   1160         "pyarrow is required for converting a pandas dataframe to Polars, "
   1161         "unless each of its columns is a simple numpy-backed one "
   1162         "(e.g. 'int64', 'bool', 'float32' - not 'Int64')"
   1163     )
-> 1164     raise ImportError(msg)
   1165 arrow_dict = {}
   1166 length = data.shape[0]

ImportError: pyarrow is required for converting a pandas dataframe to Polars, unless each of its columns is a simple numpy-backed one (e.g. 'int64', 'bool', 'float32' - not 'Int64')

Model structure

All three record which columns of the model matrix belong to each term, which is what an ANOVA or a group-wise selection procedure needs.

Where they overlap, the matrices agree: treatment and sum contrasts, and interactions such as Price*ShelveLoc, give the same columns up to order.

Defaults that differ

ModelSpecColumnTransformerpatsyformulaic
a column of ones (intercept)only with intercept=Trueno: sklearn estimators fit their ownyesyes
missing valuespropagate as NaN rowspassed through; OneHotEncoder codes a missing level as a level of its ownrows droppedrows dropped
unused levels of a categoricaldroppeddropped (OneHotEncoder learns the levels it sees)column of zeroscolumn of zeros
level unseen when fiterrorerror (OneHotEncoder’s default)errorencoded as all zeros, with a warning
string column, not categoricalerror: use astype('category') or contrast()as its transformer: 'passthrough' keeps the stringstreated as categoricaltreated as categorical
interactions without main effectsproduct of each term’s coding(no interactions)recoded to keep the model full rankrecoded to keep the model full rank

ModelSpec adds no column of ones by default, as a ColumnTransformer: sklearn and glmstar estimators fit their own intercept. Pass intercept=True for statsmodels’ models (OLS, GLM, ...), which need the column. (In ISLP before 0.7, intercept=True was the default; the examples on this page pass it explicitly.)

Ordered categoricals are coded with contrasts by ModelSpec, patsy and formulaic. ModelSpec can instead score one by the position of its level with ordinal(), which requires an explicit order: an ordered categorical (or a polars Enum), or levels=[...].

Where the others go further