【问题标题】:Custom batches for tf.data.Datasettf.data.Dataset 的自定义批次
【发布时间】:2019-02-19 20:02:39
【问题描述】:

我正在使用 tensorflow 的 Estimator API,并希望创建自定义批次进行训练。

我有如下示例

example1 = {
   "num_sentences": 3,
   "sentences": [[1, 2], [3, 4], [5, 6]] 
}
example2 = {
   "num_sentences": 2,
   "sentences": [[1, 2], [3, 4]] 
}

所以一个例子可以有任意数量的固定大小的句子。现在我想构建大小取决于批次中句子数量的批次。否则我必须使用批量大小 1,因为某些示例可能包含“批量大小”句子,并且大批量大小不适合 GPU 内存。

例如:我有 6 个批量大小和句子数量为 [5, 3, 3, 2, 2, 1] 的示例。然后我将示例分组到批次 [5]、[3, 3] 和 [2, 2, 1]。请注意,最后一批中的示例“1”将被填充。

我编写了一个算法,将示例分组到此类批次中。现在我无法将批次输入 tf.data.Dataset。

我曾尝试使用tf.data.Dataset.from_generator,但该方法似乎需要单独的示例,如果生成器生成像 [example1, example2] 这样的批次,我会收到错误。

如何为数据集提供自定义批次?有没有更优雅的方法来解决我的问题?

更新:我假设我无法正确提供输出形状参数。以下代码运行良好。

import tensorflow as tf

def gen():
    for b in range(3):
        #yield [{"num_sentences": 3, "sentences": [[1, 2], [3, 4], [5, 6]]}]
        yield {"num_sentences": 3, "sentences": [[1, 2], [3, 4], [5, 6]]}


dataset = tf.data.Dataset.from_generator(generator=gen, 
                                         output_types={'num_sentences': tf.int32, 'sentences': tf.int32},
                                         #output_shapes=tf.TensorShape([None,  {'num_sentences': tf.TensorShape(None), 'sentences': tf.TensorShape(None)}])
                                         output_shapes={'num_sentences': tf.TensorShape(None), 'sentences': tf.TensorShape(None)}
                                        )

def print_dataset(dataset):
    it = dataset.make_one_shot_iterator()
    with tf.Session() as sess:
        print(dataset.output_shapes)
        print(dataset.output_types)
        while True:
            try:
                data = it.get_next()
                print("data" + str(sess.run(data)))
            except tf.errors.OutOfRangeError:
                break

print_dataset(dataset)

如果我生成一个数组并取消注释 output_shapes 我得到一个错误“int() 参数必须是一个字符串、一个类似字节的对象或一个数字,而不是 'dict' "

【问题讨论】:

  • 感谢您的链接。似乎应该可以提供自定义批次。当我使用字典时,我无法弄清楚如何提供 output_shapes 参数。请参阅上面编辑过的帖子。

标签: tensorflow tensorflow-datasets tensorflow-estimator batchsize


【解决方案1】:

我想我已经想出了如何解决上述问题。我想我必须将示例合并到“一个”字典中。

# a batch with two examples each with sentence size 3
yield {"num_sentences": [3, 3], "sentences": [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]}

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2021-12-02
    • 2019-04-16
    • 2019-04-26
    • 2019-07-03
    相关资源
    最近更新 更多