如何在 Tensorflow 中异步更新 GAN 生成器和鉴别器?

How to update GAN Generator and Discriminator asynchronously in Tensorflow?

我想用 Tensorflow 开发一个 GAN,生成器是一个自动编码器,鉴别器是一个具有二进制输出的卷积神经网络。开发自动编码器和 CNN 没有问题,但我的想法是为每个组件(鉴别器和生成器)训练 1 个 epoch,并重复这个循环 1000 个 epoch,保持前一个训练 epoch 的结果(权重)为下一个。我该如何操作它?

如果你有两个名为 train_step_generatortrain_step_discriminator 的操作(例如,每个操作都是 tf.train.AdamOptimizer().minimize(loss) 的形式,每个操作都有适当的损失),那么你的训练循环应该类似于以下结构:

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(1000):
        if epoch%2 == 0: # train discriminator on even epochs
            for i in range(training_set_size/batch_size):
                z_ = np.random.normal(0,1,batch_size) # this is the input to the generator
                batch = get_next_batch(batch_size)
                sess.run(train_step_discriminator,feed_dict={z:z_, x:batch})
        else: # train generator on odd epochs
            for i in range(training_set_size/batch_size):
                z_ = np.random.normal(0,1,batch_size)  # this is the input to the generator
                sess.run(train_step_generator,feed_dict={z:z_})

权重将在迭代之间保持不变。

我解决了这个问题。其实我是想让autoencoder的输出作为CNN的输入,连接GAN,按照1:1的比例更新权重。我注意到我必须特别注意区分生成器和鉴别器的损失,否则在第二个循环开始时,生成器的张量损失将被浮点数替换,这是鉴别器产生的最后一个损失。

代码如下:

with tf.Session() as sess:
sess.run(init)
for i in range(1, num_steps+1):

这里是生成器训练

    batch_x, batch_y=next_batch(batch_size, x_train_noisy, x_train)        
    _, l = sess.run([optimizer, loss], feed_dict={X: batch_x.reshape(n,784),
                    Y:batch_y})
    if i % display_step == 0 or i == 1:
        print('Epoch %i: Denoising Loss: %f' % (i, l))

此处生成器的输出将用作鉴别器的输入

    output=sess.run([decoder_op],feed_dict={X: x_train})
    x_train2=np.array(output).reshape(n,784).astype(np.float64)

这里是判别器训练

    batch_x2, batch_y2 = next_batch(batch_size, x_train2, y_train)
    sess.run(train_op, feed_dict={X2: batch_x2.reshape(n,784), Y2: batch_y2, keep_prob: 0.8})
    if i % display_step == 0 or i == 1:
        loss3, acc = sess.run([loss_op2, accuracy], feed_dict={X2: batch_x2,
                                                             Y2: batch_y2,
                                                             keep_prob: 1.0})
        print("Epoch " + str(i) + ", CNN Loss= " + \
              "{:.4f}".format(loss3) + ", Training Accuracy= " + "{:.3f}".format(acc))

这样异步更新可以按1:1、1:5、5:1(判别器:生成器)或任何其他方式

进行操作