python - Tensorflow,try and except 不处理异常

标签 python image tensorflow

我是 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“结构”,请指出这一点。

最佳答案

我知道这不适用于你的例子,但我偶然发现了一个不同的场景,在这个场景中,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 包装器放在执行代码周围!

关于python - Tensorflow,try and except 不处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40693159/

相关文章:

javascript - <img> onerror 404 图像响应

java - 如何将图像加载到与类相同的包中?

Tensorflow InvalidArgumentError 无效的 JPEG 数据,大小 4096,不是 Jpeg 文件 0x00 0x05

python-3.x - 评估 tf.keras.model 输出之间的成对距离

python - SQLITE3 插入错误

Python,使用for循环打印两列数字

python - 有没有类似 Blender 节点编辑器的 Python 可重用组件?

javascript - 如何在 ng-circle-progress imageSrc 选项中附加图像?

tensorflow - 为什么卷积神经网络核大小经常选择方阵

python - Python `list.extend(iterator)` 保证是惰性的吗?