使用for循环遍历Dataset TF 2.0

问题描述 投票:2回答:1

此问题是关于在不赞成使用make_initializable_iterator()的情况下如何遍历TF数据集的问题。

我使用以下功能读取了数据集:

def read_dataset_new(filename, target='delay'):
    ds = tf.data.TFRecordDataset(filename)
    ds = ds.map(lambda buf: parse(buf, target=target))
    ds = ds.batch(1)
    return ds

然后我要遍历数据集。我一直在使用:https://www.tensorflow.org/api_docs/python/tf/data/Dataset#make_initializable_iterator

with tf.compat.v1.Session() as sess:
    data_set = tfr_utils.read_dataset_new(self.tf_rcrds_fl_nm)
    itrtr = data_set.make_initializable_iterator()
    sess.run(itrtr.initializer)
    features, label = itrtr.get_next()
    features_keys = features.keys()
...

但是“警告:此功能已弃用。它将在以后的版本中删除。更新说明:用于...在数据集中:....”

除弃用警告外,我的代码按预期工作。

但是,鉴于弃用警告,我现在正在尝试:

with tf.compat.v1.Session() as sess:
    data_set = tfr_utils.read_dataset_new(self.tf_rcrds_fl_nm)
    for features, label in data_set:
        features_keys = features.keys()
        ...

但是那不起作用。我得到:

self = <tensorflow.python.client.session.Session object at 0x12f2e57d0>
fn = <function BaseSession._do_run.<locals>._run_fn at 0x12f270440>
args = ({}, [<tensorflow.python.pywrap_tensorflow_internal.TF_Output; proxy of <Swig Object of type 'TF_Output *' at 0x12f3f75a0> >], [], None, None)
message = 'Resource AnonymousIterator/AnonymousIterator0/N10tensorflow4data16IteratorResourceE does not exist.\n\t [[node Iterat...tNext_1 (defined at /demo-routenet/tests/unit/test_tfrecord_utils.py:376) ]]'
m = <re.Match object; span=(102, 130), match='[[{{node IteratorGetNext_1}}'>

我能够找到的所有代码示例都明确创建了一个迭代器,显然这不是应该做的。我找不到一个应该做什么的例子。

我怀疑尚未初始化某些内容。因此,我也尝试过:

sess.run(data_set)

但是那也不起作用(我也没有任何理由认为它应该有,但是大家都知道我的尝试)。

因此,如弃用注释所建议的,如何在for循环中使用数据集?

python tensorflow tensorflow-datasets
1个回答
0
投票

不清楚要从输出中得到什么。如果要获取数据集输出的值,则应积极执行。例如:

tf.compat.v1.enable_eager_execution()

def read_dataset_new(filename, target='delay'):
    ds = tf.data.TFRecordDataset(filename)
    ds = ds.map(lambda buf: parse(buf, target=target))
    ds = ds.batch(1)
    return ds
# This should return your key values for each example.
for features, labels in read_dataset_new(self.tf_rcrds_fl_nm):
    features_keys = features.keys()
# This should return your tensor values if they supposed to be numeric.
for features, labels in read_dataset_new(self.tf_rcrds_fl_nm):
    features_array = numpy.array(features)
© www.soinside.com 2019 - 2024. All rights reserved.