我正在尝试使用 Tensorflow 和 Keras 实现 WGAN-GP 模型(用于来自 kaggle 的信用卡欺诈数据)。
我主要遵循Keras 网站中提供的示例代码和互联网上的其他几个示例代码(但将它们从图像更改为我的数据),它非常简单。
但是当我想更新评论家时,评论家权重的损失梯度nan在几批之后就变成了。这导致评论家的权重变成nan,然后生成器的权重变成nan......所以一切都变成了nan!
我使用tf.debugging.enable_check_numerics并发现问题出现是因为-Inf经过一些迭代后出现在渐变中。
这与损失中的梯度惩罚项直接相关,因为当我删除时,问题就消失了。
请注意,它gp本身不是nan,但是当我得到损失 wrt 评论家权重的梯度(c_grads在下面的代码中)它包含-Inf然后以某种方式变成 all nan。
我检查了数学和网络架构是否存在可能的错误(例如梯度消失的概率等),并检查了我的代码中可能存在的错误数小时。但我被困住了。
如果有人能找到问题的根源,我将不胜感激
注意: 请记住,critic 的输出和损失函数与原始论文略有不同(因为我试图使其有条件)但这与问题无关,因为正如我之前所说,整个问题都消失了当我删除梯度惩罚项时
这是我的批评者:
critic = keras.Sequential([
keras.layers.Input(shape=(x_dim,), name='c-input'),
keras.layers.Dense(64, kernel_initializer=keras.initializers.he_normal(), name='c-hidden-1'),
keras.layers.LeakyReLU(alpha=0.25, name='c-activation-1'),
keras.layers.Dense(32, kernel_initializer=keras.initializers.he_normal(), name='c-hidden-2'),
keras.layers.LeakyReLU(alpha=0.25, name='c-activation-2'),
keras.layers.Dense(2, activation='tanh', name='c-output')
], name='critic')
这是我的梯度惩罚函数:
def gradient_penalty(self, batch_size, x_real, x_fake):
# get the random linear interpolation of real and fake data (x hat)
alpha = tf.random.uniform([batch_size, 1], 0.0, 1.0)
x_interpolated = x_real + alpha * (x_fake - x_real)
with tf.GradientTape() as gp_tape:
gp_tape.watch(x_interpolated)
# Get the critic score for this interpolated data
scores = 0.5 * (self.critic(x_interpolated, training=True) + 1.0)
# Calculate the gradients w.r.t to this interpolated data
grads = gp_tape.gradient(scores, x_interpolated)
# Calculate the norm of the gradients
# Gradient penalty enforces the gradient to stay close to 1.0 (1-Lipschitz constraint)
gp = tf.reduce_mean(tf.square(tf.norm(grads, axis=-1) - 1.0))
return gp
这是评论家的更新代码
# Get random samples from latent space
z = GAN.random_samples((batch_size, self.latent_dim))
# Augment random samples with the class label (1 for class "fraud") for conditioning
z_conditioned = tf.concat([z, tf.ones((batch_size, 1))], axis=1)
# Generate fake data using random samples
x_fake = self.generator(z_conditioned, training=True)
# Calculate the loss and back-propagate
with tf.GradientTape() as c_tape:
c_tape.watch(x_fake)
c_tape.watch(x_real)
# Get the scores for the fake data
output_fake = 0.5 * (self.critic(x_fake) + 1.0)
score_fake = tf.reduce_mean(tf.reduce_sum(output_fake, axis=1))
# Get the scores for the real data
output_real = 0.5 * (self.critic(x_real, training=True) + 1.0)
score_real = tf.reduce_mean((1.0 - 2.0 * y_real) * (output_real[:, 0] - output_real[:, 1]))
# Calculate the gradient penalty
gp = self.gp_coeff * self.gradient_penalty(batch_size, x_real, x_fake)
# Calculate critic's loss (added 1.0 so its ideal value becomes zero)
c_loss = 1.0 + score_fake - score_real + gp
# Calculate the gradients
c_grads = c_tape.gradient(c_loss, self.critic.trainable_weights)
# back-propagate the loss
self.c_optimizer.apply_gradients(zip(c_grads, self.critic.trainable_weights))
另请注意:如您所见,我不使用任何交叉熵或其他自写函数,有被零除的风险。
