models¶
Model classes for neuroimaging analysis.
Provides sklearn-compatible APIs for common neuroimaging analyses.
Classes:
| Name | Description |
|---|---|
BaseModel | Abstract base class for all nltools models. |
Glm | General Linear Model for fMRI data analysis with sklearn-compatible API. |
Ridge | Ridge regression with optional GPU acceleration and banded ridge support. |
Modules:
| Name | Description |
|---|---|
base | Base classes for nltools models. |
glm | GLM model for neuroimaging data. |
ridge | Ridge regression model for neuroimaging data. |
Classes¶
BaseModel¶
BaseModel() -> NoneBases: ABC
Abstract base class for all nltools models.
Follows scikit-learn API conventions:
fit(X, y) trains the model and returns self
predict(X) generates predictions
score(X, y) evaluates model performance
Attributes:
| Name | Type | Description |
|---|---|---|
n_features_in_ | int | Number of features seen during fit |
n_samples_ | int | Number of samples seen during fit |
is_fitted_ | bool | Whether the model has been fitted |
Methods:
| Name | Description |
|---|---|
fit | Fit the model to training data. |
predict | Generate predictions for new data. |
score | Evaluate model performance. |
Methods¶
fit¶
fit(X, y) -> BaseModelFit the model to training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Training data | required |
y | ndarray of shape (n_samples,) or (n_samples, n_targets) | Target values | required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseModel | BaseModel | Fitted model instance |
predict¶
predict(X) -> np.ndarray | listGenerate predictions for new data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Data to predict on | required |
Returns:
| Name | Type | Description |
|---|---|---|
ndarray | ndarray | list | Predicted values |
score¶
score(X, y) -> float | np.ndarrayEvaluate model performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Test data | required |
y | ndarray of shape (n_samples,) or (n_samples, n_targets) | True values | required |
Returns:
| Name | Type | Description |
|---|---|---|
float | float | ndarray | Model performance metric |
Glm¶
Glm(*, t_r: float | None = None, noise_model: str = 'ols', smoothing_fwhm: float | None = None, mask: nib.Nifti1Image | None = None, progress_bar: bool = False, **kwargs: bool) -> NoneBases: BaseModel
General Linear Model for fMRI data analysis with sklearn-compatible API.
Wraps nilearn.glm.first_level.FirstLevelModel using composition pattern, similar to how BrainData holds masker objects. Provides sklearn-style interface (fit/predict/score) while exposing full nilearn GLM functionality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t_r | float | Repetition time (TR) in seconds. If None, will be inferred from data. | None |
noise_model | str, default=‘ols’ | Noise model for temporal autocorrelation (‘ols’ or ‘ar1’). - ‘ols’: Ordinary Least Squares (assumes independent errors) - ‘ar1’: Autoregressive AR(1) model (accounts for temporal correlation) | ‘ols’ |
smoothing_fwhm | float | Full-Width at Half Maximum (FWHM) in mm for spatial smoothing. If None, no smoothing is applied. | None |
mask | Nifti1Image | Mask image defining voxels to include in analysis. If None, uses MNI template mask (default, like BrainData). | None |
**kwargs | Additional arguments passed to nilearn FirstLevelModel. | {} |
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted_ | bool | Whether the model has been fitted |
Note
Access fitted results via properties: glm_, residuals, design_matrices_
Methods:
| Name | Description |
|---|---|
compute_contrast | Compute contrast using nilearn for accurate statistical inference. |
fit | Fit GLM to fMRI data. |
predict | Predict from the fitted GLM. |
report | Generate a nilearn HTML report for the fitted GLM. |
score | Return mean R² across voxels and runs. |
Examples:
>>> from nltools.models import Glm
>>> from nilearn.glm.first_level import make_first_level_design_matrix
>>> import pandas as pd
>>> import numpy as np
>>> from nibabel import Nifti1Image
>>>
>>> # Create synthetic fMRI data
>>> n_scans = 100
>>> fmri_data = np.random.randn(n_scans, 20, 20, 20)
>>> img = Nifti1Image(fmri_data.T, np.eye(4))
>>>
>>> # Create design matrix
>>> frame_times = np.arange(n_scans) * 2.0
>>> events = pd.DataFrame({
... 'onset': [10, 30, 50, 70],
... 'duration': [1, 1, 1, 1],
... 'trial_type': ['task', 'task', 'task', 'task']
... })
>>> design_matrix = make_first_level_design_matrix(frame_times, events)
>>>
>>> # Fit GLM
>>> model = Glm(t_r=2.0, noise_model='ar1')
>>> model.fit(img, design_matrices=design_matrix)
>>>
>>> # Compute contrast
>>> task_effect = model.compute_contrast('task', output_type='stat')
>>>
>>> # Get fitted values
>>> fitted_values = model.predict()
>>>
>>> # Access residuals
>>> residuals = model.residualsNote
Unlike Ridge which works with 2D arrays (samples × features), Glm works with 4D neuroimaging data (x × y × z × time) and design matrices. Therefore, it does not use BaseModel’s input validation methods.
The predict() method follows sklearn’s LinearRegression semantics:
predict() returns fitted values (predictions on training data)
predict(X) returns X @ coef_ for a new design matrix (single-run fits)
For advanced use cases, access the internal FirstLevelModel via the glm_ property to use any nilearn-specific functionality.
Methods¶
compute_contrast¶
compute_contrast(contrast_def: str | np.ndarray | list | dict, output_type: str = 'stat') -> nib.Nifti1Image | dictCompute contrast using nilearn for accurate statistical inference.
This is the primary method for extracting results from a fitted GLM. Delegates to nilearn’s FirstLevelModel.compute_contrast() for proper statistical inference with correct degrees of freedom, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contrast_def | str, array-like, or dict | Contrast specification: - str: Regressor name (e.g., ‘task’) - array-like: Contrast vector (e.g., [1, -1, 0, 0]) - dict: Multiple contrasts with names as keys | required |
output_type | str, default=‘stat’ | Type of output to return: - ‘stat’: T-statistic map (default) - ‘z_score’: Z-score map - ‘p_value’: P-value map (one-sided, per the nilearn/SPM directional-contrast convention; flip the contrast for the other direction) - ‘effect_size’: Effect size (beta) map - ‘effect_variance’: Variance of effect size - ‘all’: Dictionary with all output types | ‘stat’ |
Returns:
| Type | Description |
|---|---|
Nifti1Image | dict | Nifti1Image or dict: Contrast map(s). If output_type=‘all’, returns dict with all maps. |
Examples:
>>> # After fitting model
>>> model.fit(img, design_matrices=design_matrix)
>>>
>>> # Simple contrast by name
>>> t_map = model.compute_contrast('task')
>>>
>>> # Contrast vector
>>> contrast_map = model.compute_contrast([1, -1, 0])
>>>
>>> # Get all outputs
>>> results = model.compute_contrast('task', output_type='all')
>>> t_map = results['stat']
>>> p_map = results['p_value']fit¶
fit(X: nib.Nifti1Image | list[nib.Nifti1Image], y: None = None, *, design_matrices: pd.DataFrame | DesignMatrix | list[pd.DataFrame | DesignMatrix] | None = None, events: pd.DataFrame | list[pd.DataFrame] | None = None, **kwargs: pd.DataFrame | list[pd.DataFrame] | None) -> GlmFit GLM to fMRI data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | Nifti1Image or list of Nifti1Image | 4D fMRI image(s) to fit. Can be single run or list of runs. | required |
y | None | Not used, present for sklearn API compatibility. | None |
design_matrices | DataFrame, DesignMatrix, or list of DataFrame/DesignMatrix | Design matrix or list of design matrices (one per run). Each should have shape (n_scans, n_regressors). Accepts both pandas DataFrames and nltools DesignMatrix objects. | None |
events | DataFrame or list of DataFrame | Event specifications for automatic design matrix creation. Alternative to providing design_matrices directly. | None |
**kwargs | Additional arguments passed to FirstLevelModel.fit() | {} |
Returns:
| Name | Type | Description |
|---|---|---|
Glm | Glm | Fitted model instance (for method chaining) |
Note
Unlike BaseModel’s fit(), this method does not validate X as a 2D array because GLM works with 4D neuroimaging data. Input validation is delegated to nilearn’s FirstLevelModel.
DesignMatrix objects are automatically converted to pandas DataFrames for nilearn compatibility. The conversion is done at this boundary to keep DesignMatrix Polars-native while maintaining nilearn integration.
predict¶
predict(X: np.ndarray | pd.DataFrame | None = None) -> list[nib.Nifti1Image] | np.ndarrayPredict from the fitted GLM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | array-like, DataFrame, or None, default=None | Design matrix to predict from. - None: return the fitted values on the training data (a list of Nifti1Image, one per run), matching sklearn’s LinearRegression semantics. - array-like of shape (n_samples, n_regressors): return X @ coef_ as a 2-D ndarray (n_samples, n_voxels), mirroring Ridge.predict. Requires a single-run fit. | None |
Returns:
| Type | Description |
|---|---|
list [ Nifti1Image ] | ndarray | list of Nifti1Image or ndarray: Fitted values (X is None) or new-X predictions (X given). |
report¶
report(contrasts = None, **kwargs)Generate a nilearn HTML report for the fitted GLM.
Delegates to the underlying FirstLevelModel.generate_report, which
renders the design matrix, requested contrast maps, and model
parameters as a self-contained HTML report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contrasts | str, list, or dict | Contrast(s) to render, same forms as compute_contrast. | None |
**kwargs | Additional arguments forwarded to nilearn’s generate_report (e.g. title, threshold, alpha). | {} |
Returns:
| Name | Type | Description |
|---|---|---|
HTMLReport | nilearn report object; call .save_as_html(path) or display it in a notebook. |
score¶
score(X: None = None, y: None = None) -> floatReturn mean R² across voxels and runs.
Computes average coefficient of determination (R²) from the fitted GLM. Higher values indicate better model fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | None | Not used, present for sklearn API compatibility. | None |
y | None | Not used, present for sklearn API compatibility. | None |
Returns:
| Name | Type | Description |
|---|---|---|
float | float | Mean R² across all voxels and runs. Range: [0, 1], higher is better. |
Note
Extracts R² values from nilearn’s FirstLevelModel.r_square attribute, which returns a list of Nifti1Image objects (one per run). Computes the mean across all non-NaN voxels and all runs.
For voxel-wise R² maps, access glm_.r_square directly.
Examples:
>>> brain.fit(model='glm', X=design_matrix)
>>> r2 = brain.model_.score()
>>> print(f"Mean R²: {r2:.3f}")Ridge¶
Ridge(*, alpha: float | str = 1.0, cv: int | None = None, alphas: list[float] | np.ndarray | None = None, n_iter: int = 100, concentration: float | list[float] | None = None, device: str = 'cpu', local_alpha: bool = True, fit_intercept: bool = False, conservative: bool = False, random_state: int | None = None, progress_bar: bool = False) -> NoneBases: BaseModel
Ridge regression with optional GPU acceleration and banded ridge support.
Wraps nltools SVD-based ridge regression algorithms with scikit-learn compatible API. Supports single and multi-target regression with optional GPU acceleration via PyTorch.
Supports both regular ridge (single feature space) and banded ridge (multiple feature spaces). The model automatically detects the input type:
Array X: Single feature space → uses solve_ridge_cv
List X: Multiple feature spaces → uses solve_banded_ridge_cv (true banded/group ridge)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float or ‘auto’, default=1.0 | Regularization strength. If ‘auto’, uses cross-validation to select optimal alpha from alphas parameter. | 1.0 |
cv | int or None, default=None | Number of cross-validation folds (only used if alpha=‘auto’) | None |
alphas | array-like or None, default=None | Alpha values to try during cross-validation. Defaults to [0.1, 1.0, 10.0] if None. | None |
n_iter | int, default=100 | Number of random search iterations. Only used when X is a list (multiple feature spaces). Ignored for single feature space. | 100 |
concentration | float or list, default=[0.1, 1.0] | Concentration parameters for Dirichlet sampling. Only used when X is a list (multiple feature spaces). - A value of 1 corresponds to uniform sampling over the simplex. - A value of infinity corresponds to equal weights. - If a list, samples cycle through the list. | None |
device | str, default=‘cpu’ | Compute device. One of 'cpu' (NumPy), 'gpu' (PyTorch on CUDA/MPS when available, else torch-CPU), or 'auto' (use a GPU if one is present, otherwise NumPy). Selects where the SVD/CV math runs; distinct from any CPU-core parallelism. | ‘cpu’ |
local_alpha | bool, default=True | If True, select best alpha independently for each target. If False, select single best alpha for all targets. | True |
fit_intercept | bool, default=False | Whether to fit an intercept. | False |
conservative | bool, default=False | If True, select largest alpha within 1 std of best score (more regularization). | False |
random_state | int or None, default=None | Random seed for reproducibility (used for CV splits and random search) | None |
progress_bar | bool, default=False | Whether to display progress bar during banded ridge fitting (when X is a list). Requires tqdm. Not used for single feature space ridge regression. | False |
Attributes:
| Name | Type | Description |
|---|---|---|
coef_ | ndarray of shape (n_features,) or (n_features, n_targets | Ridge coefficients |
alpha_ | float or ndarray | Alpha value(s) used (selected via CV if alpha=‘auto’) |
cv_scores_ | ndarray | Cross-validation scores (only if alpha=‘auto’) |
deltas_ | ndarray or None | Feature space weights (only if X was a list) Shape: (n_spaces, n_targets). deltas = log(gamma / alpha) |
backend_ | Backend | Resolved backend instance used for computation (its .name reports the concrete device, e.g. 'torch-cuda'). |
Methods:
| Name | Description |
|---|---|
fit | Fit ridge regression model. |
predict | Predict using the ridge model. |
score | Return the coefficient of determination R^2 of the prediction. |
Examples:
>>> from nltools.models import Ridge
>>> import numpy as np
>>> X = np.random.randn(100, 50)
>>> y = np.random.randn(100)
>>> model = Ridge(alpha=1.0)
>>> model.fit(X, y)
Ridge(alpha=1.0, device='cpu')
>>> y_pred = model.predict(X)
>>>
>>> # Banded ridge with multiple feature spaces (automatic detection)
>>> X1 = np.random.randn(100, 30)
>>> X2 = np.random.randn(100, 20)
>>> model = Ridge(alpha='auto', cv=5, n_iter=50)
>>> model.fit([X1, X2], y)
>>> print(f"Feature space weights: {model.deltas_}")Methods¶
fit¶
fit(X: np.ndarray | list[np.ndarray], y: np.ndarray) -> RidgeFit ridge regression model.
Supports both regular ridge (single feature space) and banded ridge (multiple feature spaces). If X is a list, banded ridge is used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) or list of arrays | Training data. If list, each element is a feature space for banded ridge. | required |
y | ndarray of shape (n_samples,) or (n_samples, n_targets) | Target values | required |
Returns:
| Name | Type | Description |
|---|---|---|
Ridge | Ridge | Fitted model instance |
predict¶
predict(X: np.ndarray) -> np.ndarrayPredict using the ridge model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Samples to predict | required |
Returns:
| Type | Description |
|---|---|
ndarray | ndarray of shape (n_samples,) or (n_samples, n_targets): Predicted values |
score¶
score(X: np.ndarray, y: np.ndarray) -> float | np.ndarrayReturn the coefficient of determination R^2 of the prediction.
For multi-target regression (y is 2D), returns per-target R² scores. For single-target regression (y is 1D), returns a scalar R².
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Test samples | required |
y | ndarray of shape (n_samples,) or (n_samples, n_targets) | True values for X | required |
Returns:
| Type | Description |
|---|---|
float | ndarray | float or ndarray: - If y is 1D: scalar R² - If y is 2D: array of shape (n_targets,) with per-target R² scores |
Modules¶
base¶
Base classes for nltools models.
Provides sklearn-compatible API for neuroimaging analysis.
Classes:
| Name | Description |
|---|---|
BaseModel | Abstract base class for all nltools models. |
Classes¶
BaseModel¶
BaseModel() -> NoneBases: ABC
Abstract base class for all nltools models.
Follows scikit-learn API conventions:
fit(X, y) trains the model and returns self
predict(X) generates predictions
score(X, y) evaluates model performance
Attributes:
| Name | Type | Description |
|---|---|---|
n_features_in_ | int | Number of features seen during fit |
n_samples_ | int | Number of samples seen during fit |
is_fitted_ | bool | Whether the model has been fitted |
Methods:
| Name | Description |
|---|---|
fit | Fit the model to training data. |
predict | Generate predictions for new data. |
score | Evaluate model performance. |
####### Attributes##
is_fitted_¶
is_fitted_ = False####### Functions##
fit¶
fit(X, y) -> BaseModelFit the model to training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Training data | required |
y | ndarray of shape (n_samples,) or (n_samples, n_targets) | Target values | required |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Data to predict on | required |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Test data | required |
y | ndarray of shape (n_samples,) or (n_samples, n_targets) | True values | required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseModel | BaseModel | Fitted model instance |
######## predict
predict(X) -> np.ndarray | listGenerate predictions for new data.
Returns:
| Name | Type | Description |
|---|---|---|
ndarray | ndarray | list | Predicted values |
######## score
score(X, y) -> float | np.ndarrayEvaluate model performance.
Returns:
| Name | Type | Description |
|---|---|---|
float | float | ndarray | Model performance metric |
glm¶
GLM model for neuroimaging data.
Wraps nilearn.glm.first_level.FirstLevelModel with sklearn-compatible API.
Classes:
| Name | Description |
|---|---|
Glm | General Linear Model for fMRI data analysis with sklearn-compatible API. |
Classes¶
Glm¶
Glm(*, t_r: float | None = None, noise_model: str = 'ols', smoothing_fwhm: float | None = None, mask: nib.Nifti1Image | None = None, progress_bar: bool = False, **kwargs: bool) -> NoneBases: BaseModel
General Linear Model for fMRI data analysis with sklearn-compatible API.
Wraps nilearn.glm.first_level.FirstLevelModel using composition pattern, similar to how BrainData holds masker objects. Provides sklearn-style interface (fit/predict/score) while exposing full nilearn GLM functionality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t_r | float | Repetition time (TR) in seconds. If None, will be inferred from data. | None |
noise_model | str, default=‘ols’ | Noise model for temporal autocorrelation (‘ols’ or ‘ar1’). - ‘ols’: Ordinary Least Squares (assumes independent errors) - ‘ar1’: Autoregressive AR(1) model (accounts for temporal correlation) | ‘ols’ |
smoothing_fwhm | float | Full-Width at Half Maximum (FWHM) in mm for spatial smoothing. If None, no smoothing is applied. | None |
mask | Nifti1Image | Mask image defining voxels to include in analysis. If None, uses MNI template mask (default, like BrainData). | None |
**kwargs | Additional arguments passed to nilearn FirstLevelModel. | {} |
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted_ | bool | Whether the model has been fitted |
Note
Access fitted results via properties: glm_, residuals, design_matrices_
Methods:
| Name | Description |
|---|---|
compute_contrast | Compute contrast using nilearn for accurate statistical inference. |
fit | Fit GLM to fMRI data. |
predict | Predict from the fitted GLM. |
report | Generate a nilearn HTML report for the fitted GLM. |
score | Return mean R² across voxels and runs. |
####### Attributes##
Examples:
>>> from nltools.models import Glm
>>> from nilearn.glm.first_level import make_first_level_design_matrix
>>> import pandas as pd
>>> import numpy as np
>>> from nibabel import Nifti1Image
>>>
>>> # Create synthetic fMRI data
>>> n_scans = 100
>>> fmri_data = np.random.randn(n_scans, 20, 20, 20)
>>> img = Nifti1Image(fmri_data.T, np.eye(4))
>>>
>>> # Create design matrix
>>> frame_times = np.arange(n_scans) * 2.0
>>> events = pd.DataFrame({
... 'onset': [10, 30, 50, 70],
... 'duration': [1, 1, 1, 1],
... 'trial_type': ['task', 'task', 'task', 'task']
... })
>>> design_matrix = make_first_level_design_matrix(frame_times, events)
>>>
>>> # Fit GLM
>>> model = Glm(t_r=2.0, noise_model='ar1')
>>> model.fit(img, design_matrices=design_matrix)
>>>
>>> # Compute contrast
>>> task_effect = model.compute_contrast('task', output_type='stat')
>>>
>>> # Get fitted values
>>> fitted_values = model.predict()
>>>
>>> # Access residuals
>>> residuals = model.residualsNote
Unlike Ridge which works with 2D arrays (samples × features), Glm works with 4D neuroimaging data (x × y × z × time) and design matrices. Therefore, it does not use BaseModel’s input validation methods.
The predict() method follows sklearn’s LinearRegression semantics:
predict() returns fitted values (predictions on training data)
predict(X) returns X @ coef_ for a new design matrix (single-run fits)
For advanced use cases, access the internal FirstLevelModel via the glm_ property to use any nilearn-specific functionality.
design_matrices_¶
design_matrices_: list[pd.DataFrame]Design matrices used in fitting.
Returns:
| Type | Description |
|---|---|
list [ DataFrame ] | list of DataFrame: Design matrices for each run |
######## glm_
glm_: FirstLevelModelAccess internal FirstLevelModel for advanced use.
Provides direct access to the wrapped nilearn FirstLevelModel instance for advanced users who need functionality not exposed by the sklearn-compatible interface.
Returns:
| Name | Type | Description |
|---|---|---|
FirstLevelModel | FirstLevelModel | Internal nilearn FirstLevelModel instance |
Examples:
>>> # Access nilearn-specific attributes
>>> model.glm_.labels_
>>> model.glm_.results_
>>>
>>> # Use nilearn-specific methods
>>> model.glm_.generate_report()######## is_fitted_
is_fitted_ = False######## mask
mask = nib.load(get_brainspace().mask)######## noise_model
noise_model = noise_model######## progress_bar
progress_bar = progress_bar######## residuals
residuals: list[nib.Nifti1Image]Residuals from fitted GLM.
Returns:
| Type | Description |
|---|---|
list [ Nifti1Image ] | list of Nifti1Image: Residual images for each run (observed - predicted) |
######## smoothing_fwhm
smoothing_fwhm = smoothing_fwhm######## t_r
t_r = t_r####### Functions##
compute_contrast¶
compute_contrast(contrast_def: str | np.ndarray | list | dict, output_type: str = 'stat') -> nib.Nifti1Image | dictCompute contrast using nilearn for accurate statistical inference.
This is the primary method for extracting results from a fitted GLM. Delegates to nilearn’s FirstLevelModel.compute_contrast() for proper statistical inference with correct degrees of freedom, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contrast_def | str, array-like, or dict | Contrast specification: - str: Regressor name (e.g., ‘task’) - array-like: Contrast vector (e.g., [1, -1, 0, 0]) - dict: Multiple contrasts with names as keys | required |
output_type | str, default=‘stat’ | Type of output to return: - ‘stat’: T-statistic map (default) - ‘z_score’: Z-score map - ‘p_value’: P-value map (one-sided, per the nilearn/SPM directional-contrast convention; flip the contrast for the other direction) - ‘effect_size’: Effect size (beta) map - ‘effect_variance’: Variance of effect size - ‘all’: Dictionary with all output types | ‘stat’ |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | Nifti1Image or list of Nifti1Image | 4D fMRI image(s) to fit. Can be single run or list of runs. | required |
y | None | Not used, present for sklearn API compatibility. | None |
design_matrices | DataFrame, DesignMatrix, or list of DataFrame/DesignMatrix | Design matrix or list of design matrices (one per run). Each should have shape (n_scans, n_regressors). Accepts both pandas DataFrames and nltools DesignMatrix objects. | None |
events | DataFrame or list of DataFrame | Event specifications for automatic design matrix creation. Alternative to providing design_matrices directly. | None |
**kwargs | Additional arguments passed to FirstLevelModel.fit() | {} |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | array-like, DataFrame, or None, default=None | Design matrix to predict from. - None: return the fitted values on the training data (a list of Nifti1Image, one per run), matching sklearn’s LinearRegression semantics. - array-like of shape (n_samples, n_regressors): return X @ coef_ as a 2-D ndarray (n_samples, n_voxels), mirroring Ridge.predict. Requires a single-run fit. | None |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contrasts | str, list, or dict | Contrast(s) to render, same forms as compute_contrast. | None |
**kwargs | Additional arguments forwarded to nilearn’s generate_report (e.g. title, threshold, alpha). | {} |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | None | Not used, present for sklearn API compatibility. | None |
y | None | Not used, present for sklearn API compatibility. | None |
Returns:
| Type | Description |
|---|---|
Nifti1Image | dict | Nifti1Image or dict: Contrast map(s). If output_type=‘all’, returns dict with all maps. |
Examples:
>>> # After fitting model
>>> model.fit(img, design_matrices=design_matrix)
>>>
>>> # Simple contrast by name
>>> t_map = model.compute_contrast('task')
>>>
>>> # Contrast vector
>>> contrast_map = model.compute_contrast([1, -1, 0])
>>>
>>> # Get all outputs
>>> results = model.compute_contrast('task', output_type='all')
>>> t_map = results['stat']
>>> p_map = results['p_value']######## fit
fit(X: nib.Nifti1Image | list[nib.Nifti1Image], y: None = None, *, design_matrices: pd.DataFrame | DesignMatrix | list[pd.DataFrame | DesignMatrix] | None = None, events: pd.DataFrame | list[pd.DataFrame] | None = None, **kwargs: pd.DataFrame | list[pd.DataFrame] | None) -> GlmFit GLM to fMRI data.
Returns:
| Name | Type | Description |
|---|---|---|
Glm | Glm | Fitted model instance (for method chaining) |
Note
Unlike BaseModel’s fit(), this method does not validate X as a 2D array because GLM works with 4D neuroimaging data. Input validation is delegated to nilearn’s FirstLevelModel.
DesignMatrix objects are automatically converted to pandas DataFrames for nilearn compatibility. The conversion is done at this boundary to keep DesignMatrix Polars-native while maintaining nilearn integration.
######## predict
predict(X: np.ndarray | pd.DataFrame | None = None) -> list[nib.Nifti1Image] | np.ndarrayPredict from the fitted GLM.
Returns:
| Type | Description |
|---|---|
list [ Nifti1Image ] | ndarray | list of Nifti1Image or ndarray: Fitted values (X is None) or new-X predictions (X given). |
######## report
report(contrasts = None, **kwargs)Generate a nilearn HTML report for the fitted GLM.
Delegates to the underlying FirstLevelModel.generate_report, which
renders the design matrix, requested contrast maps, and model
parameters as a self-contained HTML report.
Returns:
| Name | Type | Description |
|---|---|---|
HTMLReport | nilearn report object; call .save_as_html(path) or display it in a notebook. |
######## score
score(X: None = None, y: None = None) -> floatReturn mean R² across voxels and runs.
Computes average coefficient of determination (R²) from the fitted GLM. Higher values indicate better model fit.
Returns:
| Name | Type | Description |
|---|---|---|
float | float | Mean R² across all voxels and runs. Range: [0, 1], higher is better. |
Note
Extracts R² values from nilearn’s FirstLevelModel.r_square attribute, which returns a list of Nifti1Image objects (one per run). Computes the mean across all non-NaN voxels and all runs.
For voxel-wise R² maps, access glm_.r_square directly.
Examples:
>>> brain.fit(model='glm', X=design_matrix)
>>> r2 = brain.model_.score()
>>> print(f"Mean R²: {r2:.3f}")Methods¶
ridge¶
Ridge regression model for neuroimaging data.
Wraps nltools.algorithms.ridge with sklearn-compatible API. Supports both regular ridge (single feature space) and banded ridge (multiple feature spaces) with optional random search over feature weights.
Classes:
| Name | Description |
|---|---|
Ridge | Ridge regression with optional GPU acceleration and banded ridge support. |
Classes¶
Ridge¶
Ridge(*, alpha: float | str = 1.0, cv: int | None = None, alphas: list[float] | np.ndarray | None = None, n_iter: int = 100, concentration: float | list[float] | None = None, device: str = 'cpu', local_alpha: bool = True, fit_intercept: bool = False, conservative: bool = False, random_state: int | None = None, progress_bar: bool = False) -> NoneBases: BaseModel
Ridge regression with optional GPU acceleration and banded ridge support.
Wraps nltools SVD-based ridge regression algorithms with scikit-learn compatible API. Supports single and multi-target regression with optional GPU acceleration via PyTorch.
Supports both regular ridge (single feature space) and banded ridge (multiple feature spaces). The model automatically detects the input type:
Array X: Single feature space → uses solve_ridge_cv
List X: Multiple feature spaces → uses solve_banded_ridge_cv (true banded/group ridge)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha | float or ‘auto’, default=1.0 | Regularization strength. If ‘auto’, uses cross-validation to select optimal alpha from alphas parameter. | 1.0 |
cv | int or None, default=None | Number of cross-validation folds (only used if alpha=‘auto’) | None |
alphas | array-like or None, default=None | Alpha values to try during cross-validation. Defaults to [0.1, 1.0, 10.0] if None. | None |
n_iter | int, default=100 | Number of random search iterations. Only used when X is a list (multiple feature spaces). Ignored for single feature space. | 100 |
concentration | float or list, default=[0.1, 1.0] | Concentration parameters for Dirichlet sampling. Only used when X is a list (multiple feature spaces). - A value of 1 corresponds to uniform sampling over the simplex. - A value of infinity corresponds to equal weights. - If a list, samples cycle through the list. | None |
device | str, default=‘cpu’ | Compute device. One of 'cpu' (NumPy), 'gpu' (PyTorch on CUDA/MPS when available, else torch-CPU), or 'auto' (use a GPU if one is present, otherwise NumPy). Selects where the SVD/CV math runs; distinct from any CPU-core parallelism. | ‘cpu’ |
local_alpha | bool, default=True | If True, select best alpha independently for each target. If False, select single best alpha for all targets. | True |
fit_intercept | bool, default=False | Whether to fit an intercept. | False |
conservative | bool, default=False | If True, select largest alpha within 1 std of best score (more regularization). | False |
random_state | int or None, default=None | Random seed for reproducibility (used for CV splits and random search) | None |
progress_bar | bool, default=False | Whether to display progress bar during banded ridge fitting (when X is a list). Requires tqdm. Not used for single feature space ridge regression. | False |
Attributes:
| Name | Type | Description |
|---|---|---|
coef_ | ndarray of shape (n_features,) or (n_features, n_targets | Ridge coefficients |
alpha_ | float or ndarray | Alpha value(s) used (selected via CV if alpha=‘auto’) |
cv_scores_ | ndarray | Cross-validation scores (only if alpha=‘auto’) |
deltas_ | ndarray or None | Feature space weights (only if X was a list) Shape: (n_spaces, n_targets). deltas = log(gamma / alpha) |
backend_ | Backend | Resolved backend instance used for computation (its .name reports the concrete device, e.g. 'torch-cuda'). |
Methods:
| Name | Description |
|---|---|
fit | Fit ridge regression model. |
predict | Predict using the ridge model. |
score | Return the coefficient of determination R^2 of the prediction. |
####### Attributes##
Examples:
>>> from nltools.models import Ridge
>>> import numpy as np
>>> X = np.random.randn(100, 50)
>>> y = np.random.randn(100)
>>> model = Ridge(alpha=1.0)
>>> model.fit(X, y)
Ridge(alpha=1.0, device='cpu')
>>> y_pred = model.predict(X)
>>>
>>> # Banded ridge with multiple feature spaces (automatic detection)
>>> X1 = np.random.randn(100, 30)
>>> X2 = np.random.randn(100, 20)
>>> model = Ridge(alpha='auto', cv=5, n_iter=50)
>>> model.fit([X1, X2], y)
>>> print(f"Feature space weights: {model.deltas_}")alpha¶
alpha = alpha######## alphas
alphas = alphas if alphas is not None else [0.1, 1.0, 10.0]######## concentration
concentration = [0.1, 1.0] if concentration is None else concentration######## conservative
conservative = conservative######## cv
cv = cv######## device
device = device######## fit_intercept
fit_intercept = fit_intercept######## is_fitted_
is_fitted_ = False######## local_alpha
local_alpha = local_alpha######## n_iter
n_iter = n_iter######## progress_bar
progress_bar = progress_bar######## random_state
random_state = random_state####### Functions##
fit¶
fit(X: np.ndarray | list[np.ndarray], y: np.ndarray) -> RidgeFit ridge regression model.
Supports both regular ridge (single feature space) and banded ridge (multiple feature spaces). If X is a list, banded ridge is used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) or list of arrays | Training data. If list, each element is a feature space for banded ridge. | required |
y | ndarray of shape (n_samples,) or (n_samples, n_targets) | Target values | required |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Samples to predict | required |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X | ndarray of shape (n_samples, n_features) | Test samples | required |
y | ndarray of shape (n_samples,) or (n_samples, n_targets) | True values for X | required |
Returns:
| Name | Type | Description |
|---|---|---|
Ridge | Ridge | Fitted model instance |
######## predict
predict(X: np.ndarray) -> np.ndarrayPredict using the ridge model.
Returns:
| Type | Description |
|---|---|
ndarray | ndarray of shape (n_samples,) or (n_samples, n_targets): Predicted values |
######## score
score(X: np.ndarray, y: np.ndarray) -> float | np.ndarrayReturn the coefficient of determination R^2 of the prediction.
For multi-target regression (y is 2D), returns per-target R² scores. For single-target regression (y is 1D), returns a scalar R².
Returns:
| Type | Description |
|---|---|
float | ndarray | float or ndarray: - If y is 1D: scalar R² - If y is 2D: array of shape (n_targets,) with per-target R² scores |