可以使用tf.cond()动态定义图

时间:2019-02-15 20:00:32

标签: 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],
                                       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,从而执行适当的功能。如果为True,则图形应从input_B开始,而不用担心input_A。

是否需要设置tf.cond()来动态处理图形?

0 个答案:

没有答案