Skip to main content
v2026.11,986 entries · CC-BY 4.0

Elastic Net in scikit-learn: ElasticNet and ElasticNetCV

How to fit an elastic net in scikit-learn: ElasticNet and ElasticNetCV syntax, parameters, outputs and common errors, checked against the 1.9.1 docs.

Written and maintained by CASRAI Editorial Board

Published

On this page

To fit an elastic net in scikit-learn, import ElasticNet from sklearn.linear_model, set alpha (overall penalty strength) and l1_ratio (the L1/L2 mix, from 0 for pure L2 to 1 for pure L1), and call fit(X, y). When you want the penalty chosen by cross-validation instead of by hand, use ElasticNetCV, which searches a grid of alphas and l1_ratio values and refits on the full training set. This guide covers both estimators (searched as sklearn elastic net, elasticnet sklearn or sklearn elasticnet), with the exact signatures, a worked example, how to read the fitted attributes and the errors that trip up code copied from older tutorials. For the statistical idea behind the penalty, see the elastic net regression guide; this page is about the API.

What it is used for in research

Elastic net is a penalised linear regression used when a study has many candidate predictors, some of them correlated. The scikit-learn user guide states the practical reason: elastic-net is useful when there are multiple features correlated with one another, because lasso is likely to pick one of them at random while elastic-net is likely to pick both. It also inherits some of ridge regression’s stability under rotation. The method is described in Friedman, Hastie and Tibshirani (2010, Journal of Statistical Software), which the user guide cites.

The objective that scikit-learn minimises for ElasticNet is the following, as given in the class documentation:

1 / (2 * n_samples) * ||y - Xw||²₂ + alpha * l1_ratio * ||w||₁ + 0.5 * alpha * (1 - l1_ratio) * ||w||²₂

If you think of the two penalties separately as a * ||w||₁ + 0.5 * b * ||w||²₂, the documentation gives the mapping alpha = a + b and l1_ratio = a / (a + b). That is the whole parameterisation: alpha sets how hard the coefficients are shrunk, and l1_ratio sets how much of that shrinkage is the sparsity-inducing L1 kind.

sklearn ElasticNet or ElasticNetCV?

Use ElasticNet when you already know the penalty (for example from a pre-registered analysis plan or an outer loop you control) and ElasticNetCV when the penalty has to be estimated from the training data. ElasticNetCV tests every l1_ratio you pass, and for each one a path of alphas, using cross-validation. The cross-validation guide explains why the fold scores of a tuned model are optimistic estimates of its performance on new data, which is why a held-out test set (see splitting data into train and test sets in Python) matters when you tune.

Install or access (official source only)

scikit-learn’s installation page gives these routes: with pip, pip install -U scikit-learn; with conda, conda create -n sklearn-env -c conda-forge scikit-learn. To confirm that the install works and see which version you have, run python -c "import sklearn; sklearn.show_versions()". The same page states the Python requirement for each release (for example, it states that scikit-learn 1.7 requires Python 3.10 or newer); check the requirement for the release you install on that page. Parameters and defaults in this guide follow the scikit-learn 1.9.1 documentation. The parameter notes mention the version in which a behaviour changed where the documentation records one.

Step-by-step: fit an elastic net

  1. Split the data first. Hold out a test set before any tuning, and do all scaling and tuning on the training portion only.
  2. Standardise the predictors. The StandardScaler documentation says that many elements used in the objective function of a learning algorithm, naming the L1 and L2 regularizers of linear models, assume that all features are centered around 0 and have variance in the same order. A penalty applied to unscaled predictors shrinks coefficients according to their units rather than their importance. StandardScaler computes z = (x − u) / s per feature, with with_mean=True and with_std=True by default.
  3. Import and instantiate. from sklearn.linear_model import ElasticNet, then model = ElasticNet(alpha=1.0, l1_ratio=0.5).
  4. Fit. model.fit(X_train, y_train).
  5. Predict and read the model. model.predict(X_new), model.coef_, model.intercept_.

The class signature in the documentation is:

ElasticNet(alpha=1.0, *, l1_ratio=0.5, fit_intercept=True, precompute=False,
           max_iter=1000, copy_X=True, tol=0.0001, warm_start=False,
           positive=False, random_state=None, selection='cyclic')

The documentation’s own example

The ElasticNet page shows this example on synthetic data (it is a scikit-learn documentation example, not research data):

from sklearn.linear_model import ElasticNet
from sklearn.datasets import make_regression

X, y = make_regression(n_features=2, random_state=0)
regr = ElasticNet(random_state=0)
regr.fit(X, y)
print(regr.coef_)              # [18.83816048 64.55968825]
print(regr.intercept_)         # 1.451...
print(regr.predict([[0, 0]]))  # [1.451...]

The coefficients and intercept in the comments are the values printed in the documentation page. The prediction at [[0, 0]] equals the intercept, as it must for a linear model with fit_intercept=True.

Tuning with ElasticNetCV

The ElasticNetCV class documentation gives this signature:

ElasticNetCV(*, l1_ratio=0.5, eps=0.001, alphas=100, fit_intercept=True,
             precompute='auto', max_iter=1000, tol=0.0001, cv=None,
             copy_X=True, verbose=0, n_jobs=None, positive=False,
             random_state=None, selection='cyclic')

A typical research workflow combines it with the scaler in a pipeline so that scaling is learned inside each fit and is never leaked from the test data:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import ElasticNetCV

model = make_pipeline(
    StandardScaler(),
    ElasticNetCV(l1_ratio=[.1, .5, .7, .9, .95, .99, 1], cv=5, n_jobs=-1, random_state=0),
)
model.fit(X_train, y_train)
enet = model.named_steps["elasticnetcv"]
print(enet.alpha_, enet.l1_ratio_)

The l1_ratio list in that snippet is the one the documentation suggests as a spread that puts more values near 1. Each l1_ratio in the list is tested by cross-validation. After the best pair is found, the model is refit on the entire training set. The documentation’s own ElasticNetCV(cv=5, random_state=0) example on make_regression(n_features=2, random_state=0) reports alpha_ of about 0.199, intercept_ of about 0.398 and a prediction at [[0, 0]] equal to that intercept.

Parameters that matter, and what the documentation says about them

The table in the data section below lists the defaults of both estimators side by side. These are the parameters where the documentation gives guidance beyond the default.

  • alpha (ElasticNet). Constant that multiplies the penalty terms. alpha=0 is ordinary least squares; the documentation recommends the LinearRegression object instead,.
  • l1_ratio. Lies in [0, 1]; 0 is pure L2 and 1 is pure L1. The documentation warns that l1_ratio ≤ 0.01 is not reliable unless you supply your own sequence of alphas.
  • selection. 'cyclic' (default) loops over features in order; 'random' updates a random coefficient each iteration and, per the documentation, often leads to significantly faster convergence, especially when tol is higher than 1e-4. random_state is used only when selection='random'.
  • tol and max_iter. If the updates are smaller than tol, the optimisation checks the dual gap and continues until that gap is also smaller than tol; max_iter is the maximum number of iterations.
  • positive. Forces coefficients to be positive when set to True.
  • cv (ElasticNetCV). None means 5-fold cross-validation (the documentation records that the default changed from 3-fold to 5-fold in version 0.22). n_jobs=-1 uses all processors.
  • alphas (ElasticNetCV). Either an array of alphas or an integer number of alphas to generate. eps (default 0.001) is the ratio of the smallest to the largest alpha in the generated path.

The ElasticNet documentation advises using Fortran-contiguous data for memory efficiency.

Output and how to read it

Attributes after fit

  • coef_ and sparse_coef_: the fitted weights, dense or as a sparse matrix. Coefficients shrunk to exactly zero are the features the model has dropped.
  • intercept_: the intercept term (0 if fit_intercept=False).
  • n_iter_ and dual_gap_: the number of iterations run and the dual gap at the end of the optimisation; inspect these when you see convergence warnings.
  • n_features_in_ (added in 0.24) and feature_names_in_ (added in 1.0): the number of features seen at fit and the feature names seen at fit.

After ElasticNetCV.fit you also get alpha_ (the penalty amount chosen by cross-validation), l1_ratio_ (the l1_ratio chosen), alphas_ (the grid of alphas used for each l1_ratio) and mse_path_.

Reading mse_path_

The documentation gives mse_path_ the shape (n_l1_ratio, n_alpha, n_folds): the mean squared error on each held-out fold, for each l1_ratio and each alpha. Averaging over the last axis gives a cross-validation error curve per l1_ratio. If the best alpha sits at an end of the grid, widen the search range.

Matching glmnet vocabulary

The same documentation page warns about a naming clash with the R package glmnet: l1_ratio in scikit-learn corresponds to glmnet’s alpha, and scikit-learn’s alpha corresponds to glmnet’s lambda. When you reproduce an analysis from a paper that used glmnet (see the glmnet guide), translate the names before comparing numbers; an unconverted alpha is a silent source of mismatched results.

Troubleshooting

ConvergenceWarning

scikit-learn raises it when the optimisation does not reach the tolerance within max_iter iterations. The levers available: raise max_iter; adjust tol; try selection='random'; and standardise the features, since the regularizers assume features of comparable scale. Inspect n_iter_ and dual_gap_ after the fit.

TypeError about n_alphas

Older tutorials call ElasticNetCV(n_alphas=...). The documentation records that in version 1.7 the alphas parameter was changed to accept an integer, and n_alphas is no longer a parameter of ElasticNetCV. Replace n_alphas=100 with alphas=100.

Unreliable results at a very small l1_ratio

Per the documentation, l1_ratio ≤ 0.01 is not reliable unless you supply your own alphas. For an almost pure ridge fit, Ridge is the dedicated estimator.

alpha=0 with ElasticNet

An alpha of 0 is ordinary least squares, and the documentation advises LinearRegression for that; use a positive alpha with ElasticNet.

Sparse input and scaling

The StandardScaler documentation states that with_mean=True raises an error on sparse input because centring would make the matrix dense, and that the scaler is sensitive to outliers. For sparse predictors use with_mean=False and check outliers before scaling.

Free alternatives and neighbouring estimators

Option Relationship to ElasticNet Where documented
Lasso (scikit-learn) The pure L1 case; per the user guide it is likely to pick one of several correlated features at random scikit-learn user guide, linear models
Ridge (scikit-learn) The L2 end of the family; the ElasticNet documentation says l1_ratio ≤ 0.01 is not reliable unless you supply alphas scikit-learn ElasticNet page
LinearRegression The alpha = 0 case; recommended by the documentation instead of ElasticNet with alpha = 0 scikit-learn ElasticNet page
glmnet (R) The same model family with different names (glmnet alpha = scikit-learn l1_ratio; glmnet lambda = scikit-learn alpha) scikit-learn ElasticNetCV page; glmnet guide

scikit-learn is free, open-source software. For a binary outcome rather than a continuous one, see scikit-learn logistic regression.

Common mistakes in research use

  • Scaling on the full data set, then splitting. Put the scaler inside a pipeline so it is fit on training folds only.
  • Reporting the cross-validated score of the winning grid point as the expected performance. Report performance on data that took no part in tuning.
  • Interpreting coefficients from unscaled predictors as effect sizes.
  • Comparing sklearn alpha with a published glmnet alpha without converting (see above).
  • Treating an exact-zero coefficient as proof that a variable is unrelated to the outcome; it only says the variable was dropped at that penalty.

Frequently asked questions

What is l1_ratio in sklearn ElasticNet?

It is the mixing parameter between the L1 and L2 penalties, in [0, 1]. A value of 0 gives pure L2 (ridge-type) penalty and 1 gives pure L1 (lasso-type); the default is 0.5.

How do I choose alpha and l1_ratio?

Use ElasticNetCV with a list of l1_ratio values and an alpha grid; it cross-validates every combination and exposes the winners as alpha_ and l1_ratio_.

Is sklearn’s alpha the same as glmnet’s alpha?

No. scikit-learn’s l1_ratio corresponds to glmnet’s alpha, and scikit-learn’s alpha corresponds to glmnet’s lambda.

Do I need to scale features before ElasticNet?

In practice yes: the StandardScaler documentation says the regularizers assume features centred around 0 with variance of the same order, so standardise inside a pipeline.

Why does ElasticNetCV no longer accept n_alphas?

Since version 1.7 the alphas parameter takes an integer, replacing n_alphas.

How many folds does ElasticNetCV use by default?

Five (cv=None means 5-fold; this default changed from 3 in version 0.22).

Sources

  • scikit-learn documentation, ElasticNet: https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNet.html (read 2026-11-14)
  • scikit-learn documentation, ElasticNetCV: https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNetCV.html (read 2026-11-14)
  • scikit-learn user guide, linear models, Elastic-Net: https://scikit-learn.org/stable/modules/linear_model.html (read 2026-11-14)
  • scikit-learn documentation, StandardScaler: https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html (read 2026-11-14)
  • scikit-learn, Installing scikit-learn: https://scikit-learn.org/stable/install.html (read 2026-11-14)

Data: scikit-learn ElasticNet and ElasticNetCV parameter defaults (version 1.9.1 docs)

Side-by-side default values of the ElasticNet and ElasticNetCV constructors as printed in the scikit-learn 1.9.1 API documentation, compiled to show where the two estimators differ (alpha versus alphas, cv, eps and precompute). Read from the official class pages on 2026-11-14.

scikit-learn ElasticNet and ElasticNetCV parameter defaults (version 1.9.1 docs)
ParameterElasticNet defaultElasticNetCV default
alpha1.0not a parameter: alphas=100 (int, number of alphas generated; array also accepted)
l1_ratio0.50.5 (a list of values is cross-validated)
fit_interceptTrueTrue
precomputeFalse'auto'
max_iter10001000
tol0.00010.0001
warm_startFalsenot a parameter
cvnot a parameterNone (5-fold)
epsnot a parameter0.001 (alpha_min / alpha_max)
selection'cyclic''cyclic'
positiveFalseFalse
random_stateNoneNone

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Elastic Net in scikit-learn: ElasticNet and ElasticNetCV

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →