(11) cuda-convnet用MNISTデータを作る(その1)

投稿者: | 2014年7月7日

2,698 views

この記事は最終更新から 1612日 が経過しています。

(1) MNIST画像データをダウンロード でダウンロードしたMNISTデータを、cuda-convnetプログラムで入力可能な形式に変換したい。Pythonに不慣れなこともあり、まずはファイルから入力した画像データを表示し、正しく読めていることを確認してみる。

事前にPythonでの画像表示に必要な以下のプログラムをインストールしておく必要がある。
PIL(Python Imaging Library)
ImageMagick

(1) 作業ディレクトリにはMNISTデータファイルが置いてある。

[user@linux]$ ll
-rw-rw-r--. 1 user user  7840016  7\u6708  7 18:08 2014 t10k-images-idx3-ubyte
-rw-rw-r--. 1 user user    10008  7\u6708  7 18:08 2014 t10k-labels-idx1-ubyte
-rw-rw-r--. 1 user user 47040016  7\u6708  7 18:08 2014 train-images-idx3-ubyte
-rw-rw-r--. 1 user user    60008  7\u6708  7 18:08 2014 train-labels-idx1-ubyte

(2) Pythonを起動する。

[user@linux]$ python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

(3) 使用するモジュールをロードする。

>>> import Image
>>> import numpy as np
>>> import struct

(4) train用データファイルをロードする。

>>> infile = open('./train-images-idx3-ubyte','rb')

(5) ヘッダ部のデータをロードする。

データファイルのフォーマットは (1) MNIST画像データをダウンロード を参照のこと。

>>> header = infile.read( 4 * 4 )
>>> header_up = struct.unpack('>4i', header)   # > : big endian, 4i: 4 x int(32bit) 
>>> numOfPixelsIn1Data = header_up[2] * header_up[3]
>>> print '# of image            : %d' % header_up[1]
# of image            : 60000
>>> print 'image width           : %d' % header_up[2]
image width           : 28
>>> print 'image height          : %d' % header_up[3]
image height          : 28
>>> print '# of pixels in a data : %d' % numOfPixelsIn1Data
# of pixels in a data : 784

(6) 先頭から5個の画像データを読み込み、表示する。

>>> for i in range(0,5):
...     data = infile.read( numOfPixelsIn1Data )
...     fmt  = '%dB' % numOfPixelsIn1Data
...     data_up = struct.unpack(fmt, data)
...     npData = np.asarray( data_up ).astype('uint8')
...     imData = np.reshape(npData, (28,28),order='C')
...     im = Image.fromarray( imData )
...     im.show()
... 

trainデータファイルの先頭にはこんな手書き数字画像が入っているようだ。
20140707_01

(7) 最後は(4)でオープンしたファイルをクローズする。

>>> infile.close()

次回「(12) cuda-convnet用MNISTデータを作る(その2)」では、ロードしたMNISTデータから cuda-convnetの batches.metaファイルを作成してみます。


コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です