8

我正在使用 TensorFlow 1.4。

我创建了一个自定义 tf.estimator 来进行分类,如下所示:

def model_fn():
    # Some operations here
    [...]

    return tf.estimator.EstimatorSpec(mode=mode,
                           predictions={"Preds": predictions},
                           loss=cost,
                           train_op=loss,
                           eval_metric_ops=eval_metric_ops,
                           training_hooks=[summary_hook])

my_estimator = tf.estimator.Estimator(model_fn=model_fn, 
                       params=model_params,
                       model_dir='/my/directory')

我可以轻松地训练它:

input_fn = create_train_input_fn(path=train_files)
my_estimator.train(input_fn=input_fn)

其中input_fn是一个使用tf.data.Dataset API从tfrecords 文件中读取数据的函数。

当我从 tfrecords 文件中读取数据时,当我进行预测时,我的内存中没有标签。

我的问题是,如何通过predict()方法或evaluate()方法返回预测和标签?

似乎没有办法两者兼得。predict()无法访问 (?) 标签,并且无法使用evaluate()方法访问预测字典。

4

1 回答 1

11

完成培训后,'/my/directory'您将拥有一堆检查点文件。

您需要再次设置输入管道,手动加载其中一个文件,然后开始循环存储预测和标签的批次:

# Rebuild the input pipeline
input_fn = create_eval_input_fn(path=eval_files)
features, labels = input_fn()

# Rebuild the model
predictions = model_fn(features, labels, tf.estimator.ModeKeys.EVAL).predictions

# Manually load the latest checkpoint
saver = tf.train.Saver()
with tf.Session() as sess:
    ckpt = tf.train.get_checkpoint_state('/my/directory')
    saver.restore(sess, ckpt.model_checkpoint_path)

    # Loop through the batches and store predictions and labels
    prediction_values = []
    label_values = []
    while True:
        try:
            preds, lbls = sess.run([predictions, labels])
            prediction_values += preds
            label_values += lbls
        except tf.errors.OutOfRangeError:
            break
    # store prediction_values and label_values somewhere

更新:更改为直接使用model_fn您已有的功能。

于 2017-11-30T13:48:03.470 回答