Tensorflow渴望执行-嵌套渐变磁带

时间:2018-10-29 14:01:34

标签: tensorflow keras eager

我一直在使用传统的图形实现在TensorFlow上测试我的WGAN-GP算法。最近,我碰巧认识了TensorFlow Eager Execution,并试图将我的代码转换为在急切的执行模式下运行。

让我先向您展示之前的代码:

self.x_ = self.g_net(self.z)
self.d  = self.d_net(self.x, reuse=False)
self.d_ = self.d_net(self.x_)

self.d_loss = tf.reduce_mean(self.d) - tf.reduce_mean(self.d_)

epsilon = tf.random_uniform([], 0.0, 1.0)

x_hat = epsilon * self.x + (1 - epsilon) * self.x_
d_hat = self.d_net(x_hat)

ddx = tf.gradients(d_hat, x_hat)[0]
ddx = tf.sqrt(tf.reduce_sum(tf.square(ddx), axis=1))
ddx = tf.reduce_mean(tf.square(ddx - 1.0) * scale)

self.d_loss = self.d_loss + ddx

self.d_adam = tf.train.AdamOptimizer().minimize(self.d_loss, var_list=self.d_net.vars)

然后将其转换为:

self.x_ = self.g_net(self.z)

epsilon = tf.random_uniform([], 0.0, 1.0)

x_hat = epsilon * self.x + (1 - epsilon) * self.x_

with tf.GradientTape(persistent=True) as temp_tape:
    temp_tape.watch(x_hat)
    d_hat = self.d_net(x_hat)

ddx = temp_tape.gradient(d_hat, x_hat)[0]
ddx = tf.sqrt(tf.reduce_sum(tf.square(ddx), axis=1))
ddx = tf.reduce_mean(tf.square(ddx - 1.0) * 10)

with tf.GradientTape() as d_tape:
    d  = self.d_net(x)
    d_ = self.d_net(x_)

    loss_d = tf.reduce_mean(d) - tf.reduce_mean(d_) + ddx

grad_d = d_tape.gradient(loss_d, self.d_net.variables)

self.d_adam.apply_gradients(zip(grad_d, self.d_net.variables))

我尝试了几种替代方法来实现WGAN-GP丢失,但无论如何d_loss都是不同的!我希望有人可以指出我的错误来启发我。

此外,我想知道是否可以在以前的损失和优化程序实现中使用Keras层。预先谢谢你!

0 个答案:

没有答案