繪制投票分類器的決策邊界?

使用Iris數據集的兩個特征繪制投票分類器的決策邊界。

繪制toy數據集中第一個樣本的類概率,由三個不同的分類器預測,并由VotingClassfier平均。

首先,初始化了三個示例性分類器(DecisionTreeClassifier,KNeighborsClassifier, 和 SVC), 并且使用權重為[2, 1, 2]的軟-投票VotingClassifier, 這意味著當計算平均概率時,DecisionTreeClassifierSVC的預測概率的權重是KNeighborsClassifier的權重的2倍。

print(__doc__)

from itertools import product

import numpy as np
import matplotlib.pyplot as plt

from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.ensemble import VotingClassifier

# Loading some example data
iris = datasets.load_iris()
X = iris.data[:, [02]]
y = iris.target

# Training classifiers
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=[212])

clf1.fit(X, y)
clf2.fit(X, y)
clf3.fit(X, y)
eclf.fit(X, y)

# Plotting decision regions
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(22, sharex='col', sharey='row', figsize=(108))

for idx, clf, tt in zip(product([01], [01]),
                        [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.462秒)

Download Python source code: plot_voting_decision_regions.py

Download Jupyter notebook:plot_voting_decision_regions.ipynb