golbin / TensorFlow-Tutorials

텐서플로우를 기초부터 응용까지 단계별로 연습할 수 있는 소스 코드를 제공합니다
2.13k stars 1k forks source link

chapter05.1 학습모델 저장 예제를 2번 실행하면 에러가 납니다.. #28

Closed hhmmkk closed 6 years ago

hhmmkk commented 6 years ago

안녕하세요. Chapter 05의 학습 모델 저장 예제 코드를 책에 나오는 대로 다시 한번 실행하면 아래와 같은 에러가 납니다. (첫 번째 실행할 때는 정상입니다..)

구글링해서 reset_default_graph() 를 사용하면 된다는 내용을 찾았는데 ㅠㅠ 비전공자다보니 정확히 어느 부분에 넣어야 할 지 모르겠습니다.

우선 4번 시작 지점에 넣어보았을땐

tf.reset_default_graph()

sess = tf.Session() saver = tf.train.Saver(tf.global_variables())

넣자마자 실행하면 에러가 뜨는데, tf.reset_default_graph() 를 주석처리하면 3회/4회 결과가 확인됩니다. 개발환경은 맥(맥북에어), python 3.6, tensorflow 1.4.1, jupyter notebook 4.3.1입니다..

=== 에러내용 ===

INFO:tensorflow:Restoring parameters from ./model/dnn.ckpt-2

NotFoundError Traceback (most recent call last) /anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, args) 1326 try: -> 1327 return fn(args) 1328 except errors.OpError as e:

/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata) 1305 feed_dict, fetch_list, target_list, -> 1306 status, run_metadata) 1307

/anaconda/lib/python3.6/contextlib.py in exit(self, type, value, traceback) 88 try: ---> 89 next(self.gen) 90 except StopIteration:

/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status() 465 compat.as_text(pywrap_tensorflow.TF_Message(status)), --> 466 pywrap_tensorflow.TF_GetCode(status)) 467 finally:

NotFoundError: Key Variable/Adam_1 not found in checkpoint [[Node: save_1/RestoreV2_2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_arg_save_1/Const_0_0, save_1/RestoreV2_2/tensor_names, save_1/RestoreV2_2/shape_and_slices)]]

During handling of the above exception, another exception occurred:

NotFoundError Traceback (most recent call last)

in () 51 ckpt = tf.train.get_checkpoint_state('./model') 52 if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path): ---> 53 saver.restore(sess, ckpt.model_checkpoint_path) 54 else: 55 sess.run(tf.global_variables_initializer()) /anaconda/lib/python3.6/site-packages/tensorflow/python/training/saver.py in restore(self, sess, save_path) 1558 logging.info("Restoring parameters from %s", save_path) 1559 sess.run(self.saver_def.restore_op_name, -> 1560 {self.saver_def.filename_tensor_name: save_path}) 1561 1562 @staticmethod /anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata) 893 try: 894 result = self._run(None, fetches, feed_dict, options_ptr, --> 895 run_metadata_ptr) 896 if run_metadata: 897 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) /anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 1122 if final_fetches or final_targets or (handle and feed_dict_tensor): 1123 results = self._do_run(handle, final_targets, final_fetches, -> 1124 feed_dict_tensor, options, run_metadata) 1125 else: 1126 results = [] /anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata) 1319 if handle is None: 1320 return self._do_call(_run_fn, self._session, feeds, fetches, targets, -> 1321 options, run_metadata) 1322 else: 1323 return self._do_call(_prun_fn, self._session, handle, feeds, fetches) /anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 1338 except KeyError: 1339 pass -> 1340 raise type(e)(node_def, op, message) 1341 1342 def _extend_graph(self): NotFoundError: Key Variable/Adam_1 not found in checkpoint [[Node: save_1/RestoreV2_2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_arg_save_1/Const_0_0, save_1/RestoreV2_2/tensor_names, save_1/RestoreV2_2/shape_and_slices)]] Caused by op 'save_1/RestoreV2_2', defined at: File "/anaconda/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/anaconda/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/anaconda/lib/python3.6/site-packages/ipykernel/__main__.py", line 3, in app.launch_new_instance() File "/anaconda/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance app.start() File "/anaconda/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 474, in start ioloop.IOLoop.instance().start() File "/anaconda/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 177, in start super(ZMQIOLoop, self).start() File "/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 887, in start handler_func(fd_obj, events) File "/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 275, in null_wrapper return fn(*args, **kwargs) File "/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events self._handle_recv() File "/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv self._run_callback(callback, msg) File "/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback callback(*args, **kwargs) File "/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 275, in null_wrapper return fn(*args, **kwargs) File "/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 276, in dispatcher return self.dispatch_shell(stream, msg) File "/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell handler(stream, idents, msg) File "/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 390, in execute_request user_expressions, allow_stdin) File "/anaconda/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 196, in do_execute res = shell.run_cell(code, store_history=store_history, silent=silent) File "/anaconda/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 501, in run_cell return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) File "/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell interactivity=interactivity, compiler=compiler, result=result) File "/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes if self.run_code(code, result): File "/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 49, in saver = tf.train.Saver(tf.global_variables()) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1140, in __init__ self.build() File "/anaconda/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 1172, in build filename=self._filename) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 688, in build restore_sequentially, reshape) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 407, in _AddRestoreOps tensors = self.restore_op(filename_tensor, saveable, preferred_shard) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/training/saver.py", line 247, in restore_op [spec.tensor.dtype])[0]) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/gen_io_ops.py", line 663, in restore_v2 dtypes=dtypes, name=name) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op op_def=op_def) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2630, in create_op original_op=self._default_original_op, op_def=op_def) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1204, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access NotFoundError (see above for traceback): Key Variable/Adam_1 not found in checkpoint [[Node: save_1/RestoreV2_2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_arg_save_1/Const_0_0, save_1/RestoreV2_2/tensor_names, save_1/RestoreV2_2/shape_and_slices)]]
golbin commented 6 years ago

tf.reset_default_graph() 는 처음에 넣으시면 되고,

저장된 모데을 읽지 못하거나 저장하지 못하는 문제이므로 model 파일이 저장되는 위치를 각각 다 다르게 주시면 됩니다.

예제 소스들은 주피터 노트북을 고려하지 않았으므로 주피터 노트북에서는 오류가 생길 수 있습니다. 뒤로 갈수록 더 그런 현상이 있을 수 있으니 터미널이나 명령창을 이용해주세요.