# Variational Autoencoder (VAE)

Author: Fanyi Pu

Published: 2026-08-29

Canonical: <https://pufanyi.com/blog/ml/ml-revisit/ae/ml-revisit-vae>

Notes for Variational Autoencoder (VAE)

最开始的文章是 ([Kingma & Welling, 2014](https://pufanyi.com/blog/ml/ml-revisit/ae/ml-revisit-vae#bib-kingma2014autoencoding))。

苏神博客亦有记载：([苏剑林, 2018](https://pufanyi.com/blog/ml/ml-revisit/ae/ml-revisit-vae#bib-kexuefm-5253)a, [2018](https://pufanyi.com/blog/ml/ml-revisit/ae/ml-revisit-vae#bib-kexuefm-5343)b)。

其他参考资料：([Grover & Ermon, 2018](https://pufanyi.com/blog/ml/ml-revisit/ae/ml-revisit-vae#bib-grover2018vae))。

给定样本 $x_i$，后验分布 $p_{\phi}(z\mid x_i)\sim \mathcal{N}(\mu_i, \sigma^2_i I)$。其中我们希望 $p_\phi(z)\sim\mathcal{N}(0, I)$。

构建网络 $\left<\mu_k, \log \sigma_k^2\right>=\phi(x_i)$。

如果酱紫直接训的话，因为取正态分布的时候会带来噪声，所以模型肯定是希望 $\sigma^2_k$ 越小越好，逐渐的会退化为普通的 autoencoder。

所以我们希望 $p_\phi(z)\sim\mathcal{N}(0, I)$，这样子加上一个

$$
\begin{aligned}
\mathcal{L}_{\mu, \sigma^2} &= D_\mathrm{KL}\left(\mathcal{N}(\mu, \sigma^2)\Vert\mathcal{N}(0, 1)\right)\\
&=\frac{1}{2}(-\log\sigma^2+\mu^2+\sigma^2-1)
\end{aligned}
$$

就行。

然后写代码的时候有个 reparameterization trick，其实就是如果我们算出 $\mu_i$ 和 $\sigma_i^2$ 然后采样，那么是不可导的。方法其实就是 $\mathcal{N}(\mu, \sigma^2 I)\sim \sigma\times\mathcal{N}(0, I)+\mu$ 就行。

## References

Grover, A., & Ermon, S. (2018). *Variational Autoencoders*. Stanford CS236: Deep Generative Models Lecture Notes. [deepgenerativemodels.github.io](https://deepgenerativemodels.github.io/notes/vae/ "https://deepgenerativemodels.github.io/notes/vae/")

Kingma, D. P., & Welling, M. (2014). Auto-Encoding Variational Bayes. *International Conference on Learning Representations*. [doi.org](https://doi.org/10.48550/arXiv.1312.6114 "https://doi.org/10.48550/arXiv.1312.6114")

苏剑林. (2018a, March). 变分自编码器（一）：原来是这么一回事. [spaces.ac.cn](https://spaces.ac.cn/archives/5253 "https://spaces.ac.cn/archives/5253")

苏剑林. (2018b, March). 变分自编码器（二）：从贝叶斯观点出发. [spaces.ac.cn](https://spaces.ac.cn/archives/5343 "https://spaces.ac.cn/archives/5343")
