class sklearn.linear_model.ElasticNet(alpha=1.0, *, l1_ratio=0.5, fit_intercept=True, normalize=False, precompute=False, max_iter=1000, copy_X=True, tol=0.0001, warm_start=False, positive=False, random_state=None, selection='cyclic') [source]

Linear regression with combined L1 and L2 priors as regularizer. Minimizes the objective function: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 If you are interested in controlling the L1 and L2 penalty separately, keep in mind that this is equivalent to: a * L1 + b * L2
 where: alpha = a + b and l1_ratio = a / (a + b)
 The parameter l1_ratio corresponds to alpha in the glmnet R package while alpha corresponds to the lambda parameter in glmnet. Specifically, l1_ratio = 1 is the lasso penalty. Currently, l1_ratio <= 0.01 is not reliable, unless you supply your own sequence of alpha. Read more in the User Guide.  Parameters

alphafloat, default=1.0

Constant that multiplies the penalty terms. Defaults to 1.0. See the notes for the exact mathematical meaning of this parameter. alpha = 0 is equivalent to an ordinary least square, solved by the LinearRegression object. For numerical reasons, using alpha = 0 with the Lasso object is not advised. Given this, you should use the LinearRegression object.
l1_ratiofloat, default=0.5

The ElasticNet mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
fit_interceptbool, default=True

Whether the intercept should be estimated or not. If False, the data is assumed to be already centered.
normalizebool, default=False

This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
precomputebool or array-like of shape (n_features, n_features), default=False

Whether to use a precomputed Gram matrix to speed up calculations. The Gram matrix can also be passed as argument. For sparse input this option is always True to preserve sparsity.
max_iterint, default=1000

The maximum number of iterations.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
tolfloat, default=1e-4

The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol.
warm_startbool, default=False

When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See the Glossary.
positivebool, default=False

When set to True, forces the coefficients to be positive.
random_stateint, RandomState instance, default=None

The seed of the pseudo random number generator that selects a random feature to update. Used when selection == ‘random’. Pass an int for reproducible output across multiple function calls. See Glossary.
selection{‘cyclic’, ‘random’}, default=’cyclic’

If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4.    Attributes

coef_ndarray of shape (n_features,) or (n_targets, n_features)

Parameter vector (w in the cost function formula).
sparse_coef_sparse matrix of shape (n_features,) or (n_tasks, n_features)

Sparse representation of the fitted coef_.
intercept_float or ndarray of shape (n_targets,)

Independent term in decision function.
n_iter_list of int

Number of iterations run by the coordinate descent solver to reach the specified tolerance.
dual_gap_float or ndarray of shape (n_targets,)

Given param alpha, the dual gaps at the end of the optimization, same shape as each observation of y.      See also
ElasticNetCV

Elastic net model with best model selection by cross-validation.
SGDRegressor

Implements elastic net regression with incremental training.
SGDClassifier

Implements logistic regression with elastic net penalty (SGDClassifier(loss="log", penalty="elasticnet")).    Notes To avoid unnecessary memory duplication the X argument of the fit method should be directly passed as a Fortran-contiguous numpy array. Examples >>> 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)
ElasticNet(random_state=0)
>>> print(regr.coef_)
[18.83816048 64.55968825]
>>> print(regr.intercept_)
1.451...
>>> print(regr.predict([[0, 0]]))
[1.451...]
 Methods
fit(X, y[, sample_weight, check_input]) Fit model with coordinate descent.
get_params([deep]) Get parameters for this estimator.
path(*args, **kwargs) Compute elastic net path with coordinate descent.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None, check_input=True) [source]

Fit model with coordinate descent.  Parameters

X{ndarray, sparse matrix} of (n_samples, n_features)

Data.
y{ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets)

Target. Will be cast to X’s dtype if necessary.
sample_weightfloat or array-like of shape (n_samples,), default=None

Sample weight.  New in version 0.23.
check_inputbool, default=True

Allow to bypass several input checking. Don’t use this parameter unless you know what you do.     Notes Coordinate descent is an algorithm that considers each column of data at a time hence it will automatically convert the X input as a Fortran-contiguous numpy array if necessary. To avoid memory re-allocation it is advised to allocate the initial data in memory directly using that format.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

static path(*args, **kwargs) [source]

Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 For multi-output tasks it is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
 Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
 i.e. the sum of norm of each row. Read more in the User Guide.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output then X can be sparse.
y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)

Target values.
l1_ratiofloat, default=0.5

Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). l1_ratio=1 corresponds to the Lasso.
epsfloat, default=1e-3

Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100

Number of alphas along the regularization path.
alphasndarray, default=None

List of alphas where to compute the models. If None alphas are set automatically.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
Xyarray-like of shape (n_features,) or (n_features, n_outputs), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
coef_initndarray of shape (n_features, ), default=None

The initial values of the coefficients.
verbosebool or int, default=False

Amount of verbosity.
return_n_iterbool, default=False

Whether to return the number of iterations or not.
positivebool, default=False

If set to True, forces coefficients to be positive. (Only allowed when y.ndim == 1).
check_inputbool, default=True

If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller.
**paramskwargs

Keyword arguments passed to the coordinate descent solver.    Returns

alphasndarray of shape (n_alphas,)

The alphas along the path where models are computed.
coefsndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)

Coefficients along the path.
dual_gapsndarray of shape (n_alphas,)

The dual gaps at the end of the optimization for each alpha.
n_iterslist of int

The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when return_n_iter is set to True).      See also
MultiTaskElasticNet

MultiTaskElasticNetCV

ElasticNet

ElasticNetCV

  Notes For an example, see examples/linear_model/plot_lasso_coordinate_descent_path.py.

predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

property sparse_coef_
Sparse representation of the fitted coef_.


sklearn.linear_model.ElasticNet
class sklearn.linear_model.ElasticNet(alpha=1.0, *, l1_ratio=0.5, fit_intercept=True, normalize=False, precompute=False, max_iter=1000, copy_X=True, tol=0.0001, warm_start=False, positive=False, random_state=None, selection='cyclic') [source]

Linear regression with combined L1 and L2 priors as regularizer. Minimizes the objective function: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 If you are interested in controlling the L1 and L2 penalty separately, keep in mind that this is equivalent to: a * L1 + b * L2
 where: alpha = a + b and l1_ratio = a / (a + b)
 The parameter l1_ratio corresponds to alpha in the glmnet R package while alpha corresponds to the lambda parameter in glmnet. Specifically, l1_ratio = 1 is the lasso penalty. Currently, l1_ratio <= 0.01 is not reliable, unless you supply your own sequence of alpha. Read more in the User Guide.  Parameters

alphafloat, default=1.0

Constant that multiplies the penalty terms. Defaults to 1.0. See the notes for the exact mathematical meaning of this parameter. alpha = 0 is equivalent to an ordinary least square, solved by the LinearRegression object. For numerical reasons, using alpha = 0 with the Lasso object is not advised. Given this, you should use the LinearRegression object.
l1_ratiofloat, default=0.5

The ElasticNet mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
fit_interceptbool, default=True

Whether the intercept should be estimated or not. If False, the data is assumed to be already centered.
normalizebool, default=False

This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
precomputebool or array-like of shape (n_features, n_features), default=False

Whether to use a precomputed Gram matrix to speed up calculations. The Gram matrix can also be passed as argument. For sparse input this option is always True to preserve sparsity.
max_iterint, default=1000

The maximum number of iterations.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
tolfloat, default=1e-4

The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol.
warm_startbool, default=False

When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See the Glossary.
positivebool, default=False

When set to True, forces the coefficients to be positive.
random_stateint, RandomState instance, default=None

The seed of the pseudo random number generator that selects a random feature to update. Used when selection == ‘random’. Pass an int for reproducible output across multiple function calls. See Glossary.
selection{‘cyclic’, ‘random’}, default=’cyclic’

If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4.    Attributes

coef_ndarray of shape (n_features,) or (n_targets, n_features)

Parameter vector (w in the cost function formula).
sparse_coef_sparse matrix of shape (n_features,) or (n_tasks, n_features)

Sparse representation of the fitted coef_.
intercept_float or ndarray of shape (n_targets,)

Independent term in decision function.
n_iter_list of int

Number of iterations run by the coordinate descent solver to reach the specified tolerance.
dual_gap_float or ndarray of shape (n_targets,)

Given param alpha, the dual gaps at the end of the optimization, same shape as each observation of y.      See also
ElasticNetCV

Elastic net model with best model selection by cross-validation.
SGDRegressor

Implements elastic net regression with incremental training.
SGDClassifier

Implements logistic regression with elastic net penalty (SGDClassifier(loss="log", penalty="elasticnet")).    Notes To avoid unnecessary memory duplication the X argument of the fit method should be directly passed as a Fortran-contiguous numpy array. Examples >>> 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)
ElasticNet(random_state=0)
>>> print(regr.coef_)
[18.83816048 64.55968825]
>>> print(regr.intercept_)
1.451...
>>> print(regr.predict([[0, 0]]))
[1.451...]
 Methods
fit(X, y[, sample_weight, check_input]) Fit model with coordinate descent.
get_params([deep]) Get parameters for this estimator.
path(*args, **kwargs) Compute elastic net path with coordinate descent.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None, check_input=True) [source]

Fit model with coordinate descent.  Parameters

X{ndarray, sparse matrix} of (n_samples, n_features)

Data.
y{ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets)

Target. Will be cast to X’s dtype if necessary.
sample_weightfloat or array-like of shape (n_samples,), default=None

Sample weight.  New in version 0.23.
check_inputbool, default=True

Allow to bypass several input checking. Don’t use this parameter unless you know what you do.     Notes Coordinate descent is an algorithm that considers each column of data at a time hence it will automatically convert the X input as a Fortran-contiguous numpy array if necessary. To avoid memory re-allocation it is advised to allocate the initial data in memory directly using that format.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

static path(*args, **kwargs) [source]

Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 For multi-output tasks it is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
 Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
 i.e. the sum of norm of each row. Read more in the User Guide.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output then X can be sparse.
y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)

Target values.
l1_ratiofloat, default=0.5

Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). l1_ratio=1 corresponds to the Lasso.
epsfloat, default=1e-3

Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100

Number of alphas along the regularization path.
alphasndarray, default=None

List of alphas where to compute the models. If None alphas are set automatically.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
Xyarray-like of shape (n_features,) or (n_features, n_outputs), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
coef_initndarray of shape (n_features, ), default=None

The initial values of the coefficients.
verbosebool or int, default=False

Amount of verbosity.
return_n_iterbool, default=False

Whether to return the number of iterations or not.
positivebool, default=False

If set to True, forces coefficients to be positive. (Only allowed when y.ndim == 1).
check_inputbool, default=True

If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller.
**paramskwargs

Keyword arguments passed to the coordinate descent solver.    Returns

alphasndarray of shape (n_alphas,)

The alphas along the path where models are computed.
coefsndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)

Coefficients along the path.
dual_gapsndarray of shape (n_alphas,)

The dual gaps at the end of the optimization for each alpha.
n_iterslist of int

The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when return_n_iter is set to True).      See also
MultiTaskElasticNet

MultiTaskElasticNetCV

ElasticNet

ElasticNetCV

  Notes For an example, see examples/linear_model/plot_lasso_coordinate_descent_path.py.

predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

property sparse_coef_
Sparse representation of the fitted coef_.

 Examples using sklearn.linear_model.ElasticNet

  Release Highlights for scikit-learn 0.23

  Lasso and Elastic Net for Sparse Signals

  Train error vs Test error


fit(X, y, sample_weight=None, check_input=True) [source]

Fit model with coordinate descent.  Parameters

X{ndarray, sparse matrix} of (n_samples, n_features)

Data.
y{ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets)

Target. Will be cast to X’s dtype if necessary.
sample_weightfloat or array-like of shape (n_samples,), default=None

Sample weight.  New in version 0.23.
check_inputbool, default=True

Allow to bypass several input checking. Don’t use this parameter unless you know what you do.     Notes Coordinate descent is an algorithm that considers each column of data at a time hence it will automatically convert the X input as a Fortran-contiguous numpy array if necessary. To avoid memory re-allocation it is advised to allocate the initial data in memory directly using that format.


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


static path(*args, **kwargs) [source]

Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 For multi-output tasks it is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
 Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
 i.e. the sum of norm of each row. Read more in the User Guide.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output then X can be sparse.
y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)

Target values.
l1_ratiofloat, default=0.5

Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). l1_ratio=1 corresponds to the Lasso.
epsfloat, default=1e-3

Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100

Number of alphas along the regularization path.
alphasndarray, default=None

List of alphas where to compute the models. If None alphas are set automatically.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
Xyarray-like of shape (n_features,) or (n_features, n_outputs), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
coef_initndarray of shape (n_features, ), default=None

The initial values of the coefficients.
verbosebool or int, default=False

Amount of verbosity.
return_n_iterbool, default=False

Whether to return the number of iterations or not.
positivebool, default=False

If set to True, forces coefficients to be positive. (Only allowed when y.ndim == 1).
check_inputbool, default=True

If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller.
**paramskwargs

Keyword arguments passed to the coordinate descent solver.    Returns

alphasndarray of shape (n_alphas,)

The alphas along the path where models are computed.
coefsndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)

Coefficients along the path.
dual_gapsndarray of shape (n_alphas,)

The dual gaps at the end of the optimization for each alpha.
n_iterslist of int

The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when return_n_iter is set to True).      See also
MultiTaskElasticNet

MultiTaskElasticNetCV

ElasticNet

ElasticNetCV

  Notes For an example, see examples/linear_model/plot_lasso_coordinate_descent_path.py.


predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.


score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


property sparse_coef_
Sparse representation of the fitted coef_.


class sklearn.linear_model.ElasticNetCV(*, l1_ratio=0.5, eps=0.001, n_alphas=100, alphas=None, fit_intercept=True, normalize=False, 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') [source]

Elastic Net model with iterative fitting along a regularization path. See glossary entry for cross-validation estimator. Read more in the User Guide.  Parameters

l1_ratiofloat or list of float, default=0.5

float between 0 and 1 passed to ElasticNet (scaling between l1 and l2 penalties). For l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2 This parameter can be a list, in which case the different values are tested by cross-validation and the one giving the best prediction score is used. Note that a good choice of list of values for l1_ratio is often to put more values close to 1 (i.e. Lasso) and less close to 0 (i.e. Ridge), as in [.1, .5, .7,
.9, .95, .99, 1].
epsfloat, default=1e-3

Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100

Number of alphas along the regularization path, used for each l1_ratio.
alphasndarray, default=None

List of alphas where to compute the models. If None alphas are set automatically.
fit_interceptbool, default=True

Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
normalizebool, default=False

This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
max_iterint, default=1000

The maximum number of iterations.
tolfloat, default=1e-4

The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol.
cvint, cross-validation generator or iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:  None, to use the default 5-fold cross-validation, int, to specify the number of folds.
CV splitter, An iterable yielding (train, test) splits as arrays of indices.  For int/None inputs, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
verbosebool or int, default=0

Amount of verbosity.
n_jobsint, default=None

Number of CPUs to use during the cross validation. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
positivebool, default=False

When set to True, forces the coefficients to be positive.
random_stateint, RandomState instance, default=None

The seed of the pseudo random number generator that selects a random feature to update. Used when selection == ‘random’. Pass an int for reproducible output across multiple function calls. See Glossary.
selection{‘cyclic’, ‘random’}, default=’cyclic’

If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4.    Attributes

alpha_float

The amount of penalization chosen by cross validation.
l1_ratio_float

The compromise between l1 and l2 penalization chosen by cross validation.
coef_ndarray of shape (n_features,) or (n_targets, n_features)

Parameter vector (w in the cost function formula).
intercept_float or ndarray of shape (n_targets, n_features)

Independent term in the decision function.
mse_path_ndarray of shape (n_l1_ratio, n_alpha, n_folds)

Mean square error for the test set on each fold, varying l1_ratio and alpha.
alphas_ndarray of shape (n_alphas,) or (n_l1_ratio, n_alphas)

The grid of alphas used for fitting, for each l1_ratio.
dual_gap_float

The dual gaps at the end of the optimization for the optimal alpha.
n_iter_int

Number of iterations run by the coordinate descent solver to reach the specified tolerance for the optimal alpha.      See also
enet_path

ElasticNet

  Notes For an example, see examples/linear_model/plot_lasso_model_selection.py. To avoid unnecessary memory duplication the X argument of the fit method should be directly passed as a Fortran-contiguous numpy array. The parameter l1_ratio corresponds to alpha in the glmnet R package while alpha corresponds to the lambda parameter in glmnet. More specifically, the optimization objective is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 If you are interested in controlling the L1 and L2 penalty separately, keep in mind that this is equivalent to: a * L1 + b * L2
 for: alpha = a + b and l1_ratio = a / (a + b).
 Examples >>> from sklearn.linear_model import ElasticNetCV
>>> from sklearn.datasets import make_regression
 >>> X, y = make_regression(n_features=2, random_state=0)
>>> regr = ElasticNetCV(cv=5, random_state=0)
>>> regr.fit(X, y)
ElasticNetCV(cv=5, random_state=0)
>>> print(regr.alpha_)
0.199...
>>> print(regr.intercept_)
0.398...
>>> print(regr.predict([[0, 0]]))
[0.398...]
 Methods
fit(X, y) Fit linear model with coordinate descent.
get_params([deep]) Get parameters for this estimator.
path(*args, **kwargs) Compute elastic net path with coordinate descent.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]

Fit linear model with coordinate descent. Fit is on grid of alphas and best alpha estimated by cross-validation.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output, X can be sparse.
yarray-like of shape (n_samples,) or (n_samples, n_targets)

Target values.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

static path(*args, **kwargs) [source]

Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 For multi-output tasks it is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
 Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
 i.e. the sum of norm of each row. Read more in the User Guide.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output then X can be sparse.
y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)

Target values.
l1_ratiofloat, default=0.5

Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). l1_ratio=1 corresponds to the Lasso.
epsfloat, default=1e-3

Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100

Number of alphas along the regularization path.
alphasndarray, default=None

List of alphas where to compute the models. If None alphas are set automatically.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
Xyarray-like of shape (n_features,) or (n_features, n_outputs), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
coef_initndarray of shape (n_features, ), default=None

The initial values of the coefficients.
verbosebool or int, default=False

Amount of verbosity.
return_n_iterbool, default=False

Whether to return the number of iterations or not.
positivebool, default=False

If set to True, forces coefficients to be positive. (Only allowed when y.ndim == 1).
check_inputbool, default=True

If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller.
**paramskwargs

Keyword arguments passed to the coordinate descent solver.    Returns

alphasndarray of shape (n_alphas,)

The alphas along the path where models are computed.
coefsndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)

Coefficients along the path.
dual_gapsndarray of shape (n_alphas,)

The dual gaps at the end of the optimization for each alpha.
n_iterslist of int

The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when return_n_iter is set to True).      See also
MultiTaskElasticNet

MultiTaskElasticNetCV

ElasticNet

ElasticNetCV

  Notes For an example, see examples/linear_model/plot_lasso_coordinate_descent_path.py.

predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.linear_model.ElasticNetCV
class sklearn.linear_model.ElasticNetCV(*, l1_ratio=0.5, eps=0.001, n_alphas=100, alphas=None, fit_intercept=True, normalize=False, 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') [source]

Elastic Net model with iterative fitting along a regularization path. See glossary entry for cross-validation estimator. Read more in the User Guide.  Parameters

l1_ratiofloat or list of float, default=0.5

float between 0 and 1 passed to ElasticNet (scaling between l1 and l2 penalties). For l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2 This parameter can be a list, in which case the different values are tested by cross-validation and the one giving the best prediction score is used. Note that a good choice of list of values for l1_ratio is often to put more values close to 1 (i.e. Lasso) and less close to 0 (i.e. Ridge), as in [.1, .5, .7,
.9, .95, .99, 1].
epsfloat, default=1e-3

Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100

Number of alphas along the regularization path, used for each l1_ratio.
alphasndarray, default=None

List of alphas where to compute the models. If None alphas are set automatically.
fit_interceptbool, default=True

Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
normalizebool, default=False

This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
max_iterint, default=1000

The maximum number of iterations.
tolfloat, default=1e-4

The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol.
cvint, cross-validation generator or iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:  None, to use the default 5-fold cross-validation, int, to specify the number of folds.
CV splitter, An iterable yielding (train, test) splits as arrays of indices.  For int/None inputs, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here.  Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
verbosebool or int, default=0

Amount of verbosity.
n_jobsint, default=None

Number of CPUs to use during the cross validation. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
positivebool, default=False

When set to True, forces the coefficients to be positive.
random_stateint, RandomState instance, default=None

The seed of the pseudo random number generator that selects a random feature to update. Used when selection == ‘random’. Pass an int for reproducible output across multiple function calls. See Glossary.
selection{‘cyclic’, ‘random’}, default=’cyclic’

If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4.    Attributes

alpha_float

The amount of penalization chosen by cross validation.
l1_ratio_float

The compromise between l1 and l2 penalization chosen by cross validation.
coef_ndarray of shape (n_features,) or (n_targets, n_features)

Parameter vector (w in the cost function formula).
intercept_float or ndarray of shape (n_targets, n_features)

Independent term in the decision function.
mse_path_ndarray of shape (n_l1_ratio, n_alpha, n_folds)

Mean square error for the test set on each fold, varying l1_ratio and alpha.
alphas_ndarray of shape (n_alphas,) or (n_l1_ratio, n_alphas)

The grid of alphas used for fitting, for each l1_ratio.
dual_gap_float

The dual gaps at the end of the optimization for the optimal alpha.
n_iter_int

Number of iterations run by the coordinate descent solver to reach the specified tolerance for the optimal alpha.      See also
enet_path

ElasticNet

  Notes For an example, see examples/linear_model/plot_lasso_model_selection.py. To avoid unnecessary memory duplication the X argument of the fit method should be directly passed as a Fortran-contiguous numpy array. The parameter l1_ratio corresponds to alpha in the glmnet R package while alpha corresponds to the lambda parameter in glmnet. More specifically, the optimization objective is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 If you are interested in controlling the L1 and L2 penalty separately, keep in mind that this is equivalent to: a * L1 + b * L2
 for: alpha = a + b and l1_ratio = a / (a + b).
 Examples >>> from sklearn.linear_model import ElasticNetCV
>>> from sklearn.datasets import make_regression
 >>> X, y = make_regression(n_features=2, random_state=0)
>>> regr = ElasticNetCV(cv=5, random_state=0)
>>> regr.fit(X, y)
ElasticNetCV(cv=5, random_state=0)
>>> print(regr.alpha_)
0.199...
>>> print(regr.intercept_)
0.398...
>>> print(regr.predict([[0, 0]]))
[0.398...]
 Methods
fit(X, y) Fit linear model with coordinate descent.
get_params([deep]) Get parameters for this estimator.
path(*args, **kwargs) Compute elastic net path with coordinate descent.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]

Fit linear model with coordinate descent. Fit is on grid of alphas and best alpha estimated by cross-validation.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output, X can be sparse.
yarray-like of shape (n_samples,) or (n_samples, n_targets)

Target values.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

static path(*args, **kwargs) [source]

Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 For multi-output tasks it is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
 Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
 i.e. the sum of norm of each row. Read more in the User Guide.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output then X can be sparse.
y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)

Target values.
l1_ratiofloat, default=0.5

Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). l1_ratio=1 corresponds to the Lasso.
epsfloat, default=1e-3

Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100

Number of alphas along the regularization path.
alphasndarray, default=None

List of alphas where to compute the models. If None alphas are set automatically.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
Xyarray-like of shape (n_features,) or (n_features, n_outputs), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
coef_initndarray of shape (n_features, ), default=None

The initial values of the coefficients.
verbosebool or int, default=False

Amount of verbosity.
return_n_iterbool, default=False

Whether to return the number of iterations or not.
positivebool, default=False

If set to True, forces coefficients to be positive. (Only allowed when y.ndim == 1).
check_inputbool, default=True

If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller.
**paramskwargs

Keyword arguments passed to the coordinate descent solver.    Returns

alphasndarray of shape (n_alphas,)

The alphas along the path where models are computed.
coefsndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)

Coefficients along the path.
dual_gapsndarray of shape (n_alphas,)

The dual gaps at the end of the optimization for each alpha.
n_iterslist of int

The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when return_n_iter is set to True).      See also
MultiTaskElasticNet

MultiTaskElasticNetCV

ElasticNet

ElasticNetCV

  Notes For an example, see examples/linear_model/plot_lasso_coordinate_descent_path.py.

predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


fit(X, y) [source]

Fit linear model with coordinate descent. Fit is on grid of alphas and best alpha estimated by cross-validation.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output, X can be sparse.
yarray-like of shape (n_samples,) or (n_samples, n_targets)

Target values.


sklearn.linear_model.enet_path(X, y, *, l1_ratio=0.5, eps=0.001, n_alphas=100, alphas=None, precompute='auto', Xy=None, copy_X=True, coef_init=None, verbose=False, return_n_iter=False, positive=False, check_input=True, **params) [source]

Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
 For multi-output tasks it is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
 Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
 i.e. the sum of norm of each row. Read more in the User Guide.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output then X can be sparse.
y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)

Target values.
l1_ratiofloat, default=0.5

Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). l1_ratio=1 corresponds to the Lasso.
epsfloat, default=1e-3

Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100

Number of alphas along the regularization path.
alphasndarray, default=None

List of alphas where to compute the models. If None alphas are set automatically.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
Xyarray-like of shape (n_features,) or (n_features, n_outputs), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
coef_initndarray of shape (n_features, ), default=None

The initial values of the coefficients.
verbosebool or int, default=False

Amount of verbosity.
return_n_iterbool, default=False

Whether to return the number of iterations or not.
positivebool, default=False

If set to True, forces coefficients to be positive. (Only allowed when y.ndim == 1).
check_inputbool, default=True

If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller.
**paramskwargs

Keyword arguments passed to the coordinate descent solver.    Returns

alphasndarray of shape (n_alphas,)

The alphas along the path where models are computed.
coefsndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)

Coefficients along the path.
dual_gapsndarray of shape (n_alphas,)

The dual gaps at the end of the optimization for each alpha.
n_iterslist of int

The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when return_n_iter is set to True).      See also
MultiTaskElasticNet

MultiTaskElasticNetCV

ElasticNet

ElasticNetCV

  Notes For an example, see examples/linear_model/plot_lasso_coordinate_descent_path.py.


class sklearn.linear_model.GammaRegressor(*, alpha=1.0, fit_intercept=True, max_iter=100, tol=0.0001, warm_start=False, verbose=0) [source]

Generalized Linear Model with a Gamma distribution. Read more in the User Guide.  New in version 0.23.   Parameters

alphafloat, default=1

Constant that multiplies the penalty term and thus determines the regularization strength. alpha = 0 is equivalent to unpenalized GLMs. In this case, the design matrix X must have full column rank (no collinearities).
fit_interceptbool, default=True

Specifies if a constant (a.k.a. bias or intercept) should be added to the linear predictor (X @ coef + intercept).
max_iterint, default=100

The maximal number of iterations for the solver.
tolfloat, default=1e-4

Stopping criterion. For the lbfgs solver, the iteration will stop when max{|g_j|, j = 1, ..., d} <= tol where g_j is the j-th component of the gradient (derivative) of the objective function.
warm_startbool, default=False

If set to True, reuse the solution of the previous call to fit as initialization for coef_ and intercept_ .
verboseint, default=0

For the lbfgs solver set verbose to any positive number for verbosity.    Attributes

coef_array of shape (n_features,)

Estimated coefficients for the linear predictor (X * coef_ +
intercept_) in the GLM.
intercept_float

Intercept (a.k.a. bias) added to linear predictor.
n_iter_int

Actual number of iterations used in the solver.     Examples >>> from sklearn import linear_model
>>> clf = linear_model.GammaRegressor()
>>> X = [[1, 2], [2, 3], [3, 4], [4, 3]]
>>> y = [19, 26, 33, 30]
>>> clf.fit(X, y)
GammaRegressor()
>>> clf.score(X, y)
0.773...
>>> clf.coef_
array([0.072..., 0.066...])
>>> clf.intercept_
2.896...
>>> clf.predict([[1, 0], [2, 8]])
array([19.483..., 35.795...])
 Methods
fit(X, y[, sample_weight]) Fit a Generalized Linear Model.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using GLM with feature matrix X.
score(X, y[, sample_weight]) Compute D^2, the percentage of deviance explained.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]

Fit a Generalized Linear Model.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,)

Target values.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

selfreturns an instance of self.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict using GLM with feature matrix X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Samples.    Returns

y_predarray of shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Compute D^2, the percentage of deviance explained. D^2 is a generalization of the coefficient of determination R^2. R^2 uses squared error and D^2 deviance. Note that those two are equal for family='normal'. D^2 is defined as \(D^2 = 1-\frac{D(y_{true},y_{pred})}{D_{null}}\), \(D_{null}\) is the null deviance, i.e. the deviance of a model with intercept alone, which corresponds to \(y_{pred} = \bar{y}\). The mean \(\bar{y}\) is averaged by sample_weight. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,)

True values of target.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

D^2 of self.predict(X) w.r.t. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.linear_model.GammaRegressor
class sklearn.linear_model.GammaRegressor(*, alpha=1.0, fit_intercept=True, max_iter=100, tol=0.0001, warm_start=False, verbose=0) [source]

Generalized Linear Model with a Gamma distribution. Read more in the User Guide.  New in version 0.23.   Parameters

alphafloat, default=1

Constant that multiplies the penalty term and thus determines the regularization strength. alpha = 0 is equivalent to unpenalized GLMs. In this case, the design matrix X must have full column rank (no collinearities).
fit_interceptbool, default=True

Specifies if a constant (a.k.a. bias or intercept) should be added to the linear predictor (X @ coef + intercept).
max_iterint, default=100

The maximal number of iterations for the solver.
tolfloat, default=1e-4

Stopping criterion. For the lbfgs solver, the iteration will stop when max{|g_j|, j = 1, ..., d} <= tol where g_j is the j-th component of the gradient (derivative) of the objective function.
warm_startbool, default=False

If set to True, reuse the solution of the previous call to fit as initialization for coef_ and intercept_ .
verboseint, default=0

For the lbfgs solver set verbose to any positive number for verbosity.    Attributes

coef_array of shape (n_features,)

Estimated coefficients for the linear predictor (X * coef_ +
intercept_) in the GLM.
intercept_float

Intercept (a.k.a. bias) added to linear predictor.
n_iter_int

Actual number of iterations used in the solver.     Examples >>> from sklearn import linear_model
>>> clf = linear_model.GammaRegressor()
>>> X = [[1, 2], [2, 3], [3, 4], [4, 3]]
>>> y = [19, 26, 33, 30]
>>> clf.fit(X, y)
GammaRegressor()
>>> clf.score(X, y)
0.773...
>>> clf.coef_
array([0.072..., 0.066...])
>>> clf.intercept_
2.896...
>>> clf.predict([[1, 0], [2, 8]])
array([19.483..., 35.795...])
 Methods
fit(X, y[, sample_weight]) Fit a Generalized Linear Model.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using GLM with feature matrix X.
score(X, y[, sample_weight]) Compute D^2, the percentage of deviance explained.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]

Fit a Generalized Linear Model.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,)

Target values.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

selfreturns an instance of self.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict using GLM with feature matrix X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Samples.    Returns

y_predarray of shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Compute D^2, the percentage of deviance explained. D^2 is a generalization of the coefficient of determination R^2. R^2 uses squared error and D^2 deviance. Note that those two are equal for family='normal'. D^2 is defined as \(D^2 = 1-\frac{D(y_{true},y_{pred})}{D_{null}}\), \(D_{null}\) is the null deviance, i.e. the deviance of a model with intercept alone, which corresponds to \(y_{pred} = \bar{y}\). The mean \(\bar{y}\) is averaged by sample_weight. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,)

True values of target.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

D^2 of self.predict(X) w.r.t. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

 Examples using sklearn.linear_model.GammaRegressor

  Release Highlights for scikit-learn 0.23

  Tweedie regression on insurance claims


fit(X, y, sample_weight=None) [source]

Fit a Generalized Linear Model.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,)

Target values.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

selfreturns an instance of self.


predict(X) [source]

Predict using GLM with feature matrix X.  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Samples.    Returns

y_predarray of shape (n_samples,)

Returns predicted values.


score(X, y, sample_weight=None) [source]

Compute D^2, the percentage of deviance explained. D^2 is a generalization of the coefficient of determination R^2. R^2 uses squared error and D^2 deviance. Note that those two are equal for family='normal'. D^2 is defined as \(D^2 = 1-\frac{D(y_{true},y_{pred})}{D_{null}}\), \(D_{null}\) is the null deviance, i.e. the deviance of a model with intercept alone, which corresponds to \(y_{pred} = \bar{y}\). The mean \(\bar{y}\) is averaged by sample_weight. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).  Parameters

X{array-like, sparse matrix} of shape (n_samples, n_features)

Test samples.
yarray-like of shape (n_samples,)

True values of target.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

D^2 of self.predict(X) w.r.t. y.


class sklearn.linear_model.HuberRegressor(*, epsilon=1.35, max_iter=100, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05) [source]

Linear regression model that is robust to outliers. The Huber Regressor optimizes the squared loss for the samples where |(y - X'w) / sigma| < epsilon and the absolute loss for the samples where |(y - X'w) / sigma| > epsilon, where w and sigma are parameters to be optimized. The parameter sigma makes sure that if y is scaled up or down by a certain factor, one does not need to rescale epsilon to achieve the same robustness. Note that this does not take into account the fact that the different features of X may be of different scales. This makes sure that the loss function is not heavily influenced by the outliers while not completely ignoring their effect. Read more in the User Guide  New in version 0.18.   Parameters

epsilonfloat, greater than 1.0, default=1.35

The parameter epsilon controls the number of samples that should be classified as outliers. The smaller the epsilon, the more robust it is to outliers.
max_iterint, default=100

Maximum number of iterations that scipy.optimize.minimize(method="L-BFGS-B") should run for.
alphafloat, default=0.0001

Regularization parameter.
warm_startbool, default=False

This is useful if the stored attributes of a previously used model has to be reused. If set to False, then the coefficients will be rewritten for every call to fit. See the Glossary.
fit_interceptbool, default=True

Whether or not to fit the intercept. This can be set to False if the data is already centered around the origin.
tolfloat, default=1e-05

The iteration will stop when max{|proj g_i | i = 1, ..., n} <= tol where pg_i is the i-th component of the projected gradient.    Attributes

coef_array, shape (n_features,)

Features got by optimizing the Huber loss.
intercept_float

Bias.
scale_float

The value by which |y - X'w - c| is scaled down.
n_iter_int

Number of iterations that scipy.optimize.minimize(method="L-BFGS-B") has run for.  Changed in version 0.20: In SciPy <= 1.0.0 the number of lbfgs iterations may exceed max_iter. n_iter_ will now report at most max_iter.
outliers_array, shape (n_samples,)

A boolean mask which is set to True where the samples are identified as outliers.     References
1
Peter J. Huber, Elvezio M. Ronchetti, Robust Statistics Concomitant scale estimates, pg 172
2
Art B. Owen (2006), A robust hybrid of lasso and ridge regression. https://statweb.stanford.edu/~owen/reports/hhu.pdf   Examples >>> import numpy as np
>>> from sklearn.linear_model import HuberRegressor, LinearRegression
>>> from sklearn.datasets import make_regression
>>> rng = np.random.RandomState(0)
>>> X, y, coef = make_regression(
...     n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0)
>>> X[:4] = rng.uniform(10, 20, (4, 2))
>>> y[:4] = rng.uniform(10, 20, 4)
>>> huber = HuberRegressor().fit(X, y)
>>> huber.score(X, y)
-7.284...
>>> huber.predict(X[:1,])
array([806.7200...])
>>> linear = LinearRegression().fit(X, y)
>>> print("True coefficients:", coef)
True coefficients: [20.4923...  34.1698...]
>>> print("Huber coefficients:", huber.coef_)
Huber coefficients: [17.7906... 31.0106...]
>>> print("Linear Regression coefficients:", linear.coef_)
Linear Regression coefficients: [-1.9221...  7.0226...]
 Methods
fit(X, y[, sample_weight]) Fit the model according to the given training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]

Fit the model according to the given training data.  Parameters

Xarray-like, shape (n_samples, n_features)

Training vector, where n_samples in the number of samples and n_features is the number of features.
yarray-like, shape (n_samples,)

Target vector relative to X.
sample_weightarray-like, shape (n_samples,)

Weight given to each sample.    Returns

selfobject

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.linear_model.HuberRegressor
class sklearn.linear_model.HuberRegressor(*, epsilon=1.35, max_iter=100, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05) [source]

Linear regression model that is robust to outliers. The Huber Regressor optimizes the squared loss for the samples where |(y - X'w) / sigma| < epsilon and the absolute loss for the samples where |(y - X'w) / sigma| > epsilon, where w and sigma are parameters to be optimized. The parameter sigma makes sure that if y is scaled up or down by a certain factor, one does not need to rescale epsilon to achieve the same robustness. Note that this does not take into account the fact that the different features of X may be of different scales. This makes sure that the loss function is not heavily influenced by the outliers while not completely ignoring their effect. Read more in the User Guide  New in version 0.18.   Parameters

epsilonfloat, greater than 1.0, default=1.35

The parameter epsilon controls the number of samples that should be classified as outliers. The smaller the epsilon, the more robust it is to outliers.
max_iterint, default=100

Maximum number of iterations that scipy.optimize.minimize(method="L-BFGS-B") should run for.
alphafloat, default=0.0001

Regularization parameter.
warm_startbool, default=False

This is useful if the stored attributes of a previously used model has to be reused. If set to False, then the coefficients will be rewritten for every call to fit. See the Glossary.
fit_interceptbool, default=True

Whether or not to fit the intercept. This can be set to False if the data is already centered around the origin.
tolfloat, default=1e-05

The iteration will stop when max{|proj g_i | i = 1, ..., n} <= tol where pg_i is the i-th component of the projected gradient.    Attributes

coef_array, shape (n_features,)

Features got by optimizing the Huber loss.
intercept_float

Bias.
scale_float

The value by which |y - X'w - c| is scaled down.
n_iter_int

Number of iterations that scipy.optimize.minimize(method="L-BFGS-B") has run for.  Changed in version 0.20: In SciPy <= 1.0.0 the number of lbfgs iterations may exceed max_iter. n_iter_ will now report at most max_iter.
outliers_array, shape (n_samples,)

A boolean mask which is set to True where the samples are identified as outliers.     References
1
Peter J. Huber, Elvezio M. Ronchetti, Robust Statistics Concomitant scale estimates, pg 172
2
Art B. Owen (2006), A robust hybrid of lasso and ridge regression. https://statweb.stanford.edu/~owen/reports/hhu.pdf   Examples >>> import numpy as np
>>> from sklearn.linear_model import HuberRegressor, LinearRegression
>>> from sklearn.datasets import make_regression
>>> rng = np.random.RandomState(0)
>>> X, y, coef = make_regression(
...     n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0)
>>> X[:4] = rng.uniform(10, 20, (4, 2))
>>> y[:4] = rng.uniform(10, 20, 4)
>>> huber = HuberRegressor().fit(X, y)
>>> huber.score(X, y)
-7.284...
>>> huber.predict(X[:1,])
array([806.7200...])
>>> linear = LinearRegression().fit(X, y)
>>> print("True coefficients:", coef)
True coefficients: [20.4923...  34.1698...]
>>> print("Huber coefficients:", huber.coef_)
Huber coefficients: [17.7906... 31.0106...]
>>> print("Linear Regression coefficients:", linear.coef_)
Linear Regression coefficients: [-1.9221...  7.0226...]
 Methods
fit(X, y[, sample_weight]) Fit the model according to the given training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]

Fit the model according to the given training data.  Parameters

Xarray-like, shape (n_samples, n_features)

Training vector, where n_samples in the number of samples and n_features is the number of features.
yarray-like, shape (n_samples,)

Target vector relative to X.
sample_weightarray-like, shape (n_samples,)

Weight given to each sample.    Returns

selfobject

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

 Examples using sklearn.linear_model.HuberRegressor

  HuberRegressor vs Ridge on dataset with strong outliers

  Robust linear estimator fitting


fit(X, y, sample_weight=None) [source]

Fit the model according to the given training data.  Parameters

Xarray-like, shape (n_samples, n_features)

Training vector, where n_samples in the number of samples and n_features is the number of features.
yarray-like, shape (n_samples,)

Target vector relative to X.
sample_weightarray-like, shape (n_samples,)

Weight given to each sample.    Returns

selfobject


get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.


predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.


score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


class sklearn.linear_model.Lars(*, fit_intercept=True, verbose=False, normalize=True, precompute='auto', n_nonzero_coefs=500, eps=2.220446049250313e-16, copy_X=True, fit_path=True, jitter=None, random_state=None) [source]

Least Angle Regression model a.k.a. LAR Read more in the User Guide.  Parameters

fit_interceptbool, default=True

Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
verbosebool or int, default=False

Sets the verbosity amount.
normalizebool, default=True

This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
precomputebool, ‘auto’ or array-like , default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
n_nonzero_coefsint, default=500

Target number of non-zero coefficients. Use np.inf for no limit.
epsfloat, default=np.finfo(float).eps

The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
fit_pathbool, default=True

If True the full path is stored in the coef_path_ attribute. If you compute the solution for a large problem or many targets, setting fit_path to False will lead to a speedup, especially with a small alpha.
jitterfloat, default=None

Upper bound on a uniform noise parameter to be added to the y values, to satisfy the model’s assumption of one-at-a-time computations. Might help with stability.  New in version 0.23.
random_stateint, RandomState instance or None, default=None

Determines random number generation for jittering. Pass an int for reproducible output across multiple function calls. See Glossary. Ignored if jitter is None.  New in version 0.23.     Attributes

alphas_array-like of shape (n_alphas + 1,) or list of such arrays

Maximum of covariances (in absolute value) at each iteration. n_alphas is either max_iter, n_features or the number of nodes in the path with alpha >= alpha_min, whichever is smaller. If this is a list of array-like, the length of the outer list is n_targets.
active_list of shape (n_alphas,) or list of such lists

Indices of active variables at the end of the path. If this is a list of list, the length of the outer list is n_targets.
coef_path_array-like of shape (n_features, n_alphas + 1) or list of such arrays

The varying values of the coefficients along the path. It is not present if the fit_path parameter is False. If this is a list of array-like, the length of the outer list is n_targets.
coef_array-like of shape (n_features,) or (n_targets, n_features)

Parameter vector (w in the formulation formula).
intercept_float or array-like of shape (n_targets,)

Independent term in decision function.
n_iter_array-like or int

The number of iterations taken by lars_path to find the grid of alphas for each target.      See also
lars_path, LarsCV

sklearn.decomposition.sparse_encode

  Examples >>> from sklearn import linear_model
>>> reg = linear_model.Lars(n_nonzero_coefs=1)
>>> reg.fit([[-1, 1], [0, 0], [1, 1]], [-1.1111, 0, -1.1111])
Lars(n_nonzero_coefs=1)
>>> print(reg.coef_)
[ 0. -1.11...]
 Methods
fit(X, y[, Xy]) Fit the model using X, y as training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, Xy=None) [source]

Fit the model using X, y as training data.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_targets)

Target values.
Xyarray-like of shape (n_samples,) or (n_samples, n_targets), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.    Returns

selfobject

returns an instance of self.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.linear_model.Lars
class sklearn.linear_model.Lars(*, fit_intercept=True, verbose=False, normalize=True, precompute='auto', n_nonzero_coefs=500, eps=2.220446049250313e-16, copy_X=True, fit_path=True, jitter=None, random_state=None) [source]

Least Angle Regression model a.k.a. LAR Read more in the User Guide.  Parameters

fit_interceptbool, default=True

Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
verbosebool or int, default=False

Sets the verbosity amount.
normalizebool, default=True

This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
precomputebool, ‘auto’ or array-like , default=’auto’

Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
n_nonzero_coefsint, default=500

Target number of non-zero coefficients. Use np.inf for no limit.
epsfloat, default=np.finfo(float).eps

The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization.
copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.
fit_pathbool, default=True

If True the full path is stored in the coef_path_ attribute. If you compute the solution for a large problem or many targets, setting fit_path to False will lead to a speedup, especially with a small alpha.
jitterfloat, default=None

Upper bound on a uniform noise parameter to be added to the y values, to satisfy the model’s assumption of one-at-a-time computations. Might help with stability.  New in version 0.23.
random_stateint, RandomState instance or None, default=None

Determines random number generation for jittering. Pass an int for reproducible output across multiple function calls. See Glossary. Ignored if jitter is None.  New in version 0.23.     Attributes

alphas_array-like of shape (n_alphas + 1,) or list of such arrays

Maximum of covariances (in absolute value) at each iteration. n_alphas is either max_iter, n_features or the number of nodes in the path with alpha >= alpha_min, whichever is smaller. If this is a list of array-like, the length of the outer list is n_targets.
active_list of shape (n_alphas,) or list of such lists

Indices of active variables at the end of the path. If this is a list of list, the length of the outer list is n_targets.
coef_path_array-like of shape (n_features, n_alphas + 1) or list of such arrays

The varying values of the coefficients along the path. It is not present if the fit_path parameter is False. If this is a list of array-like, the length of the outer list is n_targets.
coef_array-like of shape (n_features,) or (n_targets, n_features)

Parameter vector (w in the formulation formula).
intercept_float or array-like of shape (n_targets,)

Independent term in decision function.
n_iter_array-like or int

The number of iterations taken by lars_path to find the grid of alphas for each target.      See also
lars_path, LarsCV

sklearn.decomposition.sparse_encode

  Examples >>> from sklearn import linear_model
>>> reg = linear_model.Lars(n_nonzero_coefs=1)
>>> reg.fit([[-1, 1], [0, 0], [1, 1]], [-1.1111, 0, -1.1111])
Lars(n_nonzero_coefs=1)
>>> print(reg.coef_)
[ 0. -1.11...]
 Methods
fit(X, y[, Xy]) Fit the model using X, y as training data.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, Xy=None) [source]

Fit the model using X, y as training data.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_targets)

Target values.
Xyarray-like of shape (n_samples,) or (n_samples, n_targets), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.    Returns

selfobject

returns an instance of self.

get_params(deep=True) [source]

Get parameters for this estimator.  Parameters

deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.    Returns

paramsdict

Parameter names mapped to their values.

predict(X) [source]

Predict using the linear model.  Parameters

Xarray-like or sparse matrix, shape (n_samples, n_features)

Samples.    Returns

Carray, shape (n_samples,)

Returns predicted values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


fit(X, y, Xy=None) [source]

Fit the model using X, y as training data.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_targets)

Target values.
Xyarray-like of shape (n_samples,) or (n_samples, n_targets), default=None

Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.    Returns

selfobject

returns an instance of self.