Sure! A Conditional Variational Autoencoder (CVAE) is an extension of the Variational Autoencoder (VAE) that allows generating data conditioned on some specific information (called conditioning variables), like labels or other attributes.
🚧 Motivation
A VAE learns a probabilistic model of input data ( x ), by assuming it is generated from a latent variable ( z ). However, if you'd like to generate data conditioned on some known target or label ( y ) (for example, generating digits conditioned on a label like "3" in MNIST), a VAE doesn’t give you that control. This is where a CVAE comes in.
🔁 Generative Process in CVAE
We assume the following generative process:
-
Sample latent variable:
[
z \sim p(z)
]
(usually ( \mathcal{N}(0, I) ))
-
Generate data ( x ) conditioned on ( z ) and extra information ( y ):
[
x \sim p_\theta(x | z, y)
]
🧮 The ELBO Objective in CVAE
We can’t directly maximize the marginal likelihood ( \log p(x | y) ), so we instead optimize the Evidence Lower Bound (ELBO) using variational inference.
We introduce an approximate posterior ( q_\phi(z | x, y) ) and derive:
[
\log p_\theta(x|y) \geq \mathbb{E}{q\phi(z|x, y)}[\log p_\theta(x | z, y)] - \text{KL}(q_\phi(z|x,y) ,|, p(z|y))
]
Assuming prior independent of ( y ) (standard normal):
[
p(z|y) = p(z) = \mathcal{N}(0, I)
]
Then the ELBO becomes:
[
\mathcal{L}{\text{CVAE}}(x, y) = \mathbb{E}{q_\phi(z|x, y)}[\log p_\theta(x | z, y)] - \text{KL}(q_\phi(z|x, y) ,|, \mathcal{N}(0, I))
]
🧠 Intuition Behind the Terms
-
Reconstruction Term:
[
\mathbb{E}{q\phi(z|x, y)}[\log p_\theta(x | z, y)]
]
Ensures that the autoencoder learns to reconstruct ( x ) from ( z ) and ( y ).
-
KL Divergence Term:
[
\text{KL}(q_\phi(z|x, y) | \mathcal{N}(0, I))
]
Ensures that the latent codes remain close to a normal distribution to allow sampling.
🧱 Neural Network Setup
In practice:
-
Encoder:
[
q_\phi(z | x, y) = \mathcal{N}(z | \mu_\phi(x, y), \sigma^2_\phi(x, y))
]
-
Decoder:
[
p_\theta(x | z, y)
]
At both encoder and decoder stages, you concatenate the input ( x ) or latent ( z ) with the condition ( y ) (or embed them if they’re categorical like class labels).
🔁 Sampling and Generation
To generate new data conditioned on ( y ):
- Sample ( z \sim \mathcal{N}(0, I) )
- Feed ( (z, y) ) into the decoder: ( x \sim p_\theta(x | z, y) )
🧮 Summary Equation
The final loss function minimized in training is:
[
\mathcal{L}{\text{CVAE}} = \text{KL}(q\phi(z|x,y) || \mathcal{N}(0,I)) - \mathbb{E}{q\phi(z|x,y)}[\log p_\theta(x|z,y)]
]
This can be implemented using the reparameterization trick:
[
z = \mu + \sigma \odot \epsilon, \quad \epsilon \sim \mathcal{N}(0, I)
]
📌 Applications
CVAE can be used for:
- Conditional image generation (e.g., generating faces with specific features)
- Text generation conditioned on sentiment
- Data imputation with known context
Let me know if you'd like code examples or a diagram to go along with this!