StackingClassifier#
- class sklearn.ensemble.StackingClassifier(estimators, final_estimator=None, *, cv=None, stack_method='auto', 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
将用于组合基础估计器的分类器。默认分类器是
LogisticRegression。- cvint, cross-validation generator, iterable, or “prefit”, default=None
确定
cross_val_predict中用于训练final_estimator的交叉验证拆分策略。cv 的可能输入为None,使用默认的 5 折交叉验证,
整数,指定(分层)KFold 中的折叠数,
用作交叉验证生成器的对象,
一个生成训练、测试拆分的迭代器,
"prefit",假设estimators已经预拟合。在这种情况下,估计器将不会重新拟合。
对于整数/None 输入,如果估计器是分类器且 y 是二元或多类,则使用
StratifiedKFold。在所有其他情况下,使用KFold。这些拆分器实例化时shuffle=False,因此拆分在不同调用中将是相同的。请参阅用户指南,了解此处可使用的各种交叉验证策略。
如果传递了“prefit”,则假定所有
estimators都已拟合。final_estimator_在整个训练集上的estimators预测上进行训练,并且 不 是交叉验证的预测。请注意,如果模型已在用于训练堆叠模型的相同数据上进行训练,则存在非常高的过拟合风险。1.1 版本新增: 在 1.1 版本中增加了“prefit”选项
注意
如果训练样本数量足够大,则大量的拆分不会带来任何好处。实际上,训练时间会增加。
cv不用于模型评估,而用于预测。- stack_method{‘auto’, ‘predict_proba’, ‘decision_function’, ‘predict’}, default=’auto’
为每个基础估计器调用的方法。它可以是
如果为“auto”,它将尝试按
'predict_proba'、'decision_function'或'predict'的顺序为每个估计器调用。否则,为
'predict_proba'、'decision_function'或'predict'之一。如果估计器未实现该方法,则会引发错误。
- n_jobsint, default=None
并行运行所有
estimators的fit的作业数。None表示 1,除非在joblib.parallel_backend上下文中。-1 表示使用所有处理器。有关更多详细信息,请参阅词汇表。- passthroughbool, default=False
当为 False 时,只有估计器的预测将用作
final_estimator的训练数据。当为 True 时,final_estimator将在预测以及原始训练数据上进行训练。- verboseint, default=0
详细程度级别。
- 属性:
- classes_ndarray of shape (n_classes,) or list of ndarray if
yis of type"multilabel-indicator". 类别标签。
- estimators_估计器列表
estimators参数的元素,已在训练数据上拟合。如果估计器已设置为'drop',它将不会出现在estimators_中。当cv="prefit"时,estimators_被设置为estimators,并且不再重新拟合。- named_estimators_
Bunch 通过名称访问任何已拟合的子估计器的属性。
n_features_in_int拟合期间看到的特征数量。
- feature_names_in_ndarray of shape (
n_features_in_,) 拟合期间看到的特征名称。仅当底层估计器在拟合时公开此属性时才定义。
1.0 版本新增。
- final_estimator_估计器
在
estimators_输出上拟合的分类器,负责最终预测。- stack_method_list of str
每个基础估计器使用的方法。
- classes_ndarray of shape (n_classes,) or list of ndarray if
另请参阅
StackingRegressor带有最终回归器的估计器堆栈。
注释
当每个估计器都使用
predict_proba(即对于stack_method='auto'或专门对于stack_method='predict_proba'大多数情况)时,对于二元分类问题,每个估计器预测的第一列将被删除。实际上,两个特征将是完全共线的。在某些情况下(例如序数回归),可以将回归器作为
StackingClassifier的第一层。但是,请注意,y将在内部编码为数值递增或按字典顺序。如果此顺序不合适,则应手动将类别按所需顺序进行数值编码。参考文献
[1]Wolpert, David H. "Stacked generalization." Neural networks 5.2 (1992): 241-259.
示例
>>> from sklearn.datasets import load_iris >>> from sklearn.ensemble import RandomForestClassifier >>> from sklearn.svm import LinearSVC >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.preprocessing import StandardScaler >>> from sklearn.pipeline import make_pipeline >>> from sklearn.ensemble import StackingClassifier >>> X, y = load_iris(return_X_y=True) >>> estimators = [ ... ('rf', RandomForestClassifier(n_estimators=10, random_state=42)), ... ('svr', make_pipeline(StandardScaler(), ... LinearSVC(random_state=42))) ... ] >>> clf = StackingClassifier( ... estimators=estimators, final_estimator=LogisticRegression() ... ) >>> from sklearn.model_selection import train_test_split >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, stratify=y, random_state=42 ... ) >>> clf.fit(X_train, y_train).score(X_test, y_test) 0.9...
- decision_function(X)[source]#
使用最终估计器对
X中的样本进行决策函数。- 参数:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
训练向量,其中
n_samples是样本数,n_features是特征数。
- 返回:
- decisionsndarray of shape (n_samples,), (n_samples, n_classes), or (n_samples, n_classes * (n_classes-1) / 2)
最终估计器计算的决策函数。
- fit(X, y, **fit_params)[source]#
拟合估计器。
- 参数:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
训练向量,其中
n_samples是样本数,n_features是特征数。- yarray-like of shape (n_samples,)
目标值。请注意,
y将在内部以数值递增或字典顺序编码。如果顺序很重要(例如对于序数回归),则应在调用拟合之前对目标y进行数值编码。- **fit_paramsdict
传递给底层估计器的参数。
1.6 版本新增: 仅当
enable_metadata_routing=True时可用,可通过sklearn.set_config(enable_metadata_routing=True)进行设置。有关更多详细信息,请参阅元数据路由用户指南。
- 返回:
- self对象
返回估计器的拟合实例。
- fit_transform(X, y=None, **fit_params)[source]#
拟合数据,然后进行转换。
使用可选参数
fit_params将转换器拟合到X和y,并返回X的转换版本。- 参数:
- Xarray-like of shape (n_samples, n_features)
输入样本。
- yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
目标值(无监督转换则为 None)。
- **fit_paramsdict
额外拟合参数。
- 返回:
- X_newndarray array of shape (n_samples, n_features_new)
转换后的数组。
- get_feature_names_out(input_features=None)[source]#
获取转换的输出特征名称。
- 参数:
- input_featuresarray-like of str or None, default=None
输入特征。只有当
passthrough为True时才使用输入特征名称。如果
input_features为None,则使用feature_names_in_作为输入特征名称。如果未定义feature_names_in_,则生成名称:[x0, x1, ..., x(n_features_in_ - 1)]。如果
input_features是一个类数组对象,则如果定义了feature_names_in_,input_features必须与feature_names_in_匹配。
如果
passthrough为False,则仅使用estimators的名称来生成输出特征名称。
- 返回:
- feature_names_outndarray of str objects
转换后的特征名称。
- get_metadata_routing()[source]#
获取此对象的元数据路由。
请查阅用户指南,了解路由机制的工作原理。
1.6 版本新增。
- 返回:
- routingMetadataRouter
封装路由信息的
MetadataRouter。
- get_params(deep=True)[source]#
从集成中获取估计器的参数。
返回构造函数中给定的参数以及
estimators参数中包含的估计器。- 参数:
- deepbool, default=True
将其设置为 True 将同时获取各种估计器和估计器的参数。
- 返回:
- paramsdict
参数和估计器名称映射到它们的值,或参数名称映射到它们的值。
- predict(X, **predict_params)[source]#
预测 X 的目标。
- 参数:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
训练向量,其中
n_samples是样本数,n_features是特征数。- **predict_paramsdict of str -> obj
传递给
final_estimator调用的predict方法的参数。请注意,这可以用于从某些估计器返回不确定性,带有return_std或return_cov。请注意,它只会考虑最终估计器中的不确定性。如果
enable_metadata_routing=False(默认):参数直接传递给final_estimator的predict方法。如果
enable_metadata_routing=True:参数安全地路由到final_estimator的predict方法。有关更多详细信息,请参阅元数据路由用户指南。
1.6 版本变更:
**predict_params可通过元数据路由 API 进行路由。
- 返回:
- y_predndarray of shape (n_samples,) or (n_samples, n_output)
预测目标。
- predict_proba(X)[source]#
使用最终估计器预测
X的类别概率。- 参数:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
训练向量,其中
n_samples是样本数,n_features是特征数。
- 返回:
- probabilitiesndarray of shape (n_samples, n_classes) or list of ndarray of shape (n_output,)
输入样本的类别概率。
- score(X, y, sample_weight=None)[source]#
返回所提供数据和标签的准确率。
在多标签分类中,这是子集准确率,这是一个苛刻的指标,因为它要求每个样本的每个标签集都正确预测。
- 参数:
- Xarray-like of shape (n_samples, n_features)
测试样本。
- yarray-like of shape (n_samples,) or (n_samples, n_outputs)
X的真实标签。- sample_weightarray-like of shape (n_samples,), default=None
样本权重。
- 返回:
- scorefloat
self.predict(X)相对于y的平均准确率。
- set_output(*, transform=None)[source]#
设置输出容器。
有关如何使用 API 的示例,请参阅引入 set_output API。
- 参数:
- transform{“default”, “pandas”, “polars”}, default=None
配置
transform和fit_transform的输出。"default": 转换器的默认输出格式"pandas": DataFrame 输出"polars": Polars 输出None: 转换配置不变
1.4 版本新增: 添加了
"polars"选项。
- 返回:
- self估计器实例
估计器实例。
- set_params(**params)[source]#
设置集成中估计器的参数。
有效的参数键可以通过
get_params()列出。请注意,您可以直接设置estimators中包含的估计器的参数。- 参数:
- **params关键字参数
使用例如
set_params(parameter_name=new_value)的特定参数。此外,除了设置估计器的参数外,还可以设置estimators中单个估计器的参数,或者通过将其设置为“drop”来移除它们。
- 返回:
- self对象
估计器实例。
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') StackingClassifier[source]#
请求传递给
score方法的元数据。请注意,此方法仅在
enable_metadata_routing=True时相关(请参阅sklearn.set_config)。请参阅用户指南,了解路由机制的工作原理。每个参数的选项为
True:请求元数据,如果提供则传递给score。如果未提供元数据,则忽略该请求。False:不请求元数据,元估计器不会将其传递给score。None:不请求元数据,如果用户提供,元估计器将引发错误。str:元数据应以给定别名而不是原始名称传递给元估计器。
默认值 (
sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求,而不更改其他参数。1.3 版本新增。
注意
此方法仅当此估计器用作元估计器的子估计器时才相关,例如在
Pipeline中使用时。否则,它没有效果。- 参数:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
score方法中sample_weight参数的元数据路由。
- 返回:
- self对象
更新后的对象。