【发布时间】:2023-02-11 15:26:30
【问题描述】:
从 Tensorflow 中的目录加载图像时,您可以使用以下内容:
dataset = tf.keras.utils.image_dataset_from_directory(
"S:\\Images",
batch_size=32,
image_size=(128,128),
label_mode=None,
validation_split=0.20, #Reserve 20% of images for validation
subset='training', #If we specify a validation_split, we *must* specify subset
seed=619 #If using validation_split we *must* specify a seed to ensure there is no overlap between training and validation data
)
但当然有些图像(.jpg、.png、.gif、.bmp)将无效。所以我们想忽略这些错误;跳过它们(和理想地记录文件名,以便修复、删除或删除它们)。
在如何忽略无效图像的过程中有一些想法:
方法一:tf.contrib.data.ignore_errors(仅限 Tensorflow 1.x)
警告:tf.contrib 模块将不会包含在 TensorFlow 2.0 中。
示例用法:
dataset = dataset.apply(tf.contrib.data.ignore_errors())这种方法唯一的缺点是it was only available in Tensorflow 1。今天尝试使用它根本行不通,因为
tf.contib命名空间不再存在。这导致了一个内置方法:方法二:
tf.data.experimental.ignore_errors(log_warning=False)(弃用)从文档中:
从另一个数据集创建一个数据集并静默忽略任何错误。 (弃用)
弃用:此功能已弃用。它将在未来的版本中被删除。更新说明:改用
tf.data.Dataset.ignore_errors。示例用法:
dataset = dataset.apply(tf.data.experimental.ignore_errors(log_warning=True))而且这个方法有效。它很好用。它具有工作的优势。
但它显然已被弃用,他们的文档说我们应该使用方法 3:
方法 3 -
tf.data.Dataset.ignore_errors(log_warning=False, name=None)删除导致错误的元素。
示例用法:
dataset = dataset.ignore_errors(log_warning=True, name="Loading images from directory")除了它不起作用
dataset.ignore_errors属性不起作用,并给出错误:AttributeError: 'BatchDataset' 对象没有属性 'ignore_errors'
意思是:
- 有用的东西被弃用了
- 他们告诉我们改用其他东西
- 和“提供更新说明”
- 但另一件事不起作用
所以我们问 Stackoverflow:
我如何使用
tf.data.Dataset.ignore_errors来忽略错误?红利阅读
未经测试的解决方法
这不仅不是我要问的,而且不允许人们阅读以下内容:
看起来
tf.data.Dataset.ignore_errors()方法不是 在BatchDataset对象中可用,这就是您在 你的代码。你可以试试用tf.data.Dataset.filter()过滤掉 加载图像时导致错误的元素。你可以使用 传递给filter()的 lambda 函数内的 try-except 块 捕获错误并为导致错误的元素返回 False, 这将过滤掉它们。这是您如何使用的示例filter()实现这个:def filter_fn(x): try: # Load the image and do some processing # Return True if the image is valid, False otherwise return True except: return False dataset = dataset.filter(filter_fn)或者,您可以使用
tf.data.experimental.ignore_errors()方法,目前在 TensorFlow 2.x 中可用。这个方法 将默默地忽略处理时发生的任何错误 数据集的元素。但是,请记住,此方法是 实验性的,可能会在未来的版本中被删除或更改。
【问题讨论】:
-
我猜
tf.data.Dataset.ignore_errors()是在 TF 2.11 中引入的
标签: tensorflow tensorflow2.0 tensorflow-datasets