在鸢尾花(Iris)数据集的两个特征上绘制VotingClassifier
的决策边界。
VotingClassifier
加权平均得出的。
首先,对三个分类器进行初始化(
DecisionTreeClassifier
,
KNeighborsClassifier
和
SVC
),并用权重
[2, 1, 2]
初始化软投票(soft-voting)
VotingClassifier
,这意味着计算平均概率时,
DecisionTreeClassifier
和
SVC
的预测概率的计算权重是分类器
KNeighborsClassifier
的2倍。
![1b29a1500943f3f350a19a062a23cfa4.png](https://img-blog.csdnimg.cn/img_convert/1b29a1500943f3f350a19a062a23cfa4.png)
print(__doc__)from itertools import productimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVCfrom sklearn.ensemble import VotingClassifier# 加载一些样本数据
iris = datasets.load_iris()
X = iris.data[:, [0, 2]]
y = iris.target# 训练分类器
clf1 = DecisionTreeClassifier(max_depth=4)
clf2 = KNeighborsClassifier(n_neighbors=7)
clf3 = SVC(gamma=.1, kernel='rbf', probability=True)
eclf = VotingClassifier(estimators=[('dt', clf1), ('knn', clf2),
('svc', clf3)],
voting='soft', weights=[2, 1, 2])
clf1.fit(X, y)
clf2.fit(X, y)
clf3.fit(X, y)
eclf.fit(X, y)# 绘制决策区域
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
np.arange(y_min, y_max, 0.1))
f, axarr = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(10, 8))for idx, clf, tt in zip(product([0, 1], [0, 1]),
[clf1, clf2, clf3, eclf],
['Decision Tree (depth=4)', 'KNN (k=7)','Kernel SVM', 'Soft Voting']):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.4)
axarr[idx[0], idx[1]].scatter(X[:, 0], X[:, 1], c=y,
s=20, edgecolor='k')
axarr[idx[0], idx[1]].set_title(tt)
plt.show()
脚本的总运行时间:(0分钟0.611秒)
估计的内存使用量: 8 MB
下载Python源代码:plot_voting_decision_regions.py
下载Jupyter notebook源代码:plot_voting_decision_regions.ipynb
由Sphinx-Gallery生成的画廊
![bef618be1ee7550f4ac7945ba5ef82c6.png](https://img-blog.csdnimg.cn/img_convert/bef618be1ee7550f4ac7945ba5ef82c6.png)
![1c570737a844bd8a875ff4e58bdf9069.png](https://img-blog.csdnimg.cn/img_convert/1c570737a844bd8a875ff4e58bdf9069.png)
![b6d0f0d5e51dacc0af74e16a649b4be5.png](https://img-blog.csdnimg.cn/img_convert/b6d0f0d5e51dacc0af74e16a649b4be5.png)