VotingClassifier#

class sklearn.ensemble.VotingClassifier(estimators, *, voting='hard', weights=None, n_jobs=None, flatten_transform=True, verbose=False)[source]#

未拟合估算器的软投票/多数规则分类器。

Read more in the User Guide.

版本0.17中新增。

参数:
estimatorslist of (str, estimator) tuples

Invoking the fit method on the VotingClassifier will fit clones of those original estimators that will be stored in the class attribute self.estimators_. An estimator can be set to 'drop' using set_params.

Changed in version 0.21: 'drop' is accepted. Using None was deprecated in 0.22 and support was removed in 0.24.

voting{‘hard’, ‘soft’}, default=’hard’

If ‘hard’, uses predicted class labels for majority rule voting. Else if ‘soft’, predicts the class label based on the argmax of the sums of the predicted probabilities, which is recommended for an ensemble of well-calibrated classifiers.

weightsarray-like of shape (n_classifiers,), default=None

Sequence of weights (float or int) to weight the occurrences of predicted class labels (hard voting) or class probabilities before averaging (soft voting). Uses uniform weights if None.

n_jobsint, default=None

The number of jobs to run in parallel for fit. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

版本 0.18 新增。

flatten_transformbool, default=True

Affects shape of transform output only when voting=’soft’ If voting=’soft’ and flatten_transform=True, transform method returns matrix with shape (n_samples, n_classifiers * n_classes). If flatten_transform=False, it returns (n_classifiers, n_samples, n_classes).

verbosebool, default=False

If True, the time elapsed while fitting will be printed as it is completed.

0.23 版本新增。

属性:
estimators_list of classifiers

The collection of fitted sub-estimators as defined in estimators that are not ‘drop’.

named_estimators_Bunch

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

0.20 版本新增。

le_LabelEncoder

Transformer used to encode the labels during fit and decode during prediction.

classes_ndarray of shape (n_classes,)

类别标签。

n_features_in_int

拟合 期间看到的特征数。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

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

1.0 版本新增。

另请参阅

VotingRegressor

Prediction voting regressor.

示例

>>> import numpy as np
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.naive_bayes import GaussianNB
>>> from sklearn.ensemble import RandomForestClassifier, VotingClassifier
>>> clf1 = LogisticRegression(random_state=1)
>>> clf2 = RandomForestClassifier(n_estimators=50, random_state=1)
>>> clf3 = GaussianNB()
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> eclf1 = VotingClassifier(estimators=[
...         ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard')
>>> eclf1 = eclf1.fit(X, y)
>>> print(eclf1.predict(X))
[1 1 1 2 2 2]
>>> np.array_equal(eclf1.named_estimators_.lr.predict(X),
...                eclf1.named_estimators_['lr'].predict(X))
True
>>> eclf2 = VotingClassifier(estimators=[
...         ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
...         voting='soft')
>>> eclf2 = eclf2.fit(X, y)
>>> print(eclf2.predict(X))
[1 1 1 2 2 2]

To drop an estimator, set_params can be used to remove it. Here we dropped one of the estimators, resulting in 2 fitted estimators

>>> eclf2 = eclf2.set_params(lr='drop')
>>> eclf2 = eclf2.fit(X, y)
>>> len(eclf2.estimators_)
2

Setting flatten_transform=True with voting='soft' flattens output shape of transform

>>> eclf3 = VotingClassifier(estimators=[
...        ('lr', clf1), ('rf', clf2), ('gnb', clf3)],
...        voting='soft', weights=[2,1,1],
...        flatten_transform=True)
>>> eclf3 = eclf3.fit(X, y)
>>> print(eclf3.predict(X))
[1 1 1 2 2 2]
>>> print(eclf3.transform(X).shape)
(6, 6)
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.

Added in version 1.5: 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

返回实例本身。

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

Return class labels or probabilities for each estimator.

Return predictions for X for each estimator.

参数:
X{array-like, sparse matrix, dataframe} of shape (n_samples, n_features)

输入样本。

yndarray of shape (n_samples,), default=None

目标值(对于无监督转换,为 None)。

**fit_paramsdict

Additional fit parameters.

返回:
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

Not used, present here for API consistency by convention.

返回:
feature_names_outstr 对象的 ndarray

转换后的特征名称。

get_metadata_routing()[source]#

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

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

1.5 版本新增。

返回:
routingMetadataRouter

封装路由信息的 MetadataRouter

get_params(deep=True)[source]#

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

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

参数:
deepbool, default=True

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

返回:
paramsdict

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

property named_estimators#

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

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

Predict class labels for X.

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

输入样本。

返回:
majarray-like of shape (n_samples,)

Predicted class labels.

predict_proba(X)[source]#

Compute probabilities of possible outcomes for samples in X.

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

输入样本。

返回:
avgarray-like of shape (n_samples, n_classes)

Weighted average probability for each class per sample.

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

配置 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$') VotingClassifier[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]#

Return class labels or probabilities for X for each estimator.

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

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

返回:
probabilities_or_labels
If voting='soft' and flatten_transform=True

returns ndarray of shape (n_samples, n_classifiers * n_classes), being class probabilities calculated by each classifier.

If voting='soft' and `flatten_transform=False

ndarray of shape (n_classifiers, n_samples, n_classes)

If voting='hard'

ndarray of shape (n_samples, n_classifiers), being class labels predicted by each classifier.