【问题标题】:Tensorflow random numbers in Data Augmentation map function数据增强映射函数中的Tensorflow随机数
【发布时间】:2020-07-20 19:24:21
【问题描述】:

我想使用 crop_central 函数和 0.50-1.00 之间的随机浮点数进行数据增强。但是,当使用numpy.random.uniform(0.50, 1.00) 并绘制图像时,裁剪是不变的。我通过使用 4 张图像并绘制 8 行来调试它,图像是相同的。

一般来说,问题可以表述如下:如何在数据集映射函数中使用随机数?

def data_augment(image, label=None, seed=2020):
    # I want a random number here for every individual image
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00)) # random crop central
    image = tf.image.resize(image, INPUT_SHAPE) # the original image size

    return image

train_dataset = (
    tf.data.Dataset
        .from_tensor_slices((train_paths, train_labels))
        .map(decode_image, num_parallel_calls=AUTO)
        .map(data_augment, num_parallel_calls=AUTO)
        .repeat()
        .batch(4)
        .prefetch(AUTO)
    )

# Code to view the images
for idx, (imgs, _) in enumerate(train_dataset):
    show_imgs(imgs, 'image', imgs_per_row=4)
    if idx is 8:
        del imgs
        gc.collect()
        break

【问题讨论】:

    标签: python tensorflow tensorflow-datasets data-augmentation


    【解决方案1】:

    之前,我误读了这个问题。这是您正在寻找的答案。

    我能够使用以下代码重新创建您的问题 -

    重现问题的代码 - 裁剪图像的输出都是相同的。

    %tensorflow_version 2.x
    import tensorflow as tf
    from keras.preprocessing.image import load_img
    from keras.preprocessing.image import img_to_array, array_to_img
    from matplotlib import pyplot as plt
    import numpy as np
    AUTOTUNE = tf.data.experimental.AUTOTUNE
    
    # Set the sub plot parameters
    f, axarr = plt.subplots(5,4,figsize=(15, 15))
    
    # Load just 4 images of Cifar10
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
    images = x_train[:4]
    
    for i in range(4):
      axarr[0,i].title.set_text('Original Image')
      axarr[0,i].imshow(x_train[i])
    
    def data_augment(images):
        image = tf.image.central_crop(images, np.random.uniform(0.50, 1.00)) # random crop central
        image = tf.image.resize(image, (32,32)) # the original image size
        return image
    
    dataset = tf.data.Dataset.from_tensor_slices((images)).map(lambda x: data_augment(x)).repeat(4) 
    
    print(dataset)
    
    ix = 0
    i = 1
    count = 0
    
    for f in dataset:
      crop_img = array_to_img(f)
      axarr[i,ix].title.set_text('Crop Image')
      axarr[i,ix].imshow(crop_img)
      ix=ix+1
      count = count + 1
      if count == 4:
        i = i + 1
        count = 0
        ix = 0
    

    输出 - 第一行是原始图像。剩余的行是裁剪图像。

    嗯,这非常具有挑战性,并提供了以下两种解决方案 -

    解决方案 1: 使用 np.random.uniformtf.py_function

    1. 使用np.random.uniform(0.50, 1.00)
    2. 使用tf.py_function装饰函数调用-tf.py_function(data_augment, [x], [tf.float32])

    解决问题的代码 - 裁剪输出图像现在​​不同且不相同。

    %tensorflow_version 2.x
    import tensorflow as tf
    from keras.preprocessing.image import load_img
    from keras.preprocessing.image import img_to_array, array_to_img
    from matplotlib import pyplot as plt
    import numpy as np
    AUTOTUNE = tf.data.experimental.AUTOTUNE
    
    # Set the sub plot parameters
    f, axarr = plt.subplots(5,4,figsize=(15, 15))
    
    # Load just 4 images of Cifar10
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
    images = x_train[:4]
    
    for i in range(4):
      axarr[0,i].title.set_text('Original Image')
      axarr[0,i].imshow(x_train[i])
    
    def data_augment(images):
        image = tf.image.central_crop(images, np.random.uniform(0.50, 1.00)) # random crop central
        image = tf.image.resize(image, (32,32)) # the original image size
        return image
    
    dataset = tf.data.Dataset.from_tensor_slices((images)).map(lambda x: tf.py_function(data_augment, [x], [tf.float32])).repeat(4)
    
    ix = 0
    i = 1
    count = 0
    
    for f in dataset:
      for l in f:
        crop_img = array_to_img(l)
        axarr[i,ix].title.set_text('Crop Image')
        axarr[i,ix].imshow(crop_img)
        ix=ix+1
        count = count + 1
        if count == 4:
          i = i + 1
          count = 0
          ix = 0
    

    输出 - 第一行是原始图像。剩余的行是裁剪图像。

    解决方案 2: 使用 tf.random.uniformtf.py_function

    1. 使用tf.random.uniform(shape=(), minval=0.50, maxval=1).numpy()
    2. 仅使用上述选项,代码不起作用,因为它会引发错误AttributeError: 'Tensor' object has no attribute 'numpy'。要解决此问题,您需要使用 tf.py_function(data_augment, [x], [tf.float32]) 装饰您的函数。

    解决问题的代码 - 裁剪输出图像现在​​不同且不相同。

    %tensorflow_version 2.x
    import tensorflow as tf
    from keras.preprocessing.image import load_img
    from keras.preprocessing.image import img_to_array, array_to_img
    from matplotlib import pyplot as plt
    import numpy as np
    AUTOTUNE = tf.data.experimental.AUTOTUNE
    
    # Set the sub plot parameters
    f, axarr = plt.subplots(5,4,figsize=(15, 15))
    
    # Load just 4 images of Cifar10
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
    images = x_train[:4]
    
    for i in range(4):
      axarr[0,i].title.set_text('Original Image')
      axarr[0,i].imshow(x_train[i])
    
    def data_augment(images):
        image = tf.image.central_crop(images, tf.random.uniform(shape=(), minval=0.50, maxval=1).numpy()) # random crop central
        image = tf.image.resize(image, (32,32)) # the original image size
        return image
    
    dataset = tf.data.Dataset.from_tensor_slices((images)).map(lambda x: tf.py_function(data_augment, [x], [tf.float32])).repeat(4)
    
    ix = 0
    i = 1
    count = 0
    
    for f in dataset:
      for l in f:
        crop_img = array_to_img(l)
        axarr[i,ix].title.set_text('Crop Image')
        axarr[i,ix].imshow(crop_img)
        ix=ix+1
        count = count + 1
        if count == 4:
          i = i + 1
          count = 0
          ix = 0
    

    输出 - 第一行是原始图像。剩余的行是裁剪图像。

    希望这能回答您的问题。快乐学习。

    【讨论】:

    • @Mark wijkhuizen - 如果它回答了您的问题,请您接受并投票赞成答案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2016-09-28
    • 2020-11-05
    • 2018-10-21
    相关资源
    最近更新 更多