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 中新增: 'prefit' 选项在 1.1 中添加
注意
如果训练样本数量足够大,增加分割次数不会带来益处。相反,训练时间会增加。
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时并行运行的作业数。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_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
每个基础估计器使用的方法。
- classes_ndarray of shape (n_classes,) or list of ndarray if
另请参阅
StackingRegressor带有最终回归器的估算器堆栈。
注意事项
当每个估计器都使用
predict_proba时(即,对于stack_method='auto'或专门对于stack_method='predict_proba'的大部分时间),在二元分类问题中,每个估计器预测的第一列将被丢弃。实际上,两个特征将是完全共线的。在某些情况下(例如序数回归),可以将回归器作为
StackingClassifier的第一层传递。但是,请注意,y将在内部以数字递增顺序或词典顺序进行编码。如果此顺序不合适,应手动以所需顺序对类别进行数字编码。References
[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中的样本进行决策函数计算。- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
训练向量,其中
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]#
拟合估计器。
- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
训练向量,其中
n_samples是样本数量,n_features是特征数量。- yarray-like of shape (n_samples,)
目标值。请注意,
y将在内部以数字递增顺序或词典顺序进行编码。如果顺序很重要(例如对于序数回归),应在调用 fit 之前手动对目标y进行数字编码。- **fit_paramsdict
要传递给底层估计器的参数。
版本 1.6 中新增: 仅当
enable_metadata_routing=True时可用,可通过使用sklearn.set_config(enable_metadata_routing=True)进行设置。有关详细信息,请参阅元数据路由用户指南。
- 返回:
- selfobject
返回已拟合的估计器实例。
- fit_transform(X, y=None, **fit_params)[source]#
拟合数据,然后对其进行转换。
使用可选参数
fit_params将转换器拟合到X和y,并返回X的转换版本。- 参数:
- Xshape 为 (n_samples, n_features) 的 array-like
输入样本。
- y形状为 (n_samples,) 或 (n_samples, n_outputs) 的类数组对象,默认=None
目标值(对于无监督转换,为 None)。
- **fit_paramsdict
额外的拟合参数。仅当估计器在其
fit方法中接受额外的参数时才传递。
- 返回:
- 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是 array-like,则如果定义了feature_names_in_,input_features必须与feature_names_in_匹配。
如果
passthrough为False,则仅使用estimators的名称生成输出特征名称。
- 返回:
- feature_names_outstr 对象的 ndarray
转换后的特征名称。
- 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 的目标。
- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
训练向量,其中
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:通过元数据路由 API 安全路由到final_estimator的predict方法的参数。有关更多详细信息,请参阅 Metadata Routing User Guide。
版本 1.6 中更改:
**predict_params可以通过元数据路由 API 进行路由。
- 返回:
- y_predndarray of shape (n_samples,) or (n_samples, n_output)
预测的目标。
- predict_proba(X)[source]#
使用最终估计器预测
X的类别概率。- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
训练向量,其中
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]#
返回在提供的数据和标签上的 准确率 (accuracy)。
在多标签分类中,这是子集准确率 (subset accuracy),这是一个严格的指标,因为它要求每个样本的每个标签集都被正确预测。
- 参数:
- Xshape 为 (n_samples, n_features) 的 array-like
测试样本。
- yshape 为 (n_samples,) 或 (n_samples, n_outputs) 的 array-like
X的真实标签。- sample_weightshape 为 (n_samples,) 的 array-like, 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"选项。
- 返回:
- 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$') StackingClassifier[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
更新后的对象。