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.

Building design matrices with ModelSpec

The modelmatrix package provides a facility to build design matrices for regression and classification tasks. It provides similar functionality to the formula notation of R though uses python objects rather than specification through the special formula syntax.

Related tools include patsy and ColumnTransformer from sklearn.compose.

Perhaps the most common use is to extract some columns from a pd.DataFrame and produce a design matrix, optionally with an intercept.

Index(['Sales', 'CompPrice', 'Income', 'Advertising', 'Population', 'Price', 'ShelveLoc', 'Age', 'Education', 'Urban', 'US'], dtype='str')

We’ll first build a design matrix that we can use to model Sales in terms of the categorical variable ShelveLoc and Price.

We see first that ShelveLoc is a categorical variable:

0 Bad 1 Good 2 Medium 3 Medium 4 Bad ... 395 Good 396 Medium 397 Medium 398 Bad 399 Good Name: ShelveLoc, Length: 400, dtype: category Categories (3, str): ['Bad', 'Good', 'Medium']

This is recognized by ModelSpec and only 2 columns are added for the three levels. The default behavior is to drop the first level of the categories. Later, we will show other contrasts of the 3 columns can be produced.

This simple example below illustrates how the first argument (its terms) is used to construct a design matrix.

Loading...

We note that a column of ones, named intercept, has been added: intercept=True, as statsmodels’ models need it. The default is intercept=False, as most scikit-learn estimators (and glmstar’s) fit the intercept themselves.

Loading...

We see that ShelveLoc still only contributes two columns to the design. The ModelSpec object does no introspection of its arguments to effectively include an intercept term in the column space of the design matrix.

To include this intercept via ShelveLoc we can use 3 columns to encode this categorical variable. Following the nomenclature of R, we call this a Contrast of the categorical variable.

Loading...

This example above illustrates that columns need not be identified by name in terms. The basic role of an item in the terms sequence is a description of how to extract a column from a columnar data object, usually a pd.DataFrame.

Column(idx='ShelveLoc', name='ShelveLoc', is_categorical=True, is_ordinal=False, columns=(), encoder=Contrast(method=None))

The Column object can be used to directly extract relevant columns from a pd.DataFrame. If the encoder field is not None, then the extracted columns will be passed through encoder. The get_columns method produces these columns as well as names for the columns. The encoder of shelve itself has not been fit: fitting MS_contr fit a copy of it, so that shelve can be reused in other specifications. We ask get_columns to fit it with fit=True.

(array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], ..., [0., 0., 1.], [1., 0., 0.], [0., 1., 0.]], shape=(400, 3)), ['ShelveLoc[Bad]', 'ShelveLoc[Good]', 'ShelveLoc[Medium]'])

Let’s now fit a simple OLS model with this design.

Loading...

Interactions

One of the common uses of formulae in R is to specify interactions between variables. This is done in ModelSpec by including a tuple in the terms argument.

Loading...

The above design matrix is clearly rank deficient, as ModelSpec has not inspected the formula and attempted to produce a corresponding matrix that may or may not match a user’s intent.

Ordinal variables

Ordered categoricals, such as the income bands produced by pd.cut() below, are encoded with contrasts like any other categorical, in the order of their categories.

Part of the fit method of ModelSpec involves inspection of the columns of Carseats. The results of that inspection can be found in the column_info_ attribute:

{'Sales': Column(idx='Sales', name='Sales', is_categorical=False, is_ordinal=False, columns=('Sales',), encoder=None), 'CompPrice': Column(idx='CompPrice', name='CompPrice', is_categorical=False, is_ordinal=False, columns=('CompPrice',), encoder=None), 'Income': Column(idx='Income', name='Income', is_categorical=False, is_ordinal=False, columns=('Income',), encoder=None), 'Advertising': Column(idx='Advertising', name='Advertising', is_categorical=False, is_ordinal=False, columns=('Advertising',), encoder=None), 'Population': Column(idx='Population', name='Population', is_categorical=False, is_ordinal=False, columns=('Population',), encoder=None), 'Price': Column(idx='Price', name='Price', is_categorical=False, is_ordinal=False, columns=('Price',), encoder=None), 'ShelveLoc': Column(idx='ShelveLoc', name='ShelveLoc', is_categorical=True, is_ordinal=False, columns=('ShelveLoc[Good]', 'ShelveLoc[Medium]'), encoder=Contrast()), 'Age': Column(idx='Age', name='Age', is_categorical=False, is_ordinal=False, columns=('Age',), encoder=None), 'Education': Column(idx='Education', name='Education', is_categorical=False, is_ordinal=False, columns=('Education',), encoder=None), 'Urban': Column(idx='Urban', name='Urban', is_categorical=True, is_ordinal=False, columns=('Urban[Yes]',), encoder=Contrast()), 'US': Column(idx='US', name='US', is_categorical=True, is_ordinal=False, columns=('US[Yes]',), encoder=Contrast()), 'OIncome': Column(idx='OIncome', name='OIncome', is_categorical=True, is_ordinal=True, columns=('OIncome[M]', 'OIncome[H]'), encoder=Contrast())}

To instead encode an ordinal variable by a single column holding the position of its level, use ordinal(). The order comes from an ordered categorical, as here, or can be given with levels=[...]; for other columns, such as strings, the order would be ambiguous and ordinal() raises an error.

Loading...

Structure of a ModelSpec

The first argument to ModelSpec is stored as the terms attribute. Under the hood, this sequence is inspected to produce the terms_ attribute which specify the objects that will ultimately create the design matrix.

[Feature(variables=('ShelveLoc',), name='ShelveLoc', encoder=None, use_transform=True, pure_columns=True, override_encoder_colnames=False, spec=None), Feature(variables=('Price',), name='Price', encoder=None, use_transform=True, pure_columns=True, override_encoder_colnames=False, spec=None)]

Each element of terms_ should be a Feature which describes a set of columns to be extracted from a columnar data form as well as possible a possible encoder.

We can find the columns associated to each term using the build_columns method of ModelSpec:

Loading...

The design matrix is constructed by running through terms_ and concatenating the corresponding columns.

Feature objects

Note that Feature objects have a tuple of variables as well as an encoder attribute. The tuple of variables first creates a concatenated dataframe from all corresponding variables and then is run through encoder.transform. The encoder.fit method of each Feature is run once during the call to ModelSpec.fit.

Loading...

Let’s now transform these columns with an encoder. Within ModelSpec we will first build the arrays above and then call pca.fit and finally pca.transform within design.build_columns.

Loading...

The elements of the variables attribute may be column identifiers ( "Price"), Column instances (price) or Feature instances (pca_var).

Loading...

Predicting at new points

intercept 12.661546 Price -0.052213 Income 0.012829 dtype: float64

As ModelSpec is a transformer, it can be evaluated at new feature values. Constructing the design matrix at any values is carried out by the transform method.

array([10.70130676, 10.307465 ])

Using np.ndarray

As the basic model is to concatenate columns extracted from a columnar data representation, one can use np.ndarray as the column data. In this case, columns will be selected by integer indices.

Caveats using np.ndarray

If the terms only refer to a few columns of the data frame, the transform method only needs a dataframe with those columns. However, unless all features are floats, np.ndarray will default to a dtype of object, complicating issues.

However, if we had used an np.ndarray, the column identifiers would be integers identifying specific columns so, in order to work correctly, transform would need another np.ndarray where the columns have the same meaning.

We illustrate this below, where we build a model from Price and Income for Sales and want to find predictions at new values of Price and Location. We first find the predicitions using pd.DataFrame and then illustrate the difficulties in using np.ndarray.

We will refit this model, using ModelSpec with an np.ndarray instead

array([[ 1., 120., 73.], [ 1., 83., 48.], [ 1., 80., 35.], ..., [ 1., 159., 26.], [ 1., 95., 79.], [ 1., 120., 37.]], shape=(400, 3))
const 12.661546 x1 -0.052213 x2 0.012829 dtype: float64

Now, let’s consider finding the design matrix at new points. When using pd.DataFrame we only need to supply the transform method a data frame with columns implicated in the terms argument (in this case, Price and Income).

However, when using np.ndarray with integers as indices, Price was column 0 and Income was column 2. The only sensible way to produce a return for predict is to extract its 0th and 2nd columns. Note this means that the meaning of columns in an np.ndarray provided to transform essentially must be identical to those passed to fit. To guard against this, transform requires an np.ndarray with as many columns as it was fit with.

X has 2 features, but ModelSpec is expecting 3 features as input.

Ultimately, M expects 3 columns for new predictions because it was fit with a matrix having 3 columns (the first representing an intercept).

We might be tempted to try as with the pd.DataFrame and produce an np.ndarray with only the necessary variables.

[[ 1. 40. 10.]
 [ 1. 50. 20.]]
array([10.70130676, 10.307465 ])

For more complicated design contructions ensuring the columns of new_D match that of the original data will be more cumbersome. We expect then that pd.DataFrame (or a columnar data representation with similar API) will likely be easier to use with ModelSpec.