【Python例項第15講】分類概率圖
阿新 • • 發佈:2018-11-29
機器學習訓練營——機器學習愛好者的自由交流空間(qq 群號:696721295)
這個例子將用圖形表示不同分類器的分類概率。所謂“分類概率”,是指某個資料點屬於各個類別的概率。將所有資料點屬於任何類的概率,用顏色深淺表示,作出分類概率圖。
在這裡,我們使用一個三類的資料集,分別用支援向量機(SVC)、L1 and L2懲罰的Logistic迴歸和高斯過程分類。預設情況下,線性SVC並不是一個概率分類器,但是可以通過設定引數probability=True
改變。具有One v.s. Rest
的Logistic迴歸並不是一個多類別分類器,因此,在分隔類2,類3時要比其它分類器複雜些。
例項詳解
首先,匯入必需的庫。
print(__doc__) # Author: Alexandre Gramfort <[email protected]> # License: BSD 3 clause import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.gaussian_process import GaussianProcessClassifier from sklearn.gaussian_process.kernels import RBF from sklearn import datasets
本例使用的是鳶尾花資料集iris
, 並且只用前2個特徵作圖。
iris = datasets.load_iris()
X = iris.data[:, 0:2] # we only take the first two features for visualization
y = iris.target
n_features = X.shape[1]
定義不同的分類器,它們是:
-
L1懲罰的Logistic迴歸
-
L2懲罰的多類Logistic迴歸
-
L2懲罰的二類Logistic迴歸
-
線性SVC
-
高斯過程分類GPC
C = 10 kernel = 1.0 * RBF([1.0, 1.0]) # for GPC # Create different classifiers. classifiers = { 'L1 logistic': LogisticRegression(C=C, penalty='l1', solver='saga', multi_class='multinomial', max_iter=10000), 'L2 logistic (Multinomial)': LogisticRegression(C=C, penalty='l2', solver='saga', multi_class='multinomial', max_iter=10000), 'L2 logistic (OvR)': LogisticRegression(C=C, penalty='l2', solver='saga', multi_class='ovr', max_iter=10000), 'Linear SVC': SVC(kernel='linear', C=C, probability=True, random_state=0), 'GPC': GaussianProcessClassifier(kernel) } n_classifiers = len(classifiers)
畫出分類概率圖。
plt.figure(figsize=(3 * 2, n_classifiers * 2))
plt.subplots_adjust(bottom=.2, top=.95)
xx = np.linspace(3, 9, 100)
yy = np.linspace(1, 5, 100).T
xx, yy = np.meshgrid(xx, yy)
Xfull = np.c_[xx.ravel(), yy.ravel()]
for index, (name, classifier) in enumerate(classifiers.items()):
classifier.fit(X, y)
y_pred = classifier.predict(X)
accuracy = accuracy_score(y, y_pred)
print("Accuracy (train) for %s: %0.1f%% " % (name, accuracy * 100))
# View probabilities:
probas = classifier.predict_proba(Xfull)
n_classes = np.unique(y_pred).size
for k in range(n_classes):
plt.subplot(n_classifiers, n_classes, index * n_classes + k + 1)
plt.title("Class %d" % k)
if k == 0:
plt.ylabel(name)
imshow_handle = plt.imshow(probas[:, k].reshape((100, 100)),
extent=(3, 9, 1, 5), origin='lower')
plt.xticks(())
plt.yticks(())
idx = (y_pred == k)
if idx.any():
plt.scatter(X[idx, 0], X[idx, 1], marker='o', c='w', edgecolor='k')
ax = plt.axes([0.15, 0.04, 0.7, 0.05])
plt.title("Probability")
plt.colorbar(imshow_handle, cax=ax, orientation='horizontal')
plt.show()
閱讀更多精彩內容,請關注微信公眾號:統計學習與大資料