Image generation in deep learning centers on learning low-dimensional latent spaces from which new, realistic images can be sampled. A generator (or decoder) maps latent points to pixel grids, enabling interpolation between concepts and, with text-conditioning, language-guided creation. While impressive, such systems can produce artifacts due to a lack of true physical understanding. Among the main approaches, diffusion models have largely supplanted GANs for high-fidelity synthesis, while variational autoencoders (VAEs) remain valuable for interpretability and controllable latent spaces. The chapter focuses on building unconditioned VAEs and diffusion models from scratch, then demonstrates how to leverage a pretrained text-to-image model and analyze its latent space.
VAEs extend classical autoencoders by encoding inputs into the parameters of a probability distribution (mean and variance) and decoding a sampled latent vector back to the original domain. This stochastic “reparameterization” encourages smooth, well-structured latent manifolds where nearby points decode to similar images, making the space amenable to semantic manipulation. Training optimizes a reconstruction loss plus a KL-divergence regularizer that nudges the latent distribution toward a standard normal. A compact Keras implementation illustrates the full workflow on MNIST digits, culminating in latent-space sampling that smoothly morphs one digit into another and reveals meaningful directions (concept vectors) across the manifold.
Diffusion models recast generation as iterative denoising: starting from pure noise, a shared denoiser (often a U-Net) removes noise step by step according to a diffusion time and schedule (e.g., cosine) that control signal and noise rates. Training teaches the denoiser to predict noise masks under varying noise levels (with normalized inputs and simple losses), while inference repeatedly denoises to produce crisp images. The chapter then extends the idea to text-to-image by conditioning denoising on text embeddings, and shows practical use of a pretrained Stable Diffusion model, including negative prompts and step control. Finally, it explores the text latent space via spherical interpolation between prompts, visually demonstrating how deep models act as powerful interpolation machines across language and vision.
Using a latent vector space to sample new images
Language-guided image generation
An autoencoder: mapping an input x to a compressed representation and then decoding it back as x’
A VAE maps an image to two vectors, z_mean and z_log_sigma, which define a probability distribution over the latent space, used to sample a latent point to decode.
Grid of digits decoded from the latent space
Image super-resolution
Reverse diffusion: turning pure noise into an image via repeated denoising
Cosine relationship between noise rates and signal rates
Our cosine diffusion schedule
Examples of generated flowers
An example output from our Stable Diffusion model.
Controlling the number of diffusion steps.
Spherical interpolation keeps us close to the surface of our manifold.
Interpolating between two prompts and generating outputs.
Chapter summary
Image generation with deep learning is done by learning latent spaces that capture statistical information about a dataset of images. By sampling and decoding points from the latent space, you can generate never-before-seen images. There are three major tools to do this: VAEs, diffusion models, and GANs.
VAEs result in highly structured, continuous latent representations. For this reason, they work well for doing all sorts of image editing in latent space: face swapping, turning a frowning face into a smiling face, and so on. They also work nicely for doing latent-space-based animations, such as animating a walk along a cross section of the latent space, showing a starting image slowly morphing into different images in a continuous way.
Diffusion models result in very realistic outputs and are the dominant method of image generation today. They work by repeatedly denoising an image, starting from pure noise. They can easily be conditioned on text captions in order to create text-to-image models.
Stable Diffusion 3 is a state-of-the-art pretrained text-to-image model that you can use to create highly realistic images of your own.
The visual latent space learned by such text-to-image diffusion models is fundamentally interpolative. You can see this by interpolating between the text embeddings used as inputs to the diffusion process, and achieve a smooth interpolation between images as output.
FAQ
What is a latent space in image generation, and how is it used to create new images?In this chapter, a latent space is a low-dimensional vector space where any point can be decoded into a valid image. A generator/decoder maps latent vectors back to pixel grids. Once learned, you can sample or interpolate points in this space to synthesize new, never-before-seen images that smoothly blend concepts from the training data, and optionally steer them with text conditioning.How do Variational Autoencoders (VAEs) differ from classical autoencoders?Classical autoencoders encode inputs to a fixed code and reconstruct them, but often learn poorly structured, discontinuous latent spaces. VAEs encode inputs into the parameters of a distribution (mean and log-variance), then sample a latent point and decode it. This stochasticity, plus regularization, yields continuous, well-structured latent spaces where nearby points decode to similar images—useful for controlled manipulation.What are z_mean and z_log_var in a VAE, and what is the reparameterization trick?The encoder outputs z_mean and z_log_var, describing a normal distribution in latent space for an input image. The reparameterization trick samples z via z = z_mean + exp(0.5 * z_log_var) * epsilon, with epsilon ~ N(0, I). This keeps sampling differentiable, enabling gradient-based training while injecting useful stochasticity.Which losses are used to train a VAE, and why?Two losses are combined: (1) a reconstruction loss (e.g., pixel-wise binary crossentropy) to make decoded outputs match inputs; and (2) a KL-divergence regularization term that nudges the encoder’s latent distributions toward a standard normal N(0, I). The KL term prevents overfitting and encourages a smooth, continuous latent manifold.How is the VAE implemented with Keras in the chapter?- Encoder: a small ConvNet mapping images to z_mean and z_log_var. - Sampler layer: applies the reparameterization trick to produce z. - Decoder: Conv2DTranspose stack that maps z back to image space. - Training: a custom compute_loss method (backend-agnostic) computes reconstruction + KL; compile with no external loss and fit on MNIST; then sample a grid in the 2D latent space to visualize digit morphing.What are diffusion models, and how do they generate images from pure noise?Diffusion models are denoising autoencoders run in a loop. Starting from pure noise, the model repeatedly predicts and removes a small amount of noise, step by step, until a sharp image emerges. Conceptually, they perform reverse diffusion: transforming white noise into structured images by iteratively denoising.What are “diffusion time” and the “diffusion schedule,” and why use a cosine schedule?- Diffusion time indexes progress through the denoising loop (from high noise to low noise). - The diffusion schedule maps each time to signal and noise rates. A cosine schedule smoothly varies these rates while keeping noise_rate^2 + signal_rate^2 = 1, which stabilizes the mixing of signal and noise during training and sampling.What U-Net denoising architecture is used for diffusion, and why the skip connections?The chapter uses a U-Net with downsampling blocks, a middle stage, and upsampling blocks, plus skip connections from each down block to its mirrored up block. Skip connections preserve spatial detail lost during downsampling and ease reconstruction. The model takes two inputs: noisy images and noise_rates; it predicts a noise mask to subtract.How is the diffusion model trained, and how does sampling (generation) work?Training: normalize images; sample diffusion times; compute noise/signal rates; mix clean images with random noise; predict the noise mask with the U-Net; optimize mean absolute error between true and predicted noise masks. Generation: start from pure noise, iterate denoise steps with the schedule, progressively increasing signal and reducing noise; finally de-normalize and clip image values.How do text-to-image models add text conditioning, and what are negative prompts and latent interpolation?Text-to-image diffusion adds a pretrained text encoder; the denoiser receives both noisy images and text embeddings, guiding denoising toward the caption. Negative prompts provide embeddings of “what to avoid,” steering outputs away from unwanted attributes. To explore the text latent space, you can interpolate between embeddings of two prompts (e.g., via spherical linear interpolation, slerp) and generate a smooth visual morph between their concepts. The chapter demonstrates this using Stable Diffusion via KerasHub.
pro $24.99 per month
access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!