# Build and compile the discriminator self.discriminator = self.build_discriminator() self.discriminator.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
# Build the generator self.generator = self.build_generator()
# The generator takes noise as input and generates imgs z = Input(shape=(self.latent_dim,)) img = self.generator(z)
# For the combined model we will only train the generator self.discriminator.trainable = False
# The discriminator takes generated images as input and determines validity validity = self.discriminator(img)
# The combined model (stacked generator and discriminator) # Trains the generator to fool the discriminator self.combined = Model(z, validity) self.combined.compile(loss='binary_crossentropy', optimizer=optimizer)
缩小上面代码的范围,看这一行:
1 2
# For the combined model we will only train the generator self.discriminator.trainable = False
# Train the generator (to have the discriminator label samples as valid) g_loss = self.combined.train_on_batch(noise, valid)
看!代码中出现了# Train the discriminator的步骤!
不是说之前已经设置为判别器为不可训练状态了吗?
emm~
解决问题
经过一番搜索,终于找到了答案
1
By setting trainable=False after the discriminator has been compiled the discriminator is still trained during discriminator.train_on_batch but since it's set to non-trainable before the combined model is compiled it's not trained during combined.train_on_batch
When you call compile, it builds a trainable model, and uses the current trainable flags. A compiled model can then not have its trainable flags changed, so we are free to change them and compile another model with different flags.
Then, for some reason, those two compiled models can still have the same weights (I guess?) even though tensorflow/keras still sees them as clearly separated things.