nemos.basis._basis.Basis#
- class nemos.basis._basis.Basis(mode='eval', label=None)[source]#
Bases:
Base
,ABC
,BasisTransformerMixin
Abstract base class for defining basis functions for feature transformation.
Basis functions are mathematical constructs that can represent data in alternative, often more compact or interpretable forms. This class provides a template for such transformations, with specific implementations defining the actual behavior.
- Parameters:
mode (
Literal
['eval'
,'conv'
,'composite'
]) – The mode of operation. ‘eval’ for evaluation at sample points, ‘conv’ for convolutional operation.label (
Optional
[str
]) – The label of the basis, intended to be descriptive of the task variable being processed. For example: velocity, position, spike_counts.
- Raises:
ValueError: – If
mode
is not ‘eval’ or ‘conv’.ValueError: – If
kwargs
are not None andmode =="eval"
.ValueError: – If
kwargs
include parameters not recognized or do not have default values increate_convolutional_predictor
.ValueError: – If
axis
different from 0 is provided as a keyword argument (samples must always be in the first axis).
Attributes
Label for the basis.
Mode of operation, either
"conv"
or"eval"
.Number of basis functions.
Number of features returned by the basis.
- __init__(mode='eval', label=None)[source]#
- Parameters:
mode (Literal['eval', 'conv', 'composite'])
label (str | None)
- Return type:
None
Methods
__init__
([mode, label])compute_features
(*xi)Apply the basis transformation to the input data.
evaluate_on_grid
(*n_samples)Evaluate the basis set on a grid of equi-spaced sample points.
get_params
([deep])From scikit-learn, get parameters by inspecting init.
set_input_shape
(xi)Set the expected input shape for the basis object.
set_params
(**params)Set the parameters of this estimator.
setup_basis
(*xi)Pre-compute all basis state variables.
split_by_feature
(x[, axis])Decompose an array along a specified axis into sub-arrays based on the number of expected inputs.
Turn the Basis into a TransformerBasis for use with scikit-learn.
- __add__(other)[source]#
Add two Basis objects together.
- Parameters:
other (
Basis
) – The other Basis object to add.- Returns:
The resulting Basis object.
- Return type:
- __mul__(other)[source]#
Multiply two Basis objects together.
- Parameters:
other (
Basis
) – The other Basis object to multiply.- Return type:
- Returns:
The resulting Basis object.
- __pow__(exponent)[source]#
Exponentiation of a Basis object.
Define the power of a basis by repeatedly applying the method __multiply__. The exponent must be a positive integer.
- Parameters:
exponent (
int
) – Positive integer exponent- Return type:
- Returns:
The product of the basis with itself “exponent” times. Equivalent to
self * self * ... * self
.- Raises:
TypeError – If the provided exponent is not an integer.
ValueError – If the integer is zero or negative.
- compute_features(*xi)[source]#
Apply the basis transformation to the input data.
This method is designed to be a high-level interface for transforming input data using the basis functions defined by the subclass. Depending on the basis’ mode (‘Eval’ or ‘Conv’), it either evaluates the basis functions at the sample points or performs a convolution operation between the input data and the basis functions.
- Parameters:
*xi (ArrayLike | Tsd | TsdFrame | TsdTensor) – Input data arrays to be transformed. The shape and content requirements depend on the subclass and mode of operation (‘Eval’ or ‘Conv’).
- Return type:
FeatureMatrix
- Returns:
Transformed features. In ‘eval’ mode, it corresponds to the basis functions evaluated at the input samples. In ‘conv’ mode, it consists of convolved input samples with the basis functions. The output shape varies based on the subclass and mode.
Notes
Subclasses should implement how to handle the transformation specific to their basis function types and operation modes.
- evaluate_on_grid(*n_samples)[source]#
Evaluate the basis set on a grid of equi-spaced sample points.
- Parameters:
n_samples (
int
) – The number of samples.- Return type:
Tuple
[Tuple
[NDArray], NDArray]- Returns:
X – Array of shape (n_samples,) containing the equi-spaced sample points where we’ve evaluated the basis.
basis_funcs – Evaluated exponentially decaying basis functions, numerically orthogonalized, shape (n_samples, n_basis_funcs)
- get_params(deep=True)#
From scikit-learn, get parameters by inspecting init.
- Parameters:
deep
- Return type:
dict
- Returns:
- out:
A dictionary containing the parameters. Key is the parameter name, value is the parameter value.
- property label: str#
Label for the basis.
- property mode#
Mode of operation, either
"conv"
or"eval"
.
- property n_basis_funcs#
Number of basis functions.
- property n_output_features: int | None#
Number of features returned by the basis.
Notes
The number of output features can be determined only when the number of inputs provided to the basis is known. Therefore, before the first call to
compute_features
, this property will returnNone
. After that call, or after setting the input shape withset_input_shape
,n_output_features
will be available.
- abstract set_input_shape(xi)[source]#
Set the expected input shape for the basis object.
This method configures the shape of the input data that the basis object expects.
xi
can be specified as an integer, a tuple of integers, or derived from an array. The method also calculates the total number of input features and output features based on the number of basis functions.- Parameters:
xi (int | tuple[int, ...] | NDArray)
- set_params(**params)#
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline
). The latter have parameters of the form<component>__<parameter>
so that it’s possible to update each component of a nested object.- Parameters:
**params (dict) – Estimator parameters.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- abstract setup_basis(*xi)[source]#
Pre-compute all basis state variables.
This method is intended to be equivalent to the sklearn transformer
fit
method. As the latter, it computes all the state attributes, and store it with the convention that the attribute name must end with “_”, for exampleself.kernel_
,self._input_shape_
.The method differs from transformer’s
fit
for the structure of the input that it accepts. In particular,_fit_basis
accepts a number of different time series, one per 1D basis component, whilefit
requires all inputs to be concatenated in a single array.- Return type:
TsdFrame
|ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]- Parameters:
xi (ArrayLike)
- split_by_feature(x, axis=1)[source]#
Decompose an array along a specified axis into sub-arrays based on the number of expected inputs.
This function takes an array (e.g., a design matrix or model coefficients) and splits it along a designated axis.
How it works:
If the basis expects an input shape
(n_samples, n_inputs)
, then the feature axis length will betotal_n_features = n_inputs * n_basis_funcs
. This axis is reshaped into dimensions(n_inputs, n_basis_funcs)
.If the basis expects an input of shape
(n_samples,)
, then the feature axis length will betotal_n_features = n_basis_funcs
. This axis is reshaped into(1, n_basis_funcs)
.
For example, if the input array
x
has shape(1, 2, total_n_features, 4, 5)
, then after applying this method, it will be reshaped into(1, 2, n_inputs, n_basis_funcs, 4, 5)
.The specified axis (
axis
) determines where the split occurs, and all other dimensions remain unchanged. See the example section below for the most common use cases.- Parameters:
x (NDArray) –
The input array to be split, representing concatenated features, coefficients, or other data. The shape of
x
along the specified axis must match the total number of features generated by the basis, i.e.,self.n_output_features
.Examples:
For a design matrix:
(n_samples, total_n_features)
For model coefficients:
(total_n_features,)
or(total_n_features, n_neurons)
.
axis (int, optional) – The axis along which to split the features. Defaults to 1. Use
axis=1
for design matrices (features along columns) andaxis=0
for coefficient arrays (features along rows). All other dimensions are preserved.
- Raises:
ValueError – If the shape of
x
along the specified axis does not matchself.n_output_features
.- Returns:
A dictionary where:
Key: Label of the basis.
Value: the array reshaped to:
(..., n_inputs, n_basis_funcs, ...)
- Return type:
dict
- to_transformer()#
Turn the Basis into a TransformerBasis for use with scikit-learn.
- Return type:
Examples
Jointly cross-validating basis and GLM parameters with scikit-learn.
>>> import nemos as nmo >>> from sklearn.pipeline import Pipeline >>> from sklearn.model_selection import GridSearchCV >>> # load some data >>> X, y = np.random.normal(size=(30, 1)), np.random.poisson(size=30) >>> basis = nmo.basis.RaisedCosineLinearEval(10).set_input_shape(1).to_transformer() >>> glm = nmo.glm.GLM(regularizer="Ridge", regularizer_strength=1.) >>> pipeline = Pipeline([("basis", basis), ("glm", glm)]) >>> param_grid = dict( ... glm__regularizer_strength=(0.1, 0.01, 0.001, 1e-6), ... basis__n_basis_funcs=(3, 5, 10, 20, 100), ... ) >>> gridsearch = GridSearchCV( ... pipeline, ... param_grid=param_grid, ... cv=5, ... ) >>> gridsearch = gridsearch.fit(X, y)