Skip to Content
OchreML
Linear, GLM & Linear SVM

ElasticNet

Linear regression combining L1 (Lasso) and L2 (Ridge) regularization via coordinate descent.

Overview

ElasticNet fits a linear regression model regularized by a convex combination of L1 and L2 penalties:

min (1 / (2 * n_samples)) * ||y - (X @ w + b)||_2^2
    + alpha * l1_ratio * ||w||_1
    + 0.5 * alpha * (1 - l1_ratio) * ||w||_2^2

By blending L1 sparsity with L2 grouping stability, ElasticNet overcomes Lasso's tendency to select only one feature from a group of highly correlated predictors. Supports 1D and 2D multi-output targets, sample_weight, and positive=True.

When to Use

  • High-dimensional regression with groups of strongly correlated features where both sparsity and stability are desired.
  • Datasets with n_features > n_samples where Lasso alone can saturate at n_samples non-zero weights.
  • Setting l1_ratio=1.0 recovers Lasso; l1_ratio=0.0 yields pure L2 shrinkage.

Hardware Backend Support

BackendPrimitives UsedSupport
CPU (Rayon)Dense E1-E5, N2 (f64)Full (default fallback)
CUDA (cuda:0, cuda:all)cuBLAS FP64 Gram & projections (E1-E5, N2)Full
wgpu (wgpu)WGSL compute shaders (E1-E5, N2)Full
TPU (tpu:0)OpenXLA PJRT StableHLO dot_general (E1-E5, N2)Full

Import & Constructor

from ochreml.linear_model import ElasticNet
# or top-level lazy import:
from ochreml import ElasticNet

model = ElasticNet(
    alpha: float = 1.0,
    l1_ratio: float = 0.5,
    fit_intercept: bool = True,
    max_iter: int = 1000,
    tol: float = 1e-4,
    positive: bool = False,
    device: str | None = None,
)

Parameters

ParameterTypeDefaultDescription
alphafloat1.0Constant multiplying the combined L1 + L2 penalty terms.
l1_ratiofloat0.5ElasticNet mixing parameter in [0.0, 1.0]. 1.0 is pure L1, 0.0 is pure L2.
fit_interceptboolTrueWhether to estimate an unpenalized intercept term.
max_iterint1000Maximum number of coordinate descent iterations.
tolfloat1e-4Stopping tolerance for coordinate descent updates.
positiveboolFalseWhen True, constrains all fitted coefficients to be non-negative.
devicestr | NoneNoneTarget compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeTypeDescription
coef_ndarray of shape (n_features,) or (n_targets, n_features)Estimated weight vector or matrix.
intercept_float or ndarray of shape (n_targets,)Independent bias term(s).
n_iter_int or list[int]Number of iterations performed by coordinate descent.
n_features_in_intNumber of features seen during fit.
device_strResolved hardware device string used by the estimator.

Methods

MethodSignatureDescription
fitfit(X, y, sample_weight=None) -> selfFit ElasticNet model on 1D or 2D targets.
predictpredict(X) -> ndarrayPredict continuous values for input matrix X.
scorescore(X, y) -> floatReturn coefficient of determination R^2.
toto(device: str) -> selfMove the estimator execution target to another hardware device.
save / loadmodel.save(path) / ElasticNet.load(path, device=None)Persist or restore the model in OchreML's binary .dit format.

Usage Example

import numpy as np
import ochreml
from ochreml.linear_model import ElasticNet

rng = np.random.default_rng(10)
X = rng.standard_normal((300, 8))
X[:, 1] = X[:, 0] + rng.normal(0.0, 0.05, size=300)  # correlated pair
y = 2.0 * X[:, 0] + 2.0 * X[:, 1] - 1.5 * X[:, 4] + rng.normal(0.0, 0.2, size=300)

model = ElasticNet(alpha=0.1, l1_ratio=0.5, max_iter=1000, device="auto")
model.fit(X, y)

preds = model.predict(X[:5])
print(f"R^2: {model.score(X, y):.4f}, coef_: {model.coef_.round(3)}")

# Persist to .dit and reload
model.save("elastic_net.dit")
loaded = ochreml.load("elastic_net.dit", device="cpu")
assert np.allclose(preds, loaded.predict(X[:5]))

On this page