ElasticNetCV#
- class sklearn.linear_model.ElasticNetCV(*, l1_ratio=0.5, eps=0.001, n_alphas='deprecated', alphas='warn', fit_intercept=True, precompute='auto', max_iter=1000, tol=0.0001, cv=None, copy_X=True, verbose=0, n_jobs=None, positive=False, random_state=None, selection='cyclic')[source]#
具有沿正则化路径迭代拟合的 Elastic Net 模型。
参见词汇表条目 交叉验证估计器。
在用户指南中阅读更多内容。
- 参数:
- l1_ratiofloat 或 float 列表, default=0.5
传递给 ElasticNet 的浮点数,介于 0 和 1 之间(l1 和 l2 惩罚项之间的缩放比例)。对于
l1_ratio = 0,惩罚项为 L2 惩罚项。对于l1_ratio = 1,惩罚项为 L1 惩罚项。对于0 < l1_ratio < 1,惩罚项是 L1 和 L2 的组合。此参数可以是一个列表,在这种情况下,将通过交叉验证测试不同的值,并使用给出最佳预测分数的值。请注意,l1_ratio 值列表的一个好的选择通常是设置更多接近 1(即 Lasso)的值,而更少接近 0(即 Ridge)的值,例如[.1, .5, .7, .9, .95, .99, 1]。- epsfloat, default=1e-3
路径的长度。
eps=1e-3表示alpha_min / alpha_max = 1e-3。- n_alphasint, default=100
沿着正则化路径的 alpha 数量,用于每个 l1_ratio。
Deprecated since version 1.7:
n_alphaswas deprecated in 1.7 and will be removed in 1.9. Usealphasinstead.- alphasarray-like or int, default=None
沿着正则化路径测试的 alpha 值,用于每个 l1_ratio。如果为 int,则自动生成
alphas值。如果为 array-like,则使用 alpha 值列表。Changed in version 1.7:
alphasaccepts an integer value which removes the need to passn_alphas.Deprecated since version 1.7:
alphas=Nonewas deprecated in 1.7 and will be removed in 1.9, at which point the default value will be set to 100.- 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).
- precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’
是否使用预计算的Gram矩阵来加快计算速度。如果设置为
'auto',则由我们决定。Gram矩阵也可以作为参数传入。- max_iterint, default=1000
最大迭代次数。
- tolfloat, default=1e-4
The tolerance for the optimization: if the updates are smaller or equal to
tol, the optimization code checks the dual gap for optimality and continues until it is smaller or equal totol.- cvint, cross-validation generator or iterable, default=None
确定交叉验证拆分策略。cv 的可能输入包括
None,使用默认的 5 折交叉验证,
int, to specify the number of folds.
一个可迭代对象,产生索引数组形式的 (训练集, 测试集) 拆分。
For int/None inputs,
KFoldis used.有关此处可使用的各种交叉验证策略,请参阅 用户指南。
版本 0.22 中已更改:如果为 None,
cv默认值从 3 折更改为 5 折。- copy_Xbool, default=True
如果为
True,X将被复制;否则,它可能会被覆盖。- verbosebool 或 int, default=0
冗余度级别。
- n_jobsint, default=None
Number of CPUs to use during the cross validation.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means using all processors. See Glossary for more details.- positivebool, default=False
设置为
True时,强制系数为正。- random_stateint, RandomState instance, default=None
选择要更新的随机特征的伪随机数生成器种子。当
selection== ‘random’时使用。传入一个整数可以在多次函数调用中获得可重现的输出。请参阅词汇表。- selection{‘cyclic’, ‘random’}, default=’cyclic’
如果设置为‘random’,则每次迭代更新一个随机系数,而不是默认按顺序遍历特征。这(设置为‘random’)通常会导致显著更快的收敛,尤其当tol高于1e-4时。
- 属性:
- alpha_float
The amount of penalization chosen by cross validation.
- l1_ratio_float
通过交叉验证选择的 l1 和 l2 惩罚项之间的折衷。
- coef_ndarray of shape (n_features,) or (n_targets, n_features)
参数向量(成本函数公式中的w)。
- intercept_float 或 shape (n_targets, n_features) 的 ndarray
决策函数中的独立项。
- mse_path_shape (n_l1_ratio, n_alpha, n_folds) 的 ndarray
每个折叠的测试集上的均方误差,l1_ratio 和 alpha 变化。
- alphas_shape (n_alphas,) 或 (n_l1_ratio, n_alphas) 的 ndarray
用于拟合的 alpha 网格,用于每个 l1_ratio。
- dual_gap_float
对于最优 alpha,优化结束时的对偶间隙。
- n_iter_int
Number of iterations run by the coordinate descent solver to reach the specified tolerance for the optimal alpha.
- n_features_in_int
在 拟合 期间看到的特征数。
0.24 版本新增。
- feature_names_in_shape 为 (
n_features_in_,) 的 ndarray 在 fit 期间看到的特征名称。仅当
X具有全部为字符串的特征名称时才定义。1.0 版本新增。
另请参阅
enet_path使用坐标下降计算 elastic net 路径。
ElasticNet具有组合 L1 和 L2 先验作为正则化项的线性回归。
注意事项
在
fit中,一旦通过交叉验证找到最佳参数l1_ratio和alpha,模型将使用整个训练集再次拟合。为避免不必要的内存复制,
fit方法的X参数应直接作为 Fortran 连续 numpy 数组传递。参数
l1_ratio对应于 glmnet R 包中的 alpha,而 alpha 对应于 glmnet 中的 lambda 参数。更具体地说,优化目标是1 / (2 * n_samples) * ||y - Xw||^2_2 + alpha * l1_ratio * ||w||_1 + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
如果您对分别控制 L1 和 L2 惩罚项感兴趣,请记住这等同于
a * L1 + b * L2
对于
alpha = a + b and l1_ratio = a / (a + b).
有关示例,请参阅 examples/linear_model/plot_lasso_model_selection.py。
底层的坐标下降求解器使用间隙安全筛选规则来加快拟合时间,请参阅坐标下降用户指南。
示例
>>> 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]
- fit(X, y, sample_weight=None, **params)[source]#
使用坐标下降拟合 ElasticNet 模型。
Fit is on grid of alphas and best alpha estimated by cross-validation.
- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
训练数据。直接作为 Fortran 连续数据传递,以避免不必要的内存复制。如果 y 是单输出,则 X 可以是稀疏的。请注意,不接受需要
int64索引的大型稀疏矩阵和数组。- yarray-like of shape (n_samples,)
目标值。
- sample_weightfloat or array-like of shape (n_samples,), default=None
用于拟合和评估每个 cv 折叠的加权均方误差的样本权重。请注意,最终用于查找最佳模型的交叉验证 MSE 是对每个测试折叠的(加权)MSEs 的未加权平均值。
- **paramsdict, default=None
Parameters to be passed to the CV splitter.
Added in version 1.4: Only available if
enable_metadata_routing=True, which can be set by usingsklearn.set_config(enable_metadata_routing=True). See Metadata Routing User Guide for more details.
- 返回:
- selfobject
返回已拟合模型的实例。
- get_metadata_routing()[source]#
获取此对象的元数据路由。
请查阅 用户指南,了解路由机制如何工作。
1.4 版本新增。
- 返回:
- routingMetadataRouter
封装路由信息的
MetadataRouter。
- get_params(deep=True)[source]#
获取此估计器的参数。
- 参数:
- deepbool, default=True
如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。
- 返回:
- paramsdict
参数名称映射到其值。
- static 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]#
使用坐标下降计算 elastic net 路径。
弹性网络优化函数对于单输出和多输出任务有所不同。
对于单输出任务,它是
1 / (2 * n_samples) * ||y - Xw||^2_2 + alpha * l1_ratio * ||w||_1 + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
对于多输出任务,它是
(1 / (2 * n_samples)) * ||Y - XW||_Fro^2 + alpha * l1_ratio * ||W||_21 + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
其中
||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
即每行范数之和。
在用户指南中阅读更多内容。
- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
训练数据。直接作为Fortran连续数据传递以避免不必要的内存复制。如果
y是单输出,则X可以是稀疏的。- y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_targets)
目标值。
- l1_ratiofloat, default=0.5
传递给弹性网络的值介于0和1之间(L1和L2惩罚之间的缩放)。
l1_ratio=1对应于Lasso。- epsfloat, default=1e-3
路径的长度。
eps=1e-3表示alpha_min / alpha_max = 1e-3。- n_alphasint, default=100
正则化路径上alpha的数量。
- alphasarray-like, default=None
计算模型的alpha列表。如果为None,则自动设置alphas。
- precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’
是否使用预计算的Gram矩阵来加快计算速度。如果设置为
'auto',则由我们决定。Gram矩阵也可以作为参数传入。- Xyarray-like of shape (n_features,) or (n_features, n_targets), default=None
可以预计算的Xy = np.dot(X.T, y)。仅当Gram矩阵预计算时有用。
- copy_Xbool, default=True
如果为
True,X将被复制;否则,它可能会被覆盖。- coef_initarray-like of shape (n_features, ), default=None
系数的初始值。
- verbosebool or int, default=False
冗余度级别。
- return_n_iterbool, default=False
是否返回迭代次数。
- positivebool, default=False
如果设置为True,强制系数为正。(仅当
y.ndim == 1时允许)。- check_inputbool, default=True
如果设置为False,则跳过输入验证检查(包括提供的Gram矩阵)。假设这些检查由调用者处理。
- **paramskwargs
传递给坐标下降求解器的关键字参数。
- 返回:
- alphasndarray of shape (n_alphas,)
计算模型的路径上的alphas。
- coefsndarray of shape (n_features, n_alphas) or (n_targets, n_features, n_alphas)
路径上的系数。
- dual_gapsndarray of shape (n_alphas,)
每个alpha优化结束时的对偶间隙。
- n_iterslist of int
坐标下降优化器为达到每个alpha的指定容忍度所花费的迭代次数。(当
return_n_iter设置为True时返回)。
另请参阅
MultiTaskElasticNet使用 L1/L2 混合范数作为正则化项训练的多任务 ElasticNet 模型。
MultiTaskElasticNetCV具有内置交叉验证的多任务 L1/L2 ElasticNet。
ElasticNet具有组合 L1 和 L2 先验作为正则化项的线性回归。
ElasticNetCV具有沿正则化路径迭代拟合的 Elastic Net 模型。
注意事项
有关示例,请参阅examples/linear_model/plot_lasso_lasso_lars_elasticnet_path.py。
底层的坐标下降求解器使用间隙安全筛选规则来加快拟合时间,请参阅坐标下降用户指南。
示例
>>> from sklearn.linear_model import enet_path >>> from sklearn.datasets import make_regression >>> X, y, true_coef = make_regression( ... n_samples=100, n_features=5, n_informative=2, coef=True, random_state=0 ... ) >>> true_coef array([ 0. , 0. , 0. , 97.9, 45.7]) >>> alphas, estimated_coef, _ = enet_path(X, y, n_alphas=3) >>> alphas.shape (3,) >>> estimated_coef array([[ 0., 0.787, 0.568], [ 0., 1.120, 0.620], [-0., -2.129, -1.128], [ 0., 23.046, 88.939], [ 0., 10.637, 41.566]])
- predict(X)[source]#
使用线性模型进行预测。
- 参数:
- Xarray-like or sparse matrix, shape (n_samples, n_features)
样本。
- 返回:
- Carray, shape (n_samples,)
返回预测值。
- score(X, y, sample_weight=None)[source]#
返回测试数据的 决定系数。
决定系数 \(R^2\) 定义为 \((1 - \frac{u}{v})\),其中 \(u\) 是残差平方和
((y_true - y_pred)** 2).sum(),\(v\) 是总平方和((y_true - y_true.mean()) ** 2).sum()。最佳可能分数为 1.0,它也可以是负值(因为模型可能任意差)。一个始终预测y期望值,忽略输入特征的常数模型将获得 \(R^2\) 分数 0.0。- 参数:
- Xshape 为 (n_samples, n_features) 的 array-like
测试样本。对于某些估计器,这可能是一个预先计算的核矩阵或一个通用对象列表,形状为
(n_samples, n_samples_fitted),其中n_samples_fitted是用于估计器拟合的样本数。- yshape 为 (n_samples,) 或 (n_samples, n_outputs) 的 array-like
X的真实值。- sample_weightshape 为 (n_samples,) 的 array-like, default=None
样本权重。
- 返回:
- scorefloat
self.predict(X)相对于y的 \(R^2\)。
注意事项
在回归器上调用
score时使用的 \(R^2\) 分数从版本 0.23 开始使用multioutput='uniform_average',以与r2_score的默认值保持一致。这会影响所有多输出回归器(除了MultiOutputRegressor)的score方法。
- set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') ElasticNetCV[source]#
配置是否应请求元数据以传递给
fit方法。请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过
enable_metadata_routing=True启用了元数据路由(请参阅sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。每个参数的选项如下:
True:请求元数据,如果提供则传递给fit。如果未提供元数据,则忽略该请求。False:不请求元数据,元估计器不会将其传递给fit。None:不请求元数据,如果用户提供元数据,元估计器将引发错误。str:应将元数据以给定别名而不是原始名称传递给元估计器。
默认值 (
sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。在版本 1.3 中新增。
- 参数:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
fit方法中sample_weight参数的元数据路由。
- 返回:
- selfobject
更新后的对象。
- set_params(**params)[source]#
设置此估计器的参数。
此方法适用于简单的估计器以及嵌套对象(如
Pipeline)。后者具有<component>__<parameter>形式的参数,以便可以更新嵌套对象的每个组件。- 参数:
- **paramsdict
估计器参数。
- 返回:
- selfestimator instance
估计器实例。
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') ElasticNetCV[source]#
配置是否应请求元数据以传递给
score方法。请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过
enable_metadata_routing=True启用了元数据路由(请参阅sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。每个参数的选项如下:
True:请求元数据,如果提供则传递给score。如果未提供元数据,则忽略该请求。False:不请求元数据,元估计器不会将其传递给score。None:不请求元数据,如果用户提供元数据,元估计器将引发错误。str:应将元数据以给定别名而不是原始名称传递给元估计器。
默认值 (
sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。在版本 1.3 中新增。
- 参数:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
score方法中sample_weight参数的元数据路由。
- 返回:
- selfobject
更新后的对象。