ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何使用tf.estimator返回预测和标签(使用预测或eval方法)?

2019-06-11 05:42:27  阅读:179  来源: 互联网

标签:python tensorflow tensorflow-datasets


我正在使用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()方法访问预测字典.

解决方法:

完成培训后,在’/ 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函数.

标签:python,tensorflow,tensorflow-datasets
来源: https://codeday.me/bug/20190611/1216641.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有