1. 程式人生 > >機器學習之使用 scikit-learn 識別手寫數字

機器學習之使用 scikit-learn 識別手寫數字

機器學習案例分析一:

識別手寫數字:

scikit-learn 提供了一些標準資料集,例如 用於分類的 iris 和 digits 資料集 和 波士頓房價迴歸資料集 .
在下文中,我們從我們的 shell 啟動一個 Python 直譯器IDLE,然後載入 iris 和 digits 資料集。

資料集是一個類似字典的物件,它儲存有關資料的所有資料和一些元資料。 該資料儲存在 .data 成員中,它是 n_samples,
n_features 陣列。 在監督問題的情況下,一個或多個響應變數儲存在 .target 成員中。

識別手寫數字原始碼:

1、匯入所需模組

'''
手寫數字識別
'''
print(__doc__)

import matplotlib.pyplot as plt
from sklearn import datasets, svm, metrics

處理資料集:

# The digits dataset
digits = datasets.load_digits()

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) n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1))

資料展示:
這裡寫圖片描述

創捷支援向量機的SVM的分類器:

# Create a classifier: a support vector classifier
classifier = svm.SVC(gamma=0.001
)

學習過程:

# We learn the digits on the first half of the digits
classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2])

預測過程:

# Now predict the value of the digit on the second half:
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()