【笔记】调一下scikit-learn :
详细链接:http://xhrwang.me/2015/02/13/scikit_learn-tutorial.html
下面的例子将演示如何使用 sklearn 库中提供的数字图片 dataset 来识别它们表示的实际数字, 且标记本人的一些学习心得。
所需lib: matplotlib.pyplot & sklearn
数据源:sklearn.dataset
# -*- coding: utf-8 -*-
"""
================================
Recognizing hand-written digits
================================
An example showing how the scikit-learn can be used to recognize images of hand-written digits.
This example is commented in the
:ref:`tutorial section of the user manual <introduction>`.
"""
# 打印出上面的文档信息,Python 里面使用 """ 多行注释的信息被当作文档信息,可以对源代码、类、方法等进行注释从而生成文档,是自解释的机制
print(__doc__)
# 下面是 scikit——learn 官方例子的作者信息
# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
# License: BSD 3 clause
# 导入用于科学计算的库
import matplotlib.pyplot as plt
# 导入 sklearn 自带的手写数字 dataset,以及进行机器学习的模块
from sklearn import datasets, svm, metrics
# 加载 sklearn 自带的手写数字 dataset
digits = datasets.load_digits()
# 这里我们感兴趣的数据是不同灰度的 8x8 个小格子组成的图像
# 如果我们直接使用图像进行处理,就需要使用 pylab.imread 来加载图像数据,而且这些图像数据必须都是 8x8 的格式
# 对于这个 dataset 中的图像,dataset.target 给出了它们实际对应的数字
images_and_labels = list(zip(digits.images, digits.target))
for index, (image, label) in enumerate(images_and_labels[:4]):
plt.subplot(2, 4, index + 1)
plt.axis('off')
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
plt.title('Training: %i' % label)
# 为了使用分类器,需要将每个表示手写图像的 8x8 数字转换为一个数字数组
# 用reshape 来转换, digits.images 就变成了(采样,采样特性)的一个矩阵
n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))
print(digits.images[0])
print(data[0])
# 创建一个分类器,这里 gamma 的值是给定的,可以通过 grid search 和 cross validation 等技术算出更好的值。
# 下面的链接有个例子是自己算 gamma:
# http://efavdb.com/machine-learning-with-wearable-sensors/
# ****
classifier = svm.SVC(gamma=0.001)
# **用前半部分数据训练分类器**
classifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2])
# **对后半部分数据使用训练好的分类器进行识别****
expected = digits.target[n_samples / 2:]
predicted = classifier.predict(data[n_samples / 2:])
# 打印分类器的运行时信息以及期望值和实际识别的值
print("Classification report for classifier %s:\n%s\n"
% (classifier, metrics.classification_report(expected, predicted)))
print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))
# 画出手写数字的图像并给出识别出的值
images_and_predictions = list(zip(digits.images[n_samples / 2:], predicted))
for index, (image, prediction) in enumerate(images_and_predictions[:4]):
plt.subplot(2, 4, index + 5)
plt.axis('off')
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
plt.title('Prediction: %i' % prediction)
plt.show()
precision recall f1-score support
0 1.00 0.99 0.99 88
1 0.99 0.97 0.98 91
2 0.99 0.99 0.99 86
3 0.98 0.87 0.92 91
4 0.99 0.96 0.97 92
5 0.95 0.97 0.96 91
6 0.99 0.99 0.99 91
7 0.96 0.99 0.97 89
8 0.94 1.00 0.97 88
9 0.93 0.98 0.95 92
avg / total 0.97 0.97 0.97 899
总结:
有几点需要注意:
- n*n矩阵转成一维数组
- set coefficient gamma
- 用一半的data 训练模型
- 用模型去predict
- 可视化
思维拓展:
怎么做字母,或图像识别
还有没有别算法可以实现(KNN , 神经网络)