【发布时间】: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