StackingRegressor#

class sklearn.ensemble.StackingRegressor(estimators, final_estimator=None, *, cv=None, n_jobs=None, passthrough=False, verbose=0)[source]#

带有最终回归器的估算器堆栈。

堆叠泛化包括堆叠单个估计器的输出,并使用回归器来计算最终预测。堆叠允许通过使用每个个体估计器的输出作为最终估计器的输入来利用它们的优势。

请注意,estimators_ 是在完整的 X 上拟合的,而 final_estimator_ 是使用 cross_val_predict 对基础估计器进行交叉验证预测来训练的。

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

版本 0.22 新增。

参数:
estimatorslist of (str, estimator)

将堆叠在一起的基础估计器。列表中的每个元素定义为一个字符串(即名称)和估计器实例的元组。可以使用 set_params 将估计器设置为“drop”。

final_estimatorestimator, default=None

用于组合基础估计器的回归器。默认回归器是 RidgeCV

cvint, cross-validation generator, iterable, or “prefit”, default=None

确定在 cross_val_predict 中用于训练 final_estimator 的交叉验证分割策略。cv 的可能输入包括

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

  • 整数,用于指定 (Stratified) KFold 中的折叠数,

  • 用作交叉验证生成器的对象,

  • 产生训练集和测试集分割的可迭代对象,

  • "prefit",假设 estimators 已经预先拟合。在这种情况下,估计器将不会被重新拟合。

对于整数/None 输入,如果估计器是分类器且 y 是二元或多类,则使用 StratifiedKFold。在所有其他情况下,使用 KFold。这些分割器以 shuffle=False 实例化,因此分割在不同调用中将是相同的。

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

如果传入“prefit”,则假定所有 estimators 都已拟合。 final_estimator_ 在完整训练集上的 estimators 预测上进行训练,而不是交叉验证的预测。请注意,如果模型已在用于训练堆叠模型的相同数据上训练,则存在很高的过拟合风险。

版本 1.1 新增:“prefit”选项在 1.1 版本中添加

注意

如果训练样本数量足够大,增加分割次数不会带来益处。相反,训练时间会增加。 cv 不用于模型评估,而用于预测。

n_jobsint, default=None

用于所有 estimatorsfit 并行运行的作业数。 None 表示 1,除非在 joblib.parallel_backend 上下文中。-1 表示使用所有处理器。有关更多详细信息,请参阅词汇表

passthroughbool, default=False

当 False 时,只有估计器的预测将用作 final_estimator 的训练数据。当 True 时,final_estimator 在预测和原始训练数据上进行训练。

verboseint, default=0

详细程度。

属性:
estimators_list of estimators

在训练数据上拟合的 estimators 参数的元素。如果估计器被设置为 'drop',它将不会出现在 estimators_ 中。当 cv="prefit" 时,estimators_ 被设置为 estimators 并且不会再次拟合。

named_estimators_Bunch

按名称访问任何已拟合的子估计器的属性。

n_features_in_int

拟合 期间看到的特征数。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

fit 期间看到的特征名称。仅当底层估计器在拟合时公开此类属性时才定义。

1.0 版本新增。

final_estimator_estimator

estimators_ 输出上拟合的回归器,负责最终预测。

stack_method_list of str

每个基础估计器使用的方法。

另请参阅

StackingClassifier

带有最终分类器的估算器堆栈。

References

[1]

Wolpert, David H. “Stacked generalization.” Neural networks 5.2 (1992): 241-259.

示例

>>> from sklearn.datasets import load_diabetes
>>> from sklearn.linear_model import RidgeCV
>>> from sklearn.svm import LinearSVR
>>> from sklearn.ensemble import RandomForestRegressor
>>> from sklearn.ensemble import StackingRegressor
>>> X, y = load_diabetes(return_X_y=True)
>>> estimators = [
...     ('lr', RidgeCV()),
...     ('svr', LinearSVR(random_state=42))
... ]
>>> reg = StackingRegressor(
...     estimators=estimators,
...     final_estimator=RandomForestRegressor(n_estimators=10,
...                                           random_state=42)
... )
>>> from sklearn.model_selection import train_test_split
>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, random_state=42
... )
>>> reg.fit(X_train, y_train).score(X_test, y_test)
0.3...
fit(X, y, **fit_params)[source]#

拟合估计器。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

训练向量,其中 n_samples 是样本数量,n_features 是特征数量。

yarray-like of shape (n_samples,)

目标值。

**fit_paramsdict

Parameters to pass to the underlying estimators.

版本 1.6 中新增: 仅当 enable_metadata_routing=True 时可用,可通过使用 sklearn.set_config(enable_metadata_routing=True) 进行设置。有关详细信息,请参阅元数据路由用户指南

返回:
selfobject

返回拟合的实例。

fit_transform(X, y, **fit_params)[source]#

拟合估计器并返回 X 上每个估计器的预测。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

训练向量,其中 n_samples 是样本数量,n_features 是特征数量。

yarray-like of shape (n_samples,)

目标值。

**fit_paramsdict

Parameters to pass to the underlying estimators.

版本 1.6 中新增: 仅当 enable_metadata_routing=True 时可用,可通过使用 sklearn.set_config(enable_metadata_routing=True) 进行设置。有关详细信息,请参阅元数据路由用户指南

返回:
y_predsndarray of shape (n_samples, n_estimators)

每个估计器的预测输出。

get_feature_names_out(input_features=None)[source]#

获取转换的输出特征名称。

参数:
input_featuresarray-like of str or None, default=None

输入特征。输入特征名称仅在 passthroughTrue 时使用。

  • 如果 input_featuresNone,则使用 feature_names_in_ 作为输入特征名称。如果未定义 feature_names_in_,则生成名称:[x0, x1, ..., x(n_features_in_ - 1)]

  • 如果 input_features 是 array-like,则如果定义了 feature_names_in_input_features 必须与 feature_names_in_ 匹配。

如果 passthroughFalse,则仅使用 estimators 的名称来生成输出特征名称。

返回:
feature_names_outstr 对象的 ndarray

转换后的特征名称。

get_metadata_routing()[source]#

获取此对象的元数据路由。

请查阅 用户指南,了解路由机制如何工作。

版本 1.6 中新增。

返回:
routingMetadataRouter

封装路由信息的 MetadataRouter

get_params(deep=True)[source]#

获取集合中估计器的参数。

返回构造函数中给定的参数以及 estimators 参数中包含的估计器。

参数:
deepbool, default=True

将其设置为 True 将获取各种估计器以及估计器的参数。

返回:
paramsdict

参数和估计器名称映射到它们的值,或者参数名称映射到它们的值。

property named_estimators#

按名称访问任何已拟合的子估计器的字典。

返回:
Bunch
predict(X, **predict_params)[source]#

预测 X 的目标。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

训练向量,其中 n_samples 是样本数量,n_features 是特征数量。

**predict_paramsdict of str -> obj

final_estimator 调用的 predict 参数。请注意,这可用于从某些估计器返回不确定性,例如 return_stdreturn_cov。请注意,它只考虑最终估计器中的不确定性。

  • 如果 enable_metadata_routing=False (默认):直接传递给 final_estimatorpredict 方法的参数。

  • 如果 enable_metadata_routing=True:通过元数据路由 API 安全路由到 final_estimatorpredict 方法的参数。有关详细信息,请参阅元数据路由用户指南

版本 1.6 更改:**predict_params 可以通过元数据路由 API 进行路由。

返回:
y_predndarray of shape (n_samples,) or (n_samples, n_output)

预测目标。

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_output(*, transform=None)[source]#

设置输出容器。

有关如何使用 API 的示例,请参阅引入 set_output API

参数:
transform{“default”, “pandas”, “polars”}, default=None

配置 transformfit_transform 的输出。

  • "default": 转换器的默认输出格式

  • "pandas": DataFrame 输出

  • "polars": Polars 输出

  • None: 转换配置保持不变

1.4 版本新增: 添加了 "polars" 选项。

返回:
selfestimator instance

估计器实例。

set_params(**params)[source]#

设置集合中估计器的参数。

有效的参数键可以通过 get_params() 列出。请注意,您可以直接设置 estimators 中包含的估计器的参数。

参数:
**paramskeyword arguments

使用例如 set_params(parameter_name=new_value) 设置特定参数。除了设置估计器的参数外,还可以设置 estimators 的单个估计器,或者通过将它们设置为 ‘drop’ 来移除。

返回:
selfobject

估计器实例。

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

更新后的对象。

transform(X)[source]#

返回 X 上每个估计器的预测。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

训练向量,其中 n_samples 是样本数量,n_features 是特征数量。

返回:
y_predsndarray of shape (n_samples, n_estimators)

每个估计器的预测输出。