求助:tf.data.Dataset迭代触发RuntimeError错误的解决方法
解决
tf.data.Dataset迭代的RuntimeError问题 针对你遇到的错误,这里有几种可行的解决方法:
确保Eager Execution已启用
TensorFlow 2.x默认开启Eager模式,但如果你的环境是TF1.x或者手动关闭了该模式,需要显式开启:# TensorFlow 1.x import tensorflow as tf tf.enable_eager_execution() # TensorFlow 2.x(如果意外关闭了Eager模式) import tensorflow as tf tf.config.run_functions_eagerly(True)将迭代代码放入
tf.function中
如果需要在图模式下运行,把包含迭代的逻辑用tf.function装饰:import tensorflow as tf @tf.function def process_batch(dataset): for input_example_batch, target_example_batch in dataset.take(1): # 处理你的batch数据逻辑 print(input_example_batch.shape, target_example_batch.shape) process_batch(dataset)使用Dataset迭代器API(兼容旧版本)
如果你需要兼容TF1.x的图模式,可以使用迭代器来替代Python风格的循环:import tensorflow as tf iterator = tf.compat.v1.data.make_one_shot_iterator(dataset.take(1)) input_example_batch, target_example_batch = iterator.get_next() # 在会话中运行(TF1.x) with tf.compat.v1.Session() as sess: input_batch, target_batch = sess.run([input_example_batch, target_example_batch])
内容的提问来源于stack exchange,提问作者JimmyBinoculars
相关产品推荐
相关产品推荐

