为什么我无法恢复此模型?

时间:2017-07-04 00:45:32

标签: 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:

我已尝试为reuse=True设置tf.layers.dense(),但这导致我无法训练图表(提供与上述相同的ValueError但要求设置reuse=None)。

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

链接到整个代码:gistlink

1 个答案:

答案 0 :(得分:1)

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

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