如何在张量流中比较tf.Variable和标量的大小?

时间:2019-03-20 11:54:30

标签: python tensorflow

我使用Tensorflow来建立模型,我想判断训练步骤,如果该步骤大于10000,我的损失将会改变。以下是我的代码的一部分。

self.global_step = tf.Variable(0, name="global_step", trainable=False)
change = tf.cond(tf.greater(self.step,10000), lambda: True, lambda: False)

if change:
   self.loss = 

但是遇到如下错误:

TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. 
Use `if t is not None:` instead of `if t:` to test if a tensor is defined, 
and use TensorFlow ops such as tf.cond to execute subgraphs conditioned 
on the value of a tensor.

希望获得帮助。

2 个答案:

答案 0 :(得分:1)

您只需要先评估此张量

step = tf.Variable(0, name="global_step", trainable=False)
change = tf.cond(tf.greater(step,10000), lambda: True, lambda: False)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    if sess.run(change):   
        print('Ok')

如果将if sess.run(change)替换为if change,将会得到您提到的错误

答案 1 :(得分:1)

如果它是tensorflow 2.0,则根据doc.进行区分。

这就是它的作用。

(mouseenter)="$event.stopPropagation(); myDrop.open();"
(mouseleave)="$event.stopPropagation(); myDrop.close();"