Skip to main content
 首页 » 编程设计

python之tf.cond 变量。 tf.global_variables_initializer() 中的 FailedPreconditionError

2024年11月24日14emanlee

我在 tf.global_variables_initializer() 中遇到 FailedPreconditionError 错误。我已经将代码的以下部分归为罪魁祸首:

def __init__(...): 
    ... 
    self.global_step = tf.get_variable(initializer=tf.zeros_initializer(), trainable=False, shape=(), name='global_step') 
    ... 
    step_rampup_value = self.step_rampup(self.global_step, self.rampup_length) 
 
def step_rampup(self, global_step, rampup_length): 
    result = tf.cond(global_step < rampup_length, 
                     lambda: tf.constant(0.0), 
                     lambda: tf.constant(1.0)) 
    return tf.identity(result, name="step_rampup") 
session.run(tf.global_variables_initilizer()) 

self.global_step 将在每次迭代时由优化器递增 1。它的值(value)必须改变。所以,这就是我想要的行为。

错误信息:

FailedPreconditionError ... 
506         with tf.Session(graph=highgraph) as session: 
--> 507             session.run(tf.global_variables_initializer()) 
... 
FailedPreconditionError: Attempting to use uninitialized value global_step 
 [[node global_step/read (defined at NML_U/sNeural.py:103)  = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](global_step)]] 

为什么那部分代码是罪魁祸首? 因为,下面的代码有效

def __init__(...): 
    ... 
    self.global_step = tf.get_variable(initializer=tf.zeros_initializer(), trainable=False, shape=(), name='global_step') 
    ... 
    step_rampup_value = self.step_rampup(self.global_step, self.rampup_length) 
 
def step_rampup(self, global_step, rampup_length): 
    result = tf.cond(global_step.initialized_value() < rampup_length, 
                     lambda: tf.constant(0.0), 
                     lambda: tf.constant(1.0)) 
    return tf.identity(result, name="step_rampup") 
session.run(tf.global_variables_initilizer()) 

但这将每次都使用 self.global_step(=0) 的初始化值评估条件,这不是预期的行为

此外,

这段代码同样有效:

def __init__(...): 
    ... 
    self.global_step = tf.get_variable(initializer=tf.zeros_initializer(), trainable=False, shape=(), name='global_step') 
    self.global_step = tf.assign(self.global_step,0.) 
    ... 
    step_rampup_value = self.step_rampup(self.global_step, self.rampup_length) 
 
def step_rampup(self, global_step, rampup_length): 
    result = tf.cond(global_step < rampup_length, 
                     lambda: tf.constant(0.0), 
                     lambda: tf.constant(1.0)) 
    return tf.identity(result, name="step_rampup") 
session.run(tf.global_variables_initilizer()) 

但是(也许)这不会再次导致对 global_step 的依赖,而是对分配操作的依赖,它将继续将 0 分配给 self.global_step

我如何着手实现该行为?

请您参考如下方法:

你没有提供完整的代码,所以我只能猜测你可能正在调用 tf.global_variables_initializer() before __init__()。实际上,前者不会初始化调用后创建的变量。