绘制分类概率

Beginner

This tutorial is from open-source community. Access the source code

简介

本实验演示了如何使用 Python 的 Scikit-learn 绘制不同分类器的分类概率。我们将使用一个三类数据集,并用支持向量分类器、具有一对多或多项式设置的 L1 和 L2 惩罚逻辑回归以及高斯过程分类对其进行分类。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

导入必要的库

我们首先导入本实验所需的库。

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

加载数据集

接下来,我们从 Scikit-learn 中加载鸢尾花数据集。

iris = datasets.load_iris()
X = iris.data[:, 0:2]  ## 我们只取前两个特征用于可视化
y = iris.target
n_features = X.shape[1]

定义分类器

我们为数据集定义不同的分类器。

C = 10
kernel = 1.0 * RBF([1.0, 1.0])  ## 用于高斯过程分类器(GPC)

## 创建不同的分类器。
classifiers = {
    "L1 逻辑回归": LogisticRegression(
        C=C, penalty="l1", solver="saga", multi_class="multinomial", max_iter=10000
    ),
    "L2 逻辑回归(多项式)": LogisticRegression(
        C=C, penalty="l2", solver="saga", multi_class="multinomial", max_iter=10000
    ),
    "L2 逻辑回归(一对多)": LogisticRegression(
        C=C, penalty="l2", solver="saga", multi_class="ovr", max_iter=10000
    ),
    "线性支持向量分类器": SVC(kernel="linear", C=C, probability=True, random_state=0),
    "高斯过程分类器": GaussianProcessClassifier(kernel)
}

可视化分类概率

我们将可视化每个分类器的分类概率。

n_classifiers = len(classifiers)

plt.figure(figsize=(3 * 2, n_classifiers * 2))
plt.subplots_adjust(bottom=0.2, top=0.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))

    ## 查看概率:
    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()

总结

本实验展示了如何使用 Python 的 Scikit-learn 绘制不同分类器的分类概率。我们加载了鸢尾花数据集,定义了不同的分类器,并可视化了每个分类器的分类概率。