MultiTaskLassoCV#

class sklearn.linear_model.MultiTaskLassoCV(*, eps=0.001, n_alphas='deprecated', alphas='warn', fit_intercept=True, max_iter=1000, tol=0.0001, copy_X=True, cv=None, verbose=False, n_jobs=None, random_state=None, selection='cyclic')[source]#

使用 L1/L2 混合范数作为正则化项训练的多任务 Lasso 模型。

参见词汇表条目 交叉验证估计器

MultiTaskLasso 的优化目标是

(1 / (2 * n_samples)) * ||Y - XW||^Fro_2 + alpha * ||W||_21

其中

||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}

即每行范数之和。

用户指南中了解更多信息。

Added in version 0.15.

参数:
epsfloat, default=1e-3

路径的长度。eps=1e-3表示alpha_min / alpha_max = 1e-3

n_alphasint, default=100

正则化路径上alpha的数量。

Deprecated since version 1.7: n_alphas was deprecated in 1.7 and will be removed in 1.9. Use alphas instead.

alphasarray-like or int, default=None

沿正则化路径测试的 alpha 值。如果为 int,则自动生成 alphas 值。如果为 array-like,则使用 alpha 值列表。

Changed in version 1.7: alphas accepts an integer value which removes the need to pass n_alphas.

Deprecated since version 1.7: alphas=None was 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).

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 to tol.

copy_Xbool, default=True

如果为True,X将被复制;否则,它可能会被覆盖。

cvint, cross-validation generator or iterable, default=None

确定交叉验证拆分策略。cv 的可能输入包括

  • None,使用默认的 5 折交叉验证,

  • int, to specify the number of folds.

  • CV 分割器,

  • 一个可迭代对象,产生索引数组形式的 (训练集, 测试集) 拆分。

For int/None inputs, KFold is used.

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

版本 0.22 中已更改:如果为 None,cv 默认值从 3 折更改为 5 折。

verbosebool or int, default=False

冗余度级别。

n_jobsint, default=None

交叉验证期间使用的 CPU 数量。请注意,仅当给定多个 l1_ratio 值时才使用此参数。None 表示 1,除非在 joblib.parallel_backend 上下文中。-1 表示使用所有处理器。有关详细信息,请参阅词汇表

random_stateint, RandomState instance, default=None

选择要更新的随机特征的伪随机数生成器种子。当selection == ‘random’时使用。传入一个整数可以在多次函数调用中获得可重现的输出。请参阅词汇表

selection{‘cyclic’, ‘random’}, default=’cyclic’

如果设置为‘random’,则每次迭代更新一个随机系数,而不是默认按顺序遍历特征。这(设置为‘random’)通常会导致显著更快的收敛,尤其当tol高于1e-4时。

属性:
intercept_ndarray of shape (n_targets,)

决策函数中的独立项。

coef_ndarray of shape (n_targets, n_features)

Parameter vector (W in the cost function formula). Note that coef_ stores the transpose of W, W.T.

alpha_float

The amount of penalization chosen by cross validation.

mse_path_形状为 (n_alphas, n_folds) 的 ndarray

Mean square error for the test set on each fold, varying alpha.

alphas_形状为 (n_alphas,) 的 ndarray

用于拟合的 alpha 网格。

n_iter_int

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

dual_gap_float

最佳 alpha 的优化结束时的对偶间隙。

n_features_in_int

拟合 期间看到的特征数。

0.24 版本新增。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

fit 期间看到的特征名称。仅当 X 具有全部为字符串的特征名称时才定义。

1.0 版本新增。

另请参阅

MultiTaskElasticNet

使用 L1/L2 混合范数作为正则化项训练的多任务 ElasticNet 模型。

ElasticNetCV

通过交叉验证进行最佳模型选择的 Elastic Net 模型。

MultiTaskElasticNetCV

具有内置交叉验证的多任务 L1/L2 ElasticNet。

注意事项

用于拟合模型的算法是坐标下降法。

In fit, once the best parameter alpha is found through cross-validation, the model is fit again using the entire training set.

为避免不必要的内存复制,fit 方法的 Xy 参数应直接作为 Fortran 连续 numpy 数组传递。

示例

>>> from sklearn.linear_model import MultiTaskLassoCV
>>> from sklearn.datasets import make_regression
>>> from sklearn.metrics import r2_score
>>> X, y = make_regression(n_targets=2, noise=4, random_state=0)
>>> reg = MultiTaskLassoCV(cv=5, random_state=0).fit(X, y)
>>> r2_score(y, reg.predict(X))
0.9994
>>> reg.alpha_
np.float64(0.4321...)
>>> reg.predict(X[:1,])
array([[153.7971,  94.9015]])
fit(X, y, **params)[source]#

使用坐标下降拟合 MultiTaskLasso 模型。

Fit is on grid of alphas and best alpha estimated by cross-validation.

参数:
Xndarray of shape (n_samples, n_features)

数据。

yndarray of shape (n_samples, n_targets)

目标。如果需要,将被转换为X的数据类型。

**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 using sklearn.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, *, 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)[source]#

使用坐标下降计算 Lasso 路径。

Lasso 优化函数对于单输出和多输出有所不同。

对于单输出任务,它是

(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1

对于多输出任务,它是

(1 / (2 * n_samples)) * ||Y - XW||^2_Fro + alpha * ||W||_21

其中

||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)

目标值。

epsfloat, default=1e-3

路径的长度。eps=1e-3表示alpha_min / alpha_max = 1e-3

n_alphasint, default=100

正则化路径上alpha的数量。

alphasarray-like, default=None

计算模型的 alpha 列表。如果为 None,则自动设置 alpha。

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时允许)。

**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 达到指定容差所花费的迭代次数。

另请参阅

lars_path

Compute Least Angle Regression or Lasso path using LARS algorithm.

Lasso

Lasso 是一种估计稀疏系数的线性模型。

LassoLars

使用最小角回归(又名 Lars)拟合的 Lasso 模型。

LassoCV

具有沿正则化路径迭代拟合的 Lasso 线性模型。

LassoLarsCV

使用 LARS 算法的交叉验证 Lasso。

sklearn.decomposition.sparse_encode

可用于将信号转换为来自固定原子的稀疏线性组合的估计器。

注意事项

有关示例,请参阅examples/linear_model/plot_lasso_lasso_lars_elasticnet_path.py

为避免不必要的内存复制,fit方法的X参数应直接作为Fortran连续的numpy数组传递。

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

底层的坐标下降求解器使用间隙安全筛选规则来加快拟合时间,请参阅坐标下降用户指南

示例

比较 lasso_path 和带插值的 lars_path

>>> import numpy as np
>>> from sklearn.linear_model import lasso_path
>>> X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T
>>> y = np.array([1, 2, 3.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)[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\)

注意事项

从版本 0.23 开始,在对回归器调用 score 时使用的 \(R^2\) 分数使用 multioutput='uniform_average',以与 r2_score 的默认值保持一致。这会影响所有多输出回归器(MultiOutputRegressor 除外)的 score 方法。

set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') MultiTaskLassoCV[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$') MultiTaskLassoCV[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

更新后的对象。