not good but great

プログラミング、アート、映画・本の感想について書きます。

Python3.5.1 SKlearnのSVMでDigitsを分類し、matplotlibで表示

参考動画

ナードっぽい方がScikit Learnを説明してる動画。実行環境はWindows

Scikit Learn Machine Learning SVM Tutorial with Python p. 2 - Example - YouTube

matplitlibでエラー

下の記事で解決。matplotlibrcを作成しよう。

Python 3.3でmatplitlibとpylabを使おうとしたら RuntimeError: Python is not installed as a frameworkというエラーが発生したときの解決方法 - Qiita

digitsを表示

from sklearn import datasets

digits = datasets.load_digits()

print(digits.data)

実行すると、

[[  0.   0.   5. ...,   0.   0.   0.]
 [  0.   0.   0. ...,  10.   0.   0.]
 [  0.   0.   0. ...,  16.   9.   0.]
 ...,
 [  0.   0.   1. ...,   6.   0.   0.]
 [  0.   0.   2. ...,  12.   0.   0.]
 [  0.   0.  10. ...,  12.   1.   0.]]

が表示された。

0だけ表示

print(digits.images[0])

結果は以下。

[[  0.   0.   5.  13.   9.   1.   0.   0.]
 [  0.   0.  13.  15.  10.  15.   5.   0.]
 [  0.   3.  15.   2.   0.  11.   8.   0.]
 [  0.   4.  12.   0.   0.   8.   8.   0.]
 [  0.   5.   8.   0.   0.   9.   8.   0.]
 [  0.   4.  11.   0.   1.  12.   7.   0.]
 [  0.   2.  14.   5.  10.  12.   0.   0.]
 [  0.   0.   6.  13.  10.   0.   0.   0.]]

何の数字がよくわかってないけど、0を形成してるっぽい。

SVMを使ってみる

import matplotlib.pyplot as plt

from sklearn import datasets
from sklearn import svm

digits = datasets.load_digits()

clf = svm.SVC(gamma=0.001, C=100)

# 1796
print(len(digits.data))

# last element
x,y = digits.data[:-1], digits.target[:-1]

clf.fit(x,y)

print("Prediction:", clf.predict(digits.data[-1]))

plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation="nearest")
plt.show()

matplotlib.pyplotを使ってdigitsを表示する。SVMを使って予想する。

予測できた

Prediction: [8]

と表示された。地味だww

8を表示

スクリーンショット 2016-04-19 8.53.30.png

gammaの値を変える

gamma(学習率?)の値を大きくすると、認識がうまくいかなくなるww