python - Tensorflow tf.cond 遇到错误 : TypeError: Failed to convert object of type <class 'function' > to Tensor

标签 python tensorflow

下面是一个最小的测试用例,我在其中创建了一个变量 v,我想将其初始化为值 777(用于简化的测试用例)。

注意:我无法使用普通初始化器初始化 v,因为它依赖于跨所有变量计算的标准化常量(其中一些变量在当时尚未创建 v 已创建)。

我的解决方案(如下)是创建一个 bool 变量full_init_cond,一旦我运行了一些初始化/分配OP并使用tf.cond,我将其设置为True以确保它们只运行一次。

import tensorflow as tf

v = tf.Variable(0, trainable=False)
full_init_cond = tf.Variable(False, trainable=False, dtype=tf.bool)

with tf.control_dependencies([v]):
  tf.cond(
    full_init_cond,
    true_fn=lambda: [tf.no_op],
    false_fn=lambda: [tf.assign(v, 777), tf.assign(full_init_cond, True)]
  )

我在 tf.cond 行收到以下错误:

TypeError: Failed to convert object of type <class 'function'> to Tensor. Contents: <function no_op at 0x7f39abf51400>. Consider casting elements to a supported type.

我不太理解这个错误。

<小时/>

更新:

令我惊讶的是,这个简单的测试似乎产生了一个有效的张量:

tf.cond(full_init_cond, tf.no_op, tf.no_op)

我认为这个失败了:

tf.cond(full_init_cond, lambda: tf.no_op, lambda: tf.no_op)

我的困惑仍在继续...... 顺便说一句,Tensorflow 版本 1.5。

最佳答案

lambda: tf.no_op 不起作用,因为您传递的函数返回一个函数。

需要

tf.group,以便列表和 no_op 返回之间的结构匹配。

以下代码片段在 tf 1.11 中运行

import tensorflow as tf

v = tf.Variable(0, trainable=False)
full_init_cond = tf.Variable(False, trainable=False, dtype=tf.bool)

with tf.control_dependencies([v]):
  tf.cond(
    full_init_cond,
    true_fn=tf.no_op,
    false_fn=lambda: tf.group([tf.assign(v, 777), tf.assign(full_init_cond, True)])
  )

关于python - Tensorflow tf.cond 遇到错误 : TypeError: Failed to convert object of type <class 'function' > to Tensor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49268743/

相关文章:

linux - Apache 无法访问 Python 的模块 'numpy' - linux

python - 如何检查变量是否是类?

python - Tensorflow域适应如何同时使用两个Bazel命令?

python - tensorflow : how to get a list of checkpoints

python - Keras : AttributeError: 'int' object has no attribute 'ndim' when using model. 适合

python - 用于分类的图像转换器

Python,在保留空格的同时间隔分割字符串?

python - 如何在python的离散化方法中解决索引出界

python - 如何在方案中像 python 一样追加?

python - Numpy 中的高级索引