批量大小可变的TensorFlow DataSet from_generator

时间:2018-08-31 18:58:22

标签: python tensorflow tensorflow-datasets

我正在尝试使用from_generator方法使用TensorFlow Dataset API读取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的批次大小非常大慢。

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

1 个答案:

答案 0 :(得分:3)

from_generator中指定张量形状时,可以使用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))
    )
    ...