ModelSpec#
- class modelmatrix.ModelSpec(terms=(), intercept=False, categorical_features=None, categorical_encoders=None, sparse_output=False)#
Bases:
TransformerMixin,BaseEstimator- Parameters:
terms (sequence (optional)) – Sequence of sets whose elements are columns of X when fit. For
pd.DataFramethese can be column names.wildcardstands for every column of X, as R’s . (seeWildcard).intercept (bool, default=False) – Include a column of ones named ‘intercept’ as the first column of the design? Pass True for statsmodels’ models (OLS, GLM, …), which need the column; most scikit-learn estimators, and glmstar’s, fit the intercept themselves.
categorical_features (array-like of {bool, int} of shape (n_features)) –
or shape (n_categorical_features,), default=None.
Indicates the categorical features. Will be ignored if X is a
pd.DataFrameorpd.Series.None : no feature will be considered categorical for
np.ndarray.boolean array-like : boolean mask indicating categorical features.
integer array-like : integer indices indicating categorical features.
categorical_encoders (dict (optional)) –
Encoders for the categorical columns of X, i.e. the columns of categorical dtype of a
pd.DataFrameor those given by categorical_features for annp.ndarray. Its keys are either:’categorical’ : the encoder of every categorical column, ordered or not, without its own entry, cloned for each column. Defaults to Contrast(method=’drop’), which drops the first level.
’ordinal’ : if present, used instead for the ordered pd.Categorical columns, e.g. {‘ordinal’: Ordinal()} to score each by the position of its level. No default.
a column of X (a name for a
pd.DataFrame, an integer for annp.ndarray) : the encoder of that column. Like the others it is cloned, and the clone is fit, so the dictionary’s encoders are not modified.
For an encoder of a single term, see
contrast()andordinal().sparse_output (bool (optional)) – If True, the model matrix is a scipy.sparse.csr_matrix. Categorical encodings and their interactions are then built sparse throughout, so a design with categoricals of many levels never forms its dense columns; other columns (numeric, splines, etc.) are dense blocks stored sparsely. Not compatible with set_output.
- build_sequence(X, anova_type='sequential')#
Build implied sequence of submodels based on successively including more terms.
- Parameters:
X (array-like) – X on which columns are evaluated.
anova_type (str) – One of “sequential” or “drop”.
- Returns:
models – Generator for sequence of models for ANOVA.
- Return type:
generator
- build_submodel(X, terms)#
Build design on X after fitting.
- Parameters:
X (array-like) – X on which columns are evaluated.
terms ([Feature]) – Sequence of features. Elements of self.terms are replaced by their fitted versions in self.terms_, and a wildcard is expanded as at fit.
- Returns:
D – Design matrix created with terms
- Return type:
array-like
- fit(X, y=None)#
Fit the encoders of each term, determining the columns of the model 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. Dataframes of other backends supported by narwhals, such as polars or pyarrow, are converted to pandas; transform then returns the model matrix in the backend of its input.y (array-like (optional)) – Not used to fit, but if both X and y are pandas objects, their indices must agree. This parameter exists for compatibility with
sklearn.pipeline.Pipeline; seeResponsefor a response from X.
- fit_transform(X, y=None, **fit_params)#
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Input samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
**fit_params (dict) – Additional fit parameters. Pass only if the estimator accepts additional params in its fit method.
- Returns:
X_new – Transformed array.
- Return type:
ndarray array of shape (n_samples, n_features_new)
- get_feature_names_out(input_features=None)#
Names of the columns of the model matrix.
- Parameters:
input_features (None) – Ignored. This parameter exists only for compatibility with
sklearn.pipeline.Pipeline.- Returns:
names
- Return type:
np.ndarray of str
- get_params(deep=True)#
Get parameters of this ModelSpec.
With deep, these include the parameters of each term, as ‘terms__<i>__<parameter>’ for the term at position i of terms (‘terms__<i>__<j>__<parameter>’ for part j of an interaction), e.g. ‘terms__0__df’ for ns(‘x’, df=4).
- set_output(*, transform=None)#
Set output container.
Refer to the user guide for more details and sphx_glr_auto_examples_miscellaneous_plot_set_output.py for an example on how to use the API.
- Parameters:
transform ({"default", "pandas", "polars"}, default=None) –
Configure output of transform and fit_transform.
”default”: Default output format of a transformer
”pandas”: DataFrame output
”polars”: Polars output
None: Transform configuration is unchanged
Added in version 1.4: “polars” option was added.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- set_params(**params)#
Set parameters of this ModelSpec.
A parameter of a term is set with ‘terms__<i>__<parameter>’, where i is the position of the term in terms or the name given to it, e.g. ‘terms__price__df’ for ns(‘Price’, df=4, name=’price’). A term made by poly(), ns(), bs() or pca() is made again with the new parameter, so its name (if not given) and its columns’ names follow it. terms itself is not modified: it is replaced by a copy, in which every occurrence of the changed term (e.g. also in an interaction) is changed.
- transform(X, y=None)#
Build design on X after fitting.
- Parameters:
X (array-like)
y (None) – Ignored. This parameter exists only for compatibility with
sklearn.pipeline.Pipeline.