代码之家  ›  专栏  ›  技术社区  ›  swmfg

在Tensorflow中不断更改相同的变量

  •  0
  • swmfg  · 技术社区  · 6 年前

    我有一个复杂的用例,我把它归结为在Tensorflow中增加一个变量。

    a = tf.Variable(1, trainable=False)
    b = tf.constant(2)
    a = tf.assign_add(a, b)
    In [32]: type(a)
    Out[32]: tensorflow.python.framework.ops.Tensor
    

    a = tf.Variable(tf.assign(a, b)) 并拥有 a

    1 回复  |  直到 6 年前
        1
  •  1
  •   P-Gn    6 年前

    你想得太多了。 tf.assign_add 返回添加到变量的运算。它还返回结果值的事实只是为了方便变量 影响。

    例子:

    import tensorflow as tf
    
    a = tf.Variable(1, trainable=False)
    b = tf.constant(2)
    c = tf.assign_add(a, b)
    
    sess = tf.InteractiveSession()
    tf.global_variables_initializer().run()
    print(sess.run(a))
    # 1: the original value
    print(sess.run(c))
    # 3: the result of the addition
    print(sess.run(a))
    # 3: OK, the variable has indeed been added to