【问题标题】:Inference with a model trained with tf.Dataset使用 tf.Dataset 训练的模型进行推理
【发布时间】:2018-11-29 03:23:30
【问题描述】:

我使用tf.data.Dataset API 训练了一个模型,所以我的训练代码如下所示

with graph.as_default():
    dataset = tf.data.TFRecordDataset(tfrecord_path)
    dataset = dataset.map(scale_features, num_parallel_calls=n_workers)
    dataset = dataset.shuffle(10000)
    dataset = dataset.padded_batch(batch_size, padded_shapes={...})
    handle = tf.placeholder(tf.string, shape=[])
    iterator = tf.data.Iterator.from_string_handle(handle,
                                                   train_dataset.output_types,
                                                   train_dataset.output_shapes)
    batch = iterator.get_next()
    ... 
    # Model code
    ...
    iterator = dataset.make_initializable_iterator()

with tf.Session(graph=graph) as sess:
    train_handle = sess.run(iterator.string_handle())
    sess.run(tf.global_variables_initializer())
    for epoch in range(n_epochs):
        sess.run(train_iterator.initializer)
        while True:
            try:
                sess.run(optimizer, feed_dict={handle: train_handle})
            except tf.errors.OutOfRangeError:
               break

现在,在模型训练完成后,我想推断数据集中没有的示例,但我不知道该怎么做。

为了清楚起见,我知道如何使用另一个数据集,例如,我只是在测试时将句柄传递给我的测试集。

问题是关于给定缩放方案和网络期望句柄的事实,如果我想对未写入 TFRecord 的新示例进行预测,我将如何去做?

如果我要修改 batch,我会事先负责缩放,如果可能的话,我想避免这样做。

那么我应该如何以tf.data.Dataset 的方式从模型中推断出单个示例? (这不是出于生产目的,而是为了评估如果我更改特定功能会发生什么)

【问题讨论】:

    标签: python tensorflow tensorflow-datasets


    【解决方案1】:

    图中其​​实有一个张量名字叫“IteratorGetNext:0” 使用 dataset api 时,可以使用以下方式直接设置 输入:

    #get a tensor from a graph 
    input tensor : input = graph.get_tensor_by_name("IteratorGetNext:0")
    # difine the target tensor you want evaluate for your prediction
    prediction tensor: predictions=...
    # finally call session to run 
    then sess.run(predictions, feed_dict={input: np.asanyarray(images), ...})
    

    【讨论】:

    • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    • 您应该注意feed_dict 不是tensorflow 对生产系统的推荐。但它确实简化了事情。
    • @NarendraJadhav 感谢您的建议!我已经更新了答案!
    • @oak 我正在寻找使用 feed_dict 以外的解决方案?你有什么?或者这是唯一的方法。 “TF推荐”的目的是为了做以下坏事:“在实际运行之前优化代码”。
    • @ArtificiallyIntelligence 我们在生产中使用 TensorRT 进行推理。 TensorFlow 曾经有队列。但它已被弃用。我认为替换feed_dict 的方向是检查 tf.data
    猜你喜欢
    • 1970-01-01
    • 2020-02-28
    • 2018-08-10
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多