読者です 読者をやめる 読者になる 読者になる

Tensorflow + Jupyterのsave & restore時のトラブルとその回避方法

Tensorflowでモデルを保存しようとする場合にsaveしたモデルをrestoreすることができないトラブルに遭遇した。

保存側:

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

saver = tf.train.Saver()

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
for _ in range(3):
    print(_)
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
    save_path = saver.save(sess, "tmp/model.ckpt")
    print(save_path)

print(sess.run(b))
print(sess.run(W))

読込側:

import tensorflow as tf
import numpy as np
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
saver = tf.train.Saver()

with tf.Session() as sess:
  # Restore variables from disk.
  saver.restore(sess, "tmp/model.ckpt")
  print("Model restored.")
  print(sess.run(b))
  print(sess.run(W))

上記のコードはmnist sampleにsaveとrestoreを追加したもの。シェル上では正しく動作するのだが、jupyter上で動作させると NotFoundError: Key Variable_43 not found in checkpoint というエラーが発生する。(43の部分は実行毎に異なる)

StackOverflowには同様の事象の報告が上がっている。Googleのエンジニアからの回答によると、 ・Jupyterがコードの再実行時のパフォーマンスを上げるために勝手に変数をコピーする=> ・その結果、Tensorflowが名前の重複を避けるために新しい名前をアサインして別Variablesが増える ということが起きているようです。

これを避けるために、3つの方法が提示されています。

  1. モデルの構築を始める前にtf.reset_default_graph()を呼び出す。(defaultとして設定されているGraphが消える点に注意)

  2. tf.train.Saver()を呼び出す際に、保存するVariableを明示的に指定する。例としては saver = tf.train.Saver(var_list={"b1": b1, "W1": W1, "b2": b2, "W2": W2}) が紹介されていますが、こちらのように、Variableの宣言時にtrainable=Trueを宣言し、tf.trainable_variables()Saverに渡す方法もあるようです

  3. Graphのスコープをwith tf.Graph().as_default():で明示的に指定し、その中でモデルの宣言とrestoreを行う

副作用が少なそうで、行儀が良さそうなのは2かな..という気がするのでこれでやっています。 Tensorflowのsaveとrestoreについては、Saverコンストラクタの呼び出しタイミングがセンシティブだったりするので色々注意が必要ですね。


補足: エラー詳細

INFO:tensorflow:Restoring parameters from tmp/model.ckpt

---------------------------------------------------------------------------
NotFoundError                             Traceback (most recent call last)
<ipython-input-36-1322488c39ce> in <module>()
     12 with tf.Session() as sess:
     13   # Restore variables from disk.
---> 14   saver.restore(sess, "tmp/model.ckpt")
     15   print("Model restored.")
     16 

/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/training/saver.pyc in restore(self, sess, save_path)
   1455     logging.info("Restoring parameters from %s", save_path)
   1456     sess.run(self.saver_def.restore_op_name,
-> 1457              {self.saver_def.filename_tensor_name: save_path})
   1458 
   1459   @staticmethod

/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053 
   1054   def _extend_graph(self):

NotFoundError: Key Variable_43 not found in checkpoint
         [[Node: save_21/RestoreV2_38 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_21/Const_0, save_21/RestoreV2_38/tensor_names, save_21/RestoreV2_38/shape_and_slices)]]

Caused by op u'save_21/RestoreV2_38', defined at:
  File "/Users/miz/.pyenv/versions/2.7.11/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/Users/miz/.pyenv/versions/2.7.11/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-36-1322488c39ce>", line 10, in <module>
    saver = tf.train.Saver()
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1056, in __init__
    self.build()
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1086, in build
    restore_sequentially=self._restore_sequentially)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 691, in build
    restore_sequentially, reshape)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 407, in _AddRestoreOps
    tensors = self.restore_op(filename_tensor, saveable, preferred_shard)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 247, in restore_op
    [spec.tensor.dtype])[0])
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/ops/gen_io_ops.py", line 669, in restore_v2
    dtypes=dtypes, name=name)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/miz/.pyenv/versions/2.7.11/envs/tensorflow_test/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

NotFoundError (see above for traceback): Key Variable_43 not found in checkpoint
         [[Node: save_21/RestoreV2_38 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_21/Const_0, save_21/RestoreV2_38/tensor_names, save_21/RestoreV2_38/shape_and_slices)]]