投票法(Voting)简介
投票法(Voting)是利用多个模型来训练数据集,最终使用投票的方式来选择结果。
Voting分为两种类型:软投票(Soft Voting)和硬投票(Hard Voting)。
软投票:输出类概率
硬投票:输出类标签
投票法(Voting)实现
硬投票
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn import datasets
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.model_selection import cross_val_score
#载入数据集
iris=datasets.load_iris()
#只要1,2两列的特征
x_data,y_data=iris.data[:,1:3],iris.target
#定义三个不同的分类器
clf1=KNeighborsClassifier(n_neighbors=1)
clf2=DecisionTreeClassifier()
clf3=LogisticRegression()
vclf=VotingClassifier(estimators=[('knn',clf1),('dt',clf2),('lr',clf3)], voting='hard')
for clf, clf_name in zip([clf1, clf2, clf3, vclf],['KNN', 'DT', 'LR', 'Ensemble']):
scores = cross_val_score(clf, x_data, y_data, cv=5, scoring='accuracy')
print('Accuracy: {:.2f} (+/- {:.2f}) [{}]'.format(scores.mean(), scores.std(), clf_name))
硬投票结果如下所示:
软投票实现:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from itertools import product
soft_clf=VotingClassifier(estimators=[('knn',clf1),('dt',clf2),('lr',clf3)], voting='soft',weights=[2,1,1])
#weights控制每个算法的权重,soft:软投票
clf1.fit(x_data,y_data)#训练模型
clf2.fit(x_data,y_data)
clf3.fit(x_data,y_data)
soft_clf.fit(x_data,y_data)
x_min, x_max = x_data[:,0].min() -1, x_data[:,0].max() + 1
y_min, y_max = x_data[:,1].min() -1, x_data[:,1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01)) #创建网格
fig, axes = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(10, 8)) #共享X轴和Y轴
for idx, clf, title in zip(product([0, 1],[0, 1]),
[clf1, clf2, clf3, soft_clf],
['KNN (k=1)',
'DT',
'LR', 'Soft Voting']):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
axes[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.4)
axes[idx[0], idx[1]].scatter(x_data[:, 0],x_data[:, 1], c=y_data, s=20, edgecolor='k')
axes[idx[0], idx[1]].set_title(title)
plt.show()
软投票结果如下图所示:
参考文献:https://www.seaxiang.com/blog/c228c01936704287b0eb0949df4e97ea