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.

models

models

Model classes for neuroimaging analysis.

Provides sklearn-compatible APIs for common neuroimaging analyses.

Classes:

NameDescription
BaseModelAbstract base class for all nltools models.
GlmGeneral Linear Model for fMRI data analysis with sklearn-compatible API.
RidgeRidge regression with optional GPU acceleration and banded ridge support.

Modules:

NameDescription
baseBase classes for nltools models.
glmGLM model for neuroimaging data.
ridgeRidge regression model for neuroimaging data.

Classes

BaseModel

BaseModel() -> None

Bases: ABC

Abstract base class for all nltools models.

Follows scikit-learn API conventions:

Attributes:

NameTypeDescription
n_features_in_intNumber of features seen during fit
n_samples_intNumber of samples seen during fit
is_fitted_boolWhether the model has been fitted

Methods:

NameDescription
fitFit the model to training data.
predictGenerate predictions for new data.
scoreEvaluate model performance.

Methods

fit
fit(X, y) -> BaseModel

Fit the model to training data.

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Training datarequired
yndarray of shape (n_samples,) or (n_samples, n_targets)Target valuesrequired

Returns:

NameTypeDescription
BaseModelBaseModelFitted model instance
predict
predict(X) -> np.ndarray | list

Generate predictions for new data.

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Data to predict onrequired

Returns:

NameTypeDescription
ndarrayndarray | listPredicted values
score
score(X, y) -> float | np.ndarray

Evaluate model performance.

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Test datarequired
yndarray of shape (n_samples,) or (n_samples, n_targets)True valuesrequired

Returns:

NameTypeDescription
floatfloat | ndarrayModel 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) -> None

Bases: 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:

NameTypeDescriptionDefault
t_rfloatRepetition time (TR) in seconds. If None, will be inferred from data.None
noise_modelstr, 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_fwhmfloatFull-Width at Half Maximum (FWHM) in mm for spatial smoothing. If None, no smoothing is applied.None
maskNifti1ImageMask image defining voxels to include in analysis. If None, uses MNI template mask (default, like BrainData).None
**kwargsAdditional arguments passed to nilearn FirstLevelModel.{}

Attributes:

NameTypeDescription
is_fitted_boolWhether the model has been fitted
Note

Access fitted results via properties: glm_, residuals, design_matrices_

Methods:

NameDescription
compute_contrastCompute contrast using nilearn for accurate statistical inference.
fitFit GLM to fMRI data.
predictPredict from the fitted GLM.
reportGenerate a nilearn HTML report for the fitted GLM.
scoreReturn 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.residuals
Note

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 | dict

Compute 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:

NameTypeDescriptionDefault
contrast_defstr, array-like, or dictContrast specification: - str: Regressor name (e.g., ‘task’) - array-like: Contrast vector (e.g., [1, -1, 0, 0]) - dict: Multiple contrasts with names as keysrequired
output_typestr, 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:

TypeDescription
Nifti1Image | dictNifti1Image 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) -> Glm

Fit GLM to fMRI data.

Parameters:

NameTypeDescriptionDefault
XNifti1Image or list of Nifti1Image4D fMRI image(s) to fit. Can be single run or list of runs.required
yNoneNot used, present for sklearn API compatibility.None
design_matricesDataFrame, DesignMatrix, or list of DataFrame/DesignMatrixDesign 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
eventsDataFrame or list of DataFrameEvent specifications for automatic design matrix creation. Alternative to providing design_matrices directly.None
**kwargsAdditional arguments passed to FirstLevelModel.fit(){}

Returns:

NameTypeDescription
GlmGlmFitted 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.ndarray

Predict from the fitted GLM.

Parameters:

NameTypeDescriptionDefault
Xarray-like, DataFrame, or None, default=NoneDesign 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:

TypeDescription
list [ Nifti1Image ] | ndarraylist 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:

NameTypeDescriptionDefault
contrastsstr, list, or dictContrast(s) to render, same forms as compute_contrast.None
**kwargsAdditional arguments forwarded to nilearn’s generate_report (e.g. title, threshold, alpha).{}

Returns:

NameTypeDescription
HTMLReportnilearn report object; call .save_as_html(path) or display it in a notebook.
score
score(X: None = None, y: None = None) -> float

Return mean R² across voxels and runs.

Computes average coefficient of determination (R²) from the fitted GLM. Higher values indicate better model fit.

Parameters:

NameTypeDescriptionDefault
XNoneNot used, present for sklearn API compatibility.None
yNoneNot used, present for sklearn API compatibility.None

Returns:

NameTypeDescription
floatfloatMean 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) -> None

Bases: 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:

Parameters:

NameTypeDescriptionDefault
alphafloat or ‘auto’, default=1.0Regularization strength. If ‘auto’, uses cross-validation to select optimal alpha from alphas parameter.1.0
cvint or None, default=NoneNumber of cross-validation folds (only used if alpha=‘auto’)None
alphasarray-like or None, default=NoneAlpha values to try during cross-validation. Defaults to [0.1, 1.0, 10.0] if None.None
n_iterint, default=100Number of random search iterations. Only used when X is a list (multiple feature spaces). Ignored for single feature space.100
concentrationfloat 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
devicestr, 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_alphabool, default=TrueIf True, select best alpha independently for each target. If False, select single best alpha for all targets.True
fit_interceptbool, default=FalseWhether to fit an intercept.False
conservativebool, default=FalseIf True, select largest alpha within 1 std of best score (more regularization).False
random_stateint or None, default=NoneRandom seed for reproducibility (used for CV splits and random search)None
progress_barbool, default=FalseWhether 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:

NameTypeDescription
coef_ndarray of shape (n_features,) or (n_features, n_targetsRidge coefficients
alpha_float or ndarrayAlpha value(s) used (selected via CV if alpha=‘auto’)
cv_scores_ndarrayCross-validation scores (only if alpha=‘auto’)
deltas_ndarray or NoneFeature space weights (only if X was a list) Shape: (n_spaces, n_targets). deltas = log(gamma / alpha)
backend_BackendResolved backend instance used for computation (its .name reports the concrete device, e.g. 'torch-cuda').

Methods:

NameDescription
fitFit ridge regression model.
predictPredict using the ridge model.
scoreReturn 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) -> Ridge

Fit 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:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features) or list of arraysTraining data. If list, each element is a feature space for banded ridge.required
yndarray of shape (n_samples,) or (n_samples, n_targets)Target valuesrequired

Returns:

NameTypeDescription
RidgeRidgeFitted model instance
predict
predict(X: np.ndarray) -> np.ndarray

Predict using the ridge model.

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Samples to predictrequired

Returns:

TypeDescription
ndarrayndarray of shape (n_samples,) or (n_samples, n_targets): Predicted values
score
score(X: np.ndarray, y: np.ndarray) -> float | np.ndarray

Return 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:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Test samplesrequired
yndarray of shape (n_samples,) or (n_samples, n_targets)True values for Xrequired

Returns:

TypeDescription
float | ndarrayfloat 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:

NameDescription
BaseModelAbstract base class for all nltools models.

Classes

BaseModel
BaseModel() -> None

Bases: ABC

Abstract base class for all nltools models.

Follows scikit-learn API conventions:

Attributes:

NameTypeDescription
n_features_in_intNumber of features seen during fit
n_samples_intNumber of samples seen during fit
is_fitted_boolWhether the model has been fitted

Methods:

NameDescription
fitFit the model to training data.
predictGenerate predictions for new data.
scoreEvaluate model performance.

####### Attributes##

is_fitted_
is_fitted_ = False

####### Functions##

fit
fit(X, y) -> BaseModel

Fit the model to training data.

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Training datarequired
yndarray of shape (n_samples,) or (n_samples, n_targets)Target valuesrequired

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Data to predict onrequired

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Test datarequired
yndarray of shape (n_samples,) or (n_samples, n_targets)True valuesrequired

Returns:

NameTypeDescription
BaseModelBaseModelFitted model instance

######## predict

predict(X) -> np.ndarray | list

Generate predictions for new data.

Returns:

NameTypeDescription
ndarrayndarray | listPredicted values

######## score

score(X, y) -> float | np.ndarray

Evaluate model performance.

Returns:

NameTypeDescription
floatfloat | ndarrayModel performance metric

glm

GLM model for neuroimaging data.

Wraps nilearn.glm.first_level.FirstLevelModel with sklearn-compatible API.

Classes:

NameDescription
GlmGeneral 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) -> None

Bases: 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:

NameTypeDescriptionDefault
t_rfloatRepetition time (TR) in seconds. If None, will be inferred from data.None
noise_modelstr, 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_fwhmfloatFull-Width at Half Maximum (FWHM) in mm for spatial smoothing. If None, no smoothing is applied.None
maskNifti1ImageMask image defining voxels to include in analysis. If None, uses MNI template mask (default, like BrainData).None
**kwargsAdditional arguments passed to nilearn FirstLevelModel.{}

Attributes:

NameTypeDescription
is_fitted_boolWhether the model has been fitted
Note

Access fitted results via properties: glm_, residuals, design_matrices_

Methods:

NameDescription
compute_contrastCompute contrast using nilearn for accurate statistical inference.
fitFit GLM to fMRI data.
predictPredict from the fitted GLM.
reportGenerate a nilearn HTML report for the fitted GLM.
scoreReturn 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.residuals
Note

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:

TypeDescription
list [ DataFrame ]list of DataFrame: Design matrices for each run

######## glm_

glm_: FirstLevelModel

Access 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:

NameTypeDescription
FirstLevelModelFirstLevelModelInternal 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:

TypeDescription
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 | dict

Compute 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:

NameTypeDescriptionDefault
contrast_defstr, array-like, or dictContrast specification: - str: Regressor name (e.g., ‘task’) - array-like: Contrast vector (e.g., [1, -1, 0, 0]) - dict: Multiple contrasts with names as keysrequired
output_typestr, 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:

NameTypeDescriptionDefault
XNifti1Image or list of Nifti1Image4D fMRI image(s) to fit. Can be single run or list of runs.required
yNoneNot used, present for sklearn API compatibility.None
design_matricesDataFrame, DesignMatrix, or list of DataFrame/DesignMatrixDesign 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
eventsDataFrame or list of DataFrameEvent specifications for automatic design matrix creation. Alternative to providing design_matrices directly.None
**kwargsAdditional arguments passed to FirstLevelModel.fit(){}

Parameters:

NameTypeDescriptionDefault
Xarray-like, DataFrame, or None, default=NoneDesign 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:

NameTypeDescriptionDefault
contrastsstr, list, or dictContrast(s) to render, same forms as compute_contrast.None
**kwargsAdditional arguments forwarded to nilearn’s generate_report (e.g. title, threshold, alpha).{}

Parameters:

NameTypeDescriptionDefault
XNoneNot used, present for sklearn API compatibility.None
yNoneNot used, present for sklearn API compatibility.None

Returns:

TypeDescription
Nifti1Image | dictNifti1Image 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) -> Glm

Fit GLM to fMRI data.

Returns:

NameTypeDescription
GlmGlmFitted 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.ndarray

Predict from the fitted GLM.

Returns:

TypeDescription
list [ Nifti1Image ] | ndarraylist 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:

NameTypeDescription
HTMLReportnilearn report object; call .save_as_html(path) or display it in a notebook.

######## score

score(X: None = None, y: None = None) -> float

Return mean R² across voxels and runs.

Computes average coefficient of determination (R²) from the fitted GLM. Higher values indicate better model fit.

Returns:

NameTypeDescription
floatfloatMean 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:

NameDescription
RidgeRidge 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) -> None

Bases: 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:

Parameters:

NameTypeDescriptionDefault
alphafloat or ‘auto’, default=1.0Regularization strength. If ‘auto’, uses cross-validation to select optimal alpha from alphas parameter.1.0
cvint or None, default=NoneNumber of cross-validation folds (only used if alpha=‘auto’)None
alphasarray-like or None, default=NoneAlpha values to try during cross-validation. Defaults to [0.1, 1.0, 10.0] if None.None
n_iterint, default=100Number of random search iterations. Only used when X is a list (multiple feature spaces). Ignored for single feature space.100
concentrationfloat 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
devicestr, 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_alphabool, default=TrueIf True, select best alpha independently for each target. If False, select single best alpha for all targets.True
fit_interceptbool, default=FalseWhether to fit an intercept.False
conservativebool, default=FalseIf True, select largest alpha within 1 std of best score (more regularization).False
random_stateint or None, default=NoneRandom seed for reproducibility (used for CV splits and random search)None
progress_barbool, default=FalseWhether 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:

NameTypeDescription
coef_ndarray of shape (n_features,) or (n_features, n_targetsRidge coefficients
alpha_float or ndarrayAlpha value(s) used (selected via CV if alpha=‘auto’)
cv_scores_ndarrayCross-validation scores (only if alpha=‘auto’)
deltas_ndarray or NoneFeature space weights (only if X was a list) Shape: (n_spaces, n_targets). deltas = log(gamma / alpha)
backend_BackendResolved backend instance used for computation (its .name reports the concrete device, e.g. 'torch-cuda').

Methods:

NameDescription
fitFit ridge regression model.
predictPredict using the ridge model.
scoreReturn 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) -> Ridge

Fit 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:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features) or list of arraysTraining data. If list, each element is a feature space for banded ridge.required
yndarray of shape (n_samples,) or (n_samples, n_targets)Target valuesrequired

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Samples to predictrequired

Parameters:

NameTypeDescriptionDefault
Xndarray of shape (n_samples, n_features)Test samplesrequired
yndarray of shape (n_samples,) or (n_samples, n_targets)True values for Xrequired

Returns:

NameTypeDescription
RidgeRidgeFitted model instance

######## predict

predict(X: np.ndarray) -> np.ndarray

Predict using the ridge model.

Returns:

TypeDescription
ndarrayndarray of shape (n_samples,) or (n_samples, n_targets): Predicted values

######## score

score(X: np.ndarray, y: np.ndarray) -> float | np.ndarray

Return 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:

TypeDescription
float | ndarrayfloat or ndarray: - If y is 1D: scalar R² - If y is 2D: array of shape (n_targets,) with per-target R² scores

Methods