机器学习笔记-投票法(Voting)理论与实现

投票法(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

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值