【问题标题】:how to batch with tf.data.Dataset.from_generator? Do i needto modify generator如何使用 tf.data.Dataset.from_generator 进行批处理?我需要修改生成器吗
【发布时间】:2021-06-28 13:43:26
【问题描述】:

我正在使用batch(8) 函数,它会修改形状并添加批次尺寸,但每批次只能获取一张图像。以下是我的代码:-

import cv2
import numpy as np
import os
import tensorflow as tf
import random

folder_path = "./real/"
files = os.listdir(folder_path)

def get_image():
    index = random.randint(0,len(files)-1)
    img = cv2.imread(folder_path+files[index])
    img = cv2.resize(img,(128,128))
    img = img/255.
    #More complex transformation
    yield img

dset = tf.data.Dataset.from_generator(get_image,(tf.float32)).batch(8)

for img in dset:
    print(img.shape)
    break

即使使用了 batch(8),输出仍然是 (1, 128, 128, 3)。我是否需要修改生成器以手动创建批次?还有,如何在tensorflow中将其包裹在生成器中,使其运行得更快?

【问题讨论】:

    标签: tensorflow tensorflow2.0 tensorflow-datasets


    【解决方案1】:

    因为你的收益只需要一个你应该在一个循环中产生的图像,这里是一个例子

    def get_image():
       for file in files:
          img = cv2.imread(folder_path + file)
          img = cv2.resize(img, (128, 128))
          img = img / 255.
    
          yield img # Your supposed to yield in a loop
    
    dataset = tf.data.Dataset.from_generator(get_image, output_shapes=(128, 128), output_types=(tf.float32))
    
    next(iter(dataset.batch(8))).shape
    
    # TensorShape([8, 128, 128])
    

    【讨论】:

    • 它工作正常,谢谢。 for 循环迭代多少次才能生成一批 8 个?我的文件列表很长..这种方法是否足够优化?对不起,我不是 python 100% 的人。
    • 你可以使用它,因为它只是将 yiur 数据集设置为一组 8 个就可以了
    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多