从保存的TensorFlow随机森林分类器加载操作

问题描述 投票:0回答:1

我已经训练了一个类似于以下代码的TF随机森林分类器:

X = tf.placeholder(tf.float32, shape=[None, num_features])
Y = tf.placeholder(tf.int32, shape=[None])

hparams = tensor_forest.ForestHParams(num_classes=num_classes,
                                  num_features=num_features,
                                  num_trees=num_trees).fill()

forest_graph = tensor_forest.RandomForestGraphs(hparams)
train_op = forest_graph.training_graph(X, Y)
loss_op = forest_graph.training_loss(X, Y)
infer_op, _, _ = forest_graph.inference_graph(X)
correct_prediction = tf.equal(tf.argmax(infer_op, 1), tf.cast(Y,tf.int64))
accuracy_op = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init_vars = tf.group(tf.global_variables_initializer(),
resources.initialize_resources(resources.shared_resources()))



with tf.Session() as sess:
    sess.run(init_vars)
    saver = tf.train.Saver()

    for i in range(1, 100):
        for batch_x, batch_y in render_batch(batch_size):
        _, l = sess.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y})
        acc = sess.run(accuracy_op, feed_dict={X: batch_x, Y: batch_y})
        print('Step %i, Loss: %f, Acc: %f' % (i, l, acc))
        if acc >= 0.87:
            print("Stopping and saving")
            save_path = saver.save(sess, model_path)
            print("Model saved in file: %s" % save_path)    
            break 

现在我想重新加载我的模型并使用它来预测看不见的数据,如下所示:

with graph.as_default():
session_conf = tf.ConfigProto()
sess = tf.Session(config = session_conf)
with sess.as_default():
    saver = tf.train.import_meta_graph("{}.meta".format(model_path))
    saver.restore(sess,checkpoint_file)
    accuracy_op = graph.get_operation_by_name("accuracy_op").outputs[0]
    print(sess.run(accuracy_op, feed_dict={X: x_test, Y: y_test}))

但是,我收到以下错误消息:

KeyError: "The name 'accuracy_op' refers to an Operation not in the graph."

我的问题是 - 如何保存我的模型,这样当我重新加载它时,我可以导入上面定义的那些操作并在看不见的数据上使用它们?

谢谢!

tensorflow random-forest
1个回答
1
投票

由于您使用的是get_operation_by_name,因此您应该将op accuracy_op命名为。你可以使用tf.identity来做到这一点:

 accuracy_op = tf.identity(tf.reduce_mean(tf.cast(correct_prediction, tf.float32)), 'accuracy_op')

我看到你正在使用张量XY而不加载新图表。因此,请在原始代码中命名张量,然后使用get_tensor_by_name()重新加载

© www.soinside.com 2019 - 2024. All rights reserved.