首页 > 解决方案 > TensorFlow 数据集 .map() 方法不适用于内置 tf.keras.preprocessing.image 函数

问题描述

我这样加载数据集:

import tensorflow_datasets as tfds

ds = tfds.load(
    'caltech_birds2010',
    split='train',
    as_supervised=False)

这个功能工作正常:

import tensorflow as tf

@tf.function
def pad(image,label):
    return (tf.image.resize_with_pad(image,32,32),label)

ds = ds.map(pad)

但是当我尝试映射不同的内置函数时

from tf.keras.preprocessing.image import random_rotation

@tf.function
def rotate(image,label):
    return (random_rotation(image,90), label)

ds = ds.map(rotate)

我收到以下错误:

AttributeError:“张量”对象没有属性“ndim”

这不是唯一给我带来问题的功能,无论有没有@tf.function装饰器,它都会发生。

任何帮助是极大的赞赏!

标签: pythontensorflowkerastensorflow-datasets

解决方案


我会尝试在这里使用 tf.py_function 进行随机旋转。例如:

def rotate(image, label):
    im_shape = image.shape
    [image, label,] = tf.py_function(random_rotate,[image, label],
                                     [tf.float32, tf.string])
    image.set_shape(im_shape)
    return image, label

ds = ds.map(rotate)

虽然我认为他们根据tf.py_function 和 tf.function 的目的有什么区别?, tf.py_function 通过 tensorflow 执行 python 代码更直接,即使 tf.function 具有性能优势。


推荐阅读