从保存的TensorFlow RandomForest分类器加载操作

时间:2018-05-11 00:44:12

标签: tensorflow random-forest

我已经训练了一个类似于以下代码的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."

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

谢谢!

0 个答案:

没有答案