【问题标题】:I can't create a Dataset.from_generator() with generator that uses pandas Dataframes as arguments我无法使用使用 pandas Dataframes 作为参数的生成器创建 Dataset.from_generator()
【发布时间】:2019-06-14 12:29:28
【问题描述】:

我想从生成器创建一个数据帧管道,该生成器使用 pandas 数据帧在磁盘上查找图像路径并将它们加载到管道中。 Tensorflow 不允许我这样做,弹出一个Can't convert non-rectangular Python sequence to Tensor. 消息。

在将生成器传递给tf.data.Dataset.from_generator 时,我尝试在args 参数中使用.values,但我必须重写我使用数据帧编写的所有代码以找到正确图像的路径。

这是生成数据集的命令:

train_dataset = tf.data.Dataset.from_generator(make_triplet_dataset, (tf.float32, tf.float32, tf.float32), args = ([train_families, train_positive_relations]))

这是make_triplet_dataset 生成器(它使用熊猫数据框作为参数):

def make_triplet_dataset(families, positive_relations):
    """
    Dataset Generator that returns a random anchor, positive and negative images each time it is called
    """
    while True:
        
        # generates random triplet
        anchor, positive, negative = make_triplet(families, positive_relations)
        
        # builds the path for the randomly chosen images
        path_anchor_img = 'train/' + anchor + '/' + random.choice(os.listdir('train/' + anchor))
        path_positive_img = 'train/' + positive + '/' + random.choice(os.listdir('train/' + positive))
        path_negative_img = 'train/' + negative + '/' + random.choice(os.listdir('train/' + negative))
        
        # loads and preprocess the images to be used in the in the algorithm 
        anchor_img = preprocess_input(cv2.imread(path_anchor_img)) # preprocess does a (img/127.5) - 1 operation
        positive_img = preprocess_input(cv2.imread(path_positive_img))
        negative_img = preprocess_input(cv2.imread(path_negative_img))
        
        yield (anchor_img, positive_img, negative_img)

函数make_triplet 是一个嵌套函数,它使用pandas Dataframes 来生成图像的路径。 我希望能够使用生成器生成一个 tensorflow 数据集,该生成器可以生成三元组的图像,使用 pandas Dataframes 找到这些图像的路径并将它们加载到管道中。请,如果有人可以提供帮助,将不胜感激。

【问题讨论】:

    标签: python tensorflow machine-learning tensorflow-datasets


    【解决方案1】:

    找到了答案。我没有在tf.data.Dataset.from_generator 方法中的args 参数中为生成器函数传递pandas 数据帧参数,而是使用lambda 在生成器函数本身中传递它们:

    train_dataset = tf.data.Dataset.from_generator(lambda: make_triplet_dataset(train_families, train_positive_relations), output_types = (tf.float32, tf.float32, tf.float32))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多