【问题标题】:Determine number of records in tf.data.Dataset Tensorflow [duplicate]确定 tf.data.Dataset Tensorflow 中的记录数 [重复]
【发布时间】:2019-02-15 06:46:40
【问题描述】:

我想将数据集迭代器传递给函数,但该函数需要知道数据集的长度。在下面的示例中,我可以将len(datafiles) 传递给my_custom_fn() 函数,但我想知道我是否能够从iteratorbatch_xbatch_y 类中提取数据集的长度,所以我不必将其添加为输入。

dataset = tf.data.FixedLengthRecordDataset(datafiles, record_bytes)
iterator = dataset.make_initializable_iterator()
sess.run(iterator.initializer)
[batch_x, batch_y] = iterator.get_next()
value = my_custom_fn(batch_x, batch_y)
# lots of other stuff

谢谢!

编辑:此解决方案不适用于我的情况:tf.data.Dataset: how to get the dataset size (number of elements in a epoch)?

运行后

tf.data.Dataset.list_files('{}/*.dat')
tf.shape(tf.get_default_graph().get_tensor_by_name('MatchingFiles:0')[0])

返回

<tf.Tensor 'Shape_3:0' shape=(0,) dtype=int32>

我确实找到了适合我的解决方案。将 iterator_scope 添加到我的代码中,例如:

with tf.name_scope('iter'):
    dataset = tf.data.FixedLengthRecordDataset(datafiles, record_bytes)
    iterator = dataset.make_initializable_iterator()
    sess.run(iterator.initializer)
    [batch_x, batch_y] = iterator.get_next()
value = my_custom_fn(batch_x, batch_y)
# lots of other stuff

然后从内部my_custom_fn调用:

def my_custom_fn(batch_x, batch_y):
    filenames = batch_x.graph.get_operation_by_name(
                  'iter/InputDataSet/filenames').outputs[0]
    n_epoch = sess.run(sess.graph.get_operation_by_name(
                  'iter/Iterator/count').outputs)[0]
    batch_size = sess.run(sess.graph.get_operation_by_name(
                  'iter/Iterator/batch_size').outputs)[0]
    # lots of other stuff

不确定这是否是最好的方法,但它似乎有效。很高兴对此提出任何建议,因为这似乎有点老套。

【问题讨论】:

  • 此解决方案不适用于我的情况。我更新了我的问题以反映差异,并添加了一个对我有用的解决方案。

标签: python tensorflow machine-learning deep-learning


【解决方案1】:

iterator 的长度在您遍历它之前是未知的。您可以将len(datafiles) 显式传递到函数中,但如果您坚持数据的持久性,您可以简单地将函数设置为实例方法并将数据集的长度存储在my_custom_fn 是方法的对象中。

不幸的是,作为iterator,它不存储任何东西,它动态生成数据。但是,正如在 TensorFlow 的源代码中发现的那样,有一个“私有”变量 _batch_size 用于存储批量大小。您可以在此处查看源代码:TensorFlow source

【讨论】:

  • 但是在类的某个地方它存储了数据文件的名称,不是吗?看来我应该能够找到他们并获得他们的长度?类似地,是否可以访问批量大小的值(如果它是通过dataset.batch(1000) 设置的)?
  • @John 我已经更新了我的答案以解决您的评论。
猜你喜欢
  • 2019-10-10
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2018-11-09
  • 2020-08-28
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
相关资源
最近更新 更多