如何正确恢复张量流中的模型?

How to restore a model in tensorflow properly?

我使用以下命令在 tensorflow 中保存了一个经过训练的模型:

saver = tf.train.Saver()
ss = saver.save(sess, '/tmp/new_trained_model.ckpt')

然后,我用命令加载模型:

imported_meta = tf.train.import_meta_graph("/tmp/new_trained_model.ckpt.meta")
imported_meta.restore(sess, tf.train.latest_checkpoint(checkpoint_dir="/tmp/,latest_filename="checkpoint"))

现在,使用以下函数来评估准确性:

    correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
#logits come from the model,there is no error,so didn't post that code
    accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    #saver = tf.train.Saver()

    def evaluate(X_data, y_data):
        num_examples = len(X_data)
        total_accuracy = 0
        sess = tf.get_default_session()
        for offset in range(0, num_examples, BATCH_SIZE):
            batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
            accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})
            total_accuracy += (accuracy * len(batch_x))
        return total_accuracy / num_examples
    test_accuracy = evaluate(X_test, y_test)

但是上面的函数报错:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable_12
     [[Node: Variable_12/read = Identity[T=DT_FLOAT, _class=["loc:@Variable_12"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](Variable_12)]]

但是,当我从图中打印张量时,它显示了 Variable_12 的矩阵:

 from tensorflow.python.tools import inspect_checkpoint as chkp
    chkp.print_tensors_in_checkpoint_file("/tmp/new_trained_model.ckpt", tensor_name='',all_tensor_names='', all_tensors=True)

Variable_12:(仅显示输出中的一个变量)

tensor_name:  Variable_12
    [[-0.1013797  -0.08079438 -0.05904691 ... -0.07798752 -0.08208387
      -0.18532619]
     [ 0.10919656 -0.06162841 -0.19453178 ... -0.03241748  0.1023232
       0.07120663]
     [-0.10920436  0.00233169 -0.08879709 ... -0.09918057 -0.02546161
       0.00903581]
     ...
     [ 0.13858072  0.13791025 -0.12322884 ... -0.15006843  0.00103891
       0.06663229]
     [-0.14043045  0.14039241  0.15048873 ...  0.07272678  0.00470365
       0.0273346 ]
     [-0.10976157 -0.10873327 -0.16460624 ... -0.16509598  0.1124685
      -0.08858881]]

任何人都可以解释为什么显示未初始化的错误,因为 inspect_checkpoint 确认的值在那里?

感谢您的宝贵时间。

问题好像是你建了两个计算图

首先你提到你"executed the part where the model architecture was defined"。这会为您的模型创建计算图。

那你也做了

imported_meta = tf.train.import_meta_graph("/tmp/new_trained_model.ckpt.meta")

这会为您的模型创建第二个计算图。

根据您执行这些的具体方式,"computation graphs" 可以在一个或两个单独的 "Graph" 对象中。在任何情况下,imported_meta.restore 初始化了导入的(第二个)计算图的变量,但是您调用 session.run() 从第一个计算图计算张量。没有人初始化第一个计算图中的变量。

修复方法是不导入(元)图,如果您已经创建了图的话。只要变量名和形状没有改变,就可以直接使用 Saver 恢复变量的值,而不需要创建任何更多的变量或操作。