【问题标题】:How to slice the data of tf.data.Dataset type to certain length in TF2.0?TF2.0中如何将tf.data.Dataset类型的数据切片到一定长度?
【发布时间】:2019-07-10 15:18:40
【问题描述】:

我正在关注本教程 (https://www.tensorflow.org/beta/tutorials/load_data/text#split_the_dataset_into_text_and_train_batches),在此我想将存储在 tf.data.Dataset 类型的 (sentence, label) 元组中的每个句子的长度修剪为长度 8 或 n。我尝试将 tf.map 函数与 lambda 一起使用,但不能这样做,因为 lambda 只接受一个参数并且它正在接收 sentenceslabel 参数。 train_data = train_data.map(lambda x : x[:4])

如果有人能就如何做到这一点提出他们的想法,我将不胜感激。

【问题讨论】:

    标签: python tensorflow tensorflow2.0


    【解决方案1】:

    这里有一段代码 sn-p 来做所需的操作。

    import tensorflow as tf
    vocab_size = 10000
    
    sentences = tf.random.uniform(shape=[10000, 15], minval=0, maxval=vocab_size, dtype=tf.int32)
    labels = tf.random.uniform(shape=[10000, 1], minval=0, maxval=2, dtype=tf.int32)
    
    assert sentences.shape == tf.TensorShape([10000, 15])
    assert labels.shape == tf.TensorShape([10000, 1])
    
    
    def trim_sentences(sentence, label, n=8):
        return sentence[:n], label
    
    dataset = tf.data.Dataset.from_tensor_slices((sentences, labels)) 
    #<TensorSliceDataset shapes: ((15,), (1,)), types: (tf.int32, tf.int32)>
    
    dataset = dataset.map(trim_sentences) 
    #<MapDataset shapes: ((8,), (1,)), types: (tf.int32, tf.int32)>
    

    【讨论】:

    • 感谢您提供此解决方案。我还发现了一种更简单的方法,只需在 map 函数中添加 padded_text = encoded_text[:n](n= 填充长度)即可。但是,现在我想为 TPU 和 TPU 实现此功能,不支持 py_func。关于如何用一些 tf ops 或 tf.data 函数替换它的任何想法?
    • 是的,这和我上面写的一样。就 TPU 而言,上述数据集可以正常工作!
    • 在阅读了一些文档后,我发现from_tensor_slices,正如here 所提到的,对于像这样的小数据集,它会很好,但对于更大的数据集则不行,因为它会消耗更多的内存。你知道任何替代方案吗?
    • dataset = tf.data.Dataset.from_tensor_slices((sentences, labels)) 我这样做是为了简单。正确的做法是将您的数据转换为 tfrecords,将它们上传到 GCS 存储桶,然后编写足够快的数据输入管道以使 TPU 始终保持忙碌。更多关于这方面的信息tensorflow.org/guide/performance/datasets
    • 您提供的链接看起来是正确的。但是,我仍然无法理解如何使用 map 函数执行标记化、编码和填充。 This is 我想象它应该如何工作,但我就是无法让它工作。我也可以提供完整的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多