<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zeromathai on Medium]]></title>
        <description><![CDATA[Stories by Zeromathai on Medium]]></description>
        <link>https://medium.com/@zeromathai?source=rss-06739e04ea2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aGImdCv9gOKsc_G4</url>
            <title>Stories by Zeromathai on Medium</title>
            <link>https://medium.com/@zeromathai?source=rss-06739e04ea2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:20:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zeromathai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How Variational Autoencoders Generate Data: From Latent Distributions to Probabilistic Decoders]]></title>
            <link>https://medium.com/@zeromathai/https-zeromathai-com-en-vae-probabilistic-generation-course-en-9904c06151ae?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9904c06151ae</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Sat, 05 Dec 2026 04:56:01 GMT</pubDate>
            <atom:updated>2026-12-05T04:56:01.455Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at:<br><a href="https://zeromathai.com/en/vae-probabilistic-generation-course-en/">https://zeromathai.com/en/vae-probabilistic-generation-course-en/</a></p><p>An autoencoder can compress an image into a handful of numbers and reconstruct it. But what happens when we give its decoder a completely new set of numbers? There is no guarantee that the result will resemble anything meaningful.</p><p>This illustrates a fundamental difference between learning a representation and learning a generative model. A representation can preserve the important characteristics of existing data without providing a reliable mechanism for generating new data.</p><p>A Variational Autoencoder (VAE) addresses this problem by treating latent-variable inference and data generation as probabilistic processes. Instead of encoding an observation into a fixed point, it defines a distribution over latent variables. Instead of decoding a latent variable into a predetermined output, it defines a conditional probability distribution over possible observations.</p><p>A shared prior distribution and a joint learning objective connect these two processes.</p><p>## **Why Reconstruction Alone Is Not Enough**</p><p>Consider a 28 × 28 MNIST handwritten digit image. Although the image contains 784 pixels, much of its meaningful structure can be described through characteristics such as stroke direction, thickness, and slant. An autoencoder attempts to capture these characteristics using a lower-dimensional representation.</p><p>Suppose an encoder represents an image using the vector:</p><p>[2.1, 0.8]</p><p>The original image now corresponds to a point in a two-dimensional latent space.</p><p>Ideally, images with similar characteristics occupy nearby regions, while images with different characteristics occupy distinguishable regions. Such an arrangement can be useful for classification and similarity-based retrieval.</p><p>However, a latent space organized for reconstruction is not necessarily organized for generation. Imagine that handwritten ones occupy one region of the latent space and handwritten sevens occupy another. Between these regions, there may be locations that the decoder has rarely encountered during training. Sampling from those locations could produce meaningless images.</p><p>For generative modeling, two properties become particularly important:</p><p>- **Latent space continuity:** Nearby latent variables should produce similar outputs, allowing generated data to change gradually as latent variables change.<br>- **Latent space completeness:** Regions that are likely to be sampled should reliably produce meaningful outputs.</p><p>A VAE encourages these properties by changing how observations are encoded and how their latent distributions are organized.</p><p>## **From Fixed Coordinates to Probability Distributions**</p><p>A conventional autoencoder uses deterministic encoding. Given the same input, its encoder produces the same latent vector. If an image is encoded at coordinate 2.0, the decoder learns to reconstruct that image primarily from that particular coordinate.</p><p>A VAE replaces this fixed representation with a probability distribution.</p><p>Suppose an encoder defines a Gaussian distribution with a mean of 2.0 and a standard deviation of 0.3. For the same input and fixed encoder parameters, the distribution parameters remain unchanged. Sampling repeatedly from that distribution, however, can produce different latent values, such as 1.8, 2.1, or 2.3.</p><p>The decoder learns to explain the observation using multiple latent values rather than relying on a single coordinate. This approach is known as stochastic encoding.</p><p>In a typical Gaussian VAE, the encoder defines a multivariate Gaussian distribution with diagonal covariance:</p><p>q(z ∣ x; φ) = 𝒩(z; μ(x; φ), diag(σ²(x; φ)))</p><p>Here:</p><p>- x is the observed input.<br>- z is the latent variable.<br>- φ represents the encoder’s trainable parameters.<br>- μ(x; φ) is the latent mean vector.<br>- σ²(x; φ) is the vector of latent variances.</p><p>The diag operation places the individual variances along the diagonal of the covariance matrix. Under this Gaussian parameterization, the latent dimensions are conditionally independent given the input x.</p><p>The distinction is important: the encoder computes distribution parameters, and the sampling operation produces the latent representation.</p><p>### **Why stochastic encoding is not sufficient**</p><p>Representing observations as distributions helps the decoder learn across neighborhoods of the latent space. However, individual latent distributions could still be located far apart, leaving poorly trained regions between them.</p><p>To address this problem, VAEs introduce prior regularization. Each input-dependent latent distribution is encouraged to remain reasonably close to a shared prior distribution, p(z).</p><p>The learning process balances two objectives:</p><p>- **Reconstruction loss:** Preserve the information needed to explain the original observation.<br>- **KL divergence:** Measure the discrepancy between the input-dependent latent distribution and the prior distribution.</p><p>Reconstruction alone can preserve useful information while leaving the latent space unsuitable for generation. Conversely, minimizing only KL divergence can make the latent distributions identical, eliminating information that distinguishes individual observations.</p><p>Optimizing both objectives encourages a latent space that preserves meaningful characteristics while remaining accessible through prior sampling. This regularization improves the suitability of the latent space for generation, but it does not guarantee meaningful outputs at every possible location.</p><p>## **The Probabilistic Architecture Behind a VAE**</p><p>To understand what a VAE learns, it helps to distinguish two approaches to modeling complex data distributions.</p><p>An autoregressive model represents dependencies between observed components by conditioning each component on those that precede it:</p><p>p(x) = ∏ p(xᵢ ∣ x₁, …, xᵢ₋₁), for i = 1, …, d</p><p>The joint distribution is expressed as a product of sequential conditional probabilities.</p><p>A latent variable model takes a different approach. It introduces hidden factors that can influence multiple observed components simultaneously. In a facial image, for example, head orientation and facial expression can affect many pixels. A latent variable can represent information about such underlying factors.</p><p>The basic generative process of a VAE is:</p><p>z ∼ p(z)</p><p>x ∼ p(x ∣ z; θ)</p><p>Together, these distributions define the joint distribution:</p><p>p(x, z; θ) = p(z) p(x ∣ z; θ)</p><p>The architecture separates generation into two components: a prior distribution p(z), which determines how latent variables are sampled, and a conditional distribution p(x ∣ z; θ), which determines how observations are generated from those variables. The parameter θ represents the decoder’s trainable parameters.</p><p>During training, however, only x is observed. The corresponding latent variable is unknown. To obtain the distribution over observations, the model must account for all possible latent variables:</p><p>p(x; θ) = ∫ p(z) p(x ∣ z; θ) dz</p><p>This operation is called marginalization. The resulting quantity, p(x; θ), is the marginal likelihood of the observation.</p><p>VAE training aims to increase the log marginal likelihood of the observed data through a tractable learning objective. This introduces three interconnected design problems:</p><p>- Choosing a prior that supports efficient sampling.<br>- Constructing a decoder that models the distribution of observations given latent variables.<br>- Developing an inference mechanism that makes learning possible despite the difficult latent-variable integral.</p><p>Autoregressive and latent variable models are not mutually exclusive. A VAE can also use an autoregressive structure within its conditional decoder distribution.</p><p>## **Designing a Prior That Makes Generation Possible**</p><p>A generative model needs a practical way to select new latent variables without requiring an existing observation.</p><p>VAEs commonly use a multivariate standard Gaussian distribution:</p><p>p(z) = 𝒩(z; 0, I)</p><p>For a k-dimensional latent vector, this distribution factorizes into independent standard Gaussian distributions:</p><p>p(z) = ∏ 𝒩(zⱼ; 0, 1), for j = 1, …, k</p><p>Every latent dimension has zero mean and unit variance, with zero covariance between different dimensions. Because the distribution is Gaussian, this covariance structure implies statistical independence. Each component can therefore be sampled independently.</p><p>For example, sampling from a two-dimensional standard Gaussian might produce:</p><p>z = [0.5, −1.2]</p><p>The trained decoder transforms this latent vector into a probability distribution over possible observations.</p><p>The architectural principle is straightforward: use a simple distribution for sampling and let the decoder learn how to transform latent variables into complex data distributions.</p><p>Changing individual latent components and observing the resulting outputs can also help reveal what the latent space has learned. In facial image generation, changing a particular component might influence head orientation or facial expression.</p><p>However, statistical independence in the prior does not imply semantic independence in the learned representation. A single latent dimension may influence several characteristics simultaneously.</p><p>## **The Decoder Is a Probability Model, Not Just a Reconstruction Network**</p><p>Even when two facial images share the same orientation and expression, their individual pixel values can differ. A conditional probability distribution allows the model to represent such variability.</p><p>Rather than mapping a latent variable directly to a single observation, a VAE decoder computes the parameters of an output distribution. This is known as parameterizing a probability distribution:</p><p>p(x ∣ z; θ) = p(x; g(z; θ))</p><p>The neural network g receives the latent variable z and computes the parameters of the output distribution. Although the network parameters θ remain fixed during generation, different latent variables produce different distribution parameters.</p><p>Depending on the type of data being modeled, those parameters may represent means, variances, or category probabilities.</p><p>### **Gaussian decoder: continuous observations**</p><p>For continuous data, such as temperature or sensor measurements, the decoder can define a Gaussian distribution:</p><p>p(x ∣ z; θ) = 𝒩(x; μ(z; θ), Σ(z; θ))</p><p>The mean vector μ(z; θ) determines the center of the output distribution, while the covariance matrix Σ(z; θ) describes variability and relationships between output components.</p><p>To simplify implementation, the covariance may be fixed or restricted to a diagonal structure. The resulting distribution describes both representative output values and their variability.</p><p>### **Bernoulli decoder: binary observations**</p><p>For binary images, where each pixel is either 0 or 1, a Bernoulli distribution provides an appropriate output model. The decoder typically uses a sigmoid function to transform its network outputs into valid probabilities.</p><p>For D conditionally independent binary components:</p><p>p(x ∣ z; θ) = ∏ Bᵢ, for i = 1, …, D</p><p>Bᵢ = βᵢ(z) if xᵢ = 1, and Bᵢ = 1 − βᵢ(z) if xᵢ = 0.</p><p>Here, βᵢ(z) is the probability that the i-th component equals 1. When the observed component is 1, its probability contribution is βᵢ(z). When it is 0, the contribution is 1 − βᵢ(z).</p><p>The decoder predicts probabilities for binary outcomes rather than directly assigning binary values.</p><p>### **Categorical decoder: discrete categories**</p><p>When an observation represents one of several mutually exclusive categories, the decoder can define a categorical distribution. A softmax function typically converts network outputs into category probabilities whose sum equals 1.</p><p>For a one-hot observation with K possible categories:</p><p>p(x ∣ z; θ) = γᵢ(z), where i is the unique index with xᵢ = 1.</p><p>Here, γᵢ(z) represents the probability of selecting category i. Because x is a one-hot vector, the likelihood is the probability corresponding to the selected category.</p><p>Gaussian, Bernoulli, and categorical decoders differ in the distributions they define, but their underlying architectural principle remains the same: a neural network maps latent variables to the parameters of an observation distribution.</p><p>## **Reconstruction and Generation Are Not the Same Operation**</p><p>Suppose a Gaussian decoder defines an output distribution with a mean of 10 and a standard deviation of 0.5. We can use the expected value, which is 10, or sample from the distribution and obtain values such as 9.8 or 10.3.</p><p>Mathematically, these operations are:</p><p>**Deterministic reconstruction for a fixed latent variable:**</p><p>x̂ = 𝔼[x], with x distributed according to p(x ∣ z; θ)</p><p>**Stochastic generation:**</p><p>x̂ ∼ p(x ∣ z; θ)</p><p>The distinction becomes especially important when the expected value does not have the same form as an actual observation.</p><p>Output distribution: Gaussian — Expected value: 10 — Possible sampled output: 9.8 or 10.3</p><p>Output distribution: Bernoulli — Expected value: 0.8 — Possible sampled output: 1 or 0</p><p>Output distribution: Categorical — Expected value: [0.1, 0.7, 0.2] — Possible sampled output: [0, 1, 0]</p><p>For a Bernoulli distribution with an expected value of 0.8, an actual sample equals 1 with 80% probability and 0 with 20% probability. Displaying the expected values of a Bernoulli image decoder can therefore produce something resembling a grayscale image, even though actual samples contain only binary pixel values.</p><p>It is also important to distinguish deterministic decoding from deterministic encoding. Using the decoder’s expected output is deterministic only when z is fixed. If the encoder’s distribution is sampled repeatedly, the reconstruction of the same input can still vary.</p><p>### **How simple conditional distributions capture dependencies**</p><p>A decoder does not necessarily need a full covariance matrix to represent dependencies in the overall data distribution.</p><p>Consider a Gaussian decoder with two output components and diagonal covariance:</p><p>μ(z) = [μ₁(z), μ₂(z)]ᵀ</p><p>Σ(z) = diag(σ₁²(z), σ₂²(z))</p><p>For a fixed z, the two output components are conditionally independent. However, both components depend on the same latent variable. As z changes, their means and variances can change together.</p><p>Consequently, dependencies between the output components can emerge in the marginal data distribution, even though the conditional distribution assumes independence. Shared latent variables allow common underlying factors to influence multiple components of an observation.</p><p>During training, the decoder does not need to sample an actual output. The model can directly evaluate the log-likelihood of the observed data under the decoder’s output distribution.</p><p>## **The Inference Problem: Which Latent Variables Explain an Observation?**</p><p>Generating data from a trained VAE is conceptually simple: sample a latent variable from the prior and pass it through the decoder. Training requires solving the reverse problem: given an observed image, which latent variables are likely to explain it?</p><p>The marginal likelihood can be expressed as an expectation under the prior:</p><p>p(x; θ) = 𝔼[p(x ∣ z; θ)], with z ∼ p(z)</p><p>This suggests a direct approximation using Monte Carlo estimation. First, sample N independent latent variables:</p><p>zᵢ ∼ p(z)</p><p>Then estimate the marginal likelihood by averaging their conditional likelihoods:</p><p>p(x; θ) ≈ (1/N) · ∑ p(x ∣ zᵢ; θ), for i = 1, …, N</p><p>The method is mathematically straightforward, but its practical effectiveness depends on whether the sampled latent variables explain the observation.</p><p>Suppose the observation is a handwritten seven. Latent variables associated with zeros or threes may contribute very little to its estimated likelihood.</p><p>In a high-dimensional latent space, the region that explains a particular observation may be relatively narrow. Randomly sampling from the prior can therefore require substantial computation and produce estimates with high variability.</p><p>What we need is an observation-dependent distribution that identifies relevant latent variables more efficiently.</p><p>## **Variational Inference: Learning an Approximate Posterior**</p><p>The posterior distribution describes which latent variables are plausible after observing x. Bayes’ theorem gives:</p><p>p(z ∣ x; θ) = p(z) p(x ∣ z; θ) / p(x; θ)</p><p>The numerator combines the prior density of the latent variable with the conditional likelihood of the observation given that variable. The denominator normalizes the distribution.</p><p>Unfortunately, that denominator is precisely the marginal likelihood containing the difficult integral over latent variables. The exact posterior is therefore generally difficult to compute.</p><p>Variational inference addresses this problem by introducing a tractable approximate posterior:</p><p>q(z ∣ x; φ) ≈ p(z ∣ x; θ)</p><p>This is the deeper purpose of the VAE encoder. Its probabilistic output is not simply a mechanism for injecting randomness into a representation. It approximates the posterior distribution, providing an efficient way to sample latent variables that could explain the current observation.</p><p>The encoder performs approximate inference in the opposite direction to the generative process defined by the decoder.</p><p>## **The ELBO Connects Inference and Generation**</p><p>Once an approximate posterior is available, it might seem natural to sample from it and average the resulting conditional likelihoods. However, that would not generally recover the original marginal likelihood, which is an expectation under the prior rather than the observation-dependent approximate posterior.</p><p>Instead, VAEs maximize the Evidence Lower Bound (ELBO):</p><p>L(x; θ, φ) = 𝔼[log p(x ∣ z; θ)] − KL(q(z ∣ x; φ) ∥ p(z)), with z ∼ q(z ∣ x; φ)</p><p>This objective satisfies:</p><p>L(x; θ, φ) ≤ log p(x; θ)</p><p>The ELBO provides a tractable lower bound on the log marginal likelihood and gives a probabilistic interpretation to the two learning objectives introduced earlier.</p><p>The first term measures how well latent variables sampled from the approximate posterior explain the observation. Maximizing this expected log-likelihood encourages the model to assign high likelihood to the observed data.</p><p>The second term measures the discrepancy between the approximate posterior and the prior. Subtracting it discourages input-dependent latent distributions from deviating excessively from the shared prior.</p><p>Optimizing these terms together allows the model to learn a generative distribution and an approximate inference mechanism without directly evaluating the difficult marginal likelihood integral.</p><p>## **Amortized Inference: Why the Encoder Is a Neural Network**</p><p>Traditional variational inference can optimize a separate set of variational parameters for every observation. For an individual input x, the approximate posterior can be written as:</p><p>q(z; φₓ)</p><p>If the training dataset contains tens of thousands of images, repeatedly optimizing separate distributions can become computationally expensive.</p><p>A VAE replaces this repeated optimization with a shared inference network:</p><p>q(z ∣ x; φ)</p><p>Rather than independently optimizing the parameters of every approximate posterior, the model learns a function that predicts suitable distribution parameters from an observation. This approach is called amortized inference.</p><p>Traditional variational inference: Separate variational parameters for each observation — Amortized variational inference: Shared neural network parameters</p><p>Traditional variational inference: Repeated input-specific optimization — Amortized variational inference: Distribution parameters computed through a forward pass</p><p>Traditional variational inference: q(z; φₓ) — Amortized variational inference: q(z ∣ x; φ)</p><p>The variational encoder implements this shared inference mechanism:</p><p>q(z ∣ x; φ) = q(z; f(x; φ))</p><p>The neural network f maps the observation x to the parameters of its approximate posterior distribution.</p><p>For example, an encoder that represents two input values using a single Gaussian latent variable might define:</p><p>q(z ∣ x; φ) = 𝒩(z; μ(x; φ), σ²(x; φ))</p><p>Although the encoder outputs two values — a mean and a variance — the latent variable itself remains one-dimensional. These values describe a distribution over one latent variable. The decoder receives a sampled latent value, not the pair of distribution parameters.</p><p>## **Putting the Architecture Together**</p><p>The VAE architecture revolves around three probability distributions:</p><p>Distribution: p(z) — Role: Provides latent variables for unconditional generation</p><p>Distribution: q(z ∣ x; φ) — Role: Approximates the posterior over latent variables given an observation</p><p>Distribution: p(x ∣ z; θ) — Role: Defines how observations are generated from latent variables</p><p>These distributions play different roles during training and generation.</p><p>### **Training: learning inference and generation together**</p><p>During training, an actual observation is available. The encoder computes its approximate posterior, and the decoder uses a latent variable sampled from that distribution to define an output distribution.</p><p>The computational flow is:</p><p>x → Encoder → q(z ∣ x; φ) → Sampling → z → Decoder → p(x ∣ z; θ)</p><p>The training procedure consists of five steps:</p><p>1. Pass the observation through the encoder to obtain the approximate posterior parameters.<br>2. Sample a latent variable z from the approximate posterior.<br>3. Pass z through the decoder to obtain the conditional output distribution.<br>4. Use the sampled latent variable to estimate the expected log-likelihood term and combine it with the KL divergence to estimate the ELBO.<br>5. Update the encoder and decoder parameters jointly to maximize the ELBO.</p><p>In a typical Gaussian VAE, the reparameterization trick enables gradients to propagate back to the encoder through the latent sampling operation.</p><p>### **Generation: creating data without an original observation**</p><p>Once the model has been trained, generating new data does not require the encoder. A latent variable is sampled directly from the prior and passed to the trained decoder.</p><p>The computational flow becomes:</p><p>p(z) → Sampling → z → Decoder → p(x ∣ z; θ) → Sampling → x̂</p><p>The decoder computes the output distribution associated with the sampled latent variable. Depending on the intended use, an output can be sampled from that distribution or represented by a suitable summary value, such as its expectation.</p><p>This difference between training and generation explains why prior regularization is important to the architecture. During training, latent variables come from observation-dependent approximate posteriors. During unconditional generation, they come directly from the prior. Regularization encourages these two processes to operate within a compatible latent space.</p><p>## **The Central Insight**</p><p>A Variational Autoencoder is more than an autoencoder with randomness added to its latent representation. Its defining architectural feature is the separation of observation-dependent inference from prior-based generation, with both processes connected through joint optimization.</p><p>By learning latent representations that preserve information while remaining compatible with a shared prior, a VAE extends the reconstruction capabilities of an autoencoder into a probabilistic framework for generating new data without an original observation.</p><p>Explore more structured AI lectures:<br><a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9904c06151ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative Models and Latent Variables: Learning a Space for Data Generation]]></title>
            <link>https://medium.com/@zeromathai/https-zeromathai-com-en-generative-latent-variable-models-course-en-e319a00cde56?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e319a00cde56</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[latent-space]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 04:51:01 GMT</pubDate>
            <atom:updated>2026-12-04T04:51:01.491Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at:<br><a href="https://zeromathai.com/en/generative-latent-variable-models-course-en/">https://zeromathai.com/en/generative-latent-variable-models-course-en/</a></p><p>Generating a realistic human face requires more than learning what eyes, noses, and mouths look like. A model must also capture how these features relate to one another and how they change together as a person turns their head or changes their expression.</p><p>Randomly selecting individual pixel values would produce mostly meaningless images. The challenge of generative modeling is to learn the underlying probabilistic structure that makes data coherent.</p><p>Latent variable models approach this problem by introducing hidden factors that influence multiple observed features simultaneously. The Variational Autoencoder (VAE) builds on this idea by learning a probabilistically structured latent space from which new data can be generated.</p><p>## **Generative Modeling Is About Learning Data Distributions**</p><p>A face recognition model learns features that help distinguish one person from another. A face generation model has a different objective: learning the statistical patterns that characterize realistic faces.</p><p>These patterns constitute the **data distribution**. If x represents an observed data sample, its distribution can be written as:</p><p>p(x)</p><p>A generative model learns the characteristics of this distribution so that it can produce new samples with properties resembling those of the observed data.</p><p>Generative models can broadly be distinguished by how they represent and learn data distributions.</p><p>**Likelihood-based models** use the probability or probability density assigned to observed data as part of their learning process. Autoregressive models, Variational Autoencoders, flow-based models, and diffusion models belong to this broad category. Depending on the architecture, training may involve exact likelihood computation or an approximate likelihood-related objective.</p><p>**Implicit models** focus on learning a process that produces realistic samples without directly evaluating their probability density. Generative Adversarial Networks (GANs) are a representative example, using a discriminator to distinguish generated samples from real ones during training.</p><p>For high-dimensional data such as images, directly representing the dependencies between observed elements can be difficult. Latent variable models offer a way to express these dependencies through shared underlying factors.</p><p>## **Modeling Dependencies Through Hidden Variables**</p><p>Imagine a person slowly turning their head. The apparent position of the nose changes, the shape of the visible eyes shifts, and the outline of the face changes. Although many pixels are affected, these coordinated changes arise from a common factor: head orientation.</p><p>Facial expressions exhibit a similar structure. A smile changes not only the mouth but also the cheeks and the regions around the eyes. An ordinary photograph records pixel values without necessarily providing explicit information about head orientation or smile intensity.</p><p>A **latent variable** is a variable that is not directly observed but influences the process through which observed data is generated.</p><p>Let x represent observed data and z represent its latent variables. A latent variable model describes data generation using two probability distributions:</p><p>- **Prior distribution — p(z):** Defines how latent variables are selected before generating data.<br>- **Conditional distribution — p(x ∣ z):** Describes the possible observations associated with a particular latent variable.</p><p>The generative process follows two steps:</p><p>z ∼ p(z)</p><p>x ∼ p(x ∣ z)</p><p>First, a latent variable is sampled from the prior distribution. An observation is then sampled from the conditional distribution associated with that latent variable. Because the conditional distribution is probabilistic, the same latent variable can produce observations that differ in their finer details.</p><p>The architectural advantage is that multiple observed features can depend on the same hidden variable. Coordinated changes across an image can therefore be represented through common underlying factors rather than through separate descriptions of every affected pixel.</p><p>When the latent representation has fewer dimensions than the observed data, it can also provide a more compact representation. However, dimensionality reduction is not the primary motivation. The central idea is to capture complex dependencies through shared hidden factors.</p><p>## **From Hidden Factors to an Observable Data Distribution**</p><p>Sampling from a latent variable model follows a clear procedure once its prior and conditional distributions have been defined. Learning the model parameters presents a more difficult problem: we observe x, but we generally do not know which latent variable z produced it.</p><p>A photograph of a nearly forward-facing person, for example, might be consistent with several nearby values representing head orientation. The model must account for these possibilities rather than assuming that only one latent configuration could have produced the image.</p><p>Let θ denote the learnable parameters of the conditional distribution. The joint distribution of observed and latent variables is:</p><p>p(x, z; θ) = p(z) p(x ∣ z; θ)</p><p>This factorization separates two aspects of generation: the probability or probability density assigned to a latent variable by the prior, and the conditional probability or density of an observation given that variable.</p><p>To obtain the distribution of observed data alone, the model must account for every possible latent variable. For discrete latent variables, this involves summation. For continuous latent variables, it involves integration:</p><p>p(x; θ) = ∫ p(x, z; θ) dz</p><p>Substituting the joint distribution gives:</p><p>p(x; θ) = ∫ p(z) p(x ∣ z; θ) dz</p><p>This operation is called **marginalization**. It combines the contributions of all possible latent configurations, weighted by the prior distribution.</p><p>When viewed as a function of the model parameters θ for a fixed observation x, p(x; θ) is called the **marginal likelihood**. It provides a way to evaluate how well the model explains observed data without requiring knowledge of the underlying latent variables.</p><p>For continuous observations, this quantity represents a probability density rather than the probability of an individual observation.</p><p>### **The computational difficulty of marginalization**</p><p>The marginal likelihood provides a principled basis for learning a latent variable model. However, evaluating it exactly can become computationally difficult when the latent space is high-dimensional or the conditional distribution is complex.</p><p>This is the problem of an **intractable integral**. Defining a plausible generative process is not enough; the model also needs a practical way to optimize its parameters when the marginal likelihood cannot be evaluated efficiently.</p><p>This computational difficulty motivates the use of variational inference in Variational Autoencoders.</p><p>## **Latent Variable Models vs. Autoregressive Models**</p><p>Autoregressive models offer another way to represent complex data distributions. Rather than relying on unobserved common factors, they can express dependencies directly between observed data elements.</p><p>For an observation containing d elements, the distribution can be factorized as:</p><p>p(x) = ∏ p(xᵢ ∣ x₁, …, xᵢ₋₁), for i = 1, …, d</p><p>Each element is generated conditionally on the elements that precede it. Sentence generation illustrates this approach naturally: previously selected words provide the context for generating the next word.</p><p>The distinction lies in how the two approaches represent dependencies.</p><p>**Autoregressive models**<br>- Represent dependencies between observed elements.<br>- Factorize the data distribution into sequential conditional probabilities.<br>- Generate elements conditionally on preceding elements.</p><p>**Latent variable models**<br>- Represent dependencies through hidden common factors.<br>- Factorize the joint distribution into a prior and a conditional distribution.<br>- Generate observations conditionally on sampled latent variables.</p><p>These approaches are not mutually exclusive and can be combined. However, introducing unobserved latent variables creates an additional requirement: marginalization over those variables.</p><p>A practical latent variable generative model must therefore address three architectural questions:</p><p>- How should the prior distribution p(z) be defined so that latent variables can be sampled efficiently?<br>- How should the conditional distribution p(x ∣ z; θ) represent the relationship between latent variables and complex observations?<br>- How can the model parameters be optimized when the marginal likelihood is difficult to calculate?</p><p>A Variational Autoencoder addresses these questions by using a neural network to model the conditional distribution and variational inference to make learning computationally manageable.</p><p>## **Why Reconstruction Alone Is Not Enough for Reliable Generation**</p><p>Consider an autoencoder trained on MNIST handwritten digit images. Suppose the model represents each image using two numbers, allowing every image to be mapped to a point on a two-dimensional plane. This internal representation space is called the **latent space**.</p><p>If the autoencoder learns useful features, visually similar digits may appear close together, while digits with different characteristics may occupy separate regions. Such clustering and separation can be useful for feature extraction and similarity-based retrieval.</p><p>However, a latent space that represents existing data effectively is not necessarily suitable for generating new data.</p><p>Imagine that representations of handwritten ones and sevens occupy separate regions. Between those regions, there may be locations that the decoder rarely encountered during training. Selecting a latent variable from one of these locations and passing it to the decoder could produce a meaningless image.</p><p>The underlying problem is that successful reconstruction does not necessarily organize the latent space into a structure suitable for sampling.</p><p>Two properties are particularly important for generation:</p><p>- **Latent space continuity:** Nearby latent variables should produce similar observations, with small changes in latent coordinates leading to gradual, meaningful changes in the generated output.<br>- **Latent space completeness:** Regions that are likely to be sampled under the prior distribution should support the generation of meaningful observations.</p><p>Completeness does not require every mathematically possible latent coordinate to produce realistic data. What matters is whether the regions that the model is likely to sample are suitable for generation.</p><p>### **From fixed representations to probability distributions**</p><p>A conventional deterministic autoencoder maps each input to a fixed latent representation and learns to reconstruct the input from that representation. A Variational Autoencoder instead represents each input through a probability distribution over latent variables.</p><p>For a handwritten digit, the model no longer associates the image exclusively with one latent coordinate. It learns to reconstruct the image’s characteristics using latent variables sampled from a distribution associated with that input. This encourages the decoder to respond more consistently to small variations in latent coordinates.</p><p>Probabilistic encoding alone, however, does not solve the entire problem. If the distributions associated with different inputs remain widely separated, the latent space may still contain poorly learned regions.</p><p>The VAE addresses this limitation by encouraging individual latent distributions to remain close to a shared prior distribution. The goal is to preserve useful information about observed data while organizing latent representations into a space that supports new sample generation.</p><p>## **Learning the Generative Process in Reverse**</p><p>The generative direction of a latent variable model runs from z to x. During training, however, the model starts with an observed input x and must infer the latent variables that could explain it.</p><p>This inference problem is described by the posterior distribution:</p><p>p(z ∣ x; θ)</p><p>Computing the true posterior can be difficult because it depends on the marginal likelihood, which may involve an intractable integral.</p><p>A VAE introduces a learnable approximation:</p><p>q(z ∣ x; φ)</p><p>Here, φ represents the parameters of the encoder. The encoder typically predicts the mean and variance of a Gaussian distribution associated with the input. A latent variable is sampled from this approximate posterior and passed to the decoder.</p><p>The two neural networks serve complementary probabilistic roles. The encoder performs approximate inference, estimating a distribution over plausible latent variables for an observed input. The decoder models the conditional distribution through which observations are generated from latent variables.</p><p>Training connects these two directions through a shared learning objective.</p><p>## **Balancing Reconstruction and Latent Regularization**</p><p>A VAE must preserve enough information to explain observed data while maintaining a latent space from which new variables can be sampled. These requirements are expressed through two complementary objectives.</p><p>**Reconstruction loss** evaluates how well latent variables sampled from the approximate posterior explain the original input. Training minimizes the negative expected log-likelihood of the observation under the decoder’s conditional distribution.</p><p>**Latent regularization** reduces the discrepancy between the approximate posterior and the prior distribution. This discrepancy is measured using KL divergence, which discourages individual latent distributions from deviating excessively from the shared prior.</p><p>The two objectives are combined into the Evidence Lower Bound (ELBO), a lower bound on the log marginal likelihood:</p><p>L(x; θ, φ) = 𝔼[log p(x ∣ z; θ)] − KL(q(z ∣ x; φ) ∥ p(z)), with z ∼ q(z ∣ x; φ)</p><p>The first term rewards the model for assigning high conditional likelihood to the observed input. The second penalizes deviations between the approximate posterior and the prior.</p><p>Maximizing the ELBO jointly optimizes the encoder and decoder, balancing the ability to explain observed data against the need for a structured latent space.</p><p>The importance of this balance becomes clearer when considering what each objective contributes to the MNIST example:</p><p>- **Reconstruction alone:** The model can preserve distinguishing features and reconstruct individual digits, but their latent distributions may be arranged irregularly, making it difficult to select useful latent variables for generation.<br>- **KL regularization alone:** The approximate posteriors can move closer to the prior, but there is no reconstruction-driven incentive to preserve information that distinguishes different inputs.<br>- **Both objectives together:** The model is encouraged to retain meaningful information about each input while organizing latent distributions around a shared probabilistic structure.</p><p>Regularization helps improve latent space continuity and completeness, but it does not guarantee realistic outputs at every latent coordinate. Generation quality also depends on the suitability of the prior, the expressiveness of the latent distributions, and how effectively the decoder has been trained.</p><p>## **Why the Standard Normal Prior Is Useful**</p><p>Once a VAE has been trained, generating new data does not require an existing input. The model therefore needs a distribution from which latent variables can be sampled directly, without relying on the encoder.</p><p>A common choice is the **standard normal prior**:</p><p>p(z) = N(z; 0, I)</p><p>For a latent vector containing m dimensions, this distribution factorizes as:</p><p>p(z) = ∏ N(zⱼ; 0, 1), for j = 1, …, m</p><p>Here, I is the identity matrix. Each latent dimension has a mean of zero and a variance of one, while the covariance between distinct dimensions is zero.</p><p>For a multivariate Gaussian distribution, this covariance structure implies statistical independence between dimensions. Each coordinate can therefore be sampled independently.</p><p>The standard normal prior provides both a straightforward sampling mechanism and a common probabilistic reference for the latent distributions learned during training.</p><p>### **Statistical independence is not semantic independence**</p><p>A latent space also makes it possible to investigate how changes in individual latent variables affect generated observations.</p><p>Suppose a face generation model learns to represent head orientation and smile intensity in separate latent dimensions. Changing z₁ might gradually alter the direction of the face, while changing z₂ might alter the intensity of the smile. Varying both dimensions could produce different combinations of orientation and expression.</p><p>This illustrates how latent variables can represent meaningful factors of variation. However, statistical independence between dimensions in the prior does not guarantee that the learned dimensions represent independent semantic factors.</p><p>A single latent dimension may influence several facial characteristics simultaneously. The statistical structure of the prior and the semantic organization learned by the model are distinct properties.</p><p>## **Training and Generation Follow Different Sampling Paths**</p><p>The relationship between the encoder, decoder, and prior becomes clearer when we compare how latent variables are selected during training and generation.</p><p>### **During training**</p><p>The model starts with an observed input x. The encoder estimates its approximate posterior, a latent variable is sampled from that distribution, and the decoder uses it to reconstruct the observation.</p><p>The probabilistic flow is:</p><p>x — [q(z ∣ x; φ)]→ z — [p(x ∣ z; θ)]→ x̃</p><p>Here, x̃ represents the reconstructed observation. Both the encoder and decoder participate in learning by maximizing the ELBO.</p><p>### **During generation**</p><p>The model no longer needs an observed input or the encoder. Instead, it samples a latent variable directly from the prior:</p><p>z ∼ N(0, I)</p><p>The trained decoder then generates a new observation, x′, from its conditional distribution:</p><p>x′ ∼ p(x ∣ z; θ)</p><p>The critical difference is the source of the latent variable. Training uses an approximate posterior conditioned on an existing observation, whereas generation samples directly from the prior.</p><p>Latent regularization helps connect these two paths by encouraging the latent distributions encountered during training to remain close to the distribution used during generation.</p><p>## **The Central Insight: Learning a Space That Can Generate**</p><p>The defining difference between a conventional autoencoder and a Variational Autoencoder lies in the purpose for which the latent space is learned.</p><p>A conventional autoencoder learns representations that support reconstruction. A VAE goes further by learning a probabilistic latent structure that allows its decoder to generate new observations from variables sampled directly from the prior.</p><p>The latent space becomes more than a representation of existing data. It becomes the starting point for generating new data.</p><p>Explore more structured AI lectures:<br><a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e319a00cde56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ELBO Explained: Turning Intractable Bayesian Inference into an Optimization Problem]]></title>
            <link>https://medium.com/@zeromathai/elbo-explained-turning-intractable-bayesian-inference-into-an-optimization-problem-40eec88493d6?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/40eec88493d6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[elbo]]></category>
            <category><![CDATA[variational-inference]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Thu, 03 Dec 2026 04:46:01 GMT</pubDate>
            <atom:updated>2026-12-03T04:46:01.512Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at:<br><a href="https://zeromathai.com/en/elbo-variational-optimization-course-en/">https://zeromathai.com/en/elbo-variational-optimization-course-en/</a></p><p>Defining a probabilistic model is often much easier than performing inference with it. We may know how latent variables generate observations, yet struggle to determine their posterior distribution given the data.</p><p>Suppose you want to estimate the orientation of a person’s head from a photograph. You might be uncertain whether the person is looking 30 or 35 degrees to the right. Rather than committing to a single angle, a probabilistic model can represent that uncertainty as a distribution.</p><p>However, head orientation is not the only hidden factor. Facial expressions, lighting, and facial structure may all influence the observed image. When these latent variables interact in complex ways, computing their exact posterior distribution becomes difficult.</p><p>The **Evidence Lower Bound (ELBO)** addresses this problem by providing an objective for improving an approximate posterior without computing the exact marginal likelihood. It turns posterior inference into a distribution optimization problem.</p><p>## **From Posterior Inference to Distribution Optimization**</p><p>Let x represent observed data and z represent the latent variables underlying that data. The posterior distribution, p(z ∣ x), describes the probability distribution of the latent variables after observing x.</p><p>Variational inference replaces this potentially intractable posterior with an approximate distribution, q(z). Rather than attempting to recover the exact posterior directly, we define a family of candidate distributions, called the **variational family**, denoted by Q.</p><p>The goal is to find the distribution within this family that minimizes the KL divergence from the approximate posterior to the true posterior.</p><p>q★(z) = arg min (over q(z) ∈ Q): KL(q(z) ∥ p(z ∣ x))</p><p>KL divergence is nonnegative and equals zero when the two distributions agree almost everywhere. Minimizing it provides a precise mathematical criterion for selecting the best approximation within the chosen family.</p><p>The problem is that evaluating this criterion requires access to the very posterior distribution we cannot easily compute.</p><p>## **Why Directly Minimizing KL Divergence Is Difficult**</p><p>The KL divergence between the approximate posterior and the true posterior is defined as:</p><p>KL(q(z) ∥ p(z ∣ x)) = 𝔼[log(q(z) / p(z ∣ x))], with z ∼ q(z)</p><p>This expectation measures the discrepancy between the two distributions, weighting regions of the latent space according to q(z).</p><p>To understand why evaluating the posterior is difficult, consider four fundamental quantities in a probabilistic latent variable model:</p><p>- **Prior — p(z):** The distribution of latent variables before observing the data.<br>- **Likelihood — p(x ∣ z):** How well a particular latent variable value explains the observed data.<br>- **Joint distribution — p(x, z):** The joint probability distribution of observations and latent variables.<br>- **Marginal likelihood — p(x):** The probability or probability density of the observation after accounting for all possible latent variables. It is also called the evidence.</p><p>The joint distribution factorizes as:</p><p>p(x, z) = p(z)p(x ∣ z)</p><p>The marginal likelihood is obtained by integrating out the latent variables:</p><p>p(x) = ∫ p(x, z) dz = ∫ p(z)p(x ∣ z) dz</p><p>Bayes’ theorem then gives us the posterior:</p><p>p(z ∣ x) = p(x, z) / p(x)</p><p>For continuous latent variables, marginalization requires integration. For discrete latent variables, it requires summation over their possible values. As the dimensionality of the latent space increases or the relationships between latent variables become more complex, evaluating the marginal likelihood exactly can become computationally intractable.</p><p>This difficulty carries directly into the KL divergence. Expanding its logarithmic ratio gives:</p><p>KL(q(z) ∥ p(z ∣ x)) = 𝔼(q)[log q(z)] − 𝔼(q)[log p(z ∣ x)]</p><p>Here, 𝔼(q) denotes an expectation under q(z).</p><p>Using Bayes’ theorem, we can rewrite the log posterior as:</p><p>log p(z ∣ x) = log p(x, z) − log p(x)</p><p>Substituting this expression into the KL divergence yields:</p><p>KL(q(z) ∥ p(z ∣ x)) = 𝔼(q)[log q(z)] − 𝔼(q)[log p(x, z)] + log p(x)</p><p>The potentially intractable quantity, log p(x), is still present. However, for a fixed observation and probabilistic model, it does not depend on q(z).</p><p>Although we may not know its value, changing the approximate distribution cannot change it. This means we can compare candidate distributions without evaluating the exact KL divergence.</p><p>## **Deriving ELBO: Optimizing Without Knowing the Evidence**</p><p>Imagine comparing two candidate solutions whose objective values are C + 3 and C + 7. Even without knowing C, we can determine that the first candidate has the smaller objective value. The unknown constant affects the absolute scores but not their ordering.</p><p>The same principle applies to variational inference. Since log p(x) is constant with respect to q(z), we can optimize the remaining terms without evaluating the marginal likelihood. Reversing their signs converts the original minimization problem into a maximization problem.</p><p>We define the variational objective as:</p><p>L(q) = 𝔼(q)[log p(x, z)] − 𝔼(q)[log q(z)]</p><p>This expression combines the expected logarithm of the joint probability or probability density with the entropy of the approximate distribution.</p><p>Substituting it into the expanded KL divergence gives the fundamental ELBO identity:</p><p>log p(x) = L(q) + KL(q(z) ∥ p(z ∣ x))</p><p>Because KL divergence is nonnegative:</p><p>KL(q(z) ∥ p(z ∣ x)) ≥ 0</p><p>It follows that:</p><p>L(q) ≤ log p(x)</p><p>This is why L(q) is called the **Evidence Lower Bound**. Its value cannot exceed the log marginal likelihood, and the gap between the two is exactly the KL divergence from the approximate posterior to the true posterior.</p><p>## **What It Means to Tighten the Lower Bound**</p><p>Suppose the log marginal likelihood of a fixed probabilistic model for a given observation is −10. Different approximate distributions might produce the following ELBO values:</p><p>- ELBO = −18; log evidence = −10; KL divergence = 8.<br>- ELBO = −12; log evidence = −10; KL divergence = 2.<br>- ELBO = −10; log evidence = −10; KL divergence = 0.</p><p>When ELBO increases from −18 to −12, the gap between the lower bound and the log evidence decreases from 8 to 2. The approximate distribution has become closer to the true posterior in terms of KL divergence.</p><p>If ELBO reaches −10, the gap disappears entirely, and the approximate posterior agrees with the true posterior almost everywhere.</p><p>For a fixed observation and probabilistic model, this establishes the equivalence between the two optimization problems:</p><p>arg min (over q ∈ Q): KL(q(z) ∥ p(z ∣ x)) = arg max (over q ∈ Q): L(q)</p><p>Both objectives identify the same optimal approximate distribution within the chosen variational family.</p><p>ELBO does not, however, eliminate every computational difficulty associated with inference. We still need to evaluate the joint distribution and calculate or estimate expectations under q(z). What we no longer need is the exact marginal likelihood.</p><p>## **The Two Terms That Define ELBO**</p><p>The derivation establishes why maximizing ELBO works. Decomposing the objective reveals what the optimization encourages.</p><p>Starting from:</p><p>L(q) = 𝔼(q)[log p(x, z)] − 𝔼(q)[log q(z)]</p><p>We substitute the factorization of the joint distribution:</p><p>p(x, z) = p(z)p(x ∣ z)</p><p>This gives:</p><p>L(q) = 𝔼(q)[log p(z)] + 𝔼(q)[log p(x ∣ z)] − 𝔼(q)[log q(z)]</p><p>Combining the expectations involving the prior and approximate distribution produces a negative KL divergence. The resulting expression is:</p><p>L(q) = 𝔼(q)[log p(x ∣ z)] − KL(q(z) ∥ p(z))</p><p>This form reveals two complementary components: expected log-likelihood and prior regularization.</p><p>### **Expected Log-Likelihood**</p><p>𝔼(q)[log p(x ∣ z)]</p><p>The expected log-likelihood measures how well latent variables drawn from the approximate distribution explain the observed data, on average. Maximizing this term encourages the approximate distribution to assign probability to latent configurations that explain the observation well.</p><p>### **Prior Regularization**</p><p>KL(q(z) ∥ p(z))</p><p>The second term measures the discrepancy between the approximate distribution and the prior. Because it is subtracted from the expected log-likelihood, a larger divergence from the prior reduces ELBO when the expected log-likelihood remains unchanged.</p><p>The prior therefore influences which approximate distributions are preferred during optimization.</p><p>## **Two KL Divergences, Two Different Roles**</p><p>Two different KL divergences appear in the derivation of ELBO. Although they share the same mathematical definition, they compare different distributions and serve different purposes.</p><p>- KL(q(z) ∥ p(z ∣ x)): Measures posterior approximation error.<br>- KL(q(z) ∥ p(z)): Measures deviation from the prior.</p><p>The first divergence is the quantity variational inference ultimately seeks to minimize. Evaluating it directly is difficult because the true posterior depends on the potentially intractable marginal likelihood.</p><p>The second divergence is part of the ELBO objective itself. Since the prior is explicitly defined by the probabilistic model, this term can be calculated directly or efficiently estimated, depending on the distributions involved.</p><p>The prior KL divergence is not itself a measure of posterior approximation accuracy. It is one component of an objective whose maximization is equivalent to minimizing posterior KL divergence for a fixed observation and probabilistic model.</p><p>## **The Likelihood–Prior Tradeoff**</p><p>Consider a prior distribution that assigns a high probability to people looking straight ahead. Now suppose we observe a photograph in which the person is clearly looking to the right.</p><p>The approximate posterior should assign greater probability to latent configurations consistent with the observed orientation. Simply reproducing the prior would ignore the information provided by the photograph.</p><p>Consider what happens when we optimize the two ELBO terms separately or together:</p><p>- **Maximizing only the expected log-likelihood:** The approximate distribution may concentrate excessively on latent values that explain the data well, disregarding the prior.<br>- **Minimizing only the prior KL divergence:** The approximate distribution approaches the prior without incorporating new information from the observation.<br>- **Optimizing both terms together:** The approximate distribution accounts for both the observed data and the prior.</p><p>This relationship is known as the **likelihood–prior tradeoff**.</p><p>The objective is not to keep the approximate posterior as close to the prior as possible. Instead, it balances the cost of departing from the prior against improvements in expected log-likelihood. When the observation provides strong evidence, a substantial difference between the approximate posterior and the prior can be an appropriate inference result.</p><p>## **Why Negative ELBO Resembles a Regularized Loss**</p><p>Machine learning objectives are frequently expressed as minimization problems. A conventional regularized training objective takes the form:</p><p>E(aug) = E(train) + λΩ</p><p>Here, E(train) represents the training loss, Ω represents the regularization term, and λ controls the strength of regularization.</p><p>Reversing the sign of ELBO produces a structurally similar objective:</p><p>−L(q) = −𝔼(q)[log p(x ∣ z)] + KL(q(z) ∥ p(z))</p><p>The negative expected log-likelihood acts as a data-dependent loss, while the KL divergence from the approximate distribution to the prior acts as a regularization term.</p><p>There is an important difference, however. In a general regularized objective, λ is an adjustable coefficient. In the standard ELBO, the coefficient of the KL divergence is fixed at 1.</p><p>The balance between the two terms follows directly from the mathematical derivation of the lower bound rather than from an independently chosen regularization strength.</p><p>## **From Distribution Optimization to Parameter Optimization**</p><p>So far, we have described variational inference as a search over probability distributions. In practice, the approximate distribution is parameterized by a set of variational parameters, denoted by φ:</p><p>q(z; φ)</p><p>For example, if the approximate distribution is Gaussian, its parameters determine the mean and variance. Adjusting these parameters changes both the central location of the distribution and the uncertainty associated with the latent variable.</p><p>The optimization problem becomes:</p><p>φ★ = arg max (over φ): L(q(·; φ))</p><p>Rather than searching directly over distributions, we optimize the parameters that define a distribution within the chosen variational family. This reformulation connects probabilistic inference to parameter-based machine learning optimization.</p><p>### **The Limits of the Variational Family**</p><p>Maximizing ELBO does not guarantee that the approximate distribution will exactly reproduce the true posterior. The quality of the approximation also depends on the expressive capacity of the variational family.</p><p>For instance, a single Gaussian distribution cannot perfectly represent a posterior with multiple distinct modes. Even if optimization finds the best possible Gaussian approximation, some posterior approximation error may remain.</p><p>Choosing a variational family therefore involves balancing the expressive capacity of the approximate distribution with the efficiency of optimizing it.</p><p>## **How ELBO Connects Probabilistic Inference to Neural Networks**</p><p>The Variational Autoencoder (VAE) applies variational optimization to neural network training.</p><p>Its encoder computes the parameters of an approximate posterior distribution from the observed data, while its decoder models the conditional distribution of the data given the latent variables.</p><p>Both networks are trained to maximize ELBO. The expected log-likelihood encourages latent configurations that explain the observed data, while the prior KL divergence accounts for deviations from the prior.</p><p>Through this shared objective, variational inference becomes part of the learning process of a probabilistic generative model.</p><p>## **The Takeaway**</p><p>ELBO transforms posterior inference into an optimization problem without requiring the exact marginal likelihood.</p><p>Its defining identity is:</p><p>log p(x) = L(q) + KL(q(z) ∥ p(z ∣ x))</p><p>Its practical optimization form is:</p><p>L(q) = 𝔼(q)[log p(x ∣ z)] − KL(q(z) ∥ p(z))</p><p>For a fixed observation and probabilistic model, maximizing ELBO minimizes posterior KL divergence through an objective that balances expected log-likelihood with prior regularization.</p><p>The achievable approximation accuracy remains limited by the expressive capacity of the chosen variational family. ELBO provides the optimization objective; the variational family determines which posterior approximations are possible.</p><p>Explore more structured AI lectures:<br><a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40eec88493d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variational Inference: Turning Posterior Approximation into an Optimization Problem]]></title>
            <link>https://medium.com/@zeromathai/https-zeromathai-com-en-variational-inference-approximate-posterior-course-en-77122271af08?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/77122271af08</guid>
            <category><![CDATA[variational-inference]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[probabilistic-modelling]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 04:36:01 GMT</pubDate>
            <atom:updated>2026-12-02T04:36:01.483Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at:<br><a href="https://zeromathai.com/en/variational-inference-approximate-posterior-course-en/">https://zeromathai.com/en/variational-inference-approximate-posterior-course-en/</a></p><p>## **When the Posterior Is Too Difficult to Compute**</p><p>Imagine looking at a photograph of a face with one cheek in shadow. The shadow could result from the orientation of the face, the lighting conditions, or a combination of both. The pixels are observable, but the underlying conditions that produced them are not.</p><p>Because different combinations of hidden conditions can generate similar observations, committing to a single explanation would overlook the uncertainty involved. A probabilistic model instead represents that uncertainty through a distribution over possible explanations.</p><p>This is where Bayesian inference becomes useful. It is also where a fundamental computational problem emerges: the posterior distribution we want to obtain may be too complicated to calculate directly.</p><p>**Variational inference (VI) addresses this problem by replacing an intractable posterior distribution with a computationally manageable approximation.** Rather than calculating the exact posterior, it searches within a chosen family of distributions for an approximation that minimizes a specified divergence from the target.</p><p>The central insight is that probabilistic inference can be reformulated as an optimization problem.</p><p>## **The Computational Bottleneck Behind Bayesian Inference**</p><p>Consider a probabilistic model with two types of variables:</p><p>- x: observed data, such as the pixels of a photograph.<br>- z: latent variables, such as facial orientation and lighting conditions.</p><p>Latent variables represent underlying factors that cannot be observed directly. Before observing the photograph, the model describes possible latent configurations through a prior distribution, p(z). After observing the photograph, it updates those possibilities through a posterior distribution, p(z | x).</p><p>Bayes’ theorem connects these distributions:</p><p>p(z ∣ x) = [p(x ∣ z) · p(z)] / p(x)</p><p>Each component has a distinct role:</p><p>- **Prior — p(z):** Describes possible latent configurations before observing the data.<br>- **Likelihood — p(x | z):** Describes the probability or probability density of the observed data under a particular latent configuration.<br>- **Marginal likelihood — p(x):** Represents the probability or probability density of the observation after accounting for all possible latent configurations.<br>- **Posterior — p(z | x):** Describes the updated distribution over latent variables after observing the data.</p><p>The computational difficulty lies primarily in the denominator, p(x), also known as the evidence. For continuous latent variables, it is expressed as:</p><p>p(x) = ∫ p(x ∣ z) · p(z) dz</p><p>This integral accounts for the contribution of every possible latent configuration to the probability or probability density of the observed data. In the photograph example, the model must consider all possible facial orientations and lighting conditions that could have produced the image.</p><p>For simple probabilistic models, the integral may be evaluated exactly. As the dimensionality of the latent variables increases or their relationships become more complicated, however, exact evaluation can become computationally intractable.</p><p>Variational inference approaches this difficulty by introducing an alternative distribution whose structure is easier to work with.</p><p>## **From Exact Inference to Distribution Optimization**</p><p>Let q(z) denote a distribution intended to approximate the true posterior p(z | x). This is called a **variational distribution**. When its dependence on the observed data needs to be explicit, it can also be written as q(z | x).</p><p>Suppose we approximate the posterior over facial orientation using a Gaussian distribution. Its mean determines the central orientation, while its variance represents uncertainty around that estimate. Adjusting these quantities produces different candidate distributions.</p><p>To select an appropriate candidate, we need a criterion for measuring the discrepancy between the approximation and the true posterior. Variational inference commonly uses Kullback–Leibler divergence, or KL divergence, for this purpose.</p><p>### **KL Divergence as an Optimization Criterion**</p><p>The commonly used direction of KL divergence in variational inference is:</p><p>KL(q(z) ∥ p(z ∣ x)) = 𝔼[log(q(z) / p(z ∣ x))], with z ∼ q(z)</p><p>Equivalently:</p><p>KL(q(z) ∥ p(z ∣ x)) = 𝔼[log q(z)] − 𝔼[log p(z ∣ x)], with z ∼ q(z)</p><p>The expectation is taken with respect to the approximate distribution q(z). As a result, the discrepancy is evaluated with particular emphasis on regions where the approximation assigns substantial probability mass.</p><p>KL divergence has two important properties:</p><p>- It is nonnegative and equals zero when the two distributions agree almost everywhere.<br>- It is asymmetric: reversing the order of the distributions can change its value.</p><p>Unlike an ordinary mathematical distance, KL divergence depends on the direction in which the distributions are compared.</p><p>The objective of variational inference is to find an approximate distribution that minimizes its KL divergence from the true posterior. This approach is also known as variational Bayes. However, directly evaluating this objective remains difficult because it depends on the exact posterior that motivated the approximation in the first place.</p><p>## **The Variational Family: Choosing What the Approximation Can Represent**</p><p>Searching over arbitrary probability distributions would undermine the computational advantages of variational inference. Instead, we restrict the approximation to a predefined collection of distributions known as a **variational family**.</p><p>For example, a variational family might consist of all univariate Gaussian distributions with different means and positive variances.</p><p>Let Q denote the chosen variational family. The inference problem becomes:</p><p>q★(z) = argmin KL(q(z) ∥ p(z ∣ x)), over q ∈ Q</p><p>Here, argmin identifies the distribution that minimizes the objective, and q★(z) represents the optimal approximation within Q.</p><p>The qualification *within Q* is essential. Variational inference does not necessarily recover the true posterior. It seeks the distribution that minimizes KL divergence among the candidates permitted by the chosen family.</p><p>### **The Trade-Off Between Expressiveness and Efficiency**</p><p>Return to the facial orientation example. Suppose the true posterior assigns substantial probability to orientations near both 0° and 30°. The resulting distribution may have two distinct peaks, representing two plausible explanations for the observed photograph.</p><p>A single Gaussian distribution cannot reproduce this bimodal structure exactly, regardless of how its mean and variance are adjusted. The limitation lies in the expressive capacity of the chosen family rather than necessarily in the optimization process.</p><p>This illustrates a fundamental trade-off:</p><p>- **Computational efficiency:** Simpler distribution families make probability calculations and optimization more manageable but restrict what the approximation can represent.<br>- **Approximation accuracy:** More expressive families can capture more complicated posterior structures but may introduce additional computational and optimization costs.</p><p>Even successful optimization leaves approximation error when the true posterior lies outside the chosen family. Conversely, selecting a highly expressive family does not guarantee a good approximation if the optimization itself is difficult.</p><p>The choice of variational family therefore influences both the computational cost of inference and the posterior structures that the approximation can capture.</p><p>## **Mean-Field Approximation: Simplifying the Structure of Uncertainty**</p><p>A photograph may depend on several latent variables, including facial orientation, lighting, and expression. A posterior distribution must account not only for uncertainty about each variable but also for the relationships among them.</p><p>A joint probability distribution represents these possibilities together. As the number of latent variables increases, representing and computing their dependencies can become increasingly difficult.</p><p>The **mean-field approximation** simplifies the approximation to the joint posterior by imposing an independence assumption. Under a fully factorized mean-field approximation, the approximate joint distribution is expressed as a product of individual distributions:</p><p>q(z) = ∏ qⱼ(zⱼ), for j = 1, …, m</p><p>For three latent variables:</p><p>q(z₁, z₂, z₃) = q₁(z₁) · q₂(z₂) · q₃(z₃)</p><p>If the variables represent facial orientation, lighting, and expression, each factor describes the approximate distribution of its corresponding variable.</p><p>This decomposition of a distribution into a product of factors is called factorization. It reduces the complexity of the approximation by avoiding the need to represent dependencies explicitly.</p><p>### **Matching Distribution Types to Latent Variables**</p><p>Mean-field factorization does not require every latent variable to follow the same type of probability distribution. Individual factors can be selected according to the characteristics of the variables they represent.</p><p>Continuous: Gaussian distribution — Facial orientation<br>Binary: Bernoulli distribution — Lighting switched on or off<br>Categorical: Categorical distribution — Facial expression</p><p>A Gaussian distribution represents continuous uncertainty through its mean and variance.</p><p>A Bernoulli distribution represents uncertainty between two possible states. In a neural network, a sigmoid function can be used to compute its probability parameter.</p><p>A categorical distribution represents uncertainty across multiple discrete categories. A softmax function can produce the corresponding probabilities while ensuring that they sum to one.</p><p>### **Independence Is a Modeling Constraint**</p><p>Suppose a particular facial orientation is especially plausible under a particular lighting condition. The true posterior may capture this relationship by assigning high probability to specific combinations of the two variables. A fully factorized approximation cannot directly represent that dependency.</p><p>**The independence assumption applies to the approximate distribution, not necessarily to the underlying latent variables or the true posterior.**</p><p>Nor does independence in the approximate distribution imply independence during optimization. Although the joint approximation is expressed as a product of individual factors, those factors contribute to a shared objective. Updating one factor can therefore influence the optimization of another.</p><p>Mean-field approximation trades the ability to represent posterior dependencies for a simpler distribution structure.</p><p>## **Parameterization: From Searching Over Distributions to Optimizing Parameters**</p><p>Restricting the variational family defines which distributions are available. Parameterization provides a practical way to search among them.</p><p>Rather than modifying the probability density at every possible point, we describe the distribution through adjustable quantities that determine its shape. These quantities are called **variational parameters**, commonly denoted by φ.</p><p>A parameterized variational distribution can be written as:</p><p>q(z; φ) (the variational distribution parameterized by φ)</p><p>For a univariate Gaussian distribution:</p><p>q(z; φ) = 𝒩(z; μ, σ²)</p><p>φ = (μ, σ²)</p><p>Here, μ determines the center of the distribution, while the positive variance σ² controls its spread. Adjusting these parameters changes the distribution without requiring its probability density to be modified point by point.</p><p>The original distribution-level optimization problem can now be expressed as a parameter-level optimization problem:</p><p>φ★ = argmin KL(q(z; φ) ∥ p(z ∣ x)), over φ</p><p>The goal is to find the parameters that minimize KL divergence within the selected variational family.</p><p>Conceptually, the optimization process begins with an initial set of parameters, evaluates an appropriate objective, and repeatedly updates those parameters to improve the approximation.</p><p>This formulation brings together three complementary ideas:</p><p>- **Factorization** simplifies the structure of the approximate joint distribution.<br>- **Parameterization** expresses the distribution through adjustable quantities.<br>- **Optimization** searches for parameters that minimize the discrepancy according to the chosen objective.</p><p>Together, these ideas make complex probabilistic inference accessible to numerical optimization techniques. The resulting approximation, however, remains subject to the representational constraints of the chosen family.</p><p>## **Why Practical Variational Inference Maximizes the ELBO**</p><p>Parameterization makes the approximate distribution easier to optimize, but it does not eliminate the original computational difficulty. The KL divergence objective still contains p(z | x), which may be intractable to evaluate.</p><p>Practical variational inference addresses this problem through an alternative objective called the **Evidence Lower Bound (ELBO)**.</p><p>For fixed observed data and a fixed probabilistic model, maximizing the ELBO is equivalent to minimizing the KL divergence between the approximate posterior and the true posterior.</p><p>KL divergence defines the discrepancy that variational inference seeks to minimize, while the ELBO provides a more tractable optimization objective that avoids directly calculating the exact posterior.</p><p>## **How This Leads to Variational Autoencoders**</p><p>A Variational Autoencoder (VAE) combines variational inference with neural networks. Its encoder computes the parameters of an approximate posterior distribution conditioned on the input data, and the network is trained using an ELBO-based objective. In this way, parameterized posterior approximation becomes part of a neural network architecture without requiring direct calculation of the true posterior.</p><p>## **The Takeaway**</p><p>The defining idea of variational inference is not simply to replace a complicated distribution with a simpler one. It is to make posterior approximation an optimization problem with an explicit objective and a deliberately restricted search space.</p><p>The central trade-off is between computational efficiency and representational flexibility. A simpler variational family can make inference more manageable while sacrificing important posterior structure. A more expressive family can capture richer uncertainty but may be harder to optimize. Effective variational inference depends on balancing these competing considerations.</p><p>Explore more structured AI lectures:<br><a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77122271af08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encoder–Decoder and Autoencoders: How Neural Networks Learn to Represent Data]]></title>
            <link>https://medium.com/@zeromathai/https-zeromathai-com-en-elbo-variational-optimization-course-en-908deda928ec?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/908deda928ec</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[representation-learning]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 04:31:05 GMT</pubDate>
            <atom:updated>2026-12-01T04:31:05.071Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at:<br> <a href="https://zeromathai.com/en/encoder-decoder-autoencoder-course-en/">https://zeromathai.com/en/encoder-decoder-autoencoder-course-en/</a><br> <br> <br> ## **Learning to Represent Data Instead of Simply Storing It**<br> <br> <br> A 28 × 28 handwritten digit contains 784 pixel values. Yet much of the information that characterizes the digit lies in the relationships between those pixels: the direction of a stroke, its thickness, and the curvature of a line.<br> <br> <br> A neural network does not necessarily need to preserve every pixel independently to reconstruct a recognizable version of the image. It can learn a more compact representation that captures information distributed across the original pixels.<br> <br> <br> The challenge is determining which information to preserve without explicitly telling the network what constitutes an important feature.<br> <br> <br> Autoencoders approach this problem through reconstruction. By learning to reproduce their own inputs, they can develop internal representations that capture useful properties of the data. The architecture behind this process is a broader design pattern known as the encoder–decoder.<br> <br> <br> ## **The Encoder–Decoder Architecture: Separating Representation from Output**<br> <br> <br> The encoder–decoder architecture divides information processing into two complementary responsibilities:<br> <br> <br> — **Encoder:** Transforms input data into an internal representation suitable for a particular task.<br> — **Decoder:** Interprets that representation and produces the required output.<br> <br> <br> The basic information flow is:<br> <br> <br> x → Encoder → h → Decoder → y<br> <br> <br> Here, x is the input, h is the internal representation, and y is the output. The intermediate representation h is commonly called a **latent code** or **latent representation**.<br> <br> <br> An encoder might transform a 784-dimensional handwritten image into a 32-dimensional vector. Rather than selecting 32 individual pixels, it learns to combine information from multiple input components into a new representation. The decoder then uses that representation to construct an output.<br> <br> <br> The architectural principle is that representing information and producing an output are distinct but interconnected operations. Each component can be designed around its own responsibility while being trained as part of a larger system.<br> <br> <br> Importantly, encoding does not necessarily mean compression. The internal representation can have fewer, the same number of, or more dimensions than the input. Likewise, the decoder does not have to reproduce the original data.<br> <br> <br> This flexibility makes the encoder–decoder pattern useful across several deep learning architectures:<br> <br> <br> — **U-Net** extracts image features and produces pixel-level segmentation results. Skip connections also transfer intermediate encoder features directly to the decoder.<br> — **Sequence-to-Sequence models** transform an input sequence into an internal representation and use it to generate another sequence, such as a translated sentence.<br> — **Encoder–Decoder Transformers** use attention to represent information from an input sequence and generate an output sequence.<br> <br> <br> The encoder and decoder can be constructed using multilayer perceptrons (MLPs), convolutional neural networks (CNNs), long short-term memory networks (LSTMs), or attention mechanisms, depending on the characteristics of the data.<br> <br> <br> An autoencoder is a specific application of this architectural pattern. What distinguishes it is not the choice of neural network components, but the objective those components are trained to achieve.<br> <br> <br> ## **Autoencoders: Using Reconstruction to Learn Features**<br> <br> <br> At the beginning of training, an encoder has no predefined understanding of which properties of an image are worth preserving. An autoencoder addresses this problem by making the original input its own training target.<br> <br> <br> The network transforms the input into a latent code and then uses that code to reconstruct the original data. If the representation fails to preserve information needed for reconstruction, the output will differ from the input. That discrepancy provides a learning signal.<br> <br> <br> For the handwritten digit example, the dimensional flow is:<br> <br> <br> 784 → 32 → 784<br> <br> <br> The encoder maps the image into a 32-dimensional latent representation, and the decoder reconstructs an image with the original 784 dimensions. During training, both components are updated to reduce the difference between the original and reconstructed images.<br> <br> <br> Mathematically, let x represent the input, h the latent code, and x̃ the reconstructed output. The encoder is a function f_φ with trainable parameters φ, while the decoder is a function g_θ with trainable parameters θ.<br> <br> <br> The encoding operation is:<br> <br> <br> h = f_φ(x)<br> <br> <br> The decoding operation is:<br> <br> <br> x̃ = g_θ(h)<br> <br> <br> Combining these operations gives:<br> <br> <br> x̃ = g_θ(f_φ(x)) ≈ x<br> <br> <br> The encoder and decoder are trained jointly. The encoder learns to preserve information needed by the decoder, while the decoder learns to interpret that representation.<br> <br> <br> This arrangement also removes the need for externally supplied labels. A handwritten digit classifier typically requires information about which number appears in each image, but an autoencoder already has its training target: the image itself.<br> <br> <br> Autoencoders are therefore traditionally associated with **unsupervised learning**. They can also be understood from the perspective of **self-supervised learning**, since the training target comes directly from the input data.<br> <br> <br> ## **Reconstruction Loss: How the Network Learns What to Preserve**<br> <br> <br> Reconstruction becomes a practical learning objective only when the network has a numerical way to measure the quality of its output.<br> <br> <br> **Reconstruction loss** measures the discrepancy between the original input and its reconstruction. Early in training, reconstructed images may be blurry or contain distorted shapes. Reducing the reconstruction loss encourages the network to reproduce the input more accurately.<br> <br> <br> For continuous numerical data, one common choice is Mean Squared Error (MSE):<br> <br> <br> L_recon(x, x̃) = (1/d) Σ_{i=1}^{d} (x_i − x̃_i)²<br> <br> <br> Here:<br> <br> <br> — d is the dimensionality of the input.<br> — x_i is the original value of the i-th component.<br> — x̃_i is the corresponding reconstructed value.<br> <br> <br> MSE calculates the average squared difference between corresponding input and output components. Squaring prevents positive and negative errors from canceling each other out and penalizes larger errors more heavily.<br> <br> <br> Consider a pixel whose original value is 0.9. If the decoder reconstructs it as 0.5, the squared error is:<br> <br> <br> (0.9 − 0.5)² = 0.16<br> <br> <br> If further training improves the reconstructed value to 0.8, the squared error becomes:<br> <br> <br> (0.9 − 0.8)² = 0.01<br> <br> <br> For a handwritten image containing 784 pixels, the reconstruction loss averages these squared errors across the entire image. MSE is one possible choice; other reconstruction loss functions may be appropriate depending on the nature of the data.<br> <br> <br> Although reconstruction loss is measured at the output, its influence extends throughout the network. Backpropagation calculates the gradients of the loss with respect to the parameters of both the encoder and decoder. Through repeated parameter updates, the encoder learns to preserve information that contributes to accurate reconstruction, while the decoder learns to make better use of that information.<br> <br> <br> Once trained, the encoder can also serve as an independent feature extractor. Instead of passing the original pixel values to a classification model or clustering algorithm, we can provide the learned latent representation.<br> <br> <br> This is the broader idea of **representation learning**: learning internal features from data rather than manually specifying them.<br> <br> <br> However, information that helps reconstruct an image is not necessarily information that helps classify it or discover meaningful groups within a dataset. A low reconstruction loss does not guarantee that the latent representation captures useful semantic features.<br> <br> <br> **Reconstruction is the direct training objective; learning useful representations is the desired outcome.** The distinction between these two goals explains why architectural constraints matter.<br> <br> <br> ## **The Bottleneck: Preventing Reconstruction from Becoming Simple Copying**<br> <br> <br> Consider an autoencoder whose encoder passes the input through unchanged and whose decoder copies it directly to the output. Its reconstruction loss would be zero, but it would have no need to discover useful features or reorganize information.<br> <br> <br> The problem is not that the network has failed to optimize its objective. It has optimized that objective without learning the kind of representation we wanted.<br> <br> <br> Autoencoder design must therefore consider not only how accurately the network reconstructs its input, but also the conditions under which it achieves that reconstruction. The relationship between input dimensionality and latent dimensionality is an important part of this design.<br> <br> <br> ### **Undercomplete Autoencoders: Learning Through a Narrow Representation**<br> <br> <br> An undercomplete autoencoder has a latent representation with fewer dimensions than its input:<br> <br> <br> dim(x) &gt; dim(h)<br> <br> <br> The handwritten digit example, with its 784-dimensional input and 32-dimensional latent code, is an undercomplete architecture. Its narrow intermediate representation is known as a **bottleneck**.<br> <br> <br> By limiting the dimensionality of the information available to the decoder, the bottleneck encourages the encoder to organize information into a more compact representation rather than assigning each input component to a separate latent component.<br> <br> <br> However, a narrow latent space does not automatically guarantee meaningful features. If the bottleneck is too restrictive, important information may be lost. A sufficiently expressive neural network may also memorize its training data despite having a low-dimensional latent representation.<br> <br> <br> ### **Overcomplete Autoencoders: Learning Without Dimensionality Reduction**<br> <br> <br> An overcomplete autoencoder uses a latent representation with more dimensions than its input:<br> <br> <br> dim(h) &gt; dim(x)<br> <br> <br> For example:<br> <br> <br> 784 → 1,024 → 784<br> <br> <br> An expanded latent space provides room to represent a wider variety of features. Representation learning, in other words, does not necessarily require dimensionality reduction.<br> <br> <br> The difficulty is that a larger latent space also makes trivial copying easier. Additional training constraints become particularly important in preventing the network from reconstructing its input without developing useful internal features.<br> <br> <br> Two representative approaches address this problem:<br> <br> <br> — **Sparsity constraints** limit the number of active components in the latent representation.<br> — **Denoising objectives** train the network to reconstruct clean data from a corrupted input.<br> <br> <br> These approaches constrain how the network achieves reconstruction rather than relying exclusively on a reduction in latent dimensionality.<br> <br> <br> | Design property | Undercomplete Autoencoder | Overcomplete Autoencoder |<br> | — — | — — | — — |<br> | Latent dimensionality | Smaller than the input | Larger than the input |<br> | Example architecture | 784 → 32 → 784 | 784 → 1,024 → 784 |<br> | Representation space | Compact | Expanded |<br> | Main design risks | Information loss and memorization | Trivial copying |<br> | Important design considerations | Bottleneck size and model capacity | Additional training constraints |<br> <br> <br> The comparison reveals a broader architectural principle: the usefulness of a learned representation depends on the interaction between latent dimensionality, network capacity, and training constraints. Neither compression nor expansion alone determines representation quality.<br> <br> <br> ## **From Deterministic Codes to Probabilistic Representations**<br> <br> <br> A conventional autoencoder typically maps each input to a single latent code. With fixed model parameters, the same input produces the same representation. This is known as **deterministic encoding**.<br> <br> <br> Stochastic encoding changes the nature of this mapping. Instead of directly computing a single latent code, the encoder defines a probability distribution over possible codes.<br> <br> <br> Consider one component of a latent representation. A deterministic encoder might assign it a fixed value of 0.8. A stochastic encoder could instead define a normal distribution with a mean of 0.8 and a standard deviation of 0.1.<br> <br> <br> Sampling from that distribution might produce values such as 0.76 or 0.91. The input remains the same, but the sampled representation can vary.<br> <br> <br> The same distinction applies to decoding: a decoder can either compute an output directly or define a probability distribution from which outputs are sampled.<br> <br> <br> These probabilistic mappings are expressed using **conditional probability distributions**.<br> <br> <br> For a stochastic encoder:<br> <br> <br> h ∼ q_enc,φ(h | x)<br> <br> <br> For a stochastic decoder:<br> <br> <br> x̃ ∼ p_dec,θ(x̃ | h)<br> <br> <br> The distribution q_enc,φ describes possible latent codes given the input x. The distribution p_dec,θ describes possible reconstructed outputs given the latent code h.<br> <br> <br> The vertical bar indicates the information being conditioned on, while the symbol ∼ indicates that a value follows, or is sampled from, the specified distribution.<br> <br> <br> | Component | Deterministic | Stochastic |<br> | — — | — — | — — |<br> | Encoder | Computes a latent code | Defines a conditional distribution over latent codes |<br> | Decoder | Computes an output | Defines a conditional distribution over outputs |<br> | Repeated encoding | Same input produces the same code | Same input can produce different sampled codes |<br> | Repeated decoding | Same code produces the same output | Same code can produce different sampled outputs |<br> <br> <br> The underlying encoder–decoder pattern remains the same, but the mathematical interpretation of its components changes. Replacing deterministic transformations with probabilistic mappings allows the architecture to model variability in latent representations and outputs.<br> <br> <br> ## **Why Reconstruction Alone Is Not Enough for Generation**<br> <br> <br> Introducing randomness into an autoencoder does not automatically make it an effective generative model. The fundamental difference lies in the information available during reconstruction and generation.<br> <br> <br> During reconstruction, an existing input guides the encoder toward a latent representation from which the decoder attempts to recover the original data. During generation, there may be no original input. The model must select an appropriate latent code and produce meaningful data without relying on an existing example.<br> <br> <br> A latent space that supports accurate reconstruction is not necessarily organized in a way that supports this kind of generation.<br> <br> <br> This distinction motivates the **Variational Autoencoder (VAE)**, which combines the autoencoder architecture with probabilistic latent variable modeling and variational inference. The conceptual shift is from learning representations that preserve information for reconstruction to learning a latent space that also supports meaningful generation.<br> <br> <br> Explore more structured AI lectures:<br> <a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=908deda928ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variational Autoencoders: From Learning Representations to Generating Data]]></title>
            <link>https://medium.com/@zeromathai/https-zeromathai-com-en-variational-autoencoder-vae-course-en-b962771ceebc?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b962771ceebc</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[variational-inference]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 02:06:01 GMT</pubDate>
            <atom:updated>2026-11-30T02:06:01.485Z</atom:updated>
            <content:encoded><![CDATA[<p>“Originally published at:<br><a href="https://zeromathai.com/en/variational-autoencoder-vae-course-en/">https://zeromathai.com/en/variational-autoencoder-vae-course-en/</a></p><p>An autoencoder can learn to reconstruct a handwritten digit. But can it generate a new handwritten digit without seeing an original image?</p><p>These tasks may appear closely related, yet they place different demands on a model’s internal representation. Reconstruction requires preserving enough information about an existing input. Generation requires a way to select meaningful latent variables even when no input is available.</p><p>A Variational Autoencoder (VAE) bridges this gap by combining the representation-learning architecture of an autoencoder with probabilistic modeling and variational inference. Instead of mapping each input to a fixed latent code, it represents the input through a probability distribution and models how observations are generated from latent variables.</p><p>Understanding this transition reveals why VAEs need more than an encoder, a decoder, and a reconstruction loss. They also need an approximate posterior, a tractable learning objective, and a differentiable way to handle random sampling.</p><p>## **1. Why Reconstruction Is Not Enough**</p><p>A handwritten image contains many pixels, but its meaningful structure can often be described through a smaller set of characteristics, such as digit shape, stroke thickness, and slant. An encoder–decoder architecture exploits this distinction between raw observations and internal representations.</p><p>**Input → Encoder → Latent Representation → Decoder → Output**</p><p>The encoder extracts information from the input, while the decoder uses that information to construct an output. An autoencoder specializes this architecture for reconstruction, learning to produce an output that closely matches the original input.</p><p>h = f_φ(x)</p><p>x̃ = g_θ(h) = g_θ(f_φ(x)) ≈ x</p><p>Here, f_φ is the encoder, g_θ is the decoder, and h is the latent representation. The parameters φ and θ are learned jointly.</p><p>For continuous data, a typical reconstruction objective is mean squared error:</p><p>L_recon = (1/D) Σᵢ₌₁ᴰ (xᵢ − x̃ᵢ)²</p><p>D denotes the dimensionality of the input.</p><p>Because the input itself provides the reconstruction target, separate labels are unnecessary. The resulting latent representations can also support tasks such as classification and clustering. Learning useful internal representations from data is known as representation learning.</p><p>However, low reconstruction error does not necessarily indicate meaningful representation learning. A sufficiently flexible network may simply learn to copy its input.</p><p>Undercomplete autoencoders address this problem by restricting the latent representation to fewer dimensions than the input. Overcomplete autoencoders use larger representations, offering greater expressive capacity but potentially requiring additional constraints to prevent trivial copying.</p><p>Even when these constraints produce useful representations, another problem remains: the model has learned to decode latent codes obtained from real inputs, not arbitrary codes selected from the latent space. It may reconstruct existing images accurately while producing meaningless outputs from unfamiliar latent codes.</p><p>**A representation suitable for reconstruction is not automatically suitable for generation.**</p><p>Generating new data requires both a principled way to select latent variables and a learned relationship between those variables and observable data.</p><p>## **2. From Reconstruction to Probabilistic Generation**</p><p>A generative model learns the distribution of observed data so that it can produce new observations resembling the training data.</p><p>VAEs belong to the family of likelihood-based generative models. They define a probability distribution over observations and optimize a likelihood-related objective. In contrast, implicit generative models such as GANs learn a generation process without directly evaluating the resulting probability density.</p><p>The central idea behind a VAE is to introduce latent variables that influence how observations are generated.</p><p>Consider a handwritten digit. Changing its slant affects many pixels simultaneously. These pixels exhibit dependencies because they share underlying factors of variation.</p><p>An autoregressive model represents dependencies by conditioning each data component on previously generated components. A latent variable model takes a different approach: it introduces hidden variables that can influence multiple observed components.</p><p>The generative process of a latent variable model is defined as:</p><p>z ∼ p(z)</p><p>x ∼ p_θ(x | z)</p><p>First, a latent variable z is sampled from a prior distribution p(z). An observation x is then sampled from the conditional distribution p_θ(x | z).</p><p>Together, these distributions define the joint distribution:</p><p>p_θ(x, z) = p(z) p_θ(x | z)</p><p>This formulation gives the decoder a new role. Rather than merely converting an internal representation into an output, it defines the conditional probability distribution of observations given a latent variable.</p><p>Even when individual pixels are modeled as conditionally independent given z, dependencies can still emerge in the overall data distribution because those pixels share the same latent variable.</p><p>### **The difficulty of evaluating marginal likelihood**</p><p>Sampling from the generative model is relatively straightforward. Evaluating the probability or density assigned to a particular observation is considerably harder.</p><p>Different latent variables may generate similar observations. Evaluating the overall likelihood of an observation therefore requires accounting for all possible latent variables.</p><p>p_θ(x) = ∫ p_θ(x, z) dz</p><p>p_θ(x) = ∫ p(z) p_θ(x | z) dz</p><p>This operation is called marginalization, and p_θ(x) is the marginal likelihood. For discrete latent variables, the integral is replaced by a sum.</p><p>Ideally, the generative model would learn by assigning high marginal likelihood to the training data. However, when the latent space is high-dimensional and the conditional distribution is defined by a complex neural network, this integral is generally difficult to evaluate exactly.</p><p>This computational difficulty leads directly to variational inference.</p><p>## **3. Variational Inference: Turning Inference into Optimization**</p><p>The generative model describes how latent variables produce observations. Training also requires reasoning in the opposite direction: given an observation, which latent variables could explain it?</p><p>This relationship is described by the posterior distribution. Using Bayes’ theorem:</p><p>p_θ(z | x) = p(z) p_θ(x | z) / p_θ(x)</p><p>The numerator combines the prior density or probability of a latent variable with the likelihood of the observation given that variable. The denominator normalizes the posterior distribution.</p><p>Unfortunately, that denominator is precisely the marginal likelihood that is difficult to compute.</p><p>One possibility is to estimate the marginal likelihood by sampling latent variables from the prior and averaging their conditional likelihoods. But if the latent variables that explain an observation well occupy only a narrow region of the latent space, most prior samples may contribute little to the estimate.</p><p>Variational inference takes a different approach. Instead of calculating the true posterior directly, it introduces a tractable approximation and optimizes that approximation to resemble the true posterior.</p><p>Let q(z) denote the approximate posterior. Its discrepancy from the true posterior can be measured using Kullback–Leibler (KL) divergence:</p><p>D_KL[q(z) ∥ p_θ(z | x)] = E_{z ∼ q(z)}[log(q(z) / p_θ(z | x))]</p><p>The inference problem becomes an optimization problem:</p><p>q*(z) = argmin_{q ∈ Q} D_KL[q(z) ∥ p_θ(z | x)]</p><p>Here, Q is the variational family: the collection of distributions available to approximate the posterior.</p><p>KL divergence is nonnegative and becomes zero when the distributions coincide. It is not a symmetric distance metric, so the ordering of the distributions matters.</p><p>### **Tractability comes with a trade-off**</p><p>A common way to simplify the approximate posterior is the mean-field approximation, which factorizes the distribution across latent dimensions.</p><p>q(z) = ∏ₖ₌₁ᴷ qₖ(zₖ)</p><p>This assumption makes inference more manageable, but it restricts the dependencies that the approximate distribution can represent.</p><p>Importantly, the independence assumption belongs to the approximation. It does not imply that the true posterior has independent latent variables. Variational inference therefore involves a trade-off between computational tractability and the expressive capacity of the approximate posterior.</p><p>### **Why the encoder becomes an inference network**</p><p>If the approximate posterior is Gaussian, inference can be performed by optimizing its distribution parameters, such as its mean and variance. Repeating this optimization independently for every observation, however, can be computationally expensive.</p><p>A VAE replaces these separate optimization procedures with a shared neural network.</p><p>λₓ = f_φ(x)</p><p>q_φ(z | x) = q(z; f_φ(x))</p><p>The encoder learns to predict the parameters of an approximate posterior directly from an observation. This approach is called amortized inference.</p><p>Once trained, the encoder can construct an approximate posterior for a new input through a forward pass rather than a separate iterative optimization process. The encoder is no longer simply a feature extractor; it becomes a learned probabilistic inference mechanism.</p><p>One problem remains: the KL divergence used to define variational inference still contains the intractable true posterior. The Evidence Lower Bound resolves this difficulty.</p><p>## **4. ELBO: A Tractable Objective for Probabilistic Learning**</p><p>The Evidence Lower Bound (ELBO) is the mathematical foundation of VAE training. It replaces direct optimization of an intractable marginal likelihood with an objective that can be evaluated or estimated without computing the true posterior.</p><p>Substituting Bayes’ theorem into the posterior KL divergence gives:</p><p>D_KL[q(z) ∥ p_θ(z | x)] = E_{q(z)}[log q(z) − log p_θ(x, z)] + log p_θ(x)</p><p>For a fixed observation x and fixed generative model parameters θ, the log marginal likelihood does not depend on q. Its exact value is therefore unnecessary when optimizing the approximate posterior.</p><p>This relationship leads to the ELBO:</p><p>ELBO(q, θ; x) = E_{q(z)}[log p_θ(x, z) − log q(z)]</p><p>The log marginal likelihood can then be decomposed as:</p><p>log p_θ(x) = ELBO(q, θ; x) + D_KL[q(z) ∥ p_θ(z | x)]</p><p>Because KL divergence is nonnegative:</p><p>ELBO(q, θ; x) ≤ log p_θ(x)</p><p>The ELBO is a lower bound on the log marginal likelihood. The gap between them is exactly the KL divergence between the approximate posterior and the true posterior. When the two distributions coincide, the bound becomes exact.</p><p>For a fixed generative model, maximizing the ELBO is therefore equivalent to minimizing the KL divergence between the approximate and true posteriors.</p><p>### **Reconstruction and regularization**</p><p>Applying the latent variable factorization to the ELBO and introducing the encoder-defined posterior gives the familiar VAE objective:</p><p>ELBO(x, θ, φ) = E_{z ∼ q_φ(z | x)}[log p_θ(x | z)] − D_KL[q_φ(z | x) ∥ p(z)]</p><p>The two terms serve complementary purposes.</p><p>- **Reconstruction term:** Measures how well latent samples from the approximate posterior allow the decoder to explain the observed input.<br>- **Regularization term:** Penalizes deviations between the input-dependent approximate posterior and the shared prior distribution used for generation.</p><p>Together, they encourage the model to preserve information about individual observations while organizing latent representations around a common probabilistic structure.</p><p>### **Two KL divergences with different roles**</p><p>The ELBO derivation contains two KL divergences that should not be confused.</p><p>D_KL[q_φ(z | x) ∥ p_θ(z | x)]</p><p>This measures the posterior approximation gap and determines how tightly the ELBO bounds the log marginal likelihood.</p><p>D_KL[q_φ(z | x) ∥ p(z)]</p><p>This is the regularization term inside the VAE objective. It measures how far the approximate posterior deviates from the prior.</p><p>A small prior KL divergence does not necessarily indicate an accurate approximation of the true posterior.</p><p>There is also an important distinction between optimizing inference for a fixed generative model and jointly training the entire VAE. When θ changes, both the marginal likelihood and the true posterior change. Joint training therefore maximizes a tractable lower bound, but an increase in the ELBO does not guarantee an increase of the same magnitude in the actual log marginal likelihood.</p><p>## **5. The VAE Architecture: From Latent Points to Latent Distributions**</p><p>The mathematical framework now translates into a neural architecture. The encoder constructs an approximate posterior, a sampling operation selects a latent vector, and the decoder defines an output probability distribution.</p><p>**Input → Encoder → Approximate Posterior → Latent Sampling → Decoder → Output Probability Distribution**</p><p>Unlike a conventional autoencoder, the VAE uses both the encoder and decoder to parameterize conditional probability distributions.</p><p>### **The encoder defines a latent distribution**</p><p>A deterministic autoencoder maps an input to a single latent point. A VAE maps that input to a distribution from which different latent vectors can be sampled.</p><p>A common choice is a Gaussian approximate posterior with diagonal covariance:</p><p>q_φ(z | x) = N(z; μ_φ(x), Σ_φ(x))</p><p>Σ_φ(x) = diag(σ₁²(x), …, σ_K²(x))</p><p>For a K-dimensional latent space, the encoder determines K means and K variances.</p><p>The mean vector specifies the center of the distribution, while the variances describe the spread of the approximate posterior along individual latent dimensions. Diagonal covariance restricts the conditional covariance between distinct dimensions to zero.</p><p>The same input can produce identical distribution parameters across forward passes while yielding different sampled latent vectors. The decoder receives a sampled vector, not the entire approximate posterior.</p><p>### **The prior provides a shared sampling distribution**</p><p>To generate observations without an input, the model needs a distribution from which latent variables can be selected.</p><p>A standard VAE commonly uses a multivariate standard normal prior:</p><p>p(z) = N(z; 0, I) = ∏ₖ₌₁ᴷ N(zₖ; 0, 1)</p><p>This prior is easy to sample from. It also allows the KL divergence to be calculated analytically when the approximate posterior is Gaussian with diagonal covariance.</p><p>The encoder produces an input-dependent distribution, while the prior establishes a shared reference distribution for generation.</p><p>### **What makes a latent space useful for generation?**</p><p>Two desirable properties are continuity and completeness.</p><p>**Continuity** means that nearby latent codes should produce similar observations. Small changes in latent variables should ideally correspond to gradual changes in the generated output.</p><p>**Completeness** means that sampling from regions of the latent space where the prior places substantial probability mass should produce meaningful observations.</p><p>A conventional autoencoder can leave untrained regions between the latent codes associated with training examples. Probabilistic encoding and prior regularization help mitigate this problem by encouraging latent representations to occupy a space better suited to generation.</p><p>However, a standard Gaussian prior and KL regularization alone do not guarantee continuity or completeness. Likewise, an independent Gaussian prior does not guarantee that individual latent dimensions will correspond to distinct semantic factors of variation.</p><p>## **6. The Decoder Defines a Probability Distribution**</p><p>A VAE decoder does not simply produce a reconstructed observation. It predicts the parameters of a conditional probability distribution.</p><p>p_θ(x | z) = p(x; g_θ(z))</p><p>The reconstruction loss follows from the negative log-likelihood of the observed data under that distribution.</p><p>ℓ_NLL(x, z) = −log p_θ(x | z)</p><p>This distinction matters because identical numerical decoder outputs can have different interpretations. For example, a decoder output of 0.8 might represent an expected pixel intensity under a Gaussian distribution or an 80% probability that a binary pixel equals 1 under a Bernoulli distribution.</p><p>The choice of output distribution determines both the meaning of the decoder output and the corresponding reconstruction loss.</p><p>### **Gaussian decoder: continuous observations**</p><p>For continuous data, a Gaussian conditional distribution is a natural choice.</p><p>p_θ(x | z) = N(x; μ_θ(z), Σ_θ(z))</p><p>Σ_θ(z) = diag(σ₁²(z), …, σ_D²(z))</p><p>The decoder can predict both the mean and variance or predict the mean while keeping the variance fixed.</p><p>With a fixed isotropic covariance τ²I, the negative log-likelihood becomes:</p><p>−log p_θ(x | z) = (D/2) log(2πτ²) + (1/(2τ²)) ‖x − μ_θ(z)‖²</p><p>The first term is constant when the variance is fixed. The second is proportional to squared reconstruction error.</p><p>Under this assumption, Gaussian negative log-likelihood differs from squared error only by a positive scaling factor and an additive constant, so minimizing either objective is equivalent.</p><p>If the variance is learned, additional variance-dependent terms must be considered, and the objective is no longer equivalent to ordinary mean squared error.</p><p>### **Bernoulli decoder: binary observations**</p><p>For observations whose components take values of either 0 or 1, a Bernoulli decoder predicts the probability of each component being 1.</p><p>Assuming conditional independence:</p><p>p_θ(x | z) = ∏ᵢ₌₁ᴰ βᵢ(z)^(xᵢ) (1 − βᵢ(z))^(1 − xᵢ)</p><p>Its negative log-likelihood is:</p><p>−log p_θ(x | z) = −Σᵢ₌₁ᴰ [xᵢ log βᵢ(z) + (1 − xᵢ) log(1 − βᵢ(z))]</p><p>This is the sum of binary cross-entropy losses across output dimensions.</p><p>### **Categorical decoder: categorical observations**</p><p>When an observation represents one of several possible categories, a categorical distribution can be used. The decoder typically applies softmax to produce category probabilities whose sum equals one.</p><p>p_θ(x | z) = Cat(x; γ(z))</p><p>γⱼ(z) ≥ 0</p><p>Σ_{j=1}^C γⱼ(z) = 1</p><p>For a one-hot encoded observation, the negative log-likelihood becomes:</p><p>−log p_θ(x | z) = −Σ_{j=1}^C xⱼ log γⱼ(z)</p><p>This corresponds to categorical cross-entropy.</p><p>The relationship between the observation model and reconstruction objective can be summarized as follows:</p><p>| Output Distribution | Observation Type | Distribution Parameters | Reconstruction Objective |<br>| — — | — — | — — | — — |<br>| Gaussian | Continuous | Mean and variance | Gaussian NLL; scaled squared error plus a constant for fixed isotropic covariance |<br>| Bernoulli | Binary | Success probability | Binary cross-entropy |<br>| Categorical | Categorical | Category probabilities | Categorical cross-entropy |</p><p>### **A distribution mean is not a generated sample**</p><p>A decoder-defined distribution can be used in two different ways. Its expected value can serve as a representative reconstruction:</p><p>x̂ = E_{p_θ(x | z)}[x]</p><p>Alternatively, an observation can be sampled from the distribution:</p><p>x_sample ∼ p_θ(x | z)</p><p>For a Gaussian decoder, the mean is a representative continuous output. For a Bernoulli decoder, the mean is a probability rather than an actual binary observation.</p><p>The reconstruction loss in a VAE is therefore a probabilistic modeling objective, not merely a numerical comparison between an input and an output.</p><p>## **7. Training the VAE: Balancing Information and Regularization**</p><p>Neural network optimizers generally minimize a loss rather than maximize an objective. VAE training therefore uses the negative ELBO:</p><p>L_VAE(x, θ, φ) = −ELBO(x, θ, φ)</p><p>Expanding the objective gives:</p><p>L_VAE = −E_{z ∼ q_φ(z | x)}[log p_θ(x | z)] + D_KL[q_φ(z | x) ∥ p(z)]</p><p>Equivalently:</p><p>L_VAE = L_recon + L_KL</p><p>The reconstruction loss encourages the latent representation to retain information needed to explain the input. The KL loss encourages the approximate posterior to remain compatible with the prior.</p><p>Optimizing reconstruction alone does not ensure that the latent space supports prior-based generation. Optimizing KL divergence alone can make input-dependent posteriors identical to the prior, removing information that distinguishes observations.</p><p>The VAE objective balances these competing requirements.</p><p>### **Computing the Gaussian KL loss**</p><p>When the approximate posterior is Gaussian with diagonal covariance and the prior is a standard normal distribution, the KL divergence has a closed-form expression:</p><p>L_KL = (1/2) Σₖ₌₁ᴷ [μₖ² + σₖ² − 1 − log(σₖ²)]</p><p>This expression measures deviations from the prior’s zero means and unit variances.</p><p>In practice, the encoder often predicts log variance rather than variance directly:</p><p>vₖ = log(σₖ²)</p><p>σₖ² = exp(vₖ)</p><p>σₖ = exp(vₖ / 2)</p><p>Exponentiation ensures that the resulting variance is positive. The KL loss can then be expressed directly using the encoder’s mean and log-variance outputs:</p><p>L_KL = (1/2) Σₖ₌₁ᴷ [μₖ² + exp(vₖ) − 1 − vₖ]</p><p>This part of the objective can be evaluated analytically without sampling latent variables.</p><p>### **Estimating the expected reconstruction loss**</p><p>Unlike the Gaussian KL term, the reconstruction term is an expectation over the approximate posterior that is generally difficult to evaluate analytically when the decoder is a complex neural network.</p><p>Monte Carlo estimation provides a practical approximation:</p><p>L_recon ≈ −(1/L) Σₗ₌₁ᴸ log p_θ(x | z⁽ˡ⁾)</p><p>z⁽ˡ⁾ ∼ q_φ(z | x)</p><p>The model samples L latent vectors and averages their negative log-likelihoods.</p><p>Increasing the number of samples generally reduces estimation variability but increases computational cost. In minibatch-based training, using a small number of samples per observation is common.</p><p>Estimating the expectation solves one computational problem. It does not yet explain how gradients can pass through the stochastic latent sampling operation. That is the role of the reparameterization trick.</p><p>## **8. The Reparameterization Trick: Learning Through Randomness**</p><p>To learn an approximate posterior that produces useful latent samples, the encoder must receive gradients from the reconstruction loss through the sampled latent vector.</p><p>A direct sampling operation does not explicitly expose the differentiable relationship needed by ordinary backpropagation. The reparameterization trick restructures sampling so that randomness is separated from the learned distribution parameters.</p><p>Instead of directly sampling z from the encoder-defined Gaussian, the model first samples standard normal noise independently of the encoder parameters:</p><p>ε ∼ N(0, I)</p><p>It then transforms that noise using the encoder’s predicted mean and standard deviation:</p><p>z = μ_φ(x) + σ_φ(x) ⊙ ε</p><p>When the encoder predicts log variance, the same transformation becomes:</p><p>z = μ_φ(x) + exp(v_φ(x) / 2) ⊙ ε</p><p>The symbol ⊙ denotes element-wise multiplication.</p><p>The resulting latent vector follows the same Gaussian distribution as a direct sample from the approximate posterior. The difference lies in the computational structure: once ε has been sampled, z is a differentiable function of the encoder’s distribution parameters.</p><p>For each latent dimension:</p><p>∂zₖ / ∂μₖ = 1</p><p>∂zₖ / ∂σₖ = εₖ</p><p>Gradients can therefore propagate through the latent vector to the encoder.</p><p>**Reparameterization does not eliminate randomness. It preserves stochastic sampling while making the sampled latent vector differentiable with respect to the learned distribution parameters.**</p><p>Monte Carlo estimation and reparameterization solve different but complementary problems. Monte Carlo estimation approximates the expected reconstruction loss, while reparameterization allows that estimate to train the encoder through backpropagation.</p><p>### **Putting the training process together**</p><p>Combining the analytical Gaussian KL loss with the sampled reconstruction loss gives the practical VAE objective:</p><p>L_VAE ≈ (1/2) Σₖ₌₁ᴷ [μₖ² + σₖ² − 1 − log(σₖ²)] − (1/L) Σₗ₌₁ᴸ log p_θ(x | z⁽ˡ⁾)</p><p>Each latent sample is obtained through reparameterization:</p><p>z⁽ˡ⁾ = μ_φ(x) + σ_φ(x) ⊙ ε⁽ˡ⁾</p><p>ε⁽ˡ⁾ ∼ N(0, I)</p><p>A complete training iteration follows five stages:</p><p>1. **Encoding:** Compute the mean and log variance of the approximate posterior.<br>2. **Sampling:** Draw standard normal noise and construct a latent vector through reparameterization.<br>3. **Decoding:** Compute the parameters of the conditional output distribution.<br>4. **Loss calculation:** Evaluate the reconstruction loss and analytical KL divergence.<br>5. **Backpropagation and optimization:** Compute gradients of the combined loss and update the encoder and decoder parameters.</p><p>For a standard VAE with a fixed prior, the encoder receives gradients from both loss terms:</p><p>∇_φ L_VAE = ∇_φ L_KL + ∇_φ L_recon</p><p>The decoder receives gradients from the reconstruction term:</p><p>∇_θ L_VAE = ∇_θ L_recon</p><p>The complete optimization problem is to minimize the VAE loss across the training dataset:</p><p>(θ*, φ*) = argmin_{θ, φ} Σᵢ₌₁ᴺ L_VAE(x⁽ⁱ⁾, θ, φ)</p><p>The resulting architecture brings probabilistic modeling, approximate inference, and neural network optimization into a single training process.</p><p>## **9. One Decoder, Three Different Operations**</p><p>Training, reconstruction, and generation use the same decoder. What changes is the source of the latent variable and the purpose of the computation.</p><p>### **Training**</p><p>During training, an observed input is passed through the encoder to construct an approximate posterior. A latent vector is sampled through reparameterization, and the decoder defines an output distribution.</p><p>The reconstruction and KL losses are then used to update the network parameters.</p><p>**Observed Input → Encoder → Approximate Posterior → Reparameterized Sample → Decoder → Output Distribution → VAE Loss → Parameter Updates**</p><p>### **Reconstruction**</p><p>Reconstruction also begins with an existing observation. The encoder provides an approximate posterior, and a latent sample is decoded into an output distribution. A representative value, such as the distribution mean, can be used as the reconstructed output.</p><p>**Observed Input → Encoder → Approximate Posterior → Latent Sample → Decoder → Representative Reconstruction**</p><p>### **Generation**</p><p>Generation does not require an observed input or an encoder forward pass. Instead, the latent variable is sampled directly from the prior and passed to the decoder.</p><p>z ∼ p(z)</p><p>x_sample ∼ p_θ(x | z)</p><p>The information flow becomes:</p><p>**Prior Distribution → Latent Sample → Decoder → Output Distribution → Generated Observation**</p><p>The prior provides a defined starting point for generation, while the decoder provides the probabilistic mechanism that turns latent variables into observations.</p><p>## **10. Understanding the Trade-offs Behind the Architecture**</p><p>The standard VAE relies on several design choices that make probabilistic learning computationally manageable, but those choices also impose limitations.</p><p>A diagonal Gaussian approximate posterior simplifies inference but may not capture complex dependencies in the true posterior. A standard normal prior provides a convenient sampling distribution but does not guarantee continuity, completeness, or semantic disentanglement in the latent space.</p><p>The reconstruction and regularization objectives can also compete. Preserving information about an input and keeping its approximate posterior close to a shared prior are not necessarily aligned goals.</p><p>The decoder introduces another modeling decision: its output distribution must suit the type of data being modeled, since that distribution determines the appropriate reconstruction loss.</p><p>These trade-offs explain why understanding a VAE requires looking beyond its encoder–decoder structure to the probabilistic assumptions and learning objective that define it.</p><p>## **From Representation Learning to Probabilistic Generation**</p><p>A Variational Autoencoder is best understood not as an autoencoder with added Gaussian noise, but as a probabilistic latent variable model implemented through neural networks. Variational inference and the ELBO make posterior approximation and probabilistic learning tractable, while reparameterization connects stochastic sampling to gradient-based optimization.</p><p>The defining insight is that learning to represent existing observations and learning to generate new observations are related but distinct objectives. By connecting them through a shared probabilistic latent space, the VAE transforms an architecture designed for reconstruction into a framework for inference and generation.</p><p>Explore more structured AI lectures:<br><a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b962771ceebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diffusion Models: Learning to Generate by Reversing Noise]]></title>
            <link>https://medium.com/@zeromathai/diffusion-models-learning-to-generate-by-reversing-noise-8d1576888f07?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d1576888f07</guid>
            <category><![CDATA[score-based-model]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[ddpm]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 03:46:01 GMT</pubDate>
            <atom:updated>2026-09-18T03:46:01.489Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at: <a href="https://zeromathai.com/en/diffusion-models-course-en/">https://zeromathai.com/en/diffusion-models-course-en/</a></p><p>Generating high-dimensional data is difficult because the underlying data distribution can be highly complex. Diffusion models approach this problem indirectly. Instead of trying to generate a structured sample in a single step, they first define a process that gradually corrupts real data with Gaussian noise, then learn how to reverse that process.</p><p>The central idea is simple: move from complex data toward a simple noise distribution first, then learn the probabilistic path back.</p><p>Start with a real data sample x₀. Add a small amount of Gaussian noise, then add more over a sequence of steps. As the process continues, the original structure becomes weaker while noise becomes more dominant. Generation then runs in the opposite direction, beginning from noise and recovering structure one step at a time.</p><p>Diffusion turns one difficult generation problem into a sequence of smaller reverse steps.</p><p>From Data to Noise</p><p>The Forward Diffusion Process starts with an original sample x₀ and gradually adds Gaussian noise:</p><p>x₀ → x₁ → x₂ → … → x_T</p><p>Each intermediate state represents a different level of corruption. Early states still retain much of the original structure, while later states contain progressively more noise.</p><p>The transition from one state to the next can be represented as</p><p>q(xₜ | xₜ₋₁)</p><p>This conditional distribution describes how xₜ is produced from the previous state xₜ₋₁ by adding noise.</p><p>Repeated application of these stochastic transitions gradually removes the detailed structure of the original sample. In the theoretical limit of an increasingly long diffusion process,</p><p>T → ∞, x_T ~ 𝒩(0, I)</p><p>the final state approaches an isotropic Gaussian distribution with zero mean and identity covariance.</p><p>This makes the construction useful for generation. The original data distribution may be complicated, but sampling from a Gaussian distribution is straightforward. Once a path from data to noise has been defined, the generative problem becomes a question of how to learn the reverse direction.</p><p>Reverse Diffusion: The Generative Direction</p><p>Forward diffusion moves from data toward noise. Reverse diffusion moves in the opposite direction:</p><p>x_T → x_T₋₁ → … → x₁ → x₀</p><p>Generation begins with a noise sample drawn from the isotropic Gaussian distribution. The model then produces a sequence of progressively less noisy states until a data-like sample is obtained.</p><p>Reverse diffusion, however, is not simply the forward process with the arrows reversed. The forward corruption mechanism is defined in advance, so each step specifies how noise is added. The reverse distribution required for generation must instead be learned from data.</p><p>A single learned reverse transition is written as</p><p>p(xₜ₋₁ | xₜ; θ)</p><p>where θ denotes the learned model parameters.</p><p>A neural network is used to learn these reverse transitions. During generation, the model repeatedly moves from x_T toward x₀, gradually reducing noise and recovering data structure.</p><p>This step-by-step construction is one of the defining characteristics of diffusion models. It makes the generative process analytically tractable while remaining flexible, but it also introduces an important cost: sampling must follow a long sequence of reverse transitions.</p><p>Why Sampling Speed Becomes a Limitation</p><p>The reverse process forms a sequential Markov chain. To generate a sample, the model must move through the chain step by step rather than jumping directly from noise to the final result.</p><p>The model repeatedly applies learned reverse transitions:</p><p>x_T → x_T₋₁ → … → x₀</p><p>Because these steps must be followed sequentially, a long reverse diffusion chain can make sampling slow. The sampling limitation therefore follows directly from the structure of the generative process.</p><p>The Score-Based View</p><p>Diffusion models can also be understood through the perspective of Score-based Generative Models.</p><p>For a probability density p(x), the score function is</p><p>s(x) = ∇ₓ log p(x)</p><p>The score does not represent the probability density itself. Instead, it describes the direction in input space in which the log-density increases.</p><p>Intuitively, the score tells us which direction from the current point leads toward a region of higher probability density. This directional information can help move noisy samples toward regions that better resemble the data distribution.</p><p>This idea appears directly in Score Matching with Langevin Dynamics (SMLD).</p><p>SMLD: Scores Across Multiple Noise Scales</p><p>SMLD estimates the score function at multiple noise scales.</p><p>Generation begins at a high noise level and gradually moves toward lower noise levels. At each scale, the estimated score provides directional information that helps move the sample toward the data distribution.</p><p>SMLD uses Langevin Dynamics during sampling. The overall progression is</p><p>high noise → lower noise → data-like sample</p><p>The connection to diffusion is that SMLD also begins from progressively corrupted data and learns information that can be used to reverse that corruption during generation.</p><p>DDPM: Learning Reverse Probabilistic Transitions</p><p>A Denoising Diffusion Probabilistic Model (DDPM) addresses the same corruption-and-reversal problem through a sequence of probabilistic transitions.</p><p>The forward process adds noise to training data step by step. The model then learns a probabilistic reverse process that reverses each noise-corruption step.</p><p>The reverse transition is represented by</p><p>p(xₜ₋₁ | xₜ; θ)</p><p>and the known functional form of the Reverse Distribution allows the training problem to be formulated tractably.</p><p>DDPM therefore learns the reverse transitions associated with the sequence of noisy states created by the forward process.</p><p>How SMLD and DDPM Connect</p><p>SMLD and DDPM use different training formulations, but they share the same broad structure: data is progressively corrupted by noise, and generation is performed by learning how to reverse that corruption.</p><p>SMLD explicitly estimates the score function at different noise scales:</p><p>s(x) = ∇ₓ log p(x)</p><p>DDPM instead formulates the process through forward and reverse probabilistic transitions.</p><p>When considering a continuous state space with continuous t, the DDPM training objective can be understood as implicitly computing the score associated with each noise scale. From this perspective, SMLD and DDPM can be understood within the broader framework of Score-based Generative Models rather than as completely separate generative principles.</p><p>Diffusion Models and the Generative Modeling Trade-Off</p><p>The characteristics of diffusion models become clearer when compared with other major deep generative model families.</p><p>The representative comparison in the source highlights different limitations:</p><p>* GAN: training may be unstable, and generated diversity may be limited.<br>* VAE: sample quality and dependence on a surrogate loss are presented as key limitations.<br>* Flow-based Model: reversible transformations require specialized architectures.<br>* Diffusion Model: sampling requires a long sequence of diffusion steps, making sampling speed a major limitation.</p><p>The corresponding comparison is:</p><p>| Model family | Quality | Diversity | Speed |<br>| — — — — — — — — | — — — — | — — — — — | — — — |<br>| VAE | × | ○ | ○ |<br>| GAN | ○ | × | ○ |<br>| Flow-based Model | × | ○ | ○ |<br>| Diffusion Model | ○ | ○ | × |</p><p>This table is not an absolute ranking of every implementation. It represents the characteristic trade-offs emphasized for each model family.</p><p>Within this comparison, diffusion models are presented as strong in quality and diversity but weaker in speed. The speed limitation follows from the reverse sampling process itself: generation requires traversing a long Markov chain one step at a time.</p><p>The Core Takeaway</p><p>Diffusion models reformulate generation as a gradual reversal problem.</p><p>They first define a Forward Diffusion Process that moves data toward Gaussian noise, then learn a Reverse Diffusion Process that moves noise back toward data. SMLD approaches this through score estimation across multiple noise scales, while DDPM learns probabilistic reverse transitions and connects to the same score-based perspective when continuous t is considered.</p><p>The central strength of the approach is its stepwise formulation of a difficult generative problem. Its main structural limitation is the same sequence itself: reverse sampling proceeds step by step, making sampling speed a central trade-off.</p><p>Explore more structured AI lectures: <a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d1576888f07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Generative Models: Four Ways to Make Complex Distributions Learnable]]></title>
            <link>https://medium.com/@zeromathai/deep-generative-models-four-ways-to-make-complex-distributions-learnable-c17fc48bc5ac?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c17fc48bc5ac</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[normalizing-flow]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[gans]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 03:41:01 GMT</pubDate>
            <atom:updated>2026-09-16T03:41:01.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at: <a href="https://zeromathai.com/en/deep-generative-models-course-en/">https://zeromathai.com/en/deep-generative-models-course-en/</a></p><p>A generative model is often introduced as a model that can create new data. That is true, but generation is only the visible outcome of a deeper modeling problem.</p><p>Images, audio, and other high-dimensional observations can follow extremely complex probability distributions. The fundamental challenge is therefore not simply how to produce a new sample, but how to represent such a distribution in a form that can actually be computed and learned.</p><p>How can we turn a complex data distribution into a tractable learning problem?</p><p>Different families of deep generative models answer that question in different ways. An Autoregressive Model factorizes a joint distribution into conditional distributions. A Variational Autoencoder (VAE) introduces latent variables and approximate inference. A Flow-based Model transforms a simple distribution through invertible mappings. A Generative Adversarial Network (GAN) moves explicit density evaluation out of the center of the learning problem and instead trains a Generator through competition with a Discriminator.</p><p>These architectures can look unrelated when studied separately. Viewed through probability modeling, however, they become different structural solutions to the same underlying difficulty.</p><p>The real dividing line: what happens to likelihood?</p><p>One useful way to organize deep generative models is by how they treat likelihood.</p><p>On the likelihood-based side are Autoregressive Models, VAEs, Flow-based Models, Diffusion Models, and Score-based Models. Their mechanisms differ, but probability modeling remains central to how the problem is formulated.</p><p>A GAN represents the likelihood-free direction considered here. Rather than making the explicit evaluation of p(x) for an individual observation the central learning task, it trains a Generator through an adversarial objective.</p><p>This distinction is useful because it reveals the architectural decisions behind the model names. When a high-dimensional data distribution is too complicated to handle directly, a model needs some structural way to make the problem manageable. It can factorize the distribution, represent it indirectly through latent variables, transform a simpler distribution into a complex one, or learn the generation process without explicitly evaluating the density of each observation.</p><p>Diffusion Models and Score-based Models also belong to the likelihood-based family in this classification. Their detailed mechanisms, including Forward Diffusion, Reverse Diffusion, and Score Matching, are outside the current scope. Here, the focus is on the modeling strategies that make the broader architectural differences clear.</p><p>Why likelihood leads naturally to NLL</p><p>For likelihood-based modeling, a natural starting point is to make the model distribution as close as possible to the real data distribution.</p><p>Let the data distribution be p_data and the parameterized model distribution be p_model. One way to express the objective is to minimize KL Divergence:</p><p>min_θ D_KL[p_data(x) ∥ p_model(x; θ)]</p><p>Expanding the divergence makes the optimization structure clearer:</p><p>D_KL[p_data ∥ p_model]<br>= E_{x ~ p_data}[log p_data(x)] − E_{x ~ p_data}[log p_model(x; θ)]</p><p>The first term depends only on the data distribution. It corresponds to the negative entropy of that distribution, so once p_data is fixed, changing θ cannot affect it.</p><p>The model therefore needs to optimize only the second term. Including the sign gives</p><p>min_θ E_{x ~ p_data}[−log p_model(x; θ)]</p><p>This is the Cross-Entropy perspective: observations that occur under the real data distribution should receive high probability under the model.</p><p>In practice, the complete p_data is unknown. We only have training samples assumed to come from it, so the expectation is approximated with an average over those observations. The resulting objective is Negative Log-Likelihood (NLL) minimization.</p><p>The progression is therefore:</p><p>Minimize KL Divergence → remove the entropy term independent of θ → minimize Cross-Entropy → minimize NLL over the training data.</p><p>Conceptually, likelihood-based learning tries to place high model probability in regions where real data appears. The difficulty is that this only helps if the architecture makes the relevant likelihood computationally manageable. That requirement is where the major generative-model families begin to separate.</p><p>Strategy 1: factorize the distribution</p><p>An Autoregressive Model handles a difficult joint distribution by decomposing it into a sequence of conditional distributions:</p><p>p(x) = ∏ᵢ₌₁ⁿ p(xᵢ | x₁, …, xᵢ₋₁)</p><p>This decomposition is not an arbitrary approximation. It follows directly from the Probability Chain Rule.</p><p>If x contains a sequence of variables, we can model the first variable, then the second conditioned on the first, then the third conditioned on the previous variables, and continue in the same way. The original joint-distribution problem is reorganized into a series of conditional-distribution problems.</p><p>The complexity has not disappeared, but its form has changed. Instead of requiring one model to represent the entire p(x) at once, the architecture focuses on learning each conditional distribution well.</p><p>GPT, RNNs, PixelRNN, PixelCNN, WaveNet, NADE, and MADE differ in data type and network structure, but they share this probabilistic principle: joint density modeling is turned into conditional density modeling through exact factorization.</p><p>That is the central architectural idea behind autoregressive modeling.</p><p>Strategy 2: explain observations through latent variables</p><p>A VAE takes a different route. Instead of decomposing x according to an ordering, it introduces an unobserved latent variable z and represents the observed distribution through that hidden structure:</p><p>p(x) = ∫ p(z)p(x | z) dz</p><p>Here, p(z) describes the distribution of the latent variable, while p(x | z) describes how an observation is generated for a given latent state. Rather than treating a complex observation as appearing directly, this formulation imagines a latent state z being selected first and x then being generated from it. The probability of x is obtained by considering all possible latent states.</p><p>This gives the model a latent space through which it can represent complexity in the data space, but it also creates an inference problem. Once an observation x is given, the exact posterior over the latent variable z can be difficult to compute.</p><p>A VAE addresses this with two complementary networks. The Encoder, also called the Recognition Network, takes x and constructs an approximate distribution over z rather than mapping the input to a single fixed latent value. The Decoder, or Generative Network, models the conditional distribution of x given z.</p><p>The difficult posterior is approximated through Variational Inference, and training proceeds by maximizing the Evidence Lower Bound (ELBO). The central point here is not the detailed derivation of ELBO, but the structural move made by the VAE: latent-variable modeling and approximate inference turn a difficult probability-modeling problem into one that can be learned.</p><p>Strategy 3: transform a simple distribution into a complex one</p><p>Normalizing Flow approaches the distribution problem from another direction. Autoregressive modeling starts with a complicated joint distribution and decomposes it, while Flow-based modeling starts with a simple distribution and transforms it.</p><p>The basic picture is:</p><p>Simple Distribution → Invertible Transformation → Invertible Transformation → Target Distribution</p><p>A Normalizing Flow does not require one transformation to create the full complexity of the target distribution. Instead, it applies a sequence of transformations, gradually changing the shape of the distribution until the accumulated mapping produces a complex model distribution over the data variable x.</p><p>The critical condition is that these transformations must be invertible. Sending values from a simple distribution into a more complicated space is not sufficient by itself; the model must also be able to trace a transformed value back to its origin so that changes in probability density remain computationally manageable.</p><p>This requirement constrains the architecture. A Flow-based Model cannot freely use arbitrary neural transformations without considering invertibility. Those structural restrictions reduce flexibility, but they make it possible to construct an explicit probability density over x.</p><p>The model can therefore evaluate likelihood and directly optimize NLL on the training data. Saying that a Normalizing Flow models the data distribution does not mean the learned distribution is guaranteed to become identical to the true distribution. It means the architecture provides an explicit model distribution p(x) whose likelihood can be computed and optimized so that real observations receive high probability.</p><p>The defining trade-off is structural: Flow-based Models constrain their transformations in exchange for tractable explicit density modeling.</p><p>Strategy 4: move explicit density evaluation out of the center</p><p>GANs make a more fundamental change to the learning setup. Autoregressive Models reorganize the density, VAEs combine latent variables with approximate inference, and Normalizing Flows preserve explicit density through invertible transformations. A GAN does not make the explicit computation of p(x) for individual observations the central task.</p><p>Instead, it introduces two competing models: a Generator and a Discriminator. The Generator tries to produce samples that resemble real data, while the Discriminator tries to distinguish generated samples from real ones. As the Generator becomes more convincing, discrimination becomes harder; as the Discriminator becomes more effective, the Generator receives pressure to improve its samples.</p><p>These opposing objectives form a Minimax Problem. The learning signal therefore comes from adversarial interaction rather than from directly optimizing the explicit probability assigned to each observed x.</p><p>This is the key reason GAN is categorized here as a Likelihood-Free Model. The goal remains to learn a generation process whose samples resemble the real data distribution, but the route to that goal differs from architectures centered on explicit density evaluation.</p><p>Four structural answers to one modeling problem</p><p>The most useful way to compare these models is not to memorize their components in isolation. The important question is what each architecture does when faced with a complex high-dimensional distribution that is difficult to learn directly.</p><p>Autoregressive Model: Decompose p(x) into a product of conditional distributions, turning joint modeling into a sequence of conditional-modeling problems.</p><p>VAE: Introduce a latent variable z, represent p(x) through a latent generative process, and use Variational Inference and ELBO when exact posterior inference is difficult.</p><p>Flow-based Model: Transform a simple distribution through invertible mappings, preserving an explicit density that can be trained directly with likelihood and NLL.</p><p>GAN: Avoid making explicit p(x) evaluation the central objective and instead learn the Generator through Minimax competition with a Discriminator.</p><p>These are different structural responses to the same underlying question: how can a complex data distribution be turned into a problem that a neural network can actually learn?</p><p>Seen from this perspective, the architecture is not merely a mechanism for producing samples. Each approach reshapes the same difficult distribution-learning problem — through factorization, latent-variable modeling and approximate inference, invertible transformation, or adversarial learning — into a form that can be learned.</p><p>Explore more structured AI lectures: <a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c17fc48bc5ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Cost of Turning Neural Networks Into Probability Distributions]]></title>
            <link>https://medium.com/@zeromathai/the-hidden-cost-of-turning-neural-networks-into-probability-distributions-f871dfc11a3a?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f871dfc11a3a</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[normalization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 03:41:01 GMT</pubDate>
            <atom:updated>2026-09-16T03:41:01.280Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at: <a href="https://zeromathai.com/en/normalizing-constant-course-en/">https://zeromathai.com/en/normalizing-constant-course-en/</a></p><p>A neural network can assign a real-valued score to an input. That does not mean it has defined a probability distribution.</p><p>This distinction matters in deep generative modeling. Neural networks are useful because they can represent complicated functions and flexible data distributions. But an arbitrary network output does not automatically satisfy the mathematical requirements of probability. A valid probability density must be nonnegative, and for a continuous variable, its integral over the entire input space must equal one.</p><p>The normalizing constant enforces that second condition. It looks like a simple denominator, but in expressive neural probability models, computing it can become the central difficulty.</p><p>From a Neural Network Output to a Probability Distribution</p><p>Suppose a neural network defines a real-valued function f(x; θ). For a given input x, the network returns a number, but that number may be positive, zero, or negative. It therefore cannot be interpreted directly as a probability density.</p><p>A natural first step is to exponentiate the output:</p><p>e^{f(x; θ)}</p><p>The exponential is always positive, so it satisfies the nonnegativity requirement. But positivity alone is not enough. The resulting values must also be scaled so that their total mass across the entire input space is one.</p><p>The transformation can be viewed as:</p><p>neural network output → exponentiation → normalization → valid probability distribution</p><p>The normalized model is</p><p>p(x; θ) = e^{f(x; θ)} / Z(θ)</p><p>The numerator assigns positive relative weight to each input. The denominator Z(θ) rescales those values so that the resulting density is properly normalized.</p><p>What the Normalizing Constant Does</p><p>For a continuous probability density, we require</p><p>∫ p(x; θ) dx = 1.</p><p>If the unnormalized quantity is e^{f(x; θ)}, we first need its total mass over the entire input space. That quantity is the normalizing constant:</p><p>Z(θ) = ∫ e^{f(x; θ)} dx.</p><p>Once Z(θ) is placed in the denominator, the total probability becomes</p><p>∫ p(x; θ) dx = [1 / Z(θ)] ∫ e^{f(x; θ)} dx = 1.</p><p>The mechanism is straightforward. The numerator can assign different relative values to different inputs, while Z(θ) adjusts the overall scale so that the final density integrates to one.</p><p>The challenge is not defining Z(θ). It is computing it.</p><p>When Normalization Is Easy</p><p>Normalizing constants are not always difficult to compute. For simple, well-structured distributions, the required normalization factor can be obtained explicitly.</p><p>Consider a multivariate Gaussian with unit covariance:</p><p>p(x; μ) = [1 / (2π)^(d/2)] e^{−‖x − μ‖² / 2}</p><p>Here, the normalization factor is known and depends explicitly on the dimensionality d. The structure of the Gaussian allows the density to be written directly in normalized form.</p><p>This provides a useful contrast with flexible neural probability models. A Gaussian has a prescribed structure, so its normalization factor can be calculated directly. A neural network can represent a much more complicated function, but as that function becomes more flexible, there is no guarantee that the corresponding normalization integral will remain easy to compute.</p><p>Evaluating a Network Is Not the Same as Integrating It</p><p>There is an important computational difference between evaluating a neural network at one point and integrating the function it defines over an entire space.</p><p>For one particular input x, we evaluate</p><p>f(x; θ).</p><p>To obtain the normalizing constant, however, we must compute</p><p>Z(θ) = ∫ e^{f(x; θ)} dx.</p><p>The first operation concerns one given input. The second concerns the behavior of the exponentiated network output across all possible inputs.</p><p>High dimensionality can make this integration even more difficult, especially in domains such as images, but dimensionality alone is not the core issue. The deeper problem is that the integral must cover an arbitrary, potentially complex function defined by a neural network over the entire input space.</p><p>For sufficiently complex models, exact computation of Z(θ) can therefore become intractable.</p><p>The Tractability-Flexibility Tradeoff</p><p>Deep neural networks are useful because of their expressive power. A flexible model can represent complex data distributions, but that flexibility can make the required probability calculations harder.</p><p>A simpler model may be easier to normalize, but its expressivity may be limited. A more expressive model can represent richer distributions, while the integral required for normalization may become harder to handle.</p><p>This is the Tractability-Flexibility Tradeoff:</p><p>simpler structure → easier computation, but more limited expressivity</p><p>greater flexibility → richer distributions, but potentially harder probability computation</p><p>The contrast with the Gaussian makes this tradeoff concrete. Its fixed structure gives us an explicit normalization factor. A flexible neural network can represent a much broader range of functions, but the corresponding integral</p><p>Z(θ) = ∫ e^{f(x; θ)} dx</p><p>may become difficult or intractable to compute exactly.</p><p>Deep generative modeling therefore has to consider two goals at once: how well a model can represent a complex distribution, and whether the probability computations required by that representation can actually be carried out.</p><p>Different Ways Generative Models Handle the Problem</p><p>If the normalizing constant is difficult to compute directly, different generative model families can address the problem in different ways. Their choices reflect different ways of handling the computational difficulty created by normalization while preserving enough flexibility to model complex data.</p><p>Energy-Based Models approach the problem by approximating a normalizing constant that is difficult to compute directly.</p><p>Autoregressive Models, Flow-based Models, and Variational Autoencoders use structural constraints that make the required probability computations more manageable. In this context, a restricted neural network model does not simply mean a model with low expressive power. The restriction is introduced so that probability calculations can be handled within the model structure.</p><p>Generative Adversarial Networks take a different route. Rather than directly constructing an explicit probability density whose normalizing constant must be computed, they focus on modeling the generation process itself.</p><p>Score-based Diffusion Generative Models also avoid direct computation of the normalizing constant.</p><p>These approaches differ in how they handle the same underlying difficulty: representing complex data distributions while dealing with the computational burden introduced by normalization.</p><p>Why the Normalizing Constant Matters</p><p>The normalizing constant is more than a denominator in a probability formula. It marks the point where model expressivity meets the mathematical requirements of a valid probability distribution.</p><p>Starting from</p><p>p(x; θ) = e^{f(x; θ)} / Z(θ),</p><p>the numerator gives the model freedom to assign complex relative values across the input space. The denominator requires us to account for the total mass of that function:</p><p>Z(θ) = ∫ e^{f(x; θ)} dx.</p><p>When the function has a simple structure, as in the Gaussian case, normalization can be computed explicitly. When the function is defined by a highly flexible neural network, exact normalization may become intractable.</p><p>That tension helps explain why deep generative models adopt different strategies. Some approximate the normalizing constant. Some constrain the model so that probability computation remains manageable. Some focus on the generation process rather than directly computing an explicit density. Others avoid direct computation of the normalizing constant.</p><p>The key lesson is that expressive power cannot be considered in isolation. A generative model must also account for whether the probability computations required by that expressivity can actually be performed.</p><p>Explore more structured AI lectures: <a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f871dfc11a3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modeling the Data Distribution: What Generative Models Are Really Learning]]></title>
            <link>https://medium.com/@zeromathai/modeling-the-data-distribution-what-generative-models-are-really-learning-bec18910a54d?source=rss-06739e04ea2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec18910a54d</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[data-distribution]]></category>
            <category><![CDATA[density-estimation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Zeromathai]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 03:36:01 GMT</pubDate>
            <atom:updated>2026-09-13T04:56:04.802Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published at: <a href="https://zeromathai.com/en/data-distribution-modeling-course-en/">https://zeromathai.com/en/data-distribution-modeling-course-en/</a></p><p>A generative model does not begin with the question, “How can I create a new image?”</p><p>The deeper question is: What probability distribution could have produced the data I observe?</p><p>A dataset gives us only a finite collection of samples. The probability distribution behind those samples is hidden. If we can construct a model that approximates that distribution, several capabilities follow from the same foundation: generating new samples, evaluating how plausible an observation is, and capturing structure shared across the data.</p><p>This becomes difficult when the data is high-dimensional. Real data such as images can follow extremely complex distributions, so a useful model needs enough flexibility to capture that structure while remaining tractable enough to train and use. That tension leads directly to the motivation for deep generative models.</p><p>The Dataset Is Not the Distribution</p><p>Suppose we have an image dataset. What we directly possess is a collection of images: individual observations represented as data points. Those observations, however, are not the same thing as the Data Distribution that is assumed to have generated them.</p><p>The usual modeling assumption is that the training examples are independent and identically distributed samples from some unknown distribution:</p><p>{x₁, x₂, …, xₙ} ~ᵢ.ᵢ.ᵈ. p_data(x)</p><p>Each xᵢ is observable, but the analytical form of p_data(x) is not. The equation does not imply that we already know the mathematical formula for the true distribution. Instead, it says that we assume some probability distribution exists behind the observations and that the dataset consists of samples drawn from it.</p><p>This distinction explains why collecting many examples matters. The objective is not to store each sample as an isolated item. By observing repeated statistical patterns and shared structures across samples, we gain evidence about the distribution that cannot be observed directly.</p><p>For images, the difference is especially clear. A dataset contains particular pixel arrays, while the underlying distribution determines which kinds of images tend to occur, which forms are rare, and what structures different images share. Generative modeling tries to recover that underlying probabilistic structure from the samples we can observe.</p><p>From an Unknown Distribution to a Learnable One</p><p>Because p_data(x) is unknown, we cannot simply inspect its formula, evaluate arbitrary probabilities from it, or directly draw new samples from it. Generative modeling therefore introduces a Model Distribution: a parameterized probability distribution whose parameters can be learned from observed data.</p><p>The desired relationship is</p><p>p_model(x; θ) ≈ p_data(x)</p><p>This is not a particular training objective. It expresses the broader goal that the learned Model Distribution should approximate the unknown Data Distribution.</p><p>The distinction is fundamental:</p><p>* Data Distribution is the unknown distribution assumed to generate the observed data.<br>* Model Distribution is the parameterized probability distribution we choose and train using those observations.</p><p>We do not first discover the exact Data Distribution and then build a copy of it. The training samples are the information available to us. We choose a probability model capable of representing their structure and adjust its parameters through training.</p><p>The overall flow can be viewed as:</p><p>observed i.i.d. samples → Model Distribution and training → approximation of the unknown Data Distribution</p><p>The parameters θ determine the specific form of the Model Distribution, while the training samples provide the evidence used to determine which parameter values better represent the structure of the data. The core idea is to use observable samples to model an unobservable distribution.</p><p>Once the Model Distribution has been learned, it supports two important directions of computation. Given a data point, we can ask how plausible it is under the learned distribution. Starting from the learned distribution, we can instead draw a new data point.</p><p>One direction moves from data to probability; the other moves from probability distribution to data. Both are grounded in the same learned distribution.</p><p>One Distribution, Three Perspectives</p><p>Modeling a Data Distribution well means more than producing plausible samples. The same learned distribution can be viewed through three closely connected perspectives: Generation, Density Estimation, and Unsupervised Representation Learning.</p><p>Generation: From Distribution to New Data</p><p>Generation draws a new sample from the learned Model Distribution:</p><p>x_new ~ p_model(x; θ)</p><p>If the model has learned a distribution of dog images, for example, a newly sampled result should exhibit the same kind of structure as the training data. The point is not to reproduce an existing image exactly, but to generate a new data point consistent with the structure represented by the learned distribution.</p><p>Generation is therefore one capability that follows from learning the distribution: sampling new observations that conform to its learned structure.</p><p>Density Estimation: From Data to Probability</p><p>The same distribution can be considered from the opposite direction. Given a new input, Density Estimation asks how plausible that input is under the learned distribution.</p><p>For a model trained on dog images, an input that matches the characteristic structure of those images should be assigned higher probability than one that differs substantially from the training distribution. In this sense, the model identifies the regions in which the data tends to occur.</p><p>This perspective also connects naturally to Anomaly Detection. If an observation lies far from the structure represented by the learned distribution, it can be treated as unusual.</p><p>Generation and Density Estimation are therefore not unrelated tasks. They are two ways of using the same learned probability distribution.</p><p>Representation Learning: Discovering Shared Structure</p><p>A distribution also reflects structure shared across different observations. Individual dog images may have very different pixel values, yet recurring features such as ears, faces, tails, and bodies appear across many examples.</p><p>Learning a distribution therefore involves capturing common patterns rather than treating every observation as an unrelated point. This connects distribution modeling to Unsupervised Representation Learning and Feature Learning. From the perspective of high-dimensional space, learning the structure formed by the data also connects naturally to Manifold Learning.</p><p>Generation, Density Estimation, and Representation Learning are different views of the same underlying problem: where the data tends to exist, what structure its observations share, and what new observations are consistent with that structure. The quality of all three ultimately depends on how well the Data Distribution has been modeled.</p><p>Why High-Dimensional Data Makes Distribution Modeling Difficult</p><p>The basic idea is straightforward until the data becomes high-dimensional. For images and other data with many variables, the possible input space becomes enormous, and the distribution formed by real observations within that space can have a highly complex structure.</p><p>Making individual variables look plausible is not enough. In an image, every pixel could fall within a reasonable range while the image as a whole remains meaningless. Pixels forming an eye must relate coherently to those forming a face, and the face must fit consistently with the rest of the object.</p><p>A Model Distribution therefore has to represent not only plausible values for individual variables but also complex dependencies among many variables.</p><p>This creates the central design challenge. A simple probability distribution may be easy to evaluate and train but too limited to capture the structure of real high-dimensional data. Increasing flexibility allows a model to represent richer structures, yet probability computation and training can become more difficult as the model becomes more expressive.</p><p>The problem is therefore not merely whether we can define a probability distribution. It is whether we can define one that is expressive enough for complex data while remaining computationally manageable.</p><p>The Tractability-Flexibility Tradeoff</p><p>The tension between computational manageability and expressive power is the Tractability-Flexibility Tradeoff.</p><p>Tractability refers to whether operations such as probability evaluation and model training remain practical. Flexibility refers to how richly the model can represent complex forms of the Data Distribution.</p><p>High-dimensional data often requires substantial flexibility because the underlying distribution may contain intricate dependencies among many variables. At the same time, a probability model must remain tractable enough to train and use.</p><p>A simple Gaussian distribution provides a useful illustration. Consider an isotropic Gaussian centered at the mean vector μ:</p><p>p(x; μ) = [1 / (2π)^(d/2)] exp(−‖x − μ‖² / 2)</p><p>Here, x is the data vector, μ is the mean vector at the center of the distribution, and d is the dimensionality of the data space.</p><p>The point of this example is not to analyze the Gaussian in detail. Its simple mathematical structure makes probability evaluation and manipulation relatively easy, giving it high tractability. The same simplicity, however, limits the range of distributions it can represent.</p><p>A single isotropic Gaussian cannot adequately express the complicated structures and variable dependencies found in high-dimensional data such as real images. Its tractability therefore comes with limited flexibility.</p><p>At one end of the tradeoff, a simple model can be easy to compute with but too restrictive to capture the Data Distribution. At the other, greater flexibility is needed to represent complex real-world structure, but increasing that flexibility can make probability evaluation and learning more difficult.</p><p>Generative modeling must operate between these requirements. Oversimplifying the Model Distribution loses important structure, while increasing expressiveness without maintaining tractability can make the model difficult to use.</p><p>The requirement is not simply to increase the number of parameters. What matters is constructing a model powerful enough to represent complex high-dimensional structure while still serving as a workable probability model.</p><p>Why Deep Generative Models Become Necessary</p><p>The motivation for a Deep Generative Model follows naturally from this tradeoff.</p><p>We begin with samples drawn from an unknown Data Distribution:</p><p>{x₁, x₂, …, xₙ} ~ᵢ.ᵢ.ᵈ. p_data(x)</p><p>We then construct a parameterized Model Distribution whose goal is to approximate that hidden distribution:</p><p>p(x; θ) ≈ p_data(x)</p><p>When the true Data Distribution is complex and high-dimensional, the limited flexibility of a simple probability model becomes a serious constraint. The model needs enough expressive power to represent complicated relationships among many variables and the shared structure present across observations.</p><p>Deep Neural Networks provide a way to represent complex relationships through multiple layers. Bringing that expressive capacity into the Model Distribution allows generative modeling to move beyond the limitations of simple probability distributions and represent high-dimensional structure more flexibly.</p><p>That is the central motivation for Deep Generative Models: use the expressive power of deeper models to approximate complex Data Distributions that simpler distributions cannot represent sufficiently well.</p><p>The conceptual progression is direct:</p><p>finite observations → unknown Data Distribution → learnable Model Distribution → high-dimensional complexity → need for greater flexibility → deeper generative models</p><p>Deep generative modeling is therefore motivated by the structure of the modeling problem itself. We observe only samples, while the distribution behind complex high-dimensional data may require far more expressive power than a simple probability distribution can provide.</p><p>A Useful Mental Model</p><p>The most useful way to think about generative modeling is broader than “a model that creates things.” We observe samples rather than the distribution itself, assume those samples came from an unknown Data Distribution, and construct a parameterized Model Distribution that can be learned from them.</p><p>If that distribution is modeled well, the same foundation supports generation, probability evaluation, and representation of shared structure. The challenge is that complex high-dimensional data demands substantial flexibility while probabilistic modeling still requires tractability.</p><p>That is the bridge from basic distribution modeling to deep generative modeling: representing increasingly complex probability distributions while preserving the ability to learn and use the model.</p><p>Explore more structured AI lectures: <a href="https://zeromathai.com/en/">https://zeromathai.com/en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec18910a54d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>