2

在我的 Tensorflow 管道中,我定义了一个load()函数,用于验证给定路径下是否存在特定图像文件。它看起来有点像这样:

import tensorflow as tf

def load(image_file):

  if tf.io.gfile.exists(image_file):
    input_image = tf.io.read_file(image_file)
    # do things with input_image

  return input_image

这对自己的作品没有问题。当我稍后在设置数据集时包装此函数时会出现错误:

train_dataset = tf.data.Dataset.list_files(IMAGE_PATH)
train_dataset = train_dataset.map(load,
                              num_parallel_calls=tf.data.experimental.AUTOTUNE)


#...
TypeError: in converted code:

<ipython-input-22-bdfc518ba578>:13 load  *
    if tf.io.gfile.exists(image_file):
/home/bdavid/.conda/envs/DL_env/lib/python3.7/site-packages/tensorflow_core/python/lib/io/file_io.py:280 file_exists_v2
    pywrap_tensorflow.FileExists(compat.as_bytes(path))
/home/bdavid/.conda/envs/DL_env/lib/python3.7/site-packages/tensorflow_core/python/util/compat.py:87 as_bytes
    (bytes_or_text,))

TypeError: Expected binary or unicode string, got <tf.Tensor 'args_0:0' shape=() dtype=string>

问题似乎是image_fileEagerMode 中的评估tf.io.gfile.exists需要一个字符串作为输入,而不是字符串类型的张量。

我已经尝试使用image_file.numpy()结果返回字符串值AttributeError: 'Tensor' object has no attribute 'numpy'

我还尝试按照这个密切相关的问题tf.py_function()中的建议将我的函数包装在 a中,这在执行过程中会产生完全相同的结果。使用而不是拍摄当然也会出现同样的错误。TypeErroros.path.existstf.io.gfile.exists

任何有关解决此问题的解决方法或正确方法的建议将不胜感激!

4

1 回答 1

1

我已经创建了一个解决方法,使用我执行的map_fnmatching_files没有任何错误。

我认为您可以尝试在您的代码上实现这种方法。

def load(image_file):
  if tf.io.gfile.exists(image_file.numpy()):
    input_image = tf.io.read_file(image_file)

  return input_image

IMAGE_PATH = '/content/images'
# train_dataset = tf.data.Dataset.list_files(IMAGE_PATH)
tf_matching = tf.io.matching_files('/content/images/*.png')
# train_dataset = train_dataset.map(load, num_parallel_calls=tf.data.experimental.AUTOTUNE)
train_dataset = tf.map_fn(load, tf_matching)

我还包括了注释掉的代码供您比较。

您可以阅读有关我在这些链接中使用的这些功能的更多信息。此链接中TensorFlow Map Function
的 参考。此链接中TensorFlow 匹配文件的 参考。

于 2020-03-20T06:01:36.080 回答