【问题标题】:how to run apply_gradients for more than one trainable_weights in TensorFlow 2.0如何在 TensorFlow 2.0 中为多个 trainable_weights 运行 apply_gradients
【发布时间】:2021-01-01 17:18:40
【问题描述】:

我已经用 TensorFlow2.0 构建了一个类似于深度学习模型的编码器-解码器,由于某种原因,编码器和解码器是两个独立的模型,我想用 optimizer.apply_gradients() 函数优化这两个模型. TensorFlow document 没有为此案例提供太多信息。它表明grads_and_vars应该是“(梯度,变量)对列表”。我尝试了两种方法,如下所示:

第一种方法: optimizer.apply_gradients(zip(grads, self._encoder.trainable_weights, self._decoder.trainable_weights))

第二种方法: optimizer.apply_gradients([zip(grads, self._encoder.trainable_weights), zip(grads, self._decoder.trainable_weights)])

两者都不起作用。正确的做法是什么?

【问题讨论】:

  • 错误是什么? grads 是如何产生的?

标签: tensorflow keras tensorflow2.0 tensorflow2.x


【解决方案1】:

您可以尝试类似以下代码的训练循环,引用自DCGAN tutorial

with tf.GradientTape() as enc_tape, tf.GradientTape() as dec_tape:
    feature_space = encoder(images, training=True)
    recovered_image = decoder(feature_space, training=True)

    #Some custom loss function...
    loss = tf.keras.losses.MSE(recovered_image, images)

    gradients_of_encoder = enc_tape.gradient(loss , encoder.trainable_variables)
    gradients_of_decoder = dec_tape.gradient(loss, decoder.trainable_variables)

enc_optimizer.apply_gradients(zip(gradients_of_encoder , encoder.trainable_variables))
dec_optimizer.apply_gradients(zip(gradients_of_decoder , decoder.trainable_variables))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2020-06-11
    • 1970-01-01
    • 2018-03-18
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多