【问题标题】:Catch python exception thrown from TensorFlow捕获从 TensorFlow 抛出的 python 异常
【发布时间】:2019-11-11 11:33:52
【问题描述】:

我正在运行一个 python (v 3.6.5) 代码,该代码使用 TensorFlow (v 1.13.2) 使用经过训练的模型执行推理(在 Windows 8.1 上)。

我想捕捉(并记录)从 TensorFlow 库内部抛出的异常/错误。

例如,当批处理大小(在 session.run() 期间)太大时,进程会使用所有系统内存并崩溃。

我的代码如下所示:

import tensorflow as tf
import math
from tqdm import tqdm
# …

def parse_function(image_string, frame_id):
    image = tf.image.decode_jpeg(image_string, channels=3)
    resize_image = tf.image.resize_images(image, [224, 224], method=tf.image.ResizeMethod.BICUBIC)
    return resize_image, frame_id


def load_graph(frozen_graph_filename):
    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(graph_def, name="prefix")
    return graph


def main(_):
    batch_size = 128

    num_frames = 5000
    num_batches = int(np.ceil(num_frames / batch_size))
    frame_ids = get_ids()

    with MyFrameReader() as frd:
        im_list = []
        for id in frame_ids:
            im_list.append(frd.get_frame(id))

    dataset = tf.data.Dataset.from_tensor_slices((im_list, frame_ids))
    dataset = dataset.map(parse_function)
    batched_dataset = dataset.batch(batch_size)
    iterator = batched_dataset.make_initializable_iterator()
    next_element = iterator.get_next()

    graph = load_graph(PB_FILE)
    x = graph.get_tensor_by_name('prefix/input_image:0')
    y = graph.get_tensor_by_name('prefix/output_node:0')
    sess1 = tf.Session(graph=graph)
    sess2 = tf.Session(config= tf.ConfigProto(device_count={'GPU': 0})) # Run on CPU
    sess2.run(iterator.initializer)

    for _ in tqdm(range(num_batches)):
        try:
            # pre process
            inference_batch, frame_id_batch = sess2.run(next_element)
            # main process
            scores_np = sess1.run(y, feed_dict={x: inference_batch})
            # post process …
        except MemoryError as e:
            print('Error 1')
        except Exception as e:
            print('Error 2')
        except tf.errors.OpError as e:
            print('Error 3')
        except:
            print('Error 4')
    sess1.close()
    sess2.close()

我看到进程的内存在增长,并且在某些时候它在没有到达异常处理代码的情况下死亡。 (如果我在 python 中添加占用内存的代码,我会设法捕获内存异常)

有人可以解释发生了什么吗?

【问题讨论】:

  • 我不确定,但我认为问题出在这样一个事实,即当 tensorflow 引发的异常应该是自定义的 tensorflow.org/versions/r1.15/api_docs/python/tf/errors 时,您期望标准 python 异常?我认为你应该给我们一个你得到的回溯示例
  • 我没有得到回溯。进程终止,我在控制台上只看到这个:进程完成,退出代码 -1073740791 (0xC0000409)
  • 所以这是一个系统退出,我看到它工作的唯一方法是在每次迭代时调用一个子进程并获取它的退出代码,但我不知道如何用 tensorflow 实现它抱歉: /

标签: python python-3.x tensorflow exception


【解决方案1】:

这应该是由于捕获了不正确的异常造成的。 Tensorflow 定义了自己的 exceptions,它们是 Exception (source code) 的子类

【讨论】:

  • 即使我尝试捕获 tf.errors.ResourceExhaustedError 或 tf.errors.OpError,它也不会捕获。如果我捕捉到异常,我希望也捕捉到它的派生类,即 tf.errors.OpError 和其他 tensorflow 异常
猜你喜欢
  • 2011-05-07
  • 2011-06-27
  • 2013-06-24
  • 2016-02-17
  • 2018-08-31
  • 1970-01-01
  • 2018-03-09
  • 2017-10-14
相关资源
最近更新 更多