代码之家  ›  专栏  ›  技术社区  ›  bluesummers

用tf.dataset训练模型进行推理

  •  4
  • bluesummers  · 技术社区  · 8 年前

    我训练了一个模特 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数据集 方式? (这不是为了生产目的,而是为了评估如果我改变特定的特性会发生什么)

    1 回复  |  直到 8 年前
        1
  •  3
  •   zhao yufei    7 年前

    实际上,图中有一个名为“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), ...})
    
    推荐文章