gpt4 book ai didi

machine-learning - 当各个分类器适合不同的数据集时,如何在 sklearn 中构建投票分类器?

转载 作者:行者123 更新时间:2023-11-30 09:16:37 26 4
gpt4 key购买 nike

我正在使用高度不平衡的数据构建分类器。我感兴趣的测试策略是使用3 个不同的重采样数据集来集成模型。换句话说,每个数据集将包含稀有类别的所有样本,但仅包含丰富类别的 n 个样本 ( technique #4 mentioned in this article )。

我想在每个重采样数据集上拟合 3 个不同的 VotingClassifiers,然后使用另一个 VotingClassifier(或相似的)。我知道构建单个投票分类器如下所示:

# First Model
rnd_clf_1 = RandomForestClassifier()
xgb_clf_1 = XGBClassifier()

voting_clf_1 = VotingClassifier(
estimators = [
('rf', rnd_clf_1),
('xgb', xgb_clf_1),
],
voting='soft'
)

# And I can fit it with the first dataset this way:
voting_clf_1.fit(X_train_1, y_train_1)

但是如果将它们三个拟合到不同的数据集上,如何堆叠它们呢?例如,如果我有三个拟合模型(请参见下面的代码),我可以构建一个函数,在每个模型上调用 .predict_proba() 方法,然后“手动”平均各个概率。

但是...有更好的方法吗?

# Fitting the individual models... but how to combine the predictions?
voting_clf_1.fit(X_train_1, y_train_1)
voting_clf_2.fit(X_train_2, y_train_2)
voting_clf_3.fit(X_train_3, y_train_3)

谢谢!

最佳答案

通常,本文中显示的#4 方法是使用相同类型的分类器实现的。您似乎想在每个示例数据集上尝试 VotingClassifier

imblearn.ensemble.BalancedBaggingClassifier 中已经实现了此方法。 ,这是 Sklearn Bagging 方法的扩展。

您可以将估计器作为 VotingClassifier 提供,并将估计器的数量作为您想要执行数据集采样的次数。使用 sampling_strategy 参数指定您想要在 Majority 类上进行下采样的比例。

工作示例:

from collections import Counter
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import RandomForestClassifier
import xgboost as xgb
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
from imblearn.ensemble import BalancedBaggingClassifier # doctest: +NORMALIZE_WHITESPACE
X, y = make_classification(n_classes=2, class_sep=2,
weights=[0.1, 0.9], n_informative=3, n_redundant=1, flip_y=0,
n_features=20, n_clusters_per_class=1, n_samples=1000, random_state=10)
print('Original dataset shape %s' % Counter(y))

X_train, X_test, y_train, y_test = train_test_split(X, y,
random_state=0)

rnd_clf_1 = RandomForestClassifier()
xgb_clf_1 = xgb.XGBClassifier()

voting_clf_1 = VotingClassifier(
estimators = [
('rf', rnd_clf_1),
('xgb', xgb_clf_1),
],
voting='soft'
)

bbc = BalancedBaggingClassifier(base_estimator=voting_clf_1, random_state=42)
bbc.fit(X_train, y_train) # doctest: +ELLIPSIS

y_pred = bbc.predict(X_test)
print(confusion_matrix(y_test, y_pred))

参见here 。也许您可以在手动拟合估计器后重用 _predict_proba()_collect_probas() 函数。

关于machine-learning - 当各个分类器适合不同的数据集时,如何在 sklearn 中构建投票分类器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54535672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com