快捷搜索:  汽车  科技

python机器学习手册(用Python做科学计算工具篇)

python机器学习手册(用Python做科学计算工具篇)高斯朴素贝叶斯在每个特征上独立地将高斯分布拟合到每个训练标签,并使用它来快速给出粗略分类。对于现实世界的数据,它通常不够准确,但可以表现得非常好,例如在文本数据上。要记住的一种好方法是高斯朴素贝叶斯 ( sklearn.naive_bayes.GaussianNB)。PCA 寻求显示最大方差的特征的正交线性组合,因此可以帮助您更好地了解数据集的结构。>>>>>> from sklearn.decomposition import PCA >>> pca = PCA(n_components=2) >>> proj = pca.fit_transform(digits.data) >>> plt.scatter(proj[: 0] proj[: 1] c=digits.target) <

python机器学习手册(用Python做科学计算工具篇)(1)

所需基本库
  • NumPy
  • scipy
  • matplotlib
全章目录【本节:监督学习:手写数字的分类】
  • 简介:问题设置
  • 使用 scikit-learn 进行机器学习的基本原理
  • 监督学习:手写数字的分类
  • 监督学习:住房数据的回归
  • 测量预测性能
  • 无监督学习:降维和可视化
  • 特征脸示例:链接 PCA 和 SVM
  • 特征脸示例:链接 PCA 和 SVM
  • 参数选择、验证和测试

6.3.监督学习:手写数字的分类6.3.1. 数据的性质

在本节中,我们将 scikit-learn 应用于手写数字的分类。这将超出我们之前看到的虹膜分类:我们将讨论一些可用于评估分类模型有效性的指标。

>>>

>>> from sklearn.datasets import load_digits >>> digits = load_digits()

python机器学习手册(用Python做科学计算工具篇)(2)

让我们可视化数据并提醒我们正在查看的内容:

# plot the digits: each image is 8x8 pixels for i in range(64): ax = fig.add_subplot(8 8 i 1 xticks=[] yticks=[]) ax.imshow(digits.images[i] cmap=plt.cm.binary interpolation='nearest')

"""完整代码 Simple visualization and classification of the digits dataset ============================================================= Plot the first few samples of the digits dataset and a 2D representation built using PCA then do a simple classification """ from sklearn.datasets import load_digits digits = load_digits() ############################################################################### # Plot the data: images of digits # ------------------------------- # # Each data in a 8x8 image from matplotlib import pyplot as plt fig = plt.figure(figsize=(6 6)) # figure size in inches fig.subplots_adjust(left=0 right=1 bottom=0 top=1 hspace=0.05 wspace=0.05) for i in range(64): ax = fig.add_subplot(8 8 i 1 xticks=[] yticks=[]) ax.imshow(digits.images[i] cmap=plt.cm.binary interpolation='nearest') # label the image with the target value ax.text(0 7 str(digits.target[i])) ############################################################################### # Plot a projection on the 2 first principal axis # ------------------------------------------------ plt.figure() from sklearn.decomposition import PCA pca = PCA(n_components=2) proj = pca.fit_transform(digits.data) plt.scatter(proj[: 0] proj[: 1] c=digits.target cmap="Paired") plt.colorbar() ############################################################################### # Classify with Gaussian naive Bayes # ---------------------------------- from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split # split the data into training and validation sets X_train X_test y_train y_test = train_test_split(digits.data digits.target) # train the model clf = GaussianNB() clf.fit(X_train y_train) # use the model to predict the labels of the test data predicted = clf.predict(X_test) expected = y_test # Plot the prediction fig = plt.figure(figsize=(6 6)) # figure size in inches fig.subplots_adjust(left=0 right=1 bottom=0 top=1 hspace=0.05 wspace=0.05) # plot the digits: each image is 8x8 pixels for i in range(64): ax = fig.add_subplot(8 8 i 1 xticks=[] yticks=[]) ax.imshow(X_test.reshape(-1 8 8)[i] cmap=plt.cm.binary interpolation='nearest') # label the image with the target value if predicted[i] == expected[i]: ax.text(0 7 str(predicted[i]) color='green') else: ax.text(0 7 str(predicted[i]) color='red') ############################################################################### # Quantify the performance # ------------------------ # # First print the number of correct matches matches = (predicted == expected) print(matches.sum()) ############################################################################### # The total number of data points print(len(matches)) ############################################################################### # And now the ration of correct predictions matches.sum() / float(len(matches)) ############################################################################### # Print the classification report from sklearn import metrics print(metrics.classification_report(expected predicted)) ############################################################################### # Print the confusion matrix print(metrics.confusion_matrix(expected predicted)) plt.show() 6.3.2. 可视化数据的主要组成部分

许多问题的第一步是使用 降维技术可视化数据。我们将从最直接的一个开始,即主成分分析 (PCA)。

PCA 寻求显示最大方差的特征的正交线性组合,因此可以帮助您更好地了解数据集的结构。

>>>

>>> from sklearn.decomposition import PCA >>> pca = PCA(n_components=2) >>> proj = pca.fit_transform(digits.data) >>> plt.scatter(proj[: 0] proj[: 1] c=digits.target) <matplotlib.collections.PathCollection object at ...> >>> plt.colorbar() <matplotlib.colorbar.Colorbar object at ...>

python机器学习手册(用Python做科学计算工具篇)(3)

6.3.3. 高斯朴素贝叶斯分类

对于大多数分类问题,很高兴有一种简单、快速的方法来提供快速的基线分类。如果简单快速的方法就足够了,那么我们就不必在更复杂的模型上浪费 CPU 周期了。如果没有,我们可以使用简单方法的结果为我们提供有关数据的线索。

要记住的一种好方法是高斯朴素贝叶斯 ( sklearn.naive_bayes.GaussianNB)。

高斯朴素贝叶斯在每个特征上独立地将高斯分布拟合到每个训练标签,并使用它来快速给出粗略分类。对于现实世界的数据,它通常不够准确,但可以表现得非常好,例如在文本数据上。

>>>

>>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.model_selection import train_test_split >>> # split the data into training and validation sets >>> X_train X_test y_train y_test = train_test_split(digits.data digits.target) >>> # train the model >>> clf = GaussianNB() >>> clf.fit(X_train y_train) GaussianNB(priors=None) >>> # use the model to predict the labels of the test data >>> predicted = clf.predict(X_test) >>> expected = y_test >>> print(predicted) [1 7 7 7 8 2 8 0 4 8 7 7 0 8 2 3 5 8 5 3 7 9 6 2 8 2 2 7 3 5...] >>> print(expected) [1 0 4 7 8 2 2 0 4 3 7 7 0 8 2 3 4 8 5 3 7 9 6 3 8 2 2 9 3 5...]

如上所述,我们用预测标签绘制数字,以了解分类的工作情况。

python机器学习手册(用Python做科学计算工具篇)(4)

我们为什么将数据分成训练集和验证集?

6.3.4. 绩效的定量测量

我们想衡量我们的估计器的性能,而不必求助于绘图示例。一个简单的方法可能是简单地比较匹配的数量:

>>>

>>> matches = (predicted == expected) >>> print(matches.sum()) 367 >>> print(len(matches)) 450 >>> matches.sum() / float(len(matches)) 0.81555555555555559

我们看到超过 80% 的 450 个预测与输入匹配。但是还有其他更复杂的指标可用于判断分类器的性能: sklearn.metrics子模块中有几个可用。

最有用的指标之一是classification_report,它结合了几个度量并打印一个带有结果的表格:

>>>

>>> from sklearn import metrics >>> print(metrics.classification_report(expected predicted)) precision recall f1-score support 0 1.00 0.91 0.95 46 1 0.76 0.64 0.69 44 2 0.85 0.62 0.72 47 3 0.98 0.82 0.89 49 4 0.89 0.86 0.88 37 5 0.97 0.93 0.95 41 6 1.00 0.98 0.99 44 7 0.73 1.00 0.84 45 8 0.50 0.90 0.64 49 9 0.93 0.54 0.68 48 avg / total 0.86 0.82 0.82 450

这种多标签分类的另一个启发性指标是混淆矩阵:它帮助我们可视化哪些标签在分类错误中被互换:

>>>

>>> print(metrics.confusion_matrix(expected predicted)) [[42 0 0 0 3 0 0 1 0 0] [ 0 28 0 0 0 0 0 1 13 2] [ 0 3 29 0 0 0 0 0 15 0] [ 0 0 2 40 0 0 0 2 5 0] [ 0 0 1 0 32 1 0 3 0 0] [ 0 0 0 0 0 38 0 2 1 0] [ 0 0 1 0 0 0 43 0 0 0] [ 0 0 0 0 0 0 0 45 0 0] [ 0 3 1 0 0 0 0 1 44 0] [ 0 3 0 1 1 0 0 7 10 26]]

我们在这里看到,特别是数字 1、2、3 和 9 通常被标记为 8。


相关文章:
  • 用Python做科学计算(工具篇)——scikit-learn(机器学习)2
  • 用Python做科学计算(工具篇)——scikit-learn(机器学习)1
  • 用Python做科学计算——matplotlib绘图实例
  • 用Python做科学计算(工具篇)——1.1. NumPy 数组对象
  • 用Python做科学计算(工具篇)——scipy 使用指南
  • 用Python做科学计算(工具篇)——numpy1.2.数组的数值运算
  • 用Python做科学计算(工具篇)——sympy使用指南(符号运算)
  • 用Python做科学计算(工具篇)——numpy1.3 更精细的数组
  • 用Python做科学计算(工具篇)——numpy1.4 高级操作

猜您喜欢: