Machine learning 张量流:创建和计算图形时传递布尔变量
我想传递一个布尔值,当我计算图形时,它可以改变。我在下面发布我的代码:Machine learning 张量流:创建和计算图形时传递布尔变量,machine-learning,tensorflow,Machine Learning,Tensorflow,我想传递一个布尔值,当我计算图形时,它可以改变。我在下面发布我的代码: import tensorflow as tf from tensorflow.python.ops import control_flow_ops def my_model(input, is_freeze): trainable = tf.cond(is_freeze, lambda: tf.constant(False), lambda: tf.con
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
def my_model(input, is_freeze):
trainable = tf.cond(is_freeze, lambda: tf.constant(False),
lambda: tf.constant(True)) #Try 3
#trainable = tf.cond(is_freeze, lambda: False, lambda: True) # Try 1
#trainable = tf.logical_not(is_freeze) # Try 2
fc1_W = tf.get_variable('fc1_W', trainable = trainable,
initializer = tf.zeros(100, 2))
fc1 = tf.matmul(input, fc1_W)
return fc1
tf.reset_default_graph()
X = tf.placeholder(tf.float32)
is_freeze = tf.placeholder(tf.bool)
my_model_graph = my_model(X, is_freeze) # Getting error while creating model
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(my_optimizer, feed_dict = {is_freeze: False, X: np.zeros((50, 100))})
我得到的错误如下所示:For#Try1
AttributeError: 'bool' object has no attribute 'name'
对于#Try3
:
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.`
请有人给我解释一下我该如何克服这个问题。如果可能的话,有人能告诉我我所有的方法都错在哪里吗
基本上我做的是我有两个模型。首先我训练其中一个模型,然后使用第一个模型的学习值,我必须训练第二个模型冻结第一个模型的值
提前感谢。您不能只在“图形”中使用
True
和False
——您需要将它们从python
传递到tensorflow
,一种方法是使用tf.constant()
。你可以试试
def my_model(input, is_freeze):
trainable = tf.cond(is_freeze, lambda: tf.constant(False), lambda: tf.constant(True))
否则我看没问题!如果您需要更详细的帮助,请提供一个最小的工作示例 似乎您正试图在tensorflow图中嵌入推理/逻辑开关。这样做是不可取的。请查看新界面,了解如何实现完全相同的目标。我已经尝试过您的方法。但它不起作用。我现在已经提供了完整的代码。请检查一下。另外,在示例中,似乎没有名为
condtf
的库。请你检查一下。你能建议现在如何克服这个问题吗?我现在已经提供了完整的代码。我是否仍应使用估计器
?我将研究它们,但在此期间,您能否给出一个与我的示例相关的小代码示例。这将非常有帮助。您是否可以通过将所有节点绘制到图形中,但仅返回部分结果来实现它,从而仅通过正确的路径运行图形的一部分?