Tensorflow,try和except不能处理异常

14

我是TensorFlow的新手,目前遇到一个非常烦人的问题。

我正在编写一个程序,它从tfrecord文件中使用tf.WholeFileReader.read(image_name_queue)加载图像的"原始数据",然后使用tf.image.decode_jpeg(raw_data, channels=3)进行解码,最后将其传递给向量化函数。

主要代码

logging.info('setting up folder')
create_image_data_folder()
save_configs()

logging.info('creating graph')
filename_queue = tf.train.string_input_producer([
                                             configs.TFRECORD_IMAGES_PATH],
                                             num_epochs=1)

image_tensor, name_tensor = read_and_decode(filename_queue)
image_batch_tensor, name_batch_tensor = tf.train.shuffle_batch(
                                        [image_tensor, name_tensor],
                                        configs.BATCH_SIZE,
                                        1000 + 3 * configs.BATCH_SIZE,
                                        min_after_dequeue=1000)
image_embedding_batch_tensor = configs.IMAGE_EMBEDDING_FUNCTION(image_batch_tensor)

init = tf.initialize_all_variables()
init_local = tf.initialize_local_variables()
logging.info('starting session')
with tf.Session().as_default() as sess:
    sess.run(init)
    sess.run(init_local)
    tf.train.start_queue_runners()

    logging.info('vectorizing')
    data_points = []
    for _ in tqdm(xrange(get_n_batches())):
        name_batch = sess.run(name_batch_tensor)
        image_embedding_batch = sess.run(image_embedding_batch_tensor)
        for vector, name in zip(list(image_embedding_batch), name_batch):
            data_points.append((vector, name))

logging.info('saving')
save_pkl_file(data_points, 'vectors.pkl')

read_and_decode函数

def read_and_decode(tfrecord_file_queue):
    logging.debug('reading image and decodes it from queue')
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(tfrecord_file_queue)
    features = tf.parse_single_example(serialized_example,
        features={
            'image': tf.FixedLenFeature([], tf.string),
            'name': tf.FixedLenFeature([], tf.string)
        }
    )
    image = process_image_data(features['image'])

    return image, features['name']

这段代码本来是有效的,但最终它遇到了一个坏的、非jpeg格式的文件,就会抛出错误并且程序停止运行

错误

InvalidArgumentError (see above for traceback): Invalid JPEG data, size 556663

我想跳过这些“错误”。我尝试用tryexcept包围代码。

新代码

for _ in tqdm(xrange(get_n_batches())):
    try:
        name_batch = sess.run(name_batch_tensor)
        image_embedding_batch = sess.run(image_embedding_batch_tensor)
        for vector, name in zip(list(image_embedding_batch), name_batch):
            data_points.append((vector, name))
    except Exception as e:
        logging.warning('error occured: {}'.format(e))
当我再次运行程序时,仍然出现相同的错误,tryexcept 似乎无法处理该错误。如何处理这些异常?另外,如果您发现我误解了 TensorFlow 的“结构”,请提醒我。

3
你是怎么解决的?我在使用tensorflow时遇到了同样的问题,但try/except无法捕获异常 :( - alex
1
我没有这样做,我通过SciPy加载了图像并跳过了损坏的图像,因为我可以处理异常。 - O. Edholm
2
这里有更新吗? - YLJ
有更新吗? - Scicare
我通过使用 tf.data.experimental.ignore_errors 成功解决了这个问题。 - sumitkanoje
显示剩余3条评论
3个回答

2
我知道这与你的例子无关,但我遇到了一个不同的情况,其中 TensorFlow 似乎没有捕捉到异常,尽管执行了。
try:
    # Run code that throw tensorflow error
except:
    print('This won't catch the exception...')

这个问题的难点在于TensorFlow调试指向了错误的代码行;它告诉我错误出现在图的构建中,而不是图的执行中。
具体问题是什么?
我尝试从.meta文件中恢复模型:
try:
    saver = tf.train.import_meta_graph('my_error_generating_model.meta') # tf throws err here
    graph = tf.get_default_graph()
except:
    print('This won't run')

with tf.Session() as sess:
    # This is where error is actually generated
    saver.restore(sess, tf.train.latest_checkpoint('./'))
    sess.run(...) # Propagating through graph generates a problem

当然,解决方案是将try-catch包装器放在执行代码周围!

1

好的,为了解决您的问题,请使用v2.8.0中提供的tf.data.experimental.ignore_errors

使用下面的转换来生成一个包含与输入相同元素的数据集,但静默地删除任何导致错误的元素。例如:

dataset = tf.data.Dataset.from_tensor_slices([1., 2., 0., 4.])

# Computing `tf.debugging.check_numerics(1. / 0.)` will raise an
InvalidArgumentError.
dataset = dataset.map(lambda x: tf.debugging.check_numerics(1. / x, "error"))

# Using `ignore_errors()` will drop the element that causes an error.
dataset =
    dataset.apply(tf.data.experimental.ignore_errors())  # ==> {1., 0.5, 0.2}

请参考这里的文档(链接)


1
这有助于解决我的tf.io.decode_jpeg异常处理问题。 - Vishruit Kulshreshtha

0
问题在于使用 "except Exception" 只会捕获从通用类 Exception 继承的异常,但不是全部的异常。 如果您想捕获来自 tensorflow 的特定异常,请尝试:
try:
    # Your code
except tf.errors.InvalidArgumentError as e
    logging.warning('error occured: {}'.format(e))

如果你想捕获任何异常:
except: # Catch all exception
    logger.exception('error occured")

5
这对我来说不起作用(同样的错误)- 甚至尝试捕获任何异常也失败了。 - Josh
我不太明白:tf.error.InvalidArgumentErrorException 的子类,因此(在 tf.function 之外),except Exception 应该捕获 tf.error.InvalidArgumentError - joel
Joel,你说得对,如果tf.error.InvalidArgumentError是Exception的子类,则应该使用except Exception来捕获它。但是我的回答是4年前的事了,据我所记,那时在tensorflow的版本中并非如此。我没有检查最新版本,但他们可能已经修复了这个问题... - Zyx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接