【问题标题】:Check if path to file exists using Tensorflow's tf.io.gfile.exists使用 Tensorflow 的 tf.io.gfile.exists 检查文件路径是否存在
【发布时间】:2020-06-29 12:06:45
【问题描述】:

在我的 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>

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

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

我还尝试按照this closely related question 中的建议将我的函数包装在tf.py_function() 中,这会在执行期间产生完全相同的TypeError。使用os.path.exists 而不是tf.io.gfile.exists 当然也会出现同样的错误。

任何有关解决此问题的解决方法或正确方法的建议都将受到高度赞赏!

【问题讨论】:

    标签: python tensorflow typeerror eager-execution


    【解决方案1】:

    我已经创建了一个解决方法,使用 ma​​p_fnma​​tching_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)
    
    

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

    您可以阅读我在这些链接中使用的这些功能的更多信息。
    link 中的 TensorFlow 映射函数 参考。
    link 中的 TensorFlow 匹配文件 参考。

    【讨论】:

    • 如果 tf.map_fn 的输出类型与输入类型不同(在这种情况下,输出是图像,对我来说是tf.float32),则必须添加输出类型。虽然这克服了我得到的错误通过在 EagerMode 中评估tf.io.gfile.exists() 输入,该解决方案实际上使我的 PC 崩溃,因为它直接将该函数应用于所有图像,而不是创建计算图并仅在需要时对其进行评估。因此,它尝试将所有图像拟合到内存中,这我想总的来说这是一个坏主意。知道如何处理这个问题吗?你如何让它在你的管道中工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多