chakokuのブログ(rev4)

テック・コミック・DTM・・・ごくまれにチャリ

【DLfS】ゼロから作るDL;MNISTデータを読み込んで表示させるサンプル

学習しない俺ニューラルネットができたところで、、次は認識結果テストだ。
DLfsでは、MNISTを使って認識率の算出を行っている(学習済みのネットワークデータも用意されていて、それを使うと認識率が90%だったか)。あらかじめ用意されたMNIST読み込みライブラリを使えば、ネットから?MNISTデータを読み込んであとはよろしくやってくれるようである。自分としてはpythonでのバイナリデータ操作も理解したいので、まずはMNISTのデータを視覚化するツールを作ってみた(サイトからのダウンロードと展開は手動で行う必要あり)。unpackのところはもうちょっと簡潔に書けるはずだが、調査不十分で、ちと分からず。

#!/usr/bin/python3

import struct

image_file = "./mnist/train-images-idx3-ubyte"
label_file = "./mnist/train-labels-idx1-ubyte"

n_of_data_set = 60000

f_image = open(image_file,'rb')
f_label = open(label_file,'rb')

#
# show header of Label
#
s = struct.Struct('>2I')   # I: unsigned int (4B) read as big endian
header = s.unpack(f_label.read(int((32+32)/8)))
print("----Header(label)----")
print('0X{:08x}({:04d})'.format(header[0],header[0]))
print('N:{:05d}'.format(header[1]))
print("--------------------")

#
# show header of Image
#
s = struct.Struct('>4I')   # I: unsigned int (4B) read as big endian
header = s.unpack(f_image.read(int((32+32+32+32)/8)))
print("----Header(image)----")
print('0X{:08x}({:04d})'.format(header[0],header[0]))
print('N:{:05d}\n{:02d}x{:02d}'.format(header[1],header[2],header[3]))
print("--------------------")


count = 0
s_image = struct.Struct('784B')   #  unpack unsinged byte (784B(28x28))
s_label = struct.Struct('B')   #  unpack unsinged byte (1B)

#
# show patterns
#
while count < n_of_data_set:
    count = count + 1
    print("--------------------------------------------------------")
    print('tabel:{:1d}'.format(s_label.unpack(f_label.read(1))[0]),end='')
    print("({:d}/{:d})".format(count,n_of_data_set))
    print("--------------------------------------------------------")

    # read one of data set (28x28)
    ptn = s_image.unpack(f_image.read(28*28))
    col=0
    for val in ptn:
        if val == 0:
            print('..',end='')
        else:
            print('{:02x}'.format(val),end='')
        col = col + 1
        if col == 28:
            print("")
            col=0

f_image.close()
f_label.close()

左がツールを動作させたところ。単純に実行すると全データを表示するまで終らないので、パイプでless等でページ送りさせながら見る必要あり。

レーニングデータを見ていると、自分が見ても正解がどれか分からない文字も結構含まれる。。
■ご参考URL
MNISTのサイト(データフォーマットの説明もあり)
http://yann.lecun.com/exdb/mnist/