Parametric Elastic Linear#
elastic_linear
#
| CLASS | DESCRIPTION |
|---|---|
ElasticLinear |
Elastic net linear regression with combined L1 and L2 regularization. |
Classes#
ElasticLinear(*, model: ModelType | dict[str, ModelType], alpha: float = 1.0, l1_ratio: float = 0.5, loss_kwargs: dict | None = None, optimizer_fn: type[torch.optim.Optimizer] | str | None = None, optimizer_kwargs: dict | None = None, lr_scheduler_fn: Any | str | None = None, lr_scheduler_kwargs: dict | None = None, device: Literal['cuda', 'cpu'] = 'cuda')
#
Bases: Parametric
Elastic net linear regression with combined L1 and L2 regularization.
This class implements elastic net regression, which combines Ridge (L2) and Lasso (L1) regularization techniques. Useful for feature selection and handling multicollinearity in high-dimensional datasets.
The elastic net loss function minimizes:
\(L(w) = \frac{1}{2 N} \| y - X w \|^2_2 + \alpha l_r \| w \|_1 + \frac{\alpha}{2} (1 - l_r) \| w \|^2_2\),
where \(\alpha\) is the regularization strength parameter, \(l_r\) is the elastic net mixing parameter in [0, 1], and \(N\) is the number of samples.
Terms:
- The first term is the mean squared error (MSE) loss between the data \(X\) and the target \(y\)
- The second term is L1 penalty (Lasso) for feature selection
- The third term is L2 penalty (Ridge) for regularization
The model supports PyTorch Lightning training and provides \(R^2\) scoring for model evaluation.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Neural network model or compatible structure. Must contain exactly one linear layer for elastic net regularization to be meaningful.
TYPE:
|
alpha
|
Regularization strength parameter. Controls the overall amount of regularization applied. Must be positive. Higher values increase regularization strength.
TYPE:
|
l1_ratio
|
Elastic net mixing parameter in [0, 1]. Controls the balance between L1 and L2 regularization:
TYPE:
|
loss_kwargs
|
Additional keyword arguments to pass to the MSELoss constructor.
TYPE:
|
optimizer_fn
|
Optimizer specification for training.
TYPE:
|
optimizer_kwargs
|
Keyword arguments for optimizer instantiation
(e.g.,
TYPE:
|
lr_scheduler_fn
|
Learning rate scheduler specification.
TYPE:
|
lr_scheduler_kwargs
|
Keyword arguments for scheduler instantiation.
TYPE:
|
device
|
Computation device. Will automatically fallback to "cpu" if CUDA is not available.
TYPE:
|
Examples:
>>> import torch
>>> from spectre.parametric import ElasticLinear
>>>
>>> # Create a simple linear model
>>> linear_layer = torch.nn.Linear(10, 1)
>>> elastic = ElasticLinear(
... model=linear_layer,
... alpha=0.1,
... l1_ratio=0.5,
... )
>>>
>>> # Generate sample data
>>> X = torch.randn(100, 10)
>>> y = torch.randn(100, 1)
>>> weights = torch.ones(100)
>>>
>>> # Training step
>>> batch = (X, weights, y)
>>> loss = elastic.training_step(batch, 0)
>>>
>>> # Evaluate after training (requires is_trained=True)
>>> elastic.is_trained = True
>>> r2_score = elastic.score(X, target=y)
| METHOD | DESCRIPTION |
|---|---|
score_step |
Return the coefficient of determination of the prediction. |
training_step |
Training step for PyTorch Lightning with elastic net regularization. |
forward_step |
Forward pass through the linear model. |
loss |
Compute elastic net loss for given data and target. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
weight |
Get the weight matrix of the linear layer.
TYPE:
|
bias |
Get the bias vector of the linear layer.
TYPE:
|
Source code in spectre/parametric/elastic_linear.py
Attributes#
weight: torch.Tensor
property
#
Get the weight matrix of the linear layer.
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Weight matrix of shape (out_features, in_features). |
bias: torch.Tensor
property
#
Get the bias vector of the linear layer.
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Bias vector of shape (out_features, ). |
Functions#
score_step(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Return the coefficient of determination of the prediction.
\(R^2\) score represents the proportion of variance in the target variable that is predictable from the input features. If the score is 1.0, the model perfectly predicts the target. A score of 0.0 indicates that the model does not explain any of the variance in the target. Negative values indicate that the model performs worse than a horizontal line (mean of the target).
Defined as
\(R^2 = 1 - \frac{\sum_{i=1}^{N} (y_i - \hat{y}_i)^2} {\sum_{i=1}^{N} (y_i - \bar{y})^2}\),
where \(y\) is the true target, \(\hat{y}\) is the predicted target, and \(\bar{y}\) is the mean of the true target.
For multi-dimensional targets, \(R^2\) score is computed for each dimension and then averaged.
If sample weights are provided, a weighted \(R^2\) score is computed.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Dataset of samples.
TYPE:
|
weights
|
Sample weights.
TYPE:
|
target
|
Target values for X.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If target values are not provided. |
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Coefficient of determination of the prediction. |
Source code in spectre/parametric/elastic_linear.py
training_step(batch: DataBatch, batch_idx: int) -> torch.Tensor
#
Training step for PyTorch Lightning with elastic net regularization.
Computes the elastic net loss combining mean squared error with L1 and L2 regularization terms. Automatically logs the loss for monitoring during training.
| PARAMETER | DESCRIPTION |
|---|---|
batch
|
Input batch containing (X, weights, target) where:
TYPE:
|
batch_idx
|
Batch index (required by PyTorch Lightning interface but unused).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar training loss combining MSE with L1/L2 regularization terms. |
Source code in spectre/parametric/elastic_linear.py
forward_step(X: torch.Tensor) -> torch.Tensor
#
Forward pass through the linear model.
Computes predictions by passing input through the single linear layer.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input features.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor of shape (n_samples, out_features)
|
Model predictions. |
Source code in spectre/parametric/elastic_linear.py
loss(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Compute elastic net loss for given data and target.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input features.
TYPE:
|
weights
|
Sample weights for weighted loss computation. If None, uniform weighting is applied.
TYPE:
|
target
|
Target values.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar loss value combining MSE with L1 and L2 regularization. |