gpt4 book ai didi

python - 使用 Tensorflow 的 tf.io.gfile.exists 检查文件路径是否存在

转载 作者:行者123 更新时间:2023-12-05 05:05:02 24 4
gpt4 key购买 nike

在我的 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 需要一个字符串作为输入,而不是字符串类型的 Tensor。

我已经尝试使用 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 当然也会出现同样的错误。

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

最佳答案

我已经使用 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 匹配文件 引用.

关于python - 使用 Tensorflow 的 tf.io.gfile.exists 检查文件路径是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com