Terms#
Helpers that make terms#
- modelmatrix.poly(col, degree=1, intercept=False, raw=False, name=None)#
Create a polynomial Feature for a given column.
Additional args and kwargs are passed to Poly.
- Parameters:
col (column identifier or Column) – Column to transform.
degree (int, default=1) – Degree of polynomial.
intercept (bool, default=False) – Include a column for intercept?
raw (bool, default=False) – If False, perform a QR decomposition on the resulting matrix of powers of centered and / or scaled features.
name (str (optional)) – Defaults to one derived from col.
- Returns:
var
- Return type:
- modelmatrix.ns(col, intercept=False, name=None, **spline_args)#
Create a natural spline Feature for a given column.
Additional spline_args are passed to
NaturalSplinealong with intercept.
- modelmatrix.bs(col, intercept=False, name=None, **spline_args)#
Create a B-spline Feature for a given column.
Additional args and spline_args are passed to
modelmatrix.transforms.BSplinealong with intercept.
- modelmatrix.pca(variables, name=None, scale=False, **pca_args)#
Create PCA encoding of features from a sequence of variables.
Additional args and pca_args are passed to
sklearn.decomposition.PCA.- Parameters:
variables ([column identifier, Column, Feature or Wildcard]) – Sequence whose columns will be encoded by PCA, or
wildcardfor the columns of X: pca(wildcard(exclude=’y’), n_components=3).name (str (optional)) – Defaults to one derived from the variables.
scale (bool, default=False) – Standardize the columns before the PCA?
- Returns:
var
- Return type:
- modelmatrix.contrast(col, method='drop', drop_level=None)#
Create encoding of categorical feature.
- Parameters:
col (column identifier)
method ('drop', 'sum', None or callable)
drop_level (level identifier)
- Returns:
var
- Return type:
- modelmatrix.ordinal(col, name=None, levels=None)#
Create ordinal encoding of categorical feature: a single column holding the position of each entry’s level (see Ordinal).
- Parameters:
col (column identifier)
name (str (optional)) – Defaults to ‘ordinal(col)’.
levels (sequence (optional)) – The levels in order. Needed unless col is an ordered categorical, or numeric.
- Returns:
var
- Return type:
- modelmatrix.derived_feature(variables, encoder=None, name=None, use_transform=True)#
Create a Feature, optionally applying an encoder to the stacked columns.
- Parameters:
variables ([column identifier, Column, Feature, Wildcard]) – Variables to apply transform to. Could be column identifiers or variables: all columns will be stacked before encoding. A
wildcard(alone, or in the sequence) stands for the columns of X.name (str (optional)) – Defaults to str(encoder).
encoder (transform-like (optional)) – Transform obeying sklearn fit/transform convention.
- Returns:
var
- Return type:
- modelmatrix.build_columns(column_info, X, var, encoders={}, col_cache={}, fit=False, sparse=False, fit_only=False, as_array=False)#
Build columns for a Feature from X.
- Parameters:
column_info (dict) – Dictionary with values specifying sets of columns to be concatenated into a design matrix.
X (array-like) – X on which columns are evaluated.
var (Feature) – Feature whose columns will be built, typically a key in column_info.
encoders (dict) – Dict that stores encoder of each Feature.
col_cache (dict) – Dict where columns will be stored – if var.name in col_cache then just returns those columns.
fit (bool (optional)) – If True, then try to fit encoder. Will raise an error if encoder has already been fit.
sparse (bool (optional)) – If True, return the columns as a scipy.sparse matrix or np.ndarray (not a pd.DataFrame), keeping categorical encodings and their interactions sparse.
fit_only (bool (optional)) – With fit, fit the encoders of a Feature (and of the features and columns it is built from) without evaluating its columns: returns (None, None).
as_array (bool (optional)) – If True, return the columns as a 2-d np.ndarray rather than a pd.DataFrame.
The wildcard#
- modelmatrix.wildcard = Wildcard()#
A term standing for every column of X (but those excluded), as . in R’s formulae: with the response y a column of X, ModelSpec([wildcard(exclude=’y’)]) is the design of R’s y ~ .. It is expanded when the ModelSpec is fit, into the terms of expanded_terms_, and can also be
a part of an interaction: (wildcard, ‘g’) is R’s .:g;
a variable of a feature: pca(wildcard, n_components=3).
Columns that are terms themselves are not repeated, as in R’s y ~ x + ..
- Parameters:
pow (int, default=1) – Also the interactions of up to pow columns: wildcard(pow=2) is R’s .^2. Only as a term.
exclude (column identifier, Response, or sequence of them (optional)) – Columns left out: wildcard(exclude=’x’) is R’s . - x. A
Response, e.g. Surv(‘time’, ‘status’), leaves out its columns, so that the response is not a term of its own design.
- class modelmatrix.Wildcard(pow: int = 1, exclude: tuple = ())#
Bases:
objectA term standing for every column of X (but those excluded), as . in R’s formulae: with the response y a column of X, ModelSpec([wildcard(exclude=’y’)]) is the design of R’s y ~ .. It is expanded when the ModelSpec is fit, into the terms of expanded_terms_, and can also be
a part of an interaction: (wildcard, ‘g’) is R’s .:g;
a variable of a feature: pca(wildcard, n_components=3).
Columns that are terms themselves are not repeated, as in R’s y ~ x + ..
- Parameters:
pow (int, default=1) – Also the interactions of up to pow columns: wildcard(pow=2) is R’s .^2. Only as a term.
exclude (column identifier, Response, or sequence of them (optional)) – Columns left out: wildcard(exclude=’x’) is R’s . - x. A
Response, e.g. Surv(‘time’, ‘status’), leaves out its columns, so that the response is not a term of its own design.
Terms and columns#
- class modelmatrix.Feature(variables: tuple, name: str, encoder: Any, use_transform: bool = True, pure_columns: bool = False, override_encoder_colnames: bool = False, spec: Any = None)#
Bases:
NamedTupleAn element in a model matrix that will build columns from an array-like X.
- encoder: Any#
Alias for field number 2
- name: str#
Alias for field number 1
- override_encoder_colnames: bool#
Alias for field number 5
- pure_columns: bool#
Alias for field number 4
- spec: Any#
Alias for field number 6
- use_transform: bool#
Alias for field number 3
- variables: tuple#
Alias for field number 0
- class modelmatrix.Column(idx: Any, name: str, is_categorical: bool = False, is_ordinal: bool = False, columns: tuple = (), encoder: Any = None)#
Bases:
NamedTupleA column extractor with a possible encoder (following sklearn fit/transform template).
- columns: tuple#
Alias for field number 4
- encoder: Any#
Alias for field number 5
- fit_encoder(X)#
Fit self.encoder.
- Parameters:
X (array-like) – X on which encoder will be fit.
- Return type:
None
- get_columns(X, fit=False, sparse=False)#
Extract associated column from X, encoding it with self.encoder if not None.
- Parameters:
X (array-like) – X on which model matrix will be evaluated. If a pd.DataFrame or pd.Series, variables that are of categorical dtype will be treated as categorical.
fit (bool) – If True, fit self.encoder on corresponding column (if it is not already fit). The encoder must be fit to evaluate the columns: a Column used in the terms of a ModelSpec is not itself fit when the ModelSpec is, as a copy of it is.
sparse (bool) – If True, the columns may be returned as a scipy.sparse matrix, e.g. for a categorical encoding.
- Returns:
cols (np.ndarray) – Evaluated columns – if an encoder is used, several columns may be produced.
names ((str,)) – Column names
- idx: Any#
Alias for field number 0
- is_categorical: bool#
Alias for field number 2
- is_ordinal: bool#
Alias for field number 3
- name: str#
Alias for field number 1
Encoders of categoricals#
- class modelmatrix.Contrast(method='drop', drop_level=None)#
Bases:
TransformerMixin,BaseEstimator- fit(X, y=None)#
Construct contrast of categorical variable for use in building a design matrix.
- Parameters:
X (array-like) – X on which model matrix will be evaluated. If a
pd.DataFrameorpd.Series, variables that are of categorical dtype will be treated as categorical.- Returns:
F – Columns of design matrix implied by the categorical variable.
- Return type:
array-like