60634
2か月ほど前からプログラミングを始めたTetsuoというものです．

OSがWindows10かつColaboratory+Python3のノートブックによる環境下でTnesorflowを用いたMINISTのデータを学習を行っています．

※1 参考サイト  
「TensorFlowのMNISTチュートリアルを画像入力に対応させた」  
<https://qiita.com/JUN_NETWORKS/items/6514e017e89b9adbfb8d>

※1のサイトを参考にさせていただき，Tensorflowによる学習を行いましたが，学習済みの変数を読み込もうとしてもエラーが出て読み込めません．

私が行った手順は以下の通りです．  
(1) ※1サイトのtrain_mnist.pyをコピペして数字画像の学習をする．  
(2) 最終行で

```

    saver.save(sess, ".\ckpt\model.ckpt")
    
```

と記入し，学習済みの変数を保存する

(3)※1サイトのinput_num.pyをコピペして学習済みの変数を読み込む

すると

```

    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-43-03731490e451> in <module>()
         20     sess.run(tf.global_variables_initializer())
         21     ckpt = tf.train.get_checkpoint_state('./ckpt')
    ---> 22     saver.restore(sess, '.\ckpt\model.ckpt') # 変数データの読み込み
         23 
         24     pred = np.argmax(logits.eval(feed_dict={x_image: [ximage], keep_prob: 1.0})[0])
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py in restore(self, sess, save_path)
       1280     if not checkpoint_management.checkpoint_exists_internal(checkpoint_prefix):
       1281       raise ValueError("The passed save_path is not a valid checkpoint: " +
    -> 1282                        checkpoint_prefix)
       1283 
       1284     logging.info("Restoring parameters from %s", checkpoint_prefix)
    
    ValueError: The passed save_path is not a valid checkpoint: .\ckpt\model.ckpt
    
```

とエラーが出て変数を読み込めません．

パスの表記方が間違っているのかと考え，saver.saveおよびsaver.restoreのパスを

```

    saver.save(sess, "model.ckpt")
    saver.restore(sess, "model.ckpt")
    
```

にそれぞれ変更しましたが，この場合は以下のようなエラーが出てしまいやはり成功しません．

```

    ---------------------------------------------------------------------------
    NotFoundError                             Traceback (most recent call last)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/client/session.py in _do_call(self, fn, *args)
       1364     try:
    -> 1365       return fn(*args)
       1366     except errors.OpError as e:
    
    11 frames
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
       1349       return self._call_tf_sessionrun(options, feed_dict, fetch_list,
    -> 1350                                       target_list, run_metadata)
       1351 
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
       1442                                             fetch_list, target_list,
    -> 1443                                             run_metadata)
       1444 
    
    NotFoundError: 2 root error(s) found.
      (0) Not found: Key conv1_1/Variable not found in checkpoint
         [[{{node save_5/RestoreV2}}]]
         [[save_5/RestoreV2/_9]]
      (1) Not found: Key conv1_1/Variable not found in checkpoint
         [[{{node save_5/RestoreV2}}]]
    0 successful operations.
    0 derived errors ignored.
    
    During handling of the above exception, another exception occurred:
    
    NotFoundError                             Traceback (most recent call last)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py in restore(self, sess, save_path)
       1289         sess.run(self.saver_def.restore_op_name,
    -> 1290                  {self.saver_def.filename_tensor_name: save_path})
       1291     except errors.NotFoundError as err:
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
        955       result = self._run(None, fetches, feed_dict, options_ptr,
    --> 956                          run_metadata_ptr)
        957       if run_metadata:
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
       1179       results = self._do_run(handle, final_targets, final_fetches,
    -> 1180                              feed_dict_tensor, options, run_metadata)
       1181     else:
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
       1358       return self._do_call(_run_fn, feeds, fetches, targets, options,
    -> 1359                            run_metadata)
       1360     else:
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/client/session.py in _do_call(self, fn, *args)
       1383                     'disable_meta_optimizer = True')
    -> 1384       raise type(e)(node_def, op, message)
       1385 
    
    NotFoundError: 2 root error(s) found.
      (0) Not found: Key conv1_1/Variable not found in checkpoint
         [[node save_5/RestoreV2 (defined at /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py:1748) ]]
         [[save_5/RestoreV2/_9]]
      (1) Not found: Key conv1_1/Variable not found in checkpoint
         [[node save_5/RestoreV2 (defined at /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py:1748) ]]
    0 successful operations.
    0 derived errors ignored.
    
    Original stack trace for 'save_5/RestoreV2':
      File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
        "__main__", mod_spec)
      File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
        exec(code, run_globals)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py", line 16, in <module>
        app.launch_new_instance()
      File "/usr/local/lib/python3.6/dist-packages/traitlets/config/application.py", line 664, in launch_instance
        app.start()
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelapp.py", line 477, in start
        ioloop.IOLoop.instance().start()
      File "/usr/local/lib/python3.6/dist-packages/tornado/ioloop.py", line 888, in start
        handler_func(fd_obj, events)
      File "/usr/local/lib/python3.6/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
        return fn(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 450, in _handle_events
        self._handle_recv()
      File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 480, in _handle_recv
        self._run_callback(callback, msg)
      File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 432, in _run_callback
        callback(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
        return fn(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
        return self.dispatch_shell(stream, msg)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
        handler(stream, idents, msg)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
        user_expressions, allow_stdin)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
        res = shell.run_cell(code, store_history=store_history, silent=silent)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
        return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
        interactivity=interactivity, compiler=compiler, result=result)
      File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
        if self.run_code(code, result):
      File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-60-25ee93a2e95a>", line 19, in <module>
        saver = tf.train.Saver()
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 828, in __init__
        self.build()
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 840, in build
        self._build(self._filename, build_save=True, build_restore=True)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 878, in _build
        build_restore=build_restore)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 508, in _build_internal
        restore_sequentially, reshape)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 328, in _AddRestoreOps
        restore_sequentially)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 575, in bulk_restore
        return io_ops.restore_v2(filename_tensor, names, slices, dtypes)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/gen_io_ops.py", line 1696, in restore_v2
        name=name)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/op_def_library.py", line 794, in _apply_op_helper
        op_def=op_def)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/util/deprecation.py", line 507, in new_func
        return func(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py", line 3357, in create_op
        attrs, op_def, compute_device)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py", line 3426, in _create_op_internal
        op_def=op_def)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py", line 1748, in __init__
        self._traceback = tf_stack.extract_stack()
    
    
    During handling of the above exception, another exception occurred:
    
    NotFoundError                             Traceback (most recent call last)
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py in restore(self, sess, save_path)
       1299       try:
    -> 1300         names_to_keys = object_graph_key_mapping(save_path)
       1301       except errors.NotFoundError:
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py in object_graph_key_mapping(checkpoint_path)
       1617   reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
    -> 1618   object_graph_string = reader.get_tensor(trackable.OBJECT_GRAPH_PROTO_KEY)
       1619   object_graph_proto = (trackable_object_graph_pb2.TrackableObjectGraph())
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/pywrap_tensorflow_internal.py in get_tensor(self, tensor_str)
        914 
    --> 915       return CheckpointReader_GetTensor(self, compat.as_bytes(tensor_str))
        916 
    
    NotFoundError: Key _CHECKPOINTABLE_OBJECT_GRAPH not found in checkpoint
    
    During handling of the above exception, another exception occurred:
    
    NotFoundError                             Traceback (most recent call last)
    <ipython-input-60-25ee93a2e95a> in <module>()
         20     sess.run(tf.global_variables_initializer())
         21     ckpt = tf.train.get_checkpoint_state('./ckpt')
    ---> 22     saver.restore(sess, 'model.ckpt') # 変数データの読み込み
         23 
         24     pred = np.argmax(logits.eval(feed_dict={x_image: [ximage], keep_prob: 1.0})[0])
    
    /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py in restore(self, sess, save_path)
       1304         # a helpful message (b/110263146)
       1305         raise _wrap_restore_error_with_msg(
    -> 1306             err, "a Variable name or other graph key that is missing")
       1307 
       1308       # This is an object-based checkpoint. We'll print a warning and then do
    
    NotFoundError: Restoring from checkpoint failed. This is most likely due to a Variable name or other graph key that is missing from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error:
    
    2 root error(s) found.
      (0) Not found: Key conv1_1/Variable not found in checkpoint
         [[node save_5/RestoreV2 (defined at /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py:1748) ]]
         [[save_5/RestoreV2/_9]]
      (1) Not found: Key conv1_1/Variable not found in checkpoint
         [[node save_5/RestoreV2 (defined at /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py:1748) ]]
    0 successful operations.
    0 derived errors ignored.
    
    Original stack trace for 'save_5/RestoreV2':
      File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
        "__main__", mod_spec)
      File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
        exec(code, run_globals)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py", line 16, in <module>
        app.launch_new_instance()
      File "/usr/local/lib/python3.6/dist-packages/traitlets/config/application.py", line 664, in launch_instance
        app.start()
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelapp.py", line 477, in start
        ioloop.IOLoop.instance().start()
      File "/usr/local/lib/python3.6/dist-packages/tornado/ioloop.py", line 888, in start
        handler_func(fd_obj, events)
      File "/usr/local/lib/python3.6/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
        return fn(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 450, in _handle_events
        self._handle_recv()
      File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 480, in _handle_recv
        self._run_callback(callback, msg)
      File "/usr/local/lib/python3.6/dist-packages/zmq/eventloop/zmqstream.py", line 432, in _run_callback
        callback(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
        return fn(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
        return self.dispatch_shell(stream, msg)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
        handler(stream, idents, msg)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
        user_expressions, allow_stdin)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
        res = shell.run_cell(code, store_history=store_history, silent=silent)
      File "/usr/local/lib/python3.6/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
        return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
        interactivity=interactivity, compiler=compiler, result=result)
      File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
        if self.run_code(code, result):
      File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-60-25ee93a2e95a>", line 19, in <module>
        saver = tf.train.Saver()
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 828, in __init__
        self.build()
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 840, in build
        self._build(self._filename, build_save=True, build_restore=True)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 878, in _build
        build_restore=build_restore)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 508, in _build_internal
        restore_sequentially, reshape)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 328, in _AddRestoreOps
        restore_sequentially)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/saver.py", line 575, in bulk_restore
        return io_ops.restore_v2(filename_tensor, names, slices, dtypes)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/gen_io_ops.py", line 1696, in restore_v2
        name=name)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/op_def_library.py", line 794, in _apply_op_helper
        op_def=op_def)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/util/deprecation.py", line 507, in new_func
        return func(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py", line 3357, in create_op
        attrs, op_def, compute_device)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py", line 3426, in _create_op_internal
        op_def=op_def)
      File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/framework/ops.py", line 1748, in __init__
        self._traceback = tf_stack.extract_stack()
    
```

このような問題の解決方法をご存じでしたらご教授お願いいたします．
CC BY-SA 4.0
2019-11-17T11:16:38.567
60607
2019-11-18T12:28:25.560
36664
question
tensorflow google-colaboratory
sever.saveで保存した変数データを読み込めません
```

    saver.restore(sess, '.\ckpt\model.ckpt') # 変数データの読み込み
    
```

を次のように修正したら、うまくいきませんかね？

```

    if ckpt:
      server.restore(sess, ckpt.model_checkpoint_path) # 変数データの読み込み
    
```
CC BY-SA 4.0
2019-11-18T12:28:25.560
60634
2019-11-18T12:28:25.560
21092
60607
answer