tensorflow API:tf.train.Saver 与 NotFoundError: "x_x" not found in checkpoint

keep

Import the required modules, then create W and b in the neural network, and initialize the variables.

import tensorflow as tf
import numpy as np
## Save to file
# remember to define the same dtype and shape when restore
W = tf.Variable([[1,2,3],[3,4,5]], dtype=tf.float32, name='weights')
b = tf.Variable([[1,2,3]], dtype=tf.float32, name='biases')
# init= tf.initialize_all_variables() # tf 马上就要废弃这种写法
# 替换成下面的写法:
init = tf.global_variables_initializer()

When saving, first create a tf.train.Saver() to save and extract variables.
SaverExample:

v1 = tf.Variable(..., name='v1')
v2 = tf.Variable(..., name='v2')

# dict形式传递
saver = tf.train.Saver({'v1': v1, 'v2': v2})

# list形式传递
saver = tf.train.Saver([v1, v2])
#等价于以创建变量时取的op.name名字做为dict的key:
saver = tf.train.Saver({v.op.name: v for v in [v1, v2]})

Create another folder named my_net, use this saver to save variables to this directory "my_net/save_net.ckpt".

saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(init)
    save_path = saver.save(sess, "my_net/save_net.ckpt")
    print("Save to path: ", save_path)

"""    
Save to path:  my_net/save_net.ckpt
"""

Run this directly and report an error:
Reason: Saving and loading are performed before and after, and are defined twice before and after

W = tf.Variable(xxx,name=”weight”)

It is equivalent to creating a variable with name = "weight" twice in the stack of the TensorFlow graph, the actual name of the second (nth) will become "weight_1" ("weight_n-1"), and then we save the checkpoint in the The variable "weight_n-1" is actually searched for instead of "weight", so the error occurs.

Solution:
(1) During the loading process, define the variable with the same name and add
tf.reset_default_graph()Clear the stack of the default graph and set the global graph as the default graph

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325814986&siteId=291194637