运行时错误:tf.placeholder()与即时执行不兼容。

84

我已将tf_upgrade_v2用于将TF1代码升级到TF2。但我对两者都是新手。我遇到了以下错误:

RuntimeError: tf.placeholder() is not compatible with eager execution.

我有一些tf.compat.v1.placeholder()

self.temperature = tf.compat.v1.placeholder_with_default(1., shape=())
self.edges_labels = tf.compat.v1.placeholder(dtype=tf.int64, shape=(None, vertexes, vertexes))
self.nodes_labels = tf.compat.v1.placeholder(dtype=tf.int64, shape=(None, vertexes))
self.embeddings = tf.compat.v1.placeholder(dtype=tf.float32, shape=(None, embedding_dim))

你能给我一些建议如何继续吗?有任何“快速”解决方案吗?还是我需要重新编码?

5个回答

109

我在这里找到了一个简单的解决方案:禁用TensorFlow即时执行

基本上就是这样:

tf.compat.v1.disable_eager_execution()

使用此方法,您可以禁用默认启用的即时执行,而无需过多修改代码。


3
我认为这不是一个好主意,因为它使得在Python和TensorFlow代码中轻松交替使用变得困难。你的表达能力受到严重限制,还不如使用TF 1.X版本。如果你想将操作编译成图形组件并仍然启用即时执行,请使用“tf.function”装饰函数,该函数将代码即时编译成图形。 - cs95
1
我们在哪里使用这个方法?而不是每一个tf.compat.v1.placeholder()? - user12424147
1
在使用TF或脚本的开始。 - AMGMNPLK
5
尝试运行一些“旧”的Tensorflow代码,但感觉有一半的库已经过时了。 - jds
1
@AMGMNPLK tf.compat.v1.disable_eager_execution(),谢谢~ - Rγσ ξηg Lιαη Ημ 雷欧

23

tf.placeholder() 的作用是在运行时接收 feed dict 提供的值并执行所需的操作。通常,您会使用 'with' 关键字创建 Session() 并运行它。但由于某些情况可能不适用于所有情况,因此您需要立即执行,这称为急切执行。

示例:

通常,以下是运行会话的过程:

import tensorflow as tf

def square(num):
    return tf.square(num) 

p = tf.placeholder(tf.float32)
q = square(num)

with tf.Session() as sess:
    print(sess.run(q, feed_dict={num: 10})

但是当我们使用动态执行时,我们运行它的方式为:

import tensorflow as tf

tf.enable_eager_execution()

def square(num):
   return tf.square(num)

print(square(10)) 
因此,在大多数情况下,我们不需要显式地在会话中运行它,并且可以更加直观。这提供了更多的交互式执行。 有关更多详细信息,请访问: https://www.tensorflow.org/guide/eager 如果您正在将代码从tensorflow v1转换为tensorflow v2,则必须实现tf.compat.v1,而Placeholder存在于tf.compat.v1.placeholder中,但只能在eager mode off中执行。
tf.compat.v1.disable_eager_execution()

TensorFlow发布了即刻执行(eager execution)模式,每个节点定义后会立即执行。因此,使用tf.placeholder语句已不再有效。


谢谢Ashish。是的,我理解急切和会话的逻辑,但我说的是使用ft_upgrade_v2工具将TF1代码升级到TF2。它不会处理占位符吗? - AMGMNPLK
1
感谢您澄清问题!看起来 TensorFlow 2.0 已经移除了占位符,您需要创建一个类型为 None 的张量。此外,如果您使用 tf.compat.v1.*,由于不兼容性,您需要关闭急切执行! - Ashish Bastola
tf.compat.v1.disable_eager_execution() - Rγσ ξηg Lιαη Ημ 雷欧

12

在 TensorFlow 1.X 中,占位符是创建的,并且在实例化 tf.Session 时需要使用实际值进行填充。然而,从 TensorFlow2.0 开始,默认情况下启用了Eager Execution,因此“占位符”的概念不再有意义,因为操作会立即计算(而不是延迟到以前的模式)。

另请参见Functions, not Sessions

# TensorFlow 1.X
outputs = session.run(f(placeholder), feed_dict={placeholder: input})
# TensorFlow 2.0
outputs = f(input)

12
如果您在使用TensorFlow模型进行目标检测时遇到此错误,则请使用exporter_main_v2.py而不是export_inference_graph.py导出模型。这是正确的方法。如果您只是关闭eager_execution,那么它将解决这个错误,但会产生其他错误。
另外,请注意一些参数更改,例如在此处,您将指定检查点目录的路径而不是检查点的路径。请参考文档以了解如何使用TensorFlow V2进行目标检测。

6
为了解决这个问题,您需要禁用默认激活的急切执行。所以添加以下代码行。 tf.compat.v1.disable_eager_execution() #<--- 禁用急切执行
在错误修复之前: enter image description here 在错误修复之后: enter image description here

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