3

我正在编写一个函数来在 TensorFlow 2.0 中实现一个模型。它需要image_batch(一批 numpy RGB 格式的图像数据)并执行一些我需要的特定数据增强任务。导致我出现问题的行是:

@tf.function
def augment_data(image_batch, labels):
    import numpy as np
    from tensorflow.image import flip_left_right

    image_batch = np.append(image_batch, flip_left_right(image_batch), axis=0)

    [ ... ]

numpy当我把装饰器放在它上面时,它的.append()功能就不再起作用了。@tf.function它返回:

ValueError:无法连接零维数组

当我np.append()在函数之外使用命令时,或者没有@tf.function顶部的命令时,代码运行没有问题。

这是正常的吗?我是否被迫移除装饰器以使其工作?或者这是一个错误,因为 TensorFlow 2.0 仍然是测试版?在这种情况下,我该如何解决这个问题?

4

1 回答 1

3

只需将 numpy 操作包装到tf.py_function

def append(image_batch, tf_func):
    return np.append(image_batch, tf_func, axis=0)

@tf.function
def augment_data(image_batch):
    image = tf.py_function(append, inp=[image_batch, tf.image.flip_left_right(image_batch)], Tout=[tf.float32])
    return image
于 2019-04-14T20:27:19.853 回答