【发布时间】:2018-07-10 13:54:42
【问题描述】:
我使用 tensorflow 来运行随机森林模型。 代码:
import tensorflow as tf
from tensorflow.contrib.tensor_forest.python import tensor_forest
from tensorflow.python.ops import resources
from tensorflow.examples.tutorials.mnist import input_data
num_steps = 50000 # Total steps to train
batch_size = 1024 # The number of samples per batch
num_classes = 10 # The 10 digits
num_features = 784 # Each image is 28x28 pixels
num_trees = 10
max_nodes = 1000
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,
max_nodes=max_nodes).fill()
forest_graph = tensor_forest.RandomForestGraphs(params=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.arg_max(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()))
sess = tf.Session()
sess.run(init_vars)
test_x, test_y = mnist.test.images, mnist.test.labels
for i in range(1, num_steps + 1):
batch_x, batch_y = mnist.train.next_batch(batch_size=batch_size)
_, l = sess.run([train_op, loss_op], feed_dict={X:batch_x, Y: batch_y})
if i % 100 == 0 or i == 1:
acc = sess.run(accuracy_op, feed_dict={X:batch_x, Y: batch_y})
print('step %i, loss: %f, acc: %f' % (i, l, acc))
if i % 100 == 0:
print("Test Accuracy:", sess.run(accuracy_op, feed_dict={X: test_x, Y: test_y}))
print("Test Accuracy:", sess.run(accuracy_op, feed_dict={X: test_x, Y: test_y}))
问题:如何保存模型并恢复预测? 这是 tf 随机森林的最新版本,我使用 tf 1.2,它可以工作。我发现有人使用 TensorForestEstimator,但它不适用于 tf 1.2, tf 更新这么频繁!
【问题讨论】:
标签: python tensorflow random-forest