【问题标题】:TensorFlow tf.data.Dataset and bucketingTensorFlow tf.data.Dataset 和分桶
【发布时间】:2018-11-09 09:31:56
【问题描述】:

对于 LSTM 网络,我已经看到了分桶的巨大改进。

我遇到过bucketing section in the TensorFlow docs 其中(tf.contrib)。

虽然在我的网络中,我使用的是 tf.data.Dataset API,特别是我正在使用 TFRecords,所以我的输入管道看起来像这样

dataset = tf.data.TFRecordDataset(TFRECORDS_PATH)
dataset = dataset.map(_parse_function)
dataset = dataset.map(_scale_function)
dataset = dataset.shuffle(buffer_size=10000)
dataset = dataset.padded_batch(batch_size, padded_shapes={.....})

如何将分桶方法合并到tf.data.Dataset 管道中?

如果重要的话,在 TFRecords 文件中的每条记录中,我都会将序列长度保存为整数。

【问题讨论】:

    标签: python tensorflow tensorflow-datasets


    【解决方案1】:

    使用Dataset API 的各种bucketing 用例都很好地解释了here

    bucket_by_sequence_length() 示例:

    def elements_gen():
       text = [[1, 2, 3], [3, 4, 5, 6, 7], [1, 2], [8, 9, 0, 2]]
       label = [1, 2, 1, 2]
       for x, y in zip(text, label):
           yield (x, y)
    
    def element_length_fn(x, y):
       return tf.shape(x)[0]
    
    dataset = tf.data.Dataset.from_generator(generator=elements_gen,
                                         output_shapes=([None],[]),
                                         output_types=(tf.int32, tf.int32))
    
    dataset =   dataset.apply(tf.contrib.data.bucket_by_sequence_length(element_length_func=element_length_fn,
                                                                  bucket_batch_sizes=[2, 2, 2],
                                                                  bucket_boundaries=[0, 8]))
    
    batch = dataset.make_one_shot_iterator().get_next()
    
    with tf.Session() as sess:
    
       for _ in range(2):
          print('Get_next:')
          print(sess.run(batch))
    

    输出:

    Get_next:
    (array([[1, 2, 3, 0, 0],
       [3, 4, 5, 6, 7]], dtype=int32), array([1, 2], dtype=int32))
    Get_next:
    (array([[1, 2, 0, 0],
       [8, 9, 0, 2]], dtype=int32), array([1, 2], dtype=int32))
    

    【讨论】:

    • 在我的用例中,实际上有很多特性,其中一个是序列,假设每条记录中都有它的x['seq'],我如何将它仅应用于该元素?
    • 你需要把你的elements_gen()函数改成yield(x['seq'], y)
    • 我没有 element_gen(),因为我正在从 TFRecords 文件中读取数据,我不能将 element_length_func 更改为返回 tf.shape(x['seq'])[0] 吗?你为什么打电话给del y
    • 链接指向一个已删除的站点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    相关资源
    最近更新 更多