PythonでData Augmentation

Pythonで画像の左右反転、回転、拡大を行ってみた。 Data Augmentationに使えるかなと。

f:id:Shoto:20170602001453p:plain

左右反転

scikit-imageだけで実現したかったのだが、APIを見つけられなかったのでOpenCVで実装。 でも3つの処理の中で最も簡単に書けた。 ちなみに第2引数を1ではなく0にすると上下反転になる。

# flip
img_fliped = cv2.flip(img, 1)

回転

angleには角度(°)を指定。 resizeがFalseの場合は、そのまま回転。Trueにすると元画像の画像の角が隠れないようになる。 centerをNoneにすると、中央を原点にして回転。

# rotatate
img_rotated = skimage.transform.rotate(img, angle=10, resize=False, center=None)

拡大

目的の処理が行えるシンプルなAPIがなかったので、AffineTransform()を使用。 rateがプラスの倍率。0.2の場合は20%拡大。scaleには1-rateを指定する形となる。 拡大は左上を原点にして行われるので、元画像の中央が拡大後も中央になるようにtranslationで修正。 具体的には拡大した大きさの半分だけ左上に平行移動している。

# expand
rate = 0.2
size = img.shape[0]
matrix_expanded = skimage.transform.AffineTransform(scale=(1-rate, 1-rate), translation=(size*rate/2, size*rate/2))
img_expanded = skimage.transform.warp(img, matrix_expanded)

実行

記事のトップ画像を表示するためのコードは以下の通り。

# coding: utf-8

import numpy as np
import cv2
import matplotlib.pyplot as plt
import skimage
from skimage import io
from skimage import transform

DIR = '../data/'

class Data:
    def test(self):
        # read Lenna image
        img_raw = skimage.io.imread(DIR+'lenna.jpg')

        # resize
        #img = skimage.transform.resize(img_raw, (32, 32))
        img = img_raw

        # flip
        img_fliped = cv2.flip(img, 1)

        # rotatate
        img_rotated = skimage.transform.rotate(img, angle=10, resize=False, center=None)

        # expand
        rate = 0.2
        size = img.shape[0]
        matrix_expanded = skimage.transform.AffineTransform(scale=(1-rate, 1-rate), translation=(size*rate/2, size*rate/2))
        img_expanded = skimage.transform.warp(img, matrix_expanded)

        # white background
        fig = plt.figure()
        fig.patch.set_facecolor('white')

        # display images
        plt.subplot(141)
        plt.title('raw')
        plt.imshow(img)

        plt.subplot(142)
        plt.title('flip')
        plt.imshow(img_fliped)

        plt.subplot(143)
        plt.title('rotate')
        plt.imshow(img_rotated)

        plt.subplot(144)
        plt.title('expand')
        plt.imshow(img_expanded)

        plt.show()

参考文献

scikit-imageを使った画像の平行移動

scikit-imageという便利なライブラリーを見つけた。 画像の平行移動が2行で実装できたので、以下に示す。

import skimage as ski
from skimage import io
from skimage.transform import rescale

def test(self):
    # Lennaさんの画像を読み込み
    img_raw = ski.io.imread(DIR+'lenna.jpg')
    # 512x512から32x32にリスケール
    img = ski.transform.rescale(img_raw, 32/512)
    # 左に3ピクセル、上に5ピクセルだけ平行移動
    matrix_trans = ski.transform.AffineTransform(translation=(3,5))
    img_trans = ski.transform.warp(img, matrix_trans)

    # 画像確認用の背景を白に
    fig = plt.figure()
    fig.patch.set_facecolor('white')

    # 元画像、リスケール画像、平行移動画像を横一列に標示
    plt.subplot(331)
    plt.imshow(img_raw)
    plt.subplot(332)
    plt.imshow(img)
    plt.subplot(333)
    plt.imshow(img_trans)
    plt.show()

画像標示結果は以下の通り。 f:id:Shoto:20170531011003p:plain

scikit-imageを使うためには、import skimage as skiだけで済むはずなのだが、ioとかrescaleは別にimportしないとエラーが出るので、原因を調査中。 またWindows環境だと、PowerShellでコードを実行した際に、画像の表示にio.imshow()が使えないため、上記のようにmatplotlibを利用している。 ただ、画像の回転や拡大にも簡単に行えるようなので、OpenCVとNumPyの組み合わせよりも、Data Augmentationが簡単に実装できそうである。

参考文献

損失関数がNaNになる問題

TensorFlowでDeep Learningを実行している途中で、損失関数がNaNになる問題が発生した。

Epoch:  10,  Train Loss: 85.6908,   Train Accuracy: 0.996,      Test Error: 90.7068,  Test Accuracy: 0.985238
Epoch:  20,  Train Loss: 42.9642,   Train Accuracy: 0.998286,   Test Error: 121.561,  Test Accuracy: 0.98619
Epoch:  30,  Train Loss: 0.945895,  Train Accuracy: 1.0,        Test Error: 102.041,  Test Accuracy: 0.990476
Epoch:  40,  Train Loss: nan,       Train Accuracy: 0.101429,   Test Error: nan,      Test Accuracy: 0.1
Epoch:  50,  Train Loss: nan,       Train Accuracy: 0.0941429,  Test Error: nan,      Test Accuracy: 0.1
Epoch:  60,  Train Loss: nan,       Train Accuracy: 0.0968571,  Test Error: nan,      Test Accuracy: 0.1
Epoch:  70,  Train Loss: nan,       Train Accuracy: 0.0881429,  Test Error: nan,      Test Accuracy: 0.1
Epoch:  80,  Train Loss: nan,       Train Accuracy: 0.0931429,  Test Error: nan,      Test Accuracy: 0.1
Epoch:  90,  Train Loss: nan,       Train Accuracy: 0.0997143,  Test Error: nan,      Test Accuracy: 0.1
Epoch: 100,  Train Loss: nan,       Train Accuracy: 0.0997143,  Test Error: nan,      Test Accuracy: 0.1

原因は、損失関数に指定している交差エントロピーtf.log(Y)にあった。

cross_entropy = -tf.reduce_sum(Y_*tf.log(Y))

tf.log(Y)はln(x)(自然対数のlog)であり、xが0になるとき-∞になるため、NaNとなっていた。

f:id:Shoto:20170507182523p:plain

ゼロから作るDeep Learning ―Pythonで学ぶディープラーニングの理論と実装では、4章の「ニューラルネットワークの学習」で、 極少の数値を加算することで、この問題に対処する方法を提示している。

def cross_entropy_error(y, t):
    delta = 1e-7
    return -np.sum(t * np.log(y + delta))

しかし、TensorFlowを利用したいので、上記の問題を解決しているsoftmax_cross_entropy_with_logits()を用いて、 cross_entropyを書き換える。

#cross_entropy = -tf.reduce_sum(Y_*tf.log(Y))
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(Y, Y_))

これにより、NaNになる問題が解決できた。 しかし、学習が進み、cross_entropyが低くなるに連れて、Yは1に近づき、tf.log(Y)は0に近づくため、 cross_entropyがNaNになる確率は低くなるはずなのだが、NaNになる点は謎のままである。

Epoch:  10,  Train Error: 1.46717,  Train Accuracy: 0.995,     Test Error: 1.47448,   Test Accuracy: 0.987619
Epoch:  20,  Train Error: 1.46428,  Train Accuracy: 0.997286,  Test Error: 1.47456,   Test Accuracy: 0.985714
Epoch:  30,  Train Error: 1.46262,  Train Accuracy: 0.998715,  Test Error: 1.47142,   Test Accuracy: 0.990476
Epoch:  40,  Train Error: 1.46272,  Train Accuracy: 0.998429,  Test Error: 1.47249,   Test Accuracy: 0.989047
Epoch:  50,  Train Error: 1.46235,  Train Accuracy: 0.998857,  Test Error: 1.47399,   Test Accuracy: 0.987619
Epoch:  60,  Train Error: 1.46462,  Train Accuracy: 0.996715,  Test Error: 1.47435,   Test Accuracy: 0.987619
Epoch:  70,  Train Error: 1.46261,  Train Accuracy: 0.998572,  Test Error: 1.47196,   Test Accuracy: 0.989524
Epoch:  80,  Train Error: 1.46215,  Train Accuracy: 0.999,     Test Error: 1.47119,   Test Accuracy: 0.99
Epoch:  90,  Train Error: 1.46547,  Train Accuracy: 0.995715,  Test Error: 1.4784,    Test Accuracy: 0.982857
Epoch: 100,  Train Error: 1.46201,  Train Accuracy: 0.999143,  Test Error: 1.47057,   Test Accuracy: 0.990476

参考文献

ResourceExhaustedErrorの原因

TensorFlowで学習していると、訓練データ数が大きい場合、たまにResourceExhaustedErrorが出る。 Windows 10では、以下の内容が表示される。

ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[37800,32,28,28] 
[[Node: Conv2D = Conv2D[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 1, 1, 1], 
use_cudnn_on_gpu=true, _device="/job:localhost/replica:0/task:0/gpu:0"](Reshape, Variable/read)]]

注目すべきは[37800,32,28,28]の部分。 順にバッチ数、チャンネル数、画像の縦のピクセル数、画像の横のピクセル数を表している。 これらの積(37800x32x28x28=948326400、単位はbyteではない)がメモリーの許容サイズを超えたためエラーが起きてるのだが、 今回はバッチ数(37800)が大き過ぎることにより、ResourceExhaustedErrorが発生している。

以下のように、僕の環境では、バッチ数(n_batch)は、訓練データ数(n_record)とバッチ率(batch_rate)をかけて決定している。 そのため、訓練データ数が大きい場合は、バッチ率を小さくする必要があったのにしていなかったため、エラーが発生していた。 もしくはバッチ数をエラーが出ない固定値に設定する必要があった。

n_batch = int(n_record*batch_rate)
for start in range(0, n_record, n_batch):
    end = start + n_batch
    sess.run(train_step, feed_dict={X: train_data[start:end], Y_: train_label[start:end]})

TensorFlowのMNISTのチュートリアルでは、 以下のようにバッチ数を50に固定している。 ただし、訓練データ数が少ないMNISTだから50で良いが、訓練データ数が非常に大きいデータの場合は、 学習に時間がかかりすぎる場合がある。 そのため、やはりバッチ率を指定するなどにより、訓練データ数に合わせてバッチ数の調整が必要である。 また、run()だけでなくeval()に渡すバッチ数も調整する必要がある。

for i in range(20000):
    batch = mnist.train.next_batch(50)
    if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
        print("step %d, training accuracy %g" % (i, train_accuracy))
    train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

参考文献

Python3でcPickleのエラーを回避する

CIFAR-10を読み込もうとしたら、Python2で動いてたcPickleがPython3では動かない。 import cPickleと書けばImportError: No module named 'cPickle'と吐き、 d = cPickle.load(f)と書けばUnicodeDecodeError: 'ascii' codec can't decode byte 0x8b in position 6: ordinal not in range(128)と吐く。 これらの問題を解決する。

cPicleではなく、_pickleを使う

Python3ではcPicleなど存在しない。代わりに_pickleを使えばいいのだが、 修正を最小限にするために、以下のように記述する。

#import cPickle
import _pickle as cPickle

loadできない場合はエンコードを指定する

load()のencodinglatin1を指定すると上手くいく。

    def unpickle(self, f):
        fo = open(f, 'rb')
        d = cPickle.load(fo, encoding='latin1')
        fo.close()

        return d

参考文献

CIFAR-10の取得と整理

MNISTの識別モデルをDeep Learningで上手く学習できたので、次の対象としてCIFAR-10を選んだ。 TensorFlowを使うと、学習が上手くいくように加工してくれるみたいだが、今回は一次ソースからデータを取得する。

CIFAR-10の取得

まず、CIFAR-10 and CIFAR-100 datasetsの “CIFAR-10 python version” をクリックしてデータをダウンロードする。 解凍するとcifar-10-batches-pyというフォルダーができるので適当な場所に置く。

CIFAR-10の内容

cifar-10-batches-pyの中身は以下の通り。 data_batchは10000x5レコード、test_batchは10000レコードある。 各々データとラベルに別れる。 データは1レコードあたり3072個(=1024x3, RGB)ある。 ラベルは1レコードあたり1個(0〜9のいずれか)なので、onehotにする必要がある。

cifar-10-batches-py
├── batches.meta  
├── data_batch_1  // training data 1
├── data_batch_2  // training data 2
├── data_batch_3  // training data 3
├── data_batch_4  // training data 4
├── data_batch_5  // training data 5
├── readme.html
└── test_batch    // testing data

batches.metaは以下の通り。

{
    'num_cases_per_batch': 10000,
    'label_names': ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'],
    'num_vis': 3072
}

各ファイルは、以下のメソッドで可読できるようになる。

    import cPickle
    def unpickle(self, f):
        fo = open(f, 'rb')
        d = cPickle.load(fo)
        fo.close()

        return d

CIFAR-10の整理

Deep Learningで学習させるため、訓練データ、訓練ラベル、テストデータ、テストラベルに分ける。 さらに、ラベルはonehotにする。まずは、必要なライブラリーをインポート。

# coding: utf-8

import cPickle
import numpy as np
from sklearn.preprocessing import OneHotEncoder

ダウンロードしたCIFAR-10はDIRに置くことにする。 なお、データ整理の実行ファイルをsrc/data_cifar10.pyとする。 datasrcは同じ階層にある。

DIR = '../data/cifar10/cifar-10-batches-py/'
FILE_TRAIN = 'data_batch_%s'
FILE_TEST = 'test_batch'

訓練用のdata_batchは、5分割されているので全て結合する。 ラベルについては、onehot()によりonehotに変換する。 テスト用のtest_batchの結合する以外は、data_batchと同じ処理を行う。 結果して、訓練データ、訓練ラベル、テストデータ、テストラベルを格納したdataを返す。

注意!: np.empty()はランダムな数値で初期化するので、以下は間違ってるので使わないでください。暇ができたら修正します。

   def main(self):        
        # Training
        train_data = np.empty((0,3072))
        train_label = np.empty((0,10))
        for i in range(1, 6):
            print('read %s' % FILE_TRAIN%i)
            # data
            train_data_1 = self.unpickle(DIR+FILE_TRAIN%i)['data']
            train_data = np.concatenate((train_data, train_data_1), axis=0)
            # labels
            train_label_1 = self.unpickle(DIR+FILE_TRAIN%i)['labels']
            train_label_1 = self.onehot(train_label_1)
            train_label = np.concatenate((train_label, train_label_1), axis=0)

        # Testing
        print('read %s' % FILE_TEST)
        # data
        test_data = self.unpickle(DIR+FILE_TEST)['data']
        # labels
        test_label = self.unpickle(DIR+FILE_TEST)['labels']
        test_label = self.onehot(test_label)

        # Collect
        data = [train_data, train_label, test_data, test_label]

        return data

onehot()の各行の処理内容については、こちらが詳しい。

   def onehot(self, X):
        X = np.array(X).reshape(1, -1)
        X = X.transpose()
        encoder = OneHotEncoder(n_values=max(X)+1)
        X = encoder.fit_transform(X).toarray()

        return X

test()でmain()を実行して、結果を標準出力して内容を確認する。

   def test(self):
        data = self.main()
        
        print('')
        print('Training Data: %s columns, %s records' % (data[0].shape[1], data[0].shape[0]))
        print(data[0])
        print('')
        print('Training Labels: %s columns, %s records' % (data[1].shape[1], data[1].shape[0]))
        print(data[1])
        print('')

        print('Test Data: %s columns, %s records' % (data[2].shape[1], data[2].shape[0]))
        print(data[2])
        print('')
        print('Test Labels: %s columns, %s records' % (data[3].shape[1], data[3].shape[0]))
        print(data[3])      
        print('')

ファイル名を指定するだけで実行できるように以下を記述する。

if __name__ == "__main__":
    DataCifar10().test()

実行結果は以下の通り。 目的のデータが取得できていることが確認できる。

$ python data_cifar10.py
read data_batch_1
read data_batch_2
read data_batch_3
read data_batch_4
read data_batch_5
read test_batch

Training Data: 3072 columns, 50000 records
[[  59.   43.   50. ...,  140.   84.   72.]
 [ 154.  126.  105. ...,  139.  142.  144.]
 [ 255.  253.  253. ...,   83.   83.   84.]
 ...,
 [  35.   40.   42. ...,   77.   66.   50.]
 [ 189.  186.  185. ...,  169.  171.  171.]
 [ 229.  236.  234. ...,  173.  162.  161.]]

Training Labels: 10 columns, 50000 records
[[ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  1.]
 [ 0.  0.  0. ...,  0.  0.  1.]
 ...,
 [ 0.  0.  0. ...,  0.  0.  1.]
 [ 0.  1.  0. ...,  0.  0.  0.]
 [ 0.  1.  0. ...,  0.  0.  0.]]

Test Data: 3072 columns, 10000 records
[[158 159 165 ..., 124 129 110]
 [235 231 232 ..., 178 191 199]
 [158 158 139 ...,   8   3   7]
 ...,
 [ 20  19  15 ...,  50  53  47]
 [ 25  15  23 ...,  80  81  80]
 [ 73  98  99 ...,  94  58  26]]

Test Labels: 10 columns, 10000 records
[[ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  1.  0.]
 [ 0.  0.  0. ...,  0.  1.  0.]
 ...,
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  1.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  1.  0.  0.]]

最後に全ソースを載せておく。

# coding: utf-8

import cPickle
import numpy as np
from sklearn.preprocessing import OneHotEncoder

DIR = '../data/cifar10/cifar-10-batches-py/'
FILE_TRAIN = 'data_batch_%s'
FILE_TEST = 'test_batch'

class DataCifar10:
    def __init__(self):
        pass


    def main(self):        
        # Training
        train_data = np.empty((0,3072))
        train_label = np.empty((0,10))
        for i in range(1, 6):
            print('read %s' % FILE_TRAIN%i)
            # data
            train_data_1 = self.unpickle(DIR+FILE_TRAIN%i)['data']
            train_data = np.concatenate((train_data, train_data_1), axis=0)
            # labels
            train_label_1 = self.unpickle(DIR+FILE_TRAIN%i)['labels']
            train_label_1 = self.onehot(train_label_1)
            train_label = np.concatenate((train_label, train_label_1), axis=0)

        # Testing
        print('read %s' % FILE_TEST)
        # data
        test_data = self.unpickle(DIR+FILE_TEST)['data']
        # labels
        test_label = self.unpickle(DIR+FILE_TEST)['labels']
        test_label = self.onehot(test_label)
        
        # Collect
        data = [train_data, train_label, test_data, test_label]

        return data


    def unpickle(self, f):
        fo = open(f, 'rb')
        d = cPickle.load(fo)
        fo.close()

        return d


    def onehot(self, X):
        X = np.array(X).reshape(1, -1)
        X = X.transpose()
        encoder = OneHotEncoder(n_values=max(X)+1)
        X = encoder.fit_transform(X).toarray()

        return X


    def test(self):
        data = self.main()
        
        print('')
        print('Training Data: %s columns, %s records' % (data[0].shape[1], data[0].shape[0]))
        print(data[0])
        print('')
        print('Training Labels: %s columns, %s records' % (data[1].shape[1], data[1].shape[0]))
        print(data[1])
        print('')

        print('Test Data: %s columns, %s records' % (data[2].shape[1], data[2].shape[0]))
        print(data[2])
        print('')
        print('Test Labels: %s columns, %s records' % (data[3].shape[1], data[3].shape[0]))
        print(data[3])      
        print('')


if __name__ == "__main__":
    DataCifar10().test()

参考文献

TensorFlowでmodelを保存して復元する

modelの保存と復元は、それぞれ以下のようにシンプルな設計で行える。

  • Save a model
saver = tf.train.Saver()
saver.save(sess, '../model/test_model')
  • Restore a model
saver = tf.train.Saver()
saver.restore(sess, '../model/test_model')

本記事では、実際にmodelを訓練して保存し、そのmodelを復元して、各々のテスト精度が一致していることを確認する。

処理の流れ

# coding: utf-8

import tensorflow as tf
import random
import os

from data_fizzbuzz import DataFizzBuzz

class Test:
    def __init__(self):
        pass

    def main(self):
        data = DataFizzBuzz().main()
        model = self.design_model(data)
        self.save_model(data, model)
        self.restore_model(data, model)

データを取得して、モデルをデザインして、モデルを訓練して保存して、モデルを復元する。

データ

例によってFizzBuzz問題のためのデータを利用する。 ここ にあるので、以下で解説するソースと同じ場所に置く。

モデル

def design_model(self, data):
    X  = tf.placeholder(tf.float32, [None, data[0].shape[1]])
    W1 = tf.Variable(tf.truncated_normal([data[0].shape[1], 100], stddev=0.01), name='W1')
    B1 = tf.Variable(tf.zeros([100]), name='B1')
    H1 = tf.nn.tanh(tf.matmul(X, W1) + B1)
    W2 = tf.Variable(tf.random_normal([100, data[1].shape[1]], stddev=0.01), name='W2')
    B2 = tf.Variable(tf.zeros([data[1].shape[1]]), name='B2')
    Y = tf.matmul(H1, W2) + B2
    Y_ = tf.placeholder(tf.float32, [None, data[1].shape[1]])

    tf.add_to_collection('vars', W1)
    tf.add_to_collection('vars', B1)
    tf.add_to_collection('vars', W2)
    tf.add_to_collection('vars', B2)

    model = {'X': X, 'Y': Y, 'Y_': Y_}

    return model

1層のFFNNを訓練する。 重み(W)とバイアス(B)についてはnameを付ける。 add_to_collection()で変数として登録する。

モデルの保存

def save_model(self, data, model):
    """
    # Data
    dataは、訓練データ、訓練ラベル、テストデータ、
    テストラベルの順に格納されているので、順に取り出す。
    """
    train_data  = data[0]
    train_label = data[1]
    test_data  = data[2]
    test_label = data[3]

    """
    # Model
    設計したモデルのうち、訓練で使うのは、X, Y, Y_のみなので、それらを取り出す。
    """
    X, Y, Y_ = model['X'], model['Y'], model['Y_']

    """
    # Functions
    訓練で利用する関数をそれぞれ定義する。
    """
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(Y, Y_))
    step = tf.train.AdamOptimizer(0.05).minimize(loss)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1)), tf.float32))

    """
    # Setting
    初期化。saverは、モデルを保存するためのインスタンス。
    """
    saver = tf.train.Saver()
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())

    """
    # Randamize data
    101〜1023のデータをランダマイズする。
    """
    p = np.random.permutation(range(len(train_data)))
    train_data, train_label = train_data[p], train_label[p]

    """
    # Training
    100バッチずつ訓練するエポックを1回繰り返す。
    訓練エラー、訓練精度、テスト精度を算出する。
    """
    for start in range(0, train_label.shape[0], 1):
        end = start + 100
        sess.run(step, feed_dict={X: train_data[start:end], Y_: train_label[start:end]})

        # Testing
        train_loss = sess.run(loss, feed_dict={X: train_data, Y_: train_label})
        train_accuracy = sess.run(accuracy, feed_dict={X: train_data, Y_: train_label})
        test_accuracy = sess.run(accuracy, feed_dict={X: test_data, Y_: test_label})

    """
    # Accuracy
    学習後、訓練エラー、訓練精度、テスト精度を標準出力する。
    """
    std_output = 'Train Loss: %s, \t Train Accuracy: %s, \t Test Accuracy: %s'
    print(std_output % (train_loss, train_accuracy, test_accuracy))

    """
    # Save a model
    既存の訓練モデルを削除して、今回訓練したモデルを保存する。
    """
    for f in os.listdir('../model/'):
        os.remove('../model/'+f)
    saver.save(sess, '../model/test_model')
    print('Saved a model.')

    sess.close()

modelディレクトリーには、以下が保存される。

  • checkpoint
  • test_model.data-00000-of-00001
  • test_model.index
  • test_model.meta

モデルの復元

def restore_model(self, data, model):
    # Data
    train_data  = data[0]
    train_label = data[1]
    test_data  = data[2]
    test_label = data[3]

    # Model
    X, Y, Y_ = model['X'], model['Y'], model['Y_']

    # Function
    accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1)), tf.float32))

    """
    # Setting
    SaverとSessionのインスタンスを生成し、モデルを復元する。
    """
    saver = tf.train.Saver()
    sess = tf.Session()
    saver.restore(sess, '../model/test_model')
    print('Restored a model')

    test_accuracy = sess.run(accuracy, feed_dict={X: test_data, Y_: test_label})
    print('Test Accuracy: %s' % test_accuracy)

復元は非常に簡単。 モデルの保存で使用したデータとモデルを渡している。 データは何でもいいが、モデルは同じものが必要。 初期化は不要。

実行結果

$ python test.py
Train Loss: 1.88192,     Train Accuracy: 0.781148,   Test Accuracy: 0.762376
Saved a model.
Restored a model
Test Accuracy: 0.762376

Test Accuracyが、モデルの保存とモデルの復元で一致している。 同じモデルとテストデータだと、同じ精度が出ることが確認できた。

その他

もしモデルの復元で失敗するときは、モデルの保存を一回した後で、モデルの復元だけ実行したり、 以下のように1行足してみると上手く行くかも。

# Setting
saver = tf.train.Saver()
sess = tf.Session()
saver = tf.train.import_meta_graph('../model/test_model.meta')  ## <- add
saver.restore(sess, '../model/test_model')