具有可变批量大小的TensorFlow DataSet`from_generator`

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

我正在尝试使用TensorFlow数据集API使用from_generator方法读取HDF5文件。除非批量大小不均匀地分成事件数量,否则一切正常。我不太清楚如何使用API​​制作灵活的批处理。

如果事情没有均匀分配,则会出现以下错误:

2018-08-31 13:47:34.274303: W tensorflow/core/framework/op_kernel.cc:1263] Invalid argument: ValueError: `generator` yielded an element of shape (1, 28, 28, 1) where an element of shape (11, 28, 28, 1) was expected.
Traceback (most recent call last):

  File "/Users/perdue/miniconda3/envs/py3a/lib/python3.6/site-packages/tensorflow/python/ops/script_ops.py", line 206, in __call__
    ret = func(*args)

  File "/Users/perdue/miniconda3/envs/py3a/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 452, in generator_py_func
    "of shape %s was expected." % (ret_array.shape, expected_shape))

ValueError: `generator` yielded an element of shape (1, 28, 28, 1) where an element of shape (11, 28, 28, 1) was expected.

我有一个脚本可以重现错误(以及获取几个MB所需数据文件的说明 - Fashion MNIST):

https://gist.github.com/gnperdue/b905a9c2dd4c08b53e0539d6aa3d3dc6

最重要的代码可能是:

def make_fashion_dset(file_name, batch_size, shuffle=False):
    dgen = _make_fashion_generator_fn(file_name, batch_size)
    features_shape = [batch_size, 28, 28, 1]
    labels_shape = [batch_size, 10]
    ds = tf.data.Dataset.from_generator(
        dgen, (tf.float32, tf.uint8),
        (tf.TensorShape(features_shape), tf.TensorShape(labels_shape))
    )
    ...

其中dgen是从hdf5读取的生成器函数:

def _make_fashion_generator_fn(file_name, batch_size):
    reader = FashionHDF5Reader(file_name)
    nevents = reader.openf()

    def example_generator_fn():
        start_idx, stop_idx = 0, batch_size
        while True:
            if start_idx >= nevents:
                reader.closef()
                return
            yield reader.get_examples(start_idx, stop_idx)
            start_idx, stop_idx = start_idx + batch_size, stop_idx + batch_size

    return example_generator_fn

问题的核心是我们必须在from_generator中声明张量形状,但我们需要灵活地在迭代时改变该形状。

有一些解决方法 - 删除最后几个样本以获得均匀分区,或者只使用批量大小为1 ...但如果您不能丢失任何样本并且批量大小为1非常慢,则第一个是坏的。

有什么想法或意见吗?谢谢!

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

from_generator中指定Tensor形状时,可以使用None作为元素来指定可变大小的尺寸。这样您就可以容纳不同大小的批次,特别是“剩余”批次,这些批次比您要求的批量大小一点。所以你会用

def make_fashion_dset(file_name, batch_size, shuffle=False):
    dgen = _make_fashion_generator_fn(file_name, batch_size)
    features_shape = [None, 28, 28, 1]
    labels_shape = [None, 10]
    ds = tf.data.Dataset.from_generator(
        dgen, (tf.float32, tf.uint8),
        (tf.TensorShape(features_shape), tf.TensorShape(labels_shape))
    )
    ...
© www.soinside.com 2019 - 2024. All rights reserved.