Autoencoders, VAE and GAN
This lecture compresses high-dimensional inputs with autoencoders and then builds generative models. It covers bottleneck coding, reconstruction loss, VAE sampling with KL regularization, and the GAN minimax game. After this page you can compute MSE, reparameterization, KL, and GAN value numbers by hand.
Curse of dimensionalitySearch on YouTube
High-dimensional data often contains redundant features. Redundant features carry almost the same information. It also contains irrelevant features. Irrelevant features add noise and carry no signal. It also contains random variation from measurement errors.
As the feature count grows, the volume of the feature space grows fast. Data points become sparse in that huge volume. Sparse data shows few examples per dimension. Models that use distance or density then struggle. kNN, clustering, and neural networks all suffer.
Fewer dimensions give smaller matrices and faster distance computations. They need less memory and less storage. They also work with simpler models. The gain is large for images, text embeddings, and genomics.
Autoencoder structureSearch on YouTube
An autoencoder is a neural network that copies its input to its output through a narrow middle. It has three parts: encoder, bottleneck layer, and decoder. The bottleneck layer (also called code) holds the latent vector. After this point the page uses only "latent vector" and "bottleneck layer".
The encoder maps the input to the latent vector. The bottleneck layer stores that compressed form. The decoder rebuilds the input from it.
Think of a summary note. You compress a long chapter into half a page. Then a friend rebuilds the chapter from your note alone.
Encoder, bottleneck, and decoderSearch on YouTube
The encoder transforms input of dimensions into . The vector lies in a reduced latent space. The bottleneck layer is that compressed form. It keeps the most salient features in fewer dimensions. The decoder maps it back as . Encoding layers can be dense or convolutional. The choice depends on the input type and the task.
= encoder weight matrix. = encoder bias vector. = decoder weight matrix. = decoder bias vector. = activation function (sigmoid, ReLU, or tanh). = latent vector at the bottleneck layer.
| Method | Mapping | Handles nonlinear data |
|---|---|---|
| PCA | Linear projection only | No |
| Autoencoder | Weighted sums plus activation functions | Yes |
PCA applies only linear transformations. It fails on complex nonlinear distributions. Autoencoders apply activation functions to weighted inputs. They learn nonlinear mappings and richer low-dimensional codes.
Worked example. Image input dims. Bottleneck layer has units. Weights use float32 (4 bytes each).
Compression ratio.
Memory per sample.
Encoder size.
The bottleneck layer stores 24.5 times fewer numbers than the input.
Reconstruction lossSearch on YouTube
The decoder aims to make match . Reconstruction loss measures that gap. Training minimizes it over the training set. The slides name two loss functions. The choice depends on the data type.
= true value of feature . = reconstructed value. = input dimension. Use it for continuous values such as pixel intensities.
= true binary value (0 or 1). = predicted probability in . Use it for binary or probability outputs.
Compression, inpainting, and denoisingSearch on YouTube
Autoencoders compress data for transmission over a network. The encoder sends only the latent vector. That step cuts bandwidth needs. The decoder at the receiving end rebuilds the input, for example a downscaled image. They also restore damaged inputs. In inpainting, the model fills missing patches. In denoising, it removes noise from corrupted inputs.
Worked example. True vector . Reconstruction .
Squared gaps.
Mean.
Exam shortcut: for MSE, square each gap first and keep four decimals. Then add and divide by . For BCE with , the term is . For , the term is .
Limit of deterministic autoencodersSearch on YouTube
A standard autoencoder maps each input to one fixed point . Decoding that point always gives the same output. It cannot create diverse new samples. It also learns no smooth latent space. Nearby latent vectors need not decode to similar outputs. It does not model the probability distribution of the data. Its deterministic nature gives poor generative ability.
Variational autoencodersSearch on YouTube
A variational autoencoder (VAE) maps each input to a distribution. For each latent dimension, the encoder outputs two parts: a mean part and a standard deviation part. They define a Gaussian distribution. A sample from that distribution feeds the decoder.
Replace a fixed address with a delivery zone. Each input marks a zone (mean) with a size (spread). Each visit picks a random door inside the zone.
Because codes are probabilistic, nearby latent vectors can decode to similar outputs. Two close face codes may show visually similar faces. A VAE can shift a neutral face toward a smile. But it does not know the smile direction by itself. That direction must be learned or found by search.
VAE encoder outputsSearch on YouTube
= learned latent distribution for input . = encoder mean output per latent dimension. = encoder standard deviation output per latent dimension. = prior, usually standard normal.
Do not confuse the two uses of . In it is the activation function. In it is the standard deviation. Read the symbol from context.
VAE lossSearch on YouTube
The VAE loss has two terms. The first rebuilds the input. The second pulls the learned distribution toward the prior.
= reconstruction loss (MSE or BCE between and ). = KL divergence loss between and .
The KL term measures the gap between and the prior . It regularizes the latent space. The space then stays close to standard normal. That property allows smooth interpolation and sampling of new faces. For one Gaussian dimension against :
= learned mean. = learned standard deviation. = natural log. Sum over latent dimensions for a vector code.
R plus K: Reconstruction plus KL
Reconstruction rebuilds the input. KL pulls the code toward the prior. Memorize loss = R K.
Worked example. One latent dimension with , .
Squares and log.
KL value.
Recheck: . Then . Half of is .
Reparameterization trickSearch on YouTube
Sampling blocks gradients. The sampling node is stochastic. Backpropagation cannot pass through it. The reparameterization trick rewrites sampling with outside noise. Gradients then flow through and .
= latent sample fed to the decoder. = encoder outputs (learned). = noise from standard normal (not learned). Gradients flow through and around the noise.
Worked example. Encoder gives , . Draw gives .
Sample.
Two-dimensional check. , , .
Recheck: , plus gives . And , so .
Exam wording: "gradients flow through and " gets full credit. Add that needs no training. Then write with .
Generative models and GAN rolesSearch on YouTube
A discriminative model learns . It gives the label for input . It learns the decision boundary. Logistic regression, support vector machines, and neural network classifiers are examples. They serve classification and regression.
A generative model learns the joint distribution . It can also learn the data distribution . It can then create new points like the training data. Naive Bayes, hidden Markov models, VAEs, and GANs are examples.
= conditional probability of label given input . = joint distribution learned by generative models. = data distribution. Bayes' theorem links the two views.
Generator and discriminatorSearch on YouTube
A GAN holds a generator () and a discriminator (). Both are neural networks. They train together in a minimax game. The generator () takes random noise and makes fake data. The discriminator () is a binary classifier. It separates real training data from fake generator data.
The true distribution is high-dimensional and complex. The generator takes noise from a simple known . Its weights map noise to samples . Those outputs follow , the fake distribution. The goal is .
The generator never sees real data directly. It learns only through the discriminator feedback signal. Over many epochs, its noise-to-sample map improves. At the end, its samples look real.
G fakes, D judges
Generator fakes data from noise. Discriminator judges real against fake. Training ends when the judge guesses at chance.
GAN value functionSearch on YouTube
The discriminator outputs a probability. The value is the chance that the input is real. maximizes correct real/fake calls. minimizes the ability of to detect fakes. That conflict gives the value function .
= real sample. = noise sample. = score that real input is real. = score that fake input is real. = mean over the named distribution.
It matches binary cross-entropy. For one data point:
= true label ( = real, = fake). = discriminator score. For real data and . For fake data and .
Averaging both groups gives the same form as up to the factor of two. wants large . wants small .
Worked example. One real sample scores . One fake sample scores .
GAN value.
BCE link.
Recheck: and . Sum is . Half is . And .
Alternating trainingSearch on YouTube
Training alternates two steps. Each step freezes one network.
- Freeze . Update the discriminator with gradient ascent on . Use a minibatch of real and fake samples.
- Freeze . Update the generator with gradient descent on . This step raises for fresh fakes.
- Repeat until . Then cannot separate real from fake.
= distribution of generator outputs. = true training distribution. Training stops when the two match and guesses at chance.
Worked example. Trace two updates from above.
D update (freeze G). rises . Fake score falls .
G update (freeze D). Generator improves. Fake score rises .
rose under the step (). It fell under the step (). That rise-then-fall is the minimax pattern.
Do not swap the update directions. uses gradient ascent because it maximizes . uses gradient descent because it minimizes . Keep fixed during the step.
Train one GAN round by hand in the lab. Freeze G to raise V, then freeze D to lower it. Then move to the VAE tab and push the code toward the prior.
Bars show discriminator scores for real and fake samples. The dashed line marks the judge threshold.
V = log 0.8 + log 0.7 = -0.2231 + (-0.3567) = -0.5798 | judge accuracy 100%
Quick self-testSearch on YouTube
1. An input has pixels and a bottleneck layer of units. Find the compression ratio and the latent memory in float32.
Input has dims. Ratio is . Latent memory is bytes against bytes.
2. True values are and reconstructions are . Compute the MSE.
Squared gaps are and . MSE is .
3. Differentiate PCA and autoencoders for dimensionality reduction.
PCA uses only linear projections. Autoencoders add activation functions to weighted sums. So autoencoders capture nonlinear structure and PCA does not.
4. Encoder gives , , and draw . Find the latent sample .
.
5. Encoder gives , . Compute the single-dimension KL against standard normal.
, , . KL is . The learned code already matches the prior.
6. Why does VAE training need the reparameterization trick?
Direct sampling blocks backpropagation at the stochastic node. The trick writes . Gradients then flow through and while stays fixed noise.
7. Real score and fake score . Compute for this pair.
. Both terms agree here because .
8. Differentiate the generator and the discriminator. Which one sees real data?
The generator fakes data from noise and never sees real samples. The discriminator judges real against fake and sees both. Only the discriminator touches real data directly.
9. Why does a standard autoencoder generate poorly while a VAE can generate?
A standard autoencoder stores one fixed point per input with no smooth space. The VAE regularizes codes toward with the KL term. Sampling that smooth space gives new valid outputs.
10. In one GAN round, moves from to and then to . Which step belongs to and which to ?
The rise to belongs to the step (gradient ascent on ). The fall to belongs to the step (gradient descent on ).
- High dimensions cause sparsity: volume grows fast and distance-based models struggle.
- PCA is linear only. Autoencoders add activation functions and learn nonlinear codes.
- Encoder maps to . Bottleneck layer stores the latent vector. Decoder rebuilds .
- Example shrinks dims to (ratio , bytes to bytes).
- Reconstruction loss is MSE for continuous values and BCE for binary or probability values.
- MSE example against gives .
- Uses: compression for transmission, inpainting of missing parts, denoising of corrupted inputs.
- Standard autoencoders are deterministic and generate poorly.
- VAE outputs and , samples , and keeps a smooth latent space.
- VAE loss = R K: reconstruction plus KL against the prior.
- Reparameterization lets gradients flow through and .
- KL example , gives .
- GAN: G fakes from noise, D judges real against fake, with at convergence.
- Value matches BCE.
- GAN pair and gives and mean BCE .
- Train alternately: ascends with fixed, descends with fixed.
Variational Autoencoders Animated
Variational Autoencoder Explained
GANs
GANs Explained