【问题标题】:Load tensorflow dataset directly from cache object直接从缓存对象加载 tensorflow 数据集
【发布时间】:2021-08-04 19:27:43
【问题描述】:

我已经构建了一个tf.data.Dataset 管道来将我的数据转换为张量,并且在我的管道结束时,我正在缓存数据以加快数据的后续迭代。

tf.data.Dataset 有 .cache 函数来执行此操作,但在我的训练脚本中,我想直接从缓存对象加载数据集对象,而不是需要所有代码来构建管道。

下面是一个淡化的示例,它生成图像数据集并将其缓存到my_cache。在另一种设置(不需要管道详细信息的设置)中,我可以仅使用 my_cache 创建数据集对象吗?

import tensorflow as tf
import numpy as np

# Define some complicated tf.data pipeline
def complicated_data_generator():
    """
    Generates samples inputs,target of the form
    inputs:   ( [32,32,3], [32,32,3] )
    targets:  ( [32,32,3], )
    """
    for i in range(10):
        inputs = (np.random.rand(32,32,3).astype(np.float32),
                  np.random.rand(32,32,3).astype(np.float32))
        target = (np.random.rand(32,32,3).astype(np.float32), )
        yield inputs,target
tspec = tf.TensorSpec(shape=(32,32,3), dtype=tf.float32)
output_signature = (tspec,tspec),(tspec,)
ds = tf.data.Dataset.from_generator(complicated_data_generator,output_signature=output_signature)

@tf.function
def add_feature(inputs,target):
    return inputs+(inputs[0],),target
ds = ds.map(add_feature)
ds = ds.shuffle(5)

# Set up cache file
ds = ds.cache('my_cache')

# Loop over data once to cache
for x,y in ds:
    pass

【问题讨论】:

    标签: tensorflow tensorflow-datasets


    【解决方案1】:

    对于这种情况,我发现了以下从虚拟生成器初始化的作品。我确实需要使用 tf.TensorSpec

    提供预期的数据形状
    dum_gen = lambda : None 
    tspec = tf.TensorSpec(shape=(32,32,3), dtype=tf.float32)
    output_signature = (tspec,tspec,tspec),(tspec,)
    ds_new = tf.data.Dataset.from_generator(dum_gen,output_signature=output_signature)
    ds_new = ds_new.cache('my_cache')
    

    那么ds_new就可以被迭代了。

    【讨论】:

      猜你喜欢
      • 2018-06-05
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 2022-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多