machine-learning - 为什么我无法恢复这个模型?

标签 machine-learning tensorflow

我目前在恢复此模型以进行预测时遇到问题。

代码:

def neural_network(data):
    with tf.name_scope("network"):
        layer1 = tf.layers.dense(data, 1000, activation=tf.nn.relu, name="hidden_layer1")
        layer2 = tf.layers.dense(layer1, 1000, activation=tf.nn.relu, name="hidden_layer2")
        output = tf.layers.dense(layer2, 2, name="output_layer")

        return output


def evaluate():
    with tf.name_scope("loss"):
        global x
        xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=neural_network(x))
        loss = tf.reduce_mean(xentropy, name="loss")

    with tf.name_scope("train"):
        optimizer = tf.train.AdamOptimizer()
        training_op = optimizer.minimize(loss)

    with tf.name_scope("exec"):
        with tf.Session() as sess:
            for i in range(1, 10):
                sess.run(tf.global_variables_initializer())
                sess.run(training_op, feed_dict={x: np.array(train_data).reshape([-1, 1]), y: label})
                print "Training " + str(i)
                saver = tf.train.Saver()
                saver.save(sess, "saved_models/testing")
                print "Model Saved."


def predict():
    with tf.name_scope("predict"):
        output = neural_network(x)
        output = tf.nn.softmax(output)

        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            # saver = tf.train.Saver()
            saver.restore(sess, "saved_models/testing")
            print sess.run(output, feed_dict={x: np.array([12003]).reshape([-1, 1])})

我尝试使用tf.train.Saver()来恢复,但也给出了相同的错误。

The error given is ValueError: Variable hidden_layer1/kernel already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

我尝试为tf.layers.dense()设置reuse=True,但它导致我无法训练图表(给出与上面相同的ValueError,但要求设置reuse=None)。

我猜测这与 session 中仍然存在的图表有关,因此当我尝试恢复它时,它会检测到重复的图表。但是,我认为这不应该发生,因为 session 已经结束。

链接到整个代码:gistlink

最佳答案

我认为您正在同一个图表中加载变量。为了进行测试,尝试创建一个新图表并加载它。做这样的事情:

loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
   # Load the graph with the trained states

关于machine-learning - 为什么我无法恢复这个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44895462/

相关文章:

tensorflow - 自动编码器的 tensorflow 输入数据字符串

tensorflow - 在遵循 tensorflow 的迁移学习示例时,添加 dropout 是否有助于减少过度拟合?

machine-learning - 使用 Caffe 没有提高 RMSprop、Adam、AdaDelta 测试精度

python - 图像分类模型的网格搜索超参数

python - scikit-learn 的多级并行化

python - 更新了 : reshape each row data into a (x, 1) 数组

tensorflow - tensorflow 中的局部变量是什么?

python - MFCC Python : completely different result from librosa vs python_speech_features vs tensorflow. 信号

machine-learning - 如何获取垃圾邮件的概率而不是分类

python-3.x - 在不使用 fit 方法中的回调的情况下在 Tensorboard 中显示 Keras 图形