【问题标题】:Create counter in tensorflow graph在张量流图中创建计数器
【发布时间】:2017-09-01 08:10:58
【问题描述】:

我想在图表中创建一个计数器。每当函数运行时,它都会增加。这是我现在正在尝试的。有任何想法吗?

# init variable
tf_i = tf.Variable(1, name='v', dtype=tf.int32, expected_shape=())

# init assign op
tf_i_plus_one = tf.assign_add(tf_i, 1)
sess.run(tf.global_variables_initializer())

# simple test fx
def test(x):
    v = tf.get_variable('v', shape=())
    return x + v

# run test fx
z = tf.placeholder(tf.float32, shape=(), name='z')
out = test(z)

print(sess.run(out, feed_dict={z: 4}))
sess.run(tf_i_plus_one)

print(sess.run(out, feed_dict={z: 4}))

我现在得到:

Attempting to use uninitialized value v_1

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    如果您想要的只是一个函数的计数器,请尝试以下操作:

    def wrap_with_counter(fn, counter):
        def wrapped_fn(*args, **kwargs):
            # control_dependencies forces the assign op to be run even if we don't use the result
            with tf.control_dependencies([tf.assign_add(counter, 1)]):
                return fn(*args, **kwargs)
        return wrapped_fn
    

    示例用法:

    dense_counter = tf.get_variable(
        dtype=tf.int32, shape=(), name='dense_counter',
        initializer=tf.zeros_initializer())
    wrapped_dense = wrap_with_counter(tf.layers.dense, dense_counter)
    
    
    batch_size = 4
    n_features = 8
    # dummy input
    x = tf.random_normal(
        shape=(batch_size, n_features), dtype=tf.float32, name='x')
    
    out = wrapped_dense(x, 1)
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        c0 = sess.run(dense_counter)
        print(c0)  # 0
        sess.run(out)
        c1 = sess.run(dense_counter)
        print(c1)  # 1
    

    【讨论】:

    • 谢谢。超级有帮助。但是,为了了解 tf 如何处理图中的变量分配或更新,您对此有何见解?
    • 根据经验,在实例化会话/进行变量初始化之前完全构建图表。您在上面遇到的错误让我感到惊讶 - 我本来预计会更像Variable v already exists, disallowed,但是如果您将图形构建与会话运行分开,事情就会更加可预测。 tf.assign_add 返回一个表示更新结果的张量,但如果该结果不依赖于您在会话中调用的任何内容,它将不会运行,因此不会运行更新。添加tf.control_dependencies 是一种解决方法。
    • 我可以在Dateset map/filter/apply 函数中使用类似的东西来获取增量变量(例如global_step)吗?见stackoverflow.com/questions/60882387/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2019-10-31
    • 2016-06-23
    • 2018-05-28
    • 2016-05-29
    • 2020-06-27
    相关资源
    最近更新 更多