LoginSignup
12
11

More than 5 years have passed since last update.

手書き数字の機械学習に実際に画像をくわせてみた

Posted at

TensorFlowのチュートリアルでMNISTの手書き数字画像をソフトマックス回帰させた学習モデルに、自分で用意した数字画像を渡して正解できるかを試したものです。
学習内容について詳しくは前記事を参照してください。

用意した画像

@tomigarashさんがホワイトボードに書いた数字をいくつか拾ってきました。

IMG_0738.JPG IMG_0739.JPG IMG_0740.JPG
9 2 5

コード

前記事のコードの後に以下を追加します。

from PIL import Image
import numpy
import sys

# 画像の読み込み
image = Image.open(sys.argv[1]).convert('L')
# バックを白に
image = Image.frombytes('L', image.size,
                        bytes(map(lambda x: 255 if (x > 160) else x,
                                  image.getdata())))
image.thumbnail((28, 28))

# input_data の形に揃える
image = map(lambda x: 255 - x, image.getdata())
image = numpy.fromiter(image, dtype=numpy.uint8)
image = image.reshape(1, 784)
image = image.astype(numpy.float32)
image = numpy.multiply(image, 1.0 / 255.0)

p = sess.run(y, feed_dict={x: image, y_: [[0.0] * 10]})[0]
print(p)
print(numpy.argmax(p))

コマンドの引数としてファイル名を渡します。
最後に各数字の確率と、もっとも確率の高い数字を表示します。

実行結果

奇跡的にうまくいったときの結果を:wink:

$ python hoge.py IMG_0738.JPG
[ 0.00254864  0.14155449  0.03942517  0.0640309   0.10035493  0.24547113
  0.03151034  0.08466743  0.02800771  0.26242924]
9

$ python hoge.py IMG_0739.JPG
[ 0.0133549   0.03801349  0.27229738  0.00914067  0.05935491  0.1855848
  0.23350625  0.08867891  0.01579926  0.08426938]
2

$ python hoge.py IMG_0740.JPG
[ 0.08777995  0.00248157  0.15249293  0.00432909  0.00173489  0.63235831
  0.04411433  0.02771386  0.01238648  0.03460857]
5

実際はどれもほとんどの場合5と認識されてしまっていました:stuck_out_tongue_closed_eyes:

12
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11