gpt4 book ai didi

python-3.x - 批量标准化在 tensorflow 2.0 中没有梯度?

转载 作者:行者123 更新时间:2023-12-04 00:49:03 24 4
gpt4 key购买 nike

我正在尝试制作一个简单的 GAN 来从 MNIST 数据集中生成数字。然而,当我开始训练(这是自定义的)时,我收到了这个烦人的警告,我怀疑这是我没有像以前那样训练的原因。

请记住,这一切都在 tensorflow 2.0 中使用它的默认急切执行。

获取数据(不是那么重要)

(train_images,train_labels),(test_images,test_labels) = tf.keras.datasets.mnist.load_data()

train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]

BUFFER_SIZE = 60000
BATCH_SIZE = 256

train_dataset = tf.data.Dataset.from_tensor_slices((train_images,train_labels)).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)

GENERATOR MODEL(这是批量标准化所在的地方)
def make_generator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())

model.add(tf.keras.layers.Reshape((7, 7, 256)))
assert model.output_shape == (None, 7, 7, 256) # Note: None is the batch size

model.add(tf.keras.layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))
assert model.output_shape == (None, 7, 7, 128)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())

model.add(tf.keras.layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
assert model.output_shape == (None, 14, 14, 64)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())

model.add(tf.keras.layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 28, 28, 1)

return model

鉴别器模型(可能不那么重要)
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same'))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))

model.add(tf.keras.layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1))

return model

实例化模型(可能不那么重要)
generator = make_generator_model()
discriminator = make_discriminator_model()

定义损失(也许生成器损失很重要,因为这是梯度的来源)
def generator_loss(generated_output):
return tf.nn.sigmoid_cross_entropy_with_logits(labels = tf.ones_like(generated_output), logits = generated_output)


def discriminator_loss(real_output, generated_output):
# [1,1,...,1] with real output since it is true and we want our generated examples to look like it
real_loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(real_output), logits=real_output)

# [0,0,...,0] with generated images since they are fake
generated_loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(generated_output), logits=generated_output)

total_loss = real_loss + generated_loss

return total_loss

制作优化器(可能不重要)
generator_optimizer = tf.optimizers.Adam(1e-4)
discriminator_optimizer = tf.optimizers.Adam(1e-4)

发电机的随机噪声(可能不重要)
EPOCHS = 50
noise_dim = 100
num_examples_to_generate = 16

# We'll re-use this random vector used to seed the generator so
# it will be easier to see the improvement over time.
random_vector_for_generation = tf.random.normal([num_examples_to_generate,
noise_dim])

一个单一的火车步骤(这是我得到错误的地方
def train_step(images):
# generating noise from a normal distribution
noise = tf.random.normal([BATCH_SIZE, noise_dim])

with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images[0], training=True)
generated_output = discriminator(generated_images, training=True)

gen_loss = generator_loss(generated_output)
disc_loss = discriminator_loss(real_output, generated_output)

This line >>>>>

gradients_of_generator = gen_tape.gradient(gen_loss, generator.variables)

<<<<< This line

gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.variables)

generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.variables))
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.variables))

完整的火车(不重要,除了它调用 train_step)
def train(dataset, epochs):  
for epoch in range(epochs):
start = time.time()

for images in dataset:
train_step(images)

display.clear_output(wait=True)
generate_and_save_images(generator,
epoch + 1,
random_vector_for_generation)

# saving (checkpoint) the model every 15 epochs
if (epoch + 1) % 15 == 0:
checkpoint.save(file_prefix = checkpoint_prefix)

print ('Time taken for epoch {} is {} sec'.format(epoch + 1,
time.time()-start))
# generating after the final epoch
display.clear_output(wait=True)
generate_and_save_images(generator,
epochs,
random_vector_for_generation)


开始训练
train(train_dataset, EPOCHS)

我得到的错误如下,
W0330 19:42:57.366302 4738405824 optimizer_v2.py:928] Gradients does 
not exist for variables ['batch_normalization_v2_54/moving_mean:0',
'batch_normalization_v2_54/moving_variance:0',
'batch_normalization_v2_55/moving_mean:0',
'batch_normalization_v2_55/moving_variance:0',
'batch_normalization_v2_56/moving_mean:0',
'batch_normalization_v2_56/moving_variance:0'] when minimizing the
loss.

我从生成器中得到一个图像,如下所示:
enter image description here

如果没有标准化,这有点像我所期望的。一切都会聚集到一个角落,因为存在极端值。

最佳答案

问题在这里:

gradients_of_generator = gen_tape.gradient(gen_loss, generator.variables)

您应该只获得可训练变量的梯度。所以你应该把它改成
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)

以下三行也是如此。 variables字段包括诸如在推理过程中使用的运行平均值批处理规范之类的东西。因为在训练期间没有使用它们,所以没有定义合理的梯度,尝试计算它们会导致崩溃。

关于python-3.x - 批量标准化在 tensorflow 2.0 中没有梯度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55434653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com