【问题标题】:TensorFlow Model Restore ValueError - At least two variables have the same nameTensorFlow Model Restore ValueError - 至少两个变量具有相同的名称
【发布时间】:2017-07-09 22:51:18
【问题描述】:

我已经保存了一个模型,现在我正在尝试恢复它,恢复后它第一次正常工作,但是当我在同一个正在运行的程序上按“TEST”按钮来测试另一个图像时,它给出了错误

ValueError:至少有两个变量同名:Variable_2/Adam

def train_neural_network(x):
    prediction = neural_network_model(x)#logits

    softMax=tf.nn.softmax_cross_entropy_with_logits(
            logits=prediction, labels=y)#prediction and original comapriosn
    cost = tf.reduce_mean(softMax)#total loss
    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)#learning_rate=0.01
    hm_epochs = 20

    new_saver = tf.train.Saver()
    with tf.Session() as sess:
        global s
        s=sess
        sess.run(tf.global_variables_initializer())
        new_saver = tf.train.import_meta_graph('../MY_MODELS/my_MNIST_Model_1.meta')
        new_saver.restore(s, tf.train.latest_checkpoint('../MY_MODELS'))

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))

        print('Accuracy:', accuracy.eval(
            {x: mnist.test.images, y: mnist.test.labels}))

【问题讨论】:

    标签: python tensorflow mnist


    【解决方案1】:

    您加载的图表已经包含推理所需的所有变量。您需要从保存的图表中加载像 accuracy 这样的张量。在您的情况下,您在外部声明了相同的变量,这与图中的变量冲突。

    在训练期间,如果您使用 name='accuracy' 将张量命名为 accuracy,那么您可以使用 get_tensor_by_name('accuracy:0') 从图中加载它。在您的示例中,您还需要从图中加载输入张量 xy。你的代码应该是这样的:

    def inference():
       loaded_graph = tf.Graph()
       new_saver = tf.train.Saver()
       with tf.Session(graph=loaded_graph) as sess:
           new_saver = tf.train.import_meta_graph('../MY_MODELS/my_MNIST_Model_1.meta')
           new_saver.restore(s, tf.train.latest_checkpoint('../MY_MODELS'))
    
           #Get the tensors by their variable name 
           # Note: the names of the following tensors have to be declared in your train graph for this to work. So just name them appropriately.
          _accuracy = loaded_graph.get_tensor_by_name('accuracy:0')
          _x  = loaded_graph.get_tensor_by_name('x:0')
          _y  = loaded_graph.get_tensor_by_name('y:0')
    
           print('Accuracy:', _accuracy.eval(
            {_x: mnist.test.images, _y: mnist.test.labels}))
    

    【讨论】:

    • 训练功能(保存模型)和测试功能(恢复模型)应该不同吗?它们不能是相同的功能吗?
    • 如果您的训练和测试在同一个图表中同时进行,它们可以是相同的。但是当你这样做的时候不要再画一张图了。在您的代码中,移除图表的所有加载,并直接在默认图表上运行准确度进行预测。
    • 你可以看到预测变量,我无法将它保存在模型中,这些是我必须使用但我无法保存的logits,请帮助
    • 我已经做了另一个恢复功能,我需要在图中这个预测变量来预测我的数字
    • 你可以在同一个图中调用预测。
    猜你喜欢
    • 1970-01-01
    • 2022-06-12
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2011-06-01
    相关资源
    最近更新 更多