从Tensorflow 2.0 Beta中的tf.data.Dataset检索下一个元素 [英] retrieving the next element from tf.data.Dataset in tensorflow 2.0 beta

查看:65
本文介绍了从Tensorflow 2.0 Beta中的tf.data.Dataset检索下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在tensorflow 2.0-beta之前,要从tf.data.Dataset检索第一个元素,我们可以使用如下所示的迭代器:

Before tensorflow 2.0-beta, to retrieve the first element from tf.data.Dataset, we may use a iterator as shown below:

#!/usr/bin/python

import tensorflow as tf

train_dataset = tf.data.Dataset.from_tensor_slices([1.0, 2.0, 3.0, 4.0])
iterator = train_dataset.make_one_shot_iterator()
with tf.Session() as sess:
    # 1.0 will be printed.
    print (sess.run(iterator.get_next()))

在tensorflow 2.0-beta中,似乎已经弃用了上述单发迭代器.要打印出所有元素,我们可以使用以下 for 方法.

In tensorflow 2.0-beta, it seems that the above one-shot-iterator is now deprecated. To print out the entire elements we may use the following for approach.

#!/usr/bin/python

import tensorflow as tf

train_dataset = tf.data.Dataset.from_tensor_slices([1.0, 2.0, 3.0, 4.0])

for data in train_dataset:
    # 1.0, 2.0, 3.0, and 4.0 will be printed.
    print (data.numpy())

但是,如果我们只想从tf.data.Dataset中仅检索一个元素,那么我们如何使用tensorflow 2.0 beta?似乎不支持 next(train_dataset).如上所示,可以使用旧的单发迭代器轻松完成此操作,但是使用基于 for 的新方法并不是很明显.

However, if we only want to retrieve exactly one element from tf.data.Dataset, then how can we do with tensorflow 2.0 beta? It seems that next(train_dataset) is not supported. It could be done easily with the old one shot iterator as shown above, but it's not very obvious with the new for based approach.

欢迎任何建议.

推荐答案

您可以从数据集中 .take(1):

for elem in train_dataset.take(1):
  print (elem.numpy())

这篇关于从Tensorflow 2.0 Beta中的tf.data.Dataset检索下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆