복붙노트

[PYTHON] TensorFlow 모델 복원

PYTHON

TensorFlow 모델 복원

TensorFlow 모델을 복원하려고합니다. 나는이 예를 따랐다. http://nasdag.github.io/blog/2016/01/19/classifying-bees-with-google-tensorflow/

예제의 코드 끝에서 다음 줄을 추가했습니다.

saver = tf.train.Saver()
save_path = saver.save(sess, "model.ckpt")
print("Model saved in file: %s" % save_path)

checkpoint 및 model.ckpt라는 두 개의 파일이 생성되었습니다.

새로운 python 파일 (tomas_bees_predict.py)에서이 코드가 있습니다.

import tensorflow as tf

saver = tf.train.Saver()

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

그러나 코드를 실행할 때이 오류가 발생합니다.

Traceback (most recent call last):
  File "tomas_bees_predict.py", line 3, in <module>
    saver = tf.train.Saver()
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 705, in __init__
raise ValueError("No variables to save")

ValueError : 저장할 변수가 없습니다.

mode.ckpt 파일을 읽고 어떤 변수가 저장되는지 보는 방법이 있습니까? 또는 누군가가 모델을 저장하고 위에서 설명한 예제를 기반으로 복원하는 것을 도울 수 있습니까?

편집 1 :

모델 구조를 다시 생성하기 위해 동일한 코드를 실행하려고 시도했지만 오류가 발생했습니다. 여기에 설명 된 코드는 명명 된 변수를 사용하지 않는다는 사실과 관련 될 수 있다고 생각합니다. http://nasdag.github.io/blog/2016/01/19/classifying-bees-with-google-tensorflow/

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

그래서 나는이 실험을했다. 모델과 코드를 저장하여 모델을 복원하는 두 가지 버전의 코드 (명명 된 변수 포함 및 제외)를 작성했습니다.

tensor_save_named_vars.py:

import tensorflow as tf

# Create some variables.
v1 = tf.Variable(1, name="v1")
v2 = tf.Variable(2, name="v2")

# Add an op to initialize the variables.
init_op = tf.initialize_all_variables()

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, initialize the variables, do some work, save the
# variables to disk.
with tf.Session() as sess:
  sess.run(init_op)
  print "v1 = ", v1.eval()
  print "v2 = ", v2.eval()
  # Save the variables to disk.
  save_path = saver.save(sess, "/tmp/model.ckpt")
  print "Model saved in file: ", save_path

tensor_save_not_named_vars.py:

import tensorflow as tf

# Create some variables.
v1 = tf.Variable(1)
v2 = tf.Variable(2)

# Add an op to initialize the variables.
init_op = tf.initialize_all_variables()

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, initialize the variables, do some work, save the
# variables to disk.
with tf.Session() as sess:
  sess.run(init_op)
  print "v1 = ", v1.eval()
  print "v2 = ", v2.eval()
  # Save the variables to disk.
  save_path = saver.save(sess, "/tmp/model.ckpt")
  print "Model saved in file: ", save_path

tensor_restore.py:

import tensorflow as tf

# Create some variables.
v1 = tf.Variable(0, name="v1")
v2 = tf.Variable(0, name="v2")

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
  # Restore variables from disk.
  saver.restore(sess, "/tmp/model.ckpt")
  print "Model restored."
  print "v1 = ", v1.eval()
  print "v2 = ", v2.eval()

이 코드를 실행하면 다음과 같습니다.

$ python tensor_save_named_vars.py 

I tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4
v1 =  1
v2 =  2
Model saved in file:  /tmp/model.ckpt

$ python tensor_restore.py 

I tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4
Model restored.
v1 =  1
v2 =  2

$ python tensor_save_not_named_vars.py 

I tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4
v1 =  1
v2 =  2
Model saved in file:  /tmp/model.ckpt

$ python tensor_restore.py 
I tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4
W tensorflow/core/common_runtime/executor.cc:1076] 0x7ff953881e40 Compute status: Not found: Tensor name "v2" not found in checkpoint files /tmp/model.ckpt
     [[Node: save/restore_slice_1 = RestoreSlice[dt=DT_INT32, preferred_shard=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/restore_slice_1/tensor_name, save/restore_slice_1/shape_and_slice)]]
W tensorflow/core/common_runtime/executor.cc:1076] 0x7ff953881e40 Compute status: Not found: Tensor name "v1" not found in checkpoint files /tmp/model.ckpt
     [[Node: save/restore_slice = RestoreSlice[dt=DT_INT32, preferred_shard=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/restore_slice/tensor_name, save/restore_slice/shape_and_slice)]]
Traceback (most recent call last):
  File "tensor_restore.py", line 14, in <module>
    saver.restore(sess, "/tmp/model.ckpt")
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 891, in restore
    sess.run([self._restore_op_name], {self._filename_tensor_name: save_path})
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 368, in run
    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 444, in _do_run
    e.code)
tensorflow.python.framework.errors.NotFoundError: Tensor name "v2" not found in checkpoint files /tmp/model.ckpt
     [[Node: save/restore_slice_1 = RestoreSlice[dt=DT_INT32, preferred_shard=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/restore_slice_1/tensor_name, save/restore_slice_1/shape_and_slice)]]
Caused by op u'save/restore_slice_1', defined at:
  File "tensor_restore.py", line 8, in <module>
    saver = tf.train.Saver()
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 713, in __init__
    restore_sequentially=restore_sequentially)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 432, in build
    filename_tensor, vars_to_save, restore_sequentially, reshape)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 191, in _AddRestoreOps
    values = self.restore_op(filename_tensor, vs, preferred_shard)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 106, in restore_op
    preferred_shard=preferred_shard)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/io_ops.py", line 189, in _restore_slice
    preferred_shard, name=name)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_io_ops.py", line 271, in _restore_slice
    preferred_shard=preferred_shard, name=name)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 664, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1834, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1043, in __init__
    self._traceback = _extract_stack()

따라서 원래의 코드 (위의 외부 링크 참조)는 다음과 같이 수정할 수 있습니다.

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  weight_var = tf.Variable(initial, name="weight_var")
  return weight_var

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  bias_var = tf.Variable(initial, name="bias_var")
  return bias_var

하지만 그때 내가 가진 질문 : 예측을 구현하기에 충분한 weight_var 및 bias_var 변수를 복원하고 있습니까? GPU가있는 강력한 컴퓨터에 대한 교육을 수행 했으므로 모델을 GPU가없는 강력한 컴퓨터로 복사하여 예측을 실행하고 싶습니다.

해결법

  1. ==============================

    1.비슷한 질문이 있습니다. Tensorflow : 모델을 저장 / 복원하는 방법은 무엇입니까? TLDR; Saver 객체를 사용하여 가중치를 복원하기 전에 동일한 TensorFlow API 명령 시퀀스를 사용하여 모델 구조를 다시 생성해야합니다.

    비슷한 질문이 있습니다. Tensorflow : 모델을 저장 / 복원하는 방법은 무엇입니까? TLDR; Saver 객체를 사용하여 가중치를 복원하기 전에 동일한 TensorFlow API 명령 시퀀스를 사용하여 모델 구조를 다시 생성해야합니다.

    이것은 차선책입니다. Github 발행 # 696을 따르십시오.

  2. ==============================

    2.이 문제는 동일한 네트워크를 두 번 만들 때 이름 범위 변형에 의해 발생해야합니다.

    이 문제는 동일한 네트워크를 두 번 만들 때 이름 범위 변형에 의해 발생해야합니다.

    명령을 입력하십시오 :

    tf.reset_default_graph ()

    네트워크를 만들기 전에

  3. ==============================

    3.이와 같은 문제가 발생하면 현재 변수가 이전 충돌을 덮어 쓰므로 커널을 다시 시작하십시오. 따라서 notFoundError와 다른 문제가 발생합니다.

    이와 같은 문제가 발생하면 현재 변수가 이전 충돌을 덮어 쓰므로 커널을 다시 시작하십시오. 따라서 notFoundError와 다른 문제가 발생합니다.

    같은 유형의 문제가 발생하여 커널을 다시 시작하면 저에게 도움이되었습니다. (주의 : 커널을 여러 번 실행하지 마십시오. 모델 파일이 손상되어 기존 변수를 덮어 쓰는 변수를 다시 만들면 원래 값이 변경됩니다.)

  4. ==============================

    4.tf.train.Saver ()의 선언이 tf.Session ()으로 sess로 지정되었는지 확인하십시오

    tf.train.Saver ()의 선언이 tf.Session ()으로 sess로 지정되었는지 확인하십시오

  5. from https://stackoverflow.com/questions/34982492/restoring-tensorflow-model by cc-by-sa and MIT license