持续更新基于布尔值的tf.cond

我在使用tf.cond来控制Tensorflow图的流程。我查阅了文档并成功实现了基于tf.cond的分支。但是我的担忧在于,当图被加载时,bool变量的值会被检查,分支决定在初始化步骤就已完成。之后对bool的任何更改都不会被追踪。以下是最小工作示例(MWE),更好地描述了这个问题:

def funa():    return tf.constant(32)def funb():    return tf.constant(25)foo = Truex = tf.cond(tf.convert_to_tensor(foo), lambda: funa(), lambda: funb())for i in range(20):    global foo    if i > 10:        foo = False    print(sess.run(x))    

这只会打印32

我还尝试了eager_execution,使用以下代码:

tf.enable_eager_execution()def funa():    return tf.constant(32)def funb():    return tf.constant(21)foo = Truex = tf.cond(tf.convert_to_tensor(foo), lambda: funa(), lambda: funb())for i in range(20):    if i > 10:        foo = False    print(x)

结果仍然相同。

所以我的问题是,如何编写代码,使图的一部分可以根据bool变量的更新动态选择(如果可能的话)?谢谢。我使用的是Tensorflow v1.14。


回答:

您可以为foo创建一个占位符,并在运行会话时传入它的值。修改后的代码如下:

import tensorflow as tfdef funa():    return tf.constant(32)def funb():    return tf.constant(25)foo = Truefoo_p = tf.placeholder(tf.bool)sess = tf.Session()x = tf.cond(foo_p, lambda: funa(), lambda: funb())for i in range(20):    if i > 10:        foo = False    print(sess.run(x, {foo_p:foo}))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注