七、投票法的原理和案例分析
目录
来源
Datewhle24期__集成学习(中) :
https://github.com/datawhalechina/team-learning-data-mining/tree/master/EnsembleLearning
作者:李祖贤、薛传雨、赵可、杨毅远、陈琰钰
论坛地址:
http://datawhale.club/t/topic/1574
7.1 投票法思路
-
投票法(voting对于回归模型来说,投票法最终的预测结果是多个其他回归模型预测结果的平均值。
-
投票法(voting是集成学习里面在针对分类问题时采用结合策略。基本思想是选择所有机器学习算法当中输出最多的那个类。
-
分类的机器学习算法输出有两种类型:一种是直接输出类标签,另外一种是输出类概率,使用前者进行投票叫做硬投票(Majority/Hard voting),使用后者进行分类叫做软投票(Soft voting)。sklearn中的
VotingClassifier
是投票法的实现。 -
投票法的流程: 寻找几个基分类器,然后基于分类器的超过半数的结果作为最终的预测分类。
7.2 投票法原理
硬投票:预测结果是所有投票结果最多出现的类。
软投票:预测结果是所有投票结果中概率加和最大的类。
7.2.1 硬投票
- 硬投票通过假设投票最多的类别是获胜者,结合了许多预测。如以下三个学习器123对种类ABC的预测概率为:
- 可以看出A两票, C一票,A类将是集成法最后的预测。这是结合许多基础学习器的一种相当稳健的方法.
- 硬投票计算ACC例子:
voting='hard'
表示硬投票
硬投票是选择算法输出最多的标签,如果标签数量相等,那么按照升序的次序进行选择。
from sklearn import datasets
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
iris = datasets.load_iris() #鸢尾花数据集
X, y = iris.data[:,1:3], iris.target #自变量为第2到4列 因变量为类别
clf1 = LogisticRegression(random_state=1) # LR模型作为分类器1
clf2 = RandomForestClassifier(random_state=1) # 随机森林模型作为分类器2
clf3 = GaussianNB() #贝叶斯作为分类器3
eclf = VotingClassifier(estimators=[
('lr',clf1),('rf',clf2),
('gnb',clf3)], voting='hard')
#使用投票法将三个模型结合在以前,estimotor采用 [(name1,clf1),(name2,clf2),...]这样的输入,和Pipeline的输入相同 voting='hard'表示硬投票
for clf, clf_name in zip([clf1, clf2, clf3, eclf],['Logistic Regrsssion', 'Random Forest', 'naive Bayes', 'Ensemble']):
scores = cross_val_score(clf, X, y, cv=5, scoring='accuracy'