sklearn.linear_model.LassoCV

class sklearn.linear_model.LassoCV(*, eps=0.001, n_alphas=100, alphas=None, fit_intercept=True, normalize=False, precompute='auto', max_iter=1000, tol=0.0001, copy_X=True, cv=None, verbose=False, n_jobs=None, positive=False, random_state=None, selection='cyclic')

沿着正则化路径具有迭代拟合的套索(Lasso)线性模型。

有关交叉验证估算器,请参阅词汇表条目。

通过交叉验证选择最佳模型。

Lasso的优化目标是:

用户指南中阅读更多内容。

参数 说明
eps float, default=1e-3
路径的长度。eps=1e-3意味着alpha_min / alpha_max = 1e-3
n_alphas int, default=100
沿正则化路径的Alpha个数。
alphas ndarray, default=None
用于计算模型的alpha列表。如果为None,自动设置Alpha。
fit_intercept bool, default=True
是否计算该模型的截距。如果设置为false,则在计算中将不使用截距(即数据应中心化)。
normalize bool, default=False
fit_intercept设置为False 时,将忽略此参数。如果为True,则在回归之前通过减去均值并除以l2-范数来对回归变量X进行归一化。如果你希望标准化,请先使用 sklearn.preprocessing.StandardScaler,然后调用fit 估算器并设置normalize=False
precompute ‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’
是否使用预先计算的Gram矩阵来加快计算速度。Gram矩阵也可以作为参数传递。
max_iter int, default=1000
最大迭代次数。
tol float, default=1e-4
优化的容忍度:如果更新小于tol,则优化代码检查对偶间隙的最优性,并继续进行直到其小于tol
copy_X bool, default=True
如果True,将复制X;否则X可能会被覆盖。
cv int, cross-validation generator or iterable, default=None
确定交叉验证拆分策略。可能的输入是:

- None,使用默认的5折交叉验证
- int,用于指定折叠数。
- CV分割器
- 可迭代生成(分割训练、测试)索引数组。

对于int / None输入,使用KFold

有关可在此处使用的各种交叉验证策略,请参阅用户指南

在0.22版本中更改:cv如果是“None”,默认值从3更改为5。
verbose bool or int, default=False
日志详细程度。
n_jobs int, default=None
交叉验证期间要使用的CPU核心数量。 除非在上下文中设置了joblib.parallel_backend,否则None表示1 。 -1表示使用所有处理器。有关更多详细信息,请参见词汇表
positive bool, default=False
设置为时True,强制系数为正。
random_state int, RandomState instance, default=None
更新特征随机选择的伪随机数生成器种子。在selection=='random'时使用。在多个函数调用之间传递同一个整数实现可重复的输出。请参阅词汇表
selection {‘cyclic’, ‘random’}, default=’cyclic’
如果设置为“random”,则随机系数将在每次迭代时更新,而不是默认情况下按顺序遍历特征。这(设置为“random”)通常会导致收敛更快,尤其是当tol高于1e-4时。
属性 说明
alpha_ float
交叉验证选择的惩罚量
coef_ ndarray of shape (n_features,) or (n_targets, n_features)
参数向量(目标函数公式中的w)。
intercept_ float or ndarray of shape (n_targets,)
目标函数中的截距。
mse_path_ ndarray of shape (n_l1_ratio, n_alpha, n_folds)
每次折叠不同alpha下测试集的均方误差。
alphas_ ndarray of shape (n_alphas,) or (n_l1_ratio, n_alphas)
对于每个l1_ratio,用于拟合的alpha网格。
dual_gap_ float or ndarray of shape (n_targets,)
最佳alpha(alpha_)优化结束时的双重间隔。
n_iter_ int
坐标下降求解器运行的迭代次数,以达到指定容忍度的最优alpha。

另见

有关示例,请参见 examples / linear_model / plot_lasso_model_selection.py

为了避免不必要的内存重复,fit方法的X参数应该作为一个Fortran-contiguous numpy数组直接传递。

示例

>> from sklearn.linear_model import LassoCV
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(noise=4, random_state=0)
>>> reg = LassoCV(cv=5, random_state=0).fit(X, y)
>>> reg.score(X, y)
0.9993...
>>> reg.predict(X[:1,])
array([-78.4951...])

方法

方法 说明
fit(X, y) 用坐标下降法拟合模型。
get_params([deep]) 获取此估计器的参数。
path(X, y, *[, l1_ratio, eps, n_alphas, …]) 计算具有坐标下降的套索路径。
predict(X) 使用线性模型进行预测。
score(X, y[, sample_weight]) 返回预测的确定系数R ^ 2。
set_params(**params) 设置此估算器的参数。
__init__(*, eps=0.001, n_alphas=100, alphas=None, fit_intercept=True, normalize=False, precompute='auto', max_iter=1000, tol=0.0001, copy_X=True, cv=None, verbose=False, n_jobs=None, positive=False, random_state=None, selection='cyclic')

[源码]

初始化self, 请参阅help(type(self))以获得准确的说明。

fit(X,y)

[源码]

用坐标下降法拟合模型。

在Alpha网格上拟合并通过交叉验证估算出最佳Alpha。

参数 说明
X {array-like, sparse matrix} of shape (n_samples, n_features)
训练数据。直接作为Fortran-contiguous数据传递,以避免不必要的内存重复。如果y是单输出,则X可以是稀疏的。
y array-like of shape (n_samples,) or (n_samples, n_targets)
目标值。
get_params(deep=True)

[源码]

获取此估计量的参数。

参数 说明
deep bool, default=True
如果为True,则将返回此估算器和所包含子对象的参数。
返回值 说明
params mapping of string to any
参数名称映射到其值。
static path(X, y, *, 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, **params)

[源码]

计算具有坐标下降的套索路径。

套索优化函数针对单输出和多输出而变化。

对于单输出任务,它是:

对于多输出任务,它是:

这里

即每一行的范数之和。

用户指南中阅读更多内容。

参数 说明
X {array-like, sparse matrix} of shape (n_samples, n_features)
训练数据。直接作为Fortran-contiguous数据传递,以避免不必要的内存重复。如果y是单输出,则X 可以是稀疏的。
y {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)
目标值。
eps float, default=1e-3
路径的长度。eps=1e-3意味着 alpha_min / alpha_max = 1e-3
n_alphas int, default=100
沿着正则化路径的Alpha个数。
alphas ndarray, default=None
用于计算模型的alpha列表。如果为None,则自动设置Alpha。
precompute ‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’
是否使用预先计算的Gram矩阵来加快计算速度。Gram矩阵也可以作为参数传递。
Xy array-like of shape (n_features,) or (n_features, n_outputs), default=None
Xy = np.dot(XT,y)可以预先计算。仅当预先计算了Gram矩阵时才有用。
copy_X bool, default=True
如果True,将复制X;否则X可能会被覆盖。
coef_init ndarray of shape (n_features, ), default=None
系数的初始值。
verbose bool or int, default=False
详细程度。
return_n_iter bool, default=False
是否返回迭代次数。
positive bool, default=False
如果设置为True,则强制系数为正。(仅当y.ndim == 1时允许)。
**params kwargs
传递给坐标下降求解器的关键字参数。
返回值 说明
alphas ndarray of shape (n_alphas,)
沿模型计算路径的Alpha值。
coefs ndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)
沿路径的系数。
dual_gaps ndarray of shape (n_alphas,)
每个alpha优化结束时的双重间隔。
n_iters list of int
坐标下降优化器为达到每个alpha的指定容差所进行的迭代次数。

另见

有关示例,请参见 examples / linear_model / plot_lasso_coordinate_descent_path.py

为了避免不必要的内存重复,fit方法的X参数应该作为一个Fortran-contiguous numpy数组直接传递。

注意,在某些情况下,Lars求解器实现此功能的速度可能会快得多。特别是,线性插值可以用来检索lars_path输出值之间的模型系数。

示例

将lasso_path和lars_path与插值进行比较:

>>> X = np.array([[123.1], [2.35.44.3]]).T
>>> y = np.array([123.1])
>>> # Use lasso_path to compute a coefficient path
>>> _, coef_path, _ = lasso_path(X, y, alphas=[5.1..5])
>>> print(coef_path)
[[0.         0.         0.46874778]
 [0.2159048  0.4425765  0.23689075]]
>>> # Now use lars_path and 1D linear interpolation to compute the
>>> # same path
>>> from sklearn.linear_model import lars_path
>>> alphas, active, coef_path_lars = lars_path(X, y, method='lasso')
>>> from scipy import interpolate
>>> coef_path_continuous = interpolate.interp1d(alphas[::-1],
...                                             coef_path_lars[:, ::-1])
>>> print(coef_path_continuous([5.1..5]))
[[0.         0.         0.46915237]
 [0.2159048  0.4425765  0.23668876]]
predict(X)

[源码]

使用线性模型进行预测。

参数 说明
X array_like or sparse matrix, shape (n_samples, n_features)
样本数据
返回值 说明
C array, shape (n_samples,)
返回预测值。
score(X, y, sample_weight=None)

[源码]

返回预测的确定系数R ^ 2。

系数R ^ 2定义为(1- u / v),其中u是残差平方和((y_true-y_pred)** 2).sum(),而v是总平方和((y_true- y_true.mean())** 2).sum()。可能的最高得分为1.0,并且也可能为负(因为该模型可能会更差)。一个常数模型总是预测y的期望值,而不考虑输入特征,得到的R^2得分为0.0。

参数 说明
X array-like of shape (n_samples, n_features)
测试样本。对于某些估计量,这可以是预先计算的内核矩阵或通用对象列表,形状为(n_samples,n_samples_fitted),其中n_samples_fitted是用于拟合估计器的样本数。
y array-like of shape (n_samples,) or (n_samples, n_outputs)
X的真实值。
sample_weight array-like of shape (n_samples,), default=None
样本权重。
返回值 说明
score float
预测值与真实值的R^2。

调用回归器中的score时使用的R2分数,multioutput='uniform_average'从0.23版开始使用 ,与r2_score默认值保持一致。这会影响多输出回归的score方法( MultiOutputRegressor除外)。

set_params(**params)

[源码]

设置此估计器的参数。

该方法适用于简单的估计器以及嵌套对象(例如管道)。后者具有形式为 <component>__<parameter>的参数,这样就可以更新嵌套对象的每个组件。

参数 说明
**params dict
估计器参数。
返回值 说明
self object
估计器实例。