text
stringlengths 0
4.99k
|
---|
@tf.function
|
def train_step(x, y):
|
with tf.GradientTape() as tape:
|
logits = model(x, training=True)
|
loss_value = loss_fn(y, logits)
|
# Add any extra losses created during the forward pass.
|
loss_value += sum(model.losses)
|
grads = tape.gradient(loss_value, model.trainable_weights)
|
optimizer.apply_gradients(zip(grads, model.trainable_weights))
|
train_acc_metric.update_state(y, logits)
|
return loss_value
|
Summary
|
Now you know everything there is to know about using built-in training loops and writing your own from scratch.
|
To conclude, here's a simple end-to-end example that ties together everything you've learned in this guide: a DCGAN trained on MNIST digits.
|
End-to-end example: a GAN training loop from scratch
|
You may be familiar with Generative Adversarial Networks (GANs). GANs can generate new images that look almost real, by learning the latent distribution of a training dataset of images (the "latent space" of the images).
|
A GAN is made of two parts: a "generator" model that maps points in the latent space to points in image space, a "discriminator" model, a classifier that can tell the difference between real images (from the training dataset) and fake images (the output of the generator network).
|
A GAN training loop looks like this:
|
1) Train the discriminator. - Sample a batch of random points in the latent space. - Turn the points into fake images via the "generator" model. - Get a batch of real images and combine them with the generated images. - Train the "discriminator" model to classify generated vs. real images.
|
2) Train the generator. - Sample random points in the latent space. - Turn the points into fake images via the "generator" network. - Get a batch of real images and combine them with the generated images. - Train the "generator" model to "fool" the discriminator and classify the fake images as real.
|
For a much more detailed overview of how GANs works, see Deep Learning with Python.
|
Let's implement this training loop. First, create the discriminator meant to classify fake vs real digits:
|
discriminator = keras.Sequential(
|
[
|
keras.Input(shape=(28, 28, 1)),
|
layers.Conv2D(64, (3, 3), strides=(2, 2), padding="same"),
|
layers.LeakyReLU(alpha=0.2),
|
layers.Conv2D(128, (3, 3), strides=(2, 2), padding="same"),
|
layers.LeakyReLU(alpha=0.2),
|
layers.GlobalMaxPooling2D(),
|
layers.Dense(1),
|
],
|
name="discriminator",
|
)
|
discriminator.summary()
|
Model: "discriminator"
|
_________________________________________________________________
|
Layer (type) Output Shape Param #
|
=================================================================
|
conv2d (Conv2D) (None, 14, 14, 64) 640
|
_________________________________________________________________
|
leaky_re_lu (LeakyReLU) (None, 14, 14, 64) 0
|
_________________________________________________________________
|
conv2d_1 (Conv2D) (None, 7, 7, 128) 73856
|
_________________________________________________________________
|
leaky_re_lu_1 (LeakyReLU) (None, 7, 7, 128) 0
|
_________________________________________________________________
|
global_max_pooling2d (Global (None, 128) 0
|
_________________________________________________________________
|
dense_4 (Dense) (None, 1) 129
|
=================================================================
|
Total params: 74,625
|
Trainable params: 74,625
|
Non-trainable params: 0
|
_________________________________________________________________
|
Then let's create a generator network, that turns latent vectors into outputs of shape (28, 28, 1) (representing MNIST digits):
|
latent_dim = 128
|
generator = keras.Sequential(
|
[
|
keras.Input(shape=(latent_dim,)),
|
# We want to generate 128 coefficients to reshape into a 7x7x128 map
|
layers.Dense(7 * 7 * 128),
|
layers.LeakyReLU(alpha=0.2),
|
layers.Reshape((7, 7, 128)),
|
layers.Conv2DTranspose(128, (4, 4), strides=(2, 2), padding="same"),
|
layers.LeakyReLU(alpha=0.2),
|
layers.Conv2DTranspose(128, (4, 4), strides=(2, 2), padding="same"),
|
layers.LeakyReLU(alpha=0.2),
|
layers.Conv2D(1, (7, 7), padding="same", activation="sigmoid"),
|
],
|
name="generator",
|
)
|
Here's the key bit: the training loop. As you can see it is quite straightforward. The training step function only takes 17 lines.
|
# Instantiate one optimizer for the discriminator and another for the generator.
|
d_optimizer = keras.optimizers.Adam(learning_rate=0.0003)
|
g_optimizer = keras.optimizers.Adam(learning_rate=0.0004)
|
# Instantiate a loss function.
|
loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)
|
@tf.function
|
def train_step(real_images):
|
# Sample random points in the latent space
|
random_latent_vectors = tf.random.normal(shape=(batch_size, latent_dim))
|
# Decode them to fake images
|
generated_images = generator(random_latent_vectors)
|
# Combine them with real images
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.