【问题标题】:How to use complex variables in TensorFlow eager mode?如何在 TensorFlow Eager 模式下使用复杂变量?
【发布时间】:2019-09-22 19:45:08
【问题描述】:

在非急切模式下,我可以毫无问题地运行它:

s = tf.complex(tf.Variable(1.0), tf.Variable(1.0))
train_op = tf.train.AdamOptimizer(0.01).minimize(tf.abs(s))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(5):
        _, s_ = sess.run([train_op, s])
        print(s_)

>(1+1j)
(0.99+0.99j)
(0.98+0.98j)
(0.9700001+0.9700001j)
(0.9600001+0.9600001j)

但我似乎无法在急切模式下找到等效的表达式。我尝试了以下方法,但 TF 抱怨:

tfe = tf.contrib.eager
s = tf.complex(tfe.Variable(1.0), tfe.Variable(1.0))
def obj(s):
    return tf.abs(s)
with tf.GradientTape() as tape:
    loss = obj(s)
    grads = tape.gradient(loss, [s])
    optimizer.apply_gradients(zip(grads, [s]))

调用 GradientTape.gradient 时源张量的 dtype 必须是浮动的(例如tf.float32),得到tf.complex64

没有为任何变量提供渐变:['tf.Tensor((1+1j), shape=(), dtype=complex64)']

如何在 Eager 模式下训练复杂变量?

【问题讨论】:

    标签: python tensorflow eager-execution


    【解决方案1】:

    使用 Tensorflow 2 中的 Eager 模式,可以将实部和虚部作为实变量:

    r, i = tf.Variable(1.0), tf.Variable(1.0)
    def obj(s):
        return tf.abs(s)
    with tf.GradientTape() as tape:
        s = tf.complex(r, i)
        loss = obj(s)
        grads = tape.gradient(loss, [r, i])
        optimizer.apply_gradients(zip(grads, [r, i]))
    

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多