Python 能否使用tf.cond()动态定义图形

Python 能否使用tf.cond()动态定义图形,python,tensorflow,conditional,Python,Tensorflow,Conditional,为了构建一个测试用例代码,我只想将一个张量传递给一个图,让模型决定是乘以2一次还是两次。该决策基于对布尔值的评估。代码如下: class what_to_do(): def __init__(self): self.conditionally_determined_A = None self.conditionally_determined_B = None self.truth_values = tf.placeholder(shape=[None, 1],

为了构建一个测试用例代码,我只想将一个张量传递给一个图,让模型决定是乘以2一次还是两次。该决策基于对布尔值的评估。代码如下:

class what_to_do():
def __init__(self):

    self.conditionally_determined_A = None
    self.conditionally_determined_B = None

    self.truth_values = tf.placeholder(shape=[None, 1],
                                       dtype=tf.bool)
    self.input = tf.placeholder(shape=[None, 1],
                                dtype=tf.float32)

    # The question is, can this statement evaluate the conditional and then direct the
    # implementation of the model's components.
    _ = tf.cond(tf.constant(True),
                lambda: self.real_conditional(),
                lambda: self.fake_condition())

    self.input_A = tf.Variable(initial_value=self.conditionally_determined_A,
                               trainable=False,
                               validate_shape=False)
    self.const_A = tf.constant([2.])
    self.operation_A1 = tf.multiply(self.input_A, self.const_A)

    self.input_B = tf.Variable(initial_value=self.conditionally_determined_B,
                               trainable=False,
                               validate_shape=False)
    self.const_B = tf.constant([2.])
    self.operation_B1 = tf.multiply(self.input_B, self.const_B)

    self.output = self.operation_B1

    # These functions will serve as the condition coordinators for the model
    def real_conditional(self):
        print('in loop')
        self.conditionally_determined_B = self.input
        self.conditionally_determined_A = None
        return 1
    def fake_condition(self):
        print('not in loop')
        self.conditionally_determined_B = None
        self.conditionally_determined_A = self.input
        return 0


tf.reset_default_graph()
model = what_to_do()
data_set = np.array([[2,True], [2,True], [2,True], [2,False], [2,False], [2,False], [2,False]])
i, t = np.split(ary=data_set,
            indices_or_sections=2,
            axis=-1)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)

    output = sess.run(fetches=[model.output],
                  feed_dict={model.input_A:i, model.truth_values:t})
我在试图让tf.cond()处理张量时遇到了麻烦。它抱怨等级和类似问题(也许是另一个问题)

我对代码所做的只是将条件定义为True或False,从而执行正确的函数。如果这是真的,那么图形应该从input_B开始,而不必担心input_A


设置tf.cond()以动态操作图形有什么帮助吗?

请参阅此部分,它解释了tf.cond的行为,并参考了创建副作用。这很有帮助。谢谢。这篇文章解释了tf.cond在产生副作用方面的行为。这很有帮助。谢谢