捕获从TensorFlow引发的python异常
我正在运行一个python(v3.6.5)代码,该代码使用TensorFlow(v1.13.2)使用经过训练的模型(在Windows8.1上)执行推理 我想捕获(并记录)从TensorFlow库内部抛出的异常/错误。 例如,当批处理大小(在session.run()期间)太大时,进程将使用所有系统内存并崩溃 我的代码如下所示: 我看到进程的内存在增长,并且在某个点上它在没有到达异常处理代码的情况下死亡。 (如果我在python中添加占用内存的代码,我会设法捕获内存异常)捕获从TensorFlow引发的python异常,python,python-3.x,tensorflow,exception,Python,Python 3.x,Tensorflow,Exception,我正在运行一个python(v3.6.5)代码,该代码使用TensorFlow(v1.13.2)使用经过训练的模型(在Windows8.1上)执行推理 我想捕获(并记录)从TensorFlow库内部抛出的异常/错误。 例如,当批处理大小(在session.run()期间)太大时,进程将使用所有系统内存并崩溃 我的代码如下所示: 我看到进程的内存在增长,并且在某个点上它在没有到达异常处理代码的情况下死亡。 (如果我在python中添加占用内存的代码,我会设法捕获内存异常) 有人能解释一下发生了什么
有人能解释一下发生了什么事吗 这应该是由于捕获不正确的异常造成的。Tensorflow定义了自己的异常()子类,我不确定,但我认为问题来自这样一个事实:当Tensorflow引发的异常应该是自定义异常时,您期望出现标准python异常,对吗?我想你应该给我们一个你得到的回溯的例子我没有得到回溯。进程结束了,我在控制台上只看到了这一点:进程结束时的退出代码为-1073740791(0xC0000409),因此这是一个系统退出,我看到这一点的唯一方法是在每次迭代时调用一个子进程并获取其退出代码,但我不知道如何使用tensorflow实现它抱歉:/即使我尝试捕获tf.errors.ResourceExhustederRor或tf.errors.OpError,它也不会发出警报。若我捕捉到异常,我希望也捕捉到它的派生类,即tf.errors.OpError和其他tensorflow异常
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()