ATLAS NOVA My AtlasVelocer ↗

Technology · Machine learning

Variational autoencoder

Generative machine learning model

A variational autoencoder is a generative model: a machine learning system that learns the probability distribution of a body of data well enough to produce new examples that resemble it.

It is built from two neural networks joined at a narrow waist. The encoder takes a piece of data, such as an image, and compresses it into a small set of numbers called the latent representation; the decoder takes those numbers and reconstructs the original data from them. The narrow waist between them, the bottleneck, is what forces the compression: because only a few numbers pass through, the network must discard detail and keep whatever structure matters most.

Key facts
0.9470Mean Spearman correlation between latent step and molar weight, Winter et al. 2019⁠[1]
1296Network configurations evaluated across four integrative VAE architectures, Simidjievski et al. 2019⁠[2]
26FDA-approved drugs tested, with Dr.VAE outperforming baselines on over half, Rampášek et al. 2019⁠[3]
35Amino acid differences in the most distant functional luxA variant, Hawkins-Hooker et al. 2021⁠[4]

Overview

What a variational autoencoder is

A concrete case makes the shape of the idea clear. Suppose the data are photographs of faces. The encoder might reduce a picture of many thousands of pixels to a handful of numbers, and the decoder must turn those few numbers back into something recognisable as the same face. If it can, the small code has captured the essentials of that face. Because the code is short, faces with similar features end up with similar codes, and the space of codes takes on an organisation that reflects the data rather than the arbitrary numbering of individual files.

A handwritten seven flows through an encoder, a Gaussian latent cloud, and a decoder, with a second path from the prior into the same decoder.
An encoder describes a latent distribution, and a sampled code passes through the decoder to reconstruct the input. New examples use codes sampled from the prior. View full-size image.VAE Reconstruction and Generation Routes by Atlas Nova. Illustration generated with AI for this article and checked against its text.

What makes the model variational is how that code is treated. Rather than mapping each input to one fixed point, the encoder maps it to a small region of the latent space, described by a probability distribution. The model is trained so that these regions overlap and fill the space in an orderly way, following a simple overall shape called the prior. The practical consequence is a smooth latent space: nearby points decode to similar outputs, and a point chosen at random from the prior is likely to decode to something plausible. That is what allows the trained decoder to be used as a generator, fed fresh random codes to produce data that were never in the training set.

The framework is used for three broad purposes. As a generator, it produces new samples. As a representation learner, it supplies the encoder's compact codes as features for other tasks, such as classification or clustering. As a denoiser, it can reconstruct a cleaned version of a corrupted input.

Its recognised strengths are fast and tractable sampling and easy-to-access encoding networks. Variational autoencoders are currently outperformed by other models such as normalising flows and autoregressive models.⁠[5] A further practical difficulty sits inside the training objective itself, which balances two competing goals, accurate reconstruction and a well-ordered latent space; getting that balance right is described as one of the major problems of the method.⁠[6] The broader family of deep generative models, and how these approaches compare, is treated in a comparative review of the field, and the intuitions and mathematics behind variational autoencoders are set out in a dedicated tutorial.⁠[7][8]

A variational autoencoder compresses data to a small probabilistic code and reconstructs it, and the smoothness of that code is what lets it generate new examples.

History

From autoencoders to variational inference

A plain autoencoder is the ancestor of the variational kind, and it is easier to grasp first. It consists of two neural networks trained together: an encoder that squeezes each input into a short code, and a decoder that tries to rebuild the input from that code. Training adjusts both networks to minimise the reconstruction error, the difference between the original and the rebuilt version. Nothing else is asked of the code. The network is free to place each input's code wherever it likes, so long as the decoder can recover the input from it.

That freedom is exactly what causes trouble later. A plain autoencoder organises its latent space for reconstruction, not for sampling. The model compresses well but does not describe a distribution that can be drawn from.

The variational autoencoder is associated with Kingma and Welling (2014). Instead of treating the code as a fixed point, it is treated as a probabilistic latent variable: the data are assumed to have been produced by some underlying hidden factors, and the model's job is to infer the distribution of those factors given the data. Fitting such a model exactly is intractable, so training proceeds by variational inference, an approximation method that replaces the true, unknowable distribution over the latent variables with a simpler learned one that is as close to it as possible. The encoder network supplies that approximation, and the decoder supplies the generative side, mapping latent values back to data.

What made the approach take hold was not only its statistical grounding but its practicality. The whole construction sits on standard neural networks and is trained by stochastic gradient descent, the ordinary workhorse of deep learning, so no specialised inference machinery is needed.⁠[7] A practitioner can build a variational autoencoder from the same components as any other network and fit it with the same tools. The model is appealing because it is built on top of standard function approximators and can be trained with stochastic gradient descent.⁠[7]

The shift from reconstruction to distribution also changes what the latent space is for. The mechanism that produces this smoothness, and the cost it imposes on reconstruction, are covered later. For now the essential contrast is this: a plain autoencoder learns a code that is convenient for rebuilding its inputs, while a variational autoencoder learns a code that is also a usable model of the data's hidden structure, one that can be sampled from and reasoned about probabilistically.

The framing has proved durable. Variational autoencoders are described as powerful generative models that merge elements from statistics and information theory with the flexibility of deep neural networks, an approach that has led to research and variations in VAE design.⁠[9] The same probabilistic view is what allows the model to be extended, adapted, and applied across domains, from images to molecules to gene expression, in the ways later sections describe.

A plain autoencoder compresses for reconstruction; the variational version recasts the code as a probability distribution, fitted by variational inference and trained with ordinary neural-network tools.

How it works

The encoder, the decoder, and the bottleneck

The two halves of a variational autoencoder do different jobs, and the difference is easiest to see by following one input through the model. The encoder is a neural network that reads a piece of data and returns the parameters of a probability distribution over the latent space, so an input is summarised as a cloud of possible codes rather than one fixed point. The decoder is a second neural network that runs the other way: it takes a latent vector and produces a reconstruction in the original data space, whether that is pixels, a sequence of characters, or a table of measurements.⁠[7]

A flow diagram with boxes labeled x, Probabilistic Encoder, μ, σ, ε, z, Probabilistic Decoder, and x', connected by arrows.
A flow diagram with boxes labeled x, Probabilistic Encoder, μ, σ, ε, z, Probabilistic Decoder, and x', connected by arrows. View full-size image.Reparameterized Variational Autoencoder by EugenioTL. CC BY-SA 4.0, via Wikimedia Commons. Scaled to 960 pixels wide; no crop or other changes by Atlas Nova.

Between the two sits the bottleneck, the layer through which the latent vector passes. Its width is constrained so that only a few numbers can carry information from encoder to decoder.⁠[2] That constraint is the whole point. A decoder that could see the full input would have nothing to learn; forced to work from a short code, the pair must discover which features of the data are worth keeping. The compression is lossy by construction, and what survives it tends to be the structure shared across many examples rather than the idiosyncrasies of any one.⁠[2]

During training the encoder's output is used as a distribution, not a point. A latent vector is drawn from the distribution the encoder just described, and that draw is what the decoder receives. Two inputs that are similar will therefore produce overlapping clouds, and the same input can yield slightly different codes on different passes. This sampling is what makes the model variational in practice and not only in name: the decoder is trained to reconstruct correctly from a whole neighbourhood of codes, not from one privileged location, which is what later allows fresh points in that neighbourhood to decode into plausible data.

The shape of those clouds is not left to the network to choose freely. Training pulls the aggregate of the encoded distributions toward a fixed reference distribution called the prior.⁠[10] The prior plays two roles at once. It supplies a target that keeps the clouds from drifting apart into isolated islands, and it defines the region of latent space from which random vectors can later be drawn to generate new samples. If the encoder were allowed to place its clouds anywhere, the space between them would be meaningless and sampling from the prior would produce nonsense; holding the clouds near a known, simple distribution is what makes the space usable as a whole.

A useful way to picture the arrangement is a map on which every input is a small patch of fog rather than a pin. The encoder decides where each patch sits and how spread out it is; the prior is a gentle pull toward the centre of the map and toward a standard size. Because the patches are wide and are drawn toward the same region, neighbouring patches merge, and the map has no blank wilderness between clusters. The decoder, trained on samples from these patches, learns to turn any point in the fog into something recognisable.

Work on sequential data has extended the same encoder-decoder arrangement so that the latent space also carries dependencies across time, using recurrent networks or state-space models to relate one latent vector to the next rather than treating each input independently.⁠[11] The principle survives the extension: an encoder describes a distribution, a decoder consumes draws from it, and a prior keeps the whole space orderly.

One consequence of this design deserves emphasis here, because it shapes everything that follows. The encoder never hands the decoder a definite code; it hands over a distribution, and the training signal must pass through a random draw. How that draw is made compatible with ordinary gradient-based training, and how the two competing pressures on the latent space are balanced in a single objective, are the subjects of the sections that follow.

The encoder returns a mean and a variance, a latent vector is sampled from that distribution, and the decoder rebuilds the input from the sample, all under pressure from a narrow bottleneck and a simple Gaussian prior.

The loss function: reconstruction versus regularization

Training a variational autoencoder means adjusting the encoder and the decoder together so that a single number, the loss, becomes as small as possible. That number is the sum of two terms pulling in different directions. The reconstruction term measures how badly the decoder fails to rebuild its input from the sampled latent code; it is small when the output matches the original closely. The regularization term measures how far the encoder's distributions have drifted from the prior, and it is computed as a Kullback-Leibler divergence, a quantity that scores how much one probability distribution differs from another. The first term wants the code to carry as much detail as possible; the second wants the code to look like the simple reference distribution and nothing more.

A branching diagram connects an encoder, posterior, latent sample, decoder, reconstruction term, and prior comparison to a summed loss, with a numerical example.
The VAE loss adds reconstruction cost to the KL divergence from the prior. A scalar Gaussian example gives a KL term of 0.5 and a total loss of 2.5. View full-size image.Reconstruction and Regularization in VAE Training by Atlas Nova. Illustration generated with AI for this article and checked against its text.

The tension is easy to state in practical terms. If reconstruction dominates, the encoder is free to scatter its distributions wherever it likes, because accurate rebuilding is all that is rewarded. The latent space then becomes sharp and informative for the training examples but poorly organised for anything else: the regions between encoded clouds are uncharted, and a vector drawn from the prior may decode to noise. If the regularization term dominates, the opposite happens. Every encoded distribution is squashed onto the prior, the decoder receives nearly the same code whatever the input, and the reconstructions turn blurry and generic. It has been observed that variational autoencoders tend to ignore the latent variables when the decoding distribution is too flexible, and the cause has been identified in existing training criteria.⁠[12]

Getting the balance right is not a minor detail. The loss of a variational autoencoder is the sum of these two components with contrasting effects, and correctly balancing them is described as a delicate issue and one of the major problems of the method. The difficulty is structural rather than a matter of careless tuning: as reconstruction improves during training, the reconstruction term shrinks, and a fixed weighting lets the regularization term dominate by default, which then blocks further improvement in the quality of reconstructions.⁠[6] A common remedy is to let the weighting adapt. One approach replaces hand-tuned scheduling with a simple deterministic computation that expresses the balancing factor as a running average of the reconstruction error over recent minibatches, so that as reconstruction improves the divergence term is proportionally reduced;.

The two terms also interact with how tightly the model is fitted to the data at all. The training objective is a lower bound on the likelihood of the data, and a loose bound permits the model to settle for simplified representations that fail to use the network's full capacity. Drawing several samples from the encoder's distribution for each input and weighting them gives a strictly tighter bound, and models trained this way learn richer latent representations, with improved test likelihood on density-estimation benchmarks.⁠[13] The same underlying issue appears from another angle in work that decomposes the objective and isolates a term measuring the total correlation between latent variables; that analysis motivated a refinement of the objective aimed at disentangled representations, requiring no additional hyperparameters during training.⁠[14] Both lines of work treat the balance between the two terms not as a nuisance to be tuned away but as the place where the model's behaviour is decided.

A useful way to hold the two pressures together is to think of the loss as a negotiation over how much the code is allowed to say. The reconstruction term argues for detail; the divergence term argues for conformity to a simple, sampleable shape. The trained model is the settlement they reach, and the settlement determines what the latent space is good for. A model that leans toward reconstruction yields faithful reconstructions and a code rich in information about the training data, which suits it to being used as a feature extractor. A model that leans toward the prior yields a tidy space that can be sampled from freely, at some cost in sharpness. Neither setting is correct in the abstract; the right balance depends on whether the model is wanted chiefly as a generator or as a representation learner, a distinction that later applications make concrete.

The loss is a tug-of-war between rebuilding the input faithfully and keeping the latent code close to a simple prior, and where the rope settles decides whether the model is a sharp reconstructor or a clean generator.

Reparameterization and the training trick

The loss described so far cannot be minimised by the usual method without a further step, and the obstacle is the random draw at the centre of the model. Neural networks are trained by backpropagation, which carries an error signal backwards through each computation to work out how a small change in every weight would change the loss. That procedure needs every step in the forward pass to be a deterministic function of its inputs, so that a derivative can be written for it. Sampling a latent vector from the encoder's distribution is not such a function: it is a random event, and randomness has no derivative to pass backwards. Left in that form, the training signal would stop dead at the sampling step and the encoder would never learn.

A two-panel diagram with Ukrainian labels showing a original formulation where a stochastic node z is sampled from Φ and x and feeds t, and a reparameterized formulation where z is computed from Φ, x and a noise node ϵ, with forward-propagation and backpropagation arrows and a legend.
A two-panel diagram with Ukrainian labels showing a original formulation where a stochastic node z is sampled from Φ and x and feeds t, and a reparameterized formulation where z is computed from Φ, x and a noise node ϵ, with forward-propagation and backpropagation arrows and a legend. View full-size image.Reparameterization Trick uk by File:Reparameterization Trick.jpg : EugenioTL derivative work: Olexa Riznyk. CC BY-SA 4.0, via Wikimedia Commons. Scaled to 960 pixels wide; no crop or other changes by Atlas Nova.

The reparameterization trick removes the blockage by rewriting the draw. Instead of sampling a vector directly from the encoder's distribution, the model samples a fixed random noise vector from a simple standard distribution, one that does not depend on any network weight, and then builds the latent vector from that noise by an ordinary arithmetic formula. For a Gaussian encoder the formula is a shift and a stretch: take the encoder's mean, add the encoder's standard deviation multiplied by the noise draw, and the result is a sample from the intended distribution. The randomness now enters as an input rather than as an operation inside the path, and the mean and standard deviation sit in the formula as ordinary values that can be differentiated.

The consequence is that gradients flow through the sample to both networks. The noise draw is treated as fixed for that pass, so the derivative with respect to the mean is one and with respect to the standard deviation is the noise itself, and the error signal continues backwards into the encoder's weights. Encoder and decoder are then trained together by the same optimiser, end to end, with no separate inference procedure and no special machinery beyond the standard tools of deep learning. This is the step that lets the whole model be trained end to end with stochastic gradient descent.⁠[7]

The trick also explains why the encoder is built to output a mean and a variance rather than a single code. Those two quantities are exactly what the formula needs, and they are what the regularisation term compares against the prior, so one design choice serves both the sampling and the training objective. The statistical grounding of the whole arrangement, in which a learned approximation stands in for a distribution that cannot be computed exactly, is the variational inference framework on which the model rests.⁠[7]

Sampling is rewritten as a deterministic function of the encoder's mean, its standard deviation, and a fixed noise draw, which lets gradients pass through the random step and the whole model train end to end.

Uses

Generating new samples and exploring the latent space

Once training is finished, the decoder becomes a generator in its own right. The encoder is no longer needed for this use: a vector is drawn at random from the prior, handed to the decoder, and the decoder turns it into an output in the data space. Because training pulled the encoder's distributions toward that same prior, a random draw lands in a region the decoder has been trained to handle, so the result is usually something plausible rather than noise. Drawing many such vectors produces many samples, each different, all sharing the general character of the training data. This is the plainest sense in which the model is generative: it does not retrieve stored examples but constructs new ones from a distribution it has learned.

A flowchart diagram with boxes and arrows showing input x passing through a green trapezoid labeled in Ukrainian as a probabilistic encoder, then to μ, σ, and ε boxes combined into latent z, then through a blue trapezoid labeled as a probabilistic decoder to output x'.
A flowchart diagram with boxes and arrows showing input x passing through a green trapezoid labeled in Ukrainian as a probabilistic encoder, then to μ, σ, and ε boxes combined into latent z, then through a blue trapezoid labeled as a probabilistic decoder to output x'. View full-size image.Reparameterized Variational Autoencoder uk by File:Reparameterized Variational Autoencoder.jpg : EugenioTL derivative work: Olexa Riznyk. CC BY-SA 4.0, via Wikimedia Commons. Scaled to 960 pixels wide; no crop or other changes by Atlas Nova.

The second use of the trained model is quieter but often more useful. The latent space is continuous, and the decoder is a smooth function of its input, so a small step in the latent space tends to produce a small change in the output. Moving along a path between two encoded points yields a sequence of outputs that shade gradually from one to the other, rather than jumping between unrelated results. This property is what makes the space navigable: a direction in it can be treated as a knob, and turning the knob changes some quality of the generated output in a graded way. The catch is that the axes of the space are not labelled. Nothing in training says which direction controls which feature, so the directions have to be discovered by experiment.

Chemistry offers a clear demonstration, because a molecule can be written as a string of characters and a string can be encoded. A translation model built on the autoencoder idea was trained on roughly 72 million compounds to convert one textual representation of a molecule into another, forcing the shared chemical meaning through a low-dimensional continuous vector.⁠[1] Once trained, that vector served as a reversible descriptor: any molecule could be encoded into it, and any point in it could be decoded back into a structure.

Shifting a molecule's vector step by step along the first principal component of the training data produced smooth structural transitions, apparently adding or removing atoms; shifting along the second component appeared to alter the molecule's polarity.⁠[1] The impression was checked numerically. Across 1000 randomly picked compounds shifted ten steps each way along the first component, the mean Spearman correlation between step and molar weight was r = 0.9470, and along the second component the mean Spearman correlation between step and partition coefficient was r = –0.916.⁠[1] These are correlations between a direction in the learned space and a measurable property, not proof that the model was told about either.

The same logic applies to biological sequences, where the space of possible molecules is far too large to search by hand. Variational autoencoders trained on a family of almost 70,000 luciferase-like protein sequences were used to generate new variants of the luxA subunit of bacterial luciferase, and a number of the generated sequences were synthesised and tested for light production in E. coli. Of the variants generated without any conditioning, 6 of 12 from the model working on raw sequences and 9 of 11 from the model working on aligned sequences retained measurable luminescence, and all 23 of the closer variants produced by conditional versions of the models did so; the most distant functional variant differed from its nearest training sequence at 35 positions. Conditional versions, trained with solubility information attached, also produced variants with increased solubility without disrupting function.⁠[4]

What these examples share is a shift in what the latent space is for. In reconstruction it is a compressed description of the input; in generation it is a workshop. A point in it is a recipe, the decoder is the machine that builds from the recipe, and the smoothness of the mapping is what makes the workshop safe to move around in. A random point gives a plausible object; a short step gives a similar object with one quality nudged; a long step gives something further away, and the further the step the greater the chance the decoder produces something invalid or implausible. The chemistry case makes the last point concrete: shifting along a direction correlated with molecular size corresponds to adding or removing atoms.⁠[1]

Two cautions follow from the same picture. The first is that a direction found in one dataset need not mean the same thing in another, since the axes are an artefact of training rather than a fixed coordinate system with named dimensions. The second is that a correlation between a direction and a property is a description of the trained model, not a law about molecules or proteins; it says that this decoder, trained on this data, happens to organise its space that way. Both cautions matter when the space is used to propose candidates for synthesis or testing, because a proposal is only as meaningful as the region it came from.

The generative and exploratory uses are therefore two sides of one capability. Sampling from the prior produces novel outputs; moving through the space produces related outputs in a controlled way. Neither requires labels, and neither requires retraining once the model is fitted, which is why the approach has been taken up wherever a large unlabelled corpus exists and the supply of labelled examples is short. How the same latent vectors serve as features for prediction tasks, and where the approach runs into difficulty, are covered later.

A trained decoder turns random prior vectors into new samples and turns short steps in the latent space into graded changes in the output, which makes the space something to explore rather than merely to compress with.

FROM THE STUDY [4]

Variants retaining measurable luminescence

Unconditional AR-VAE
50% · 6 of 12
Unconditional MSA VAE
≈ 81.82% · 9 of 11
Variants retaining measurable luminescenceUnconditional AR-VAE: 6 / 12 observations · 50%; Unconditional MSA VAE: 9 / 11 observations · ≈ 81.82%
0255075100
Percent (%)
Variants retaining measurable luminescence. Percent (%). Count (n): observations. Bars are each count as a share of its total. Source: Hawkins-Hooker.

About half the variants from the unconditional AR-VAE kept measurable luminescence, compared with most of those from the unconditional MSA VAE. So the MSA VAE did better, though the groups were small.

Exact supplied values
Exact supplied values
Record IDSourceSource locatorGroupNumeratorDenominator
g1-unconditional-ar-vaepaper“Altogether 6/12 of the variants generated using the unconditional AR-VAE and 9/11 generated using the unconditional MSA VAE retained measurable luminescence, together with all 23 of the less distant variants generated by conditional versions of the models; the most distant functional variant contain”Unconditional AR-VAE612
g2-unconditional-msa-vaepaper“Altogether 6/12 of the variants generated using the unconditional AR-VAE and 9/11 generated using the unconditional MSA VAE retained measurable luminescence, together with all 23 of the less distant variants generated by conditional versions of the models; the most distant functional variant contain”Unconditional MSA VAE911
Study context and limitations

Population: Hawkins-Hooker, A., Depardieu, F., Baur, S., Couairon, G., Chen, A., & Bikard, D. (2021). Generating functional protein variants with variational autoencoders. PLOS Computational Biology , 17 (2), e1008736. doi:10.1371/journal.pcbi.1008736

Design: Other. Each bar is a count out of its own total, both exactly as the source prints them.

Selection: The 2 counts the source's text prints together with a total.

Limitations: Values are exactly as printed in the source; nothing was calculated, rounded or inferred. A difference between rows is not by itself a causal comparison.

Sources and provenance

Source titles, citations and record identifiers remain in their original form.

Representation learning for downstream tasks

A trained encoder is a machine for turning an object into a short list of numbers, and that list can be handed to any other model as a feature vector: a fixed-length numerical description of an input, used as the input to a separate predictor or grouping method. Nothing about this use requires the decoder. Once the encoder has learned to compress in a way that lets the decoder rebuild its inputs, the codes themselves carry the structure the model found, and a classifier, a clustering routine, or a plotting method can work on those codes instead of on the raw data. The appeal is that the features are learned from the data rather than designed by hand, so they can capture regularities that a person writing rules might not think to encode.

An upper encoder and decoder training pipeline connects to a lower frozen encoder whose numerical feature vector branches to classification, clustering, and plotting.
Unlabeled training learns an encoder that can supply compact features to other methods. Labels are used to fit the downstream classifier. View full-size image.Reusing Learned Codes for Downstream Tasks by Atlas Nova. Illustration generated with AI for this article and checked against its text.

The case for learned features is strongest where handcrafted descriptions are well established and can be compared against directly. Molecular fingerprints are the standard example: they encode structural or functional features of a molecule as a bit string, and they are used for virtual screening, similarity searching, and clustering.⁠[1] A fingerprint is a human design choice about which substructures count. A model trained on a large corpus of chemical structures can instead learn a continuous descriptor from the data itself, and the question is whether that learned description does the same jobs as well.

That question was put to a direct test with a model built on the autoencoder idea, trained on roughly 72 million compounds to translate one textual representation of a molecule into another and thereby force the shared chemical meaning through a low-dimensional continuous vector.⁠[1] The resulting vector was then used as a descriptor in quantitative structure-activity relationship modelling, the task of predicting a measured biological or physical property of a molecule from its structure. Benchmarked against several human-engineered fingerprints and against graph-convolution models trained end-to-end on each dataset, the learned descriptor performed competitively across all the analysed datasets. The authors also note that their feature extraction was fixed using two datasets while the baselines were allowed to choose among nine fingerprint flavours and three learning algorithms per task, so the comparison ran against their method rather than in its favour.⁠[1]

The same pattern appears outside chemistry, in a domain where the handcrafted features are acoustic rather than structural. Birdsong and mouse vocalisations are usually described by a small set of named measurements computed per syllable, such as duration, spectral entropy, and goodness of pitch, and these numbers then feed clustering and comparison. A variational autoencoder trained instead on spectrograms of single syllables learned its own compact description, and that learned description outperformed the common handpicked feature sets on a range of analysis tasks: capturing acoustic similarity, representing a known effect of social context on zebra finch song, and comparing the vocalisations of different mouse strains. The learned features were also more parsimonious and captured more of the variability in the data.⁠[15] The finding is not that the acoustic measurements were wrong, but that a description fitted to the data found dimensions of variation the handpicked list did not cover.

A third setting shows why the representation is often wanted as a preprocessing step rather than as an end in itself. Cancer patient data arrive in several forms at once, from gene expression to clinical records, and the sample sizes are small relative to the number of measured variables. Variational autoencoders can be used to learn a joint low-dimensional representation of such heterogeneous data, which is then available to any downstream machine learning technique. In an evaluation on breast cancer data, all four integrative architectures tested produced better representations than a linear transformation approach, which indicates that the models were capturing non-linear structure in the integrated data while still reducing its dimensionality.⁠[2] The details of that comparison, and the role of regularization in it, are covered later.

What ties these cases together is a division of labour. The autoencoder is trained without labels, on nothing but the data's own structure, and the labels enter only afterwards, when the extracted features are used to predict something. This is what makes the approach attractive when labelled examples are scarce and unlabelled ones are plentiful: the expensive part, learning a good description, does not need the labels, and the cheap part, fitting a predictor on top of the description, does. The vocalisation study makes the trade explicit, noting that its model must be trained per dataset, at a cost of roughly an hour on a graphics processor, and that the resulting features are less interpretable than named acoustic measurements like duration.⁠[15]

That last point is the standing cost of the method. A learned feature vector has no natural name, and its individual dimensions need not correspond to anything a domain expert would recognise. The chemistry case offers a partial answer, since the descriptor space was continuous and reversible, and shifts along its principal components correlated with molecular weight and with polarity.⁠[1] But that is a description of how one trained model happened to organise its space, discovered by experiment, not a guarantee that the axes mean anything in general. Where interpretability matters, the learned representation is usually paired with a separate step that tries to attach meaning to it, and where it does not, the representation is simply used as a convenient input to the next model in the chain.

An encoder trained without labels yields a compact feature vector that can feed any downstream predictor, and in chemistry and in animal vocalisation studies those learned features matched or beat the handcrafted descriptions they were compared against.

Research

Evidence from biomedical data integration

Biomedical research rarely produces one tidy table per patient. A cancer study may measure gene expression, copy number changes, methylation, and clinical history for the same person, and each of these is a different modality: a distinct kind of measurement, taken with its own instrument, carrying its own noise and its own scale. Analysing each modality separately misses the relationships between them, and the relationships are often where the biology is. A variational autoencoder offers a way to combine them, because its encoder can be built to read several inputs at once and compress them into a single shared latent representation, from which the decoder tries to rebuild every modality. The model is then trained on the whole patient at once rather than on one data type at a time.

A diagram with a purple proteomics retention-time abundance plot on the left, a QTL analysis box plot of quantitative trait by genotype (A/A, A/G, G/G) on the right, and a brace below labeled pQTL Analysis.
A diagram with a purple proteomics retention-time abundance plot on the left, a QTL analysis box plot of quantitative trait by genotype (A/A, A/G, G/G) on the right, and a brace below labeled pQTL Analysis. View full-size image.PQTL analysis 1 by Waldmanhd. CC BY-SA 4.0, via Wikimedia Commons. Scaled to 960 pixels wide; no crop or other changes by Atlas Nova.

The reason this matters is that the modalities are not independent views of nothing; they are partial views of one underlying state. Gene expression and protein abundance can be complementary, each revealing something the other does not, and they can also be redundant, with a protein's abundance confirming that a particular transcript was translated. A joint representation can in principle capture both the shared signal and the modality-specific detail, which is what makes the combined code more informative than any single measurement.⁠[16] The practical hope is that the resulting low-dimensional vector summarises a patient well enough that a simple classifier on top of it can predict diagnosis or survival.

That hope was tested directly on breast cancer data. A systematic evaluation built four different integrative variational autoencoder architectures and ran them across 1296 network configurations, integrating multi-omics and clinical data from the Molecular Taxonomy of Breast Cancer International Consortium cohort.⁠[2] The scale of the sweep is the point: rather than proposing one architecture and reporting that it works, the study varied how the data were fused, how wide the hidden layers were, and how the latent space was regularised, then compared the outcomes. All four integrative architectures produced better representations of the data than a linear transformation approach, which suggests the models were capturing non-linear structure in the integrated data while still reducing its dimensionality.⁠[2]

Two findings from that sweep are more useful than the headline. The first concerns regularisation. The quality of the learned representations depended heavily on choosing an appropriate regularisation term during training, and the integrative models yielded better and more disentangled representations when a maximum mean discrepancy term was used, a measure of how far two distributions differ that here pushes the encoded distributions toward the prior. Giving that term a moderately large weight improved the representations further. The second finding is a negative one, and it is just as informative: the quality of the representations was mostly invariant to the size of the hidden layers and to the embedding dimension.⁠[2] Widening the network or lengthening the code did not rescue a poorly regularised model, and shrinking them did not ruin a well-regularised one. What the model learned was governed by the pressure on its latent space, not by its capacity.

The comparison between architectures adds a practical note. The hierarchical (H-VAE) and cross-modal (X-VAE) designs performed best overall, followed by the simpler CNC-VAE and MM-VAE, and the hierarchical model exhibited more stable behavior, though it required more time to learn. The study also found that some data types integrate more amenably than others: combining clinical and mRNA data, paired with the right classifier, gave better downstream predictive performance than combining copy number and mRNA data.⁠[2] That is a statement about this cohort and these classification tasks, not a ranking of biological measurements in general, but it makes the point that the choice of what to fuse is part of the design, not an afterthought.

A second line of work shows the same machinery used for prediction rather than description. Drug response in cancer cell lines is hard to predict because the number of measured features dwarfs the number of samples, and because a drug's effect on a cell is not captured by baseline gene expression alone. A model called Dr.VAE was built to learn a latent representation of pre-treatment gene expression jointly with the drug-induced change in expression, and to predict response from that shared representation.⁠[3]

The joint modelling is the substantive choice: the perturbation data, which are unlabelled with respect to response, help shape the latent space, and the response classifier is trained alongside it rather than bolted on afterwards. Across 26 approved drug compounds, the model significantly outperformed logistic regression, random forest, and support vector machines on more than half of the drugs and performed on par on most of the others. Ablation experiments attributed the improvement to the joint modelling of perturbation effects with treatment sensitivity. Even the unsupervised part alone, a representation learned from gene expression and drug-induced perturbations without any response labels, was better suited to training standard classifiers than the original data or a principal component representation.⁠[3]

The pattern across these studies is consistent with what the earlier sections described. The value of the variational autoencoder here is not that it generates new patients; it is that the encoder produces a compact, continuous summary in which several noisy measurements of the same person are brought into one space. Whether that summary is any good turns out to depend on how the latent space is constrained, which is why the regularisation term, and not the width of the network, was the lever that mattered in the breast cancer sweep.⁠[2] The same lesson appears in the drug response work, where the gain came from what was modelled jointly, not from adding depth; attempts to use deeper networks or more complex posterior approximations did not significantly improve performance enough to justify the added complexity.⁠[3]

One further development deserves a mention because it shows where the approach is heading. When the modalities are RNA and surface proteins measured in the same cell, the technical biases of the two measurements differ sharply, and a model that ignores this will let one modality dominate the shared representation. A framework called totalVI addresses this by explicitly representing protein background as a separate component alongside the biological signal, so that the joint latent space is not distorted by non-specifically bound antibodies.⁠[17] The general lesson carries over from the cancer studies: integrating heterogeneous data is less about concatenating inputs and more about modelling what makes each input unreliable.

Integrative variational autoencoders turn several noisy measurements of one patient into a single latent summary, and the studies that tested them found the regularisation of that latent space, not the size of the network, decided how useful the summary was.

Risks and limits

Limits, failure modes, and open problems

The weaknesses of a variational autoencoder are not accidents of a particular implementation. They follow from the structure of the model, and each one can be traced back to a design choice described earlier: the two-term loss, the probabilistic code, and the decoder that must rebuild everything from a short vector.

Two rows compare distinct latent density curves and digit reconstructions with coincident prior curves, ignored latent connections, and one output distribution.
Distinct input-dependent distributions become identical to the prior under exact posterior collapse. The decoder ignores the latent code, so its output distribution is independent of that code. View full-size image.Information Loss Through Posterior Collapse by Atlas Nova. Illustration generated with AI for this article and checked against its text.

The most visible limit is sample quality. Variational autoencoders are generally outperformed on that measure by other likelihood-based generative models, such as normalising flows and autoregressive models.⁠[5] The reason lies in the loss. The reconstruction term rewards matching the input on average, and an output that is the average of several plausible answers scores well under that rule while looking soft to a human eye. A model trained this way tends to produce outputs that are recognisably of the right kind but slightly blurred or generic, because sharp detail is a specific choice among many and averaging over choices smooths it away. This is a consequence of the objective, not a bug to be patched, and it is why the model's recognised strengths are placed elsewhere: fast and tractable sampling and an encoder that is easy to obtain and reuse once training is done.⁠[5]

The second failure mode is more serious because it can leave the model apparently working while it has quietly stopped using its latent code. Posterior collapse is the condition in which the encoder's distributions are squashed onto the prior and the decoder learns to produce an average output on its own, ignoring the code entirely. The training loss can look acceptable while this happens, since a decoder that has memorised the average of the data reconstructs that average reasonably well. What is lost is the whole point of the exercise: the latent space no longer carries information about individual inputs, so sampling from it produces the same bland output every time and the encoder's codes are useless as features. The cause is the imbalance described earlier, where the regularization term dominates and the cheapest way for the model to reduce the loss is to stop encoding anything. It has been observed that variational autoencoders tend to ignore the latent variables when combined with a decoding distribution that is too flexible.⁠[12]

The third limit is the delicacy of the balance itself. The loss is the sum of two components with contrasting effects, and correctly balancing them is described as a delicate issue and one of the major problems of the method. The difficulty is structural: as reconstruction improves during training, the reconstruction term shrinks, and a fixed weighting lets the regularization term take over by default, which then blocks further improvement in the quality of reconstructions.⁠[6] A practitioner therefore faces a tuning problem with no universal answer, since the right balance depends on whether the model is wanted chiefly as a generator or as a representation learner. The VAE objective can lead to overly simplified representations which fail to use the network's entire modeling capacity, and an importance weighted autoencoder using a strictly tighter log-likelihood lower bound was shown to learn richer latent space representations.⁠[13]

Interpretability is a fourth and quieter problem. A learned latent vector has no natural name, and its individual dimensions need not correspond to anything a domain expert would recognise. The chemistry case offered a partial answer, since shifts along the first principal component of the descriptor space correlated with molecular weight (mean Spearman r = 0.9470) and shifts along the second correlated with the partition coefficient log P (mean r = –0.916), but that was a description of how one trained model happened to organise its space, discovered by experiment.⁠[1] Nothing in training guarantees that the axes mean anything in general, and where interpretability matters the representation is usually paired with a separate step that tries to attach meaning to it.

A fifth limit concerns sequences, where the relevant structure often spans long distances. In protein work, a model trained on raw sequences was found to be less effective at capturing the long-range dependencies between amino acids at different positions than a model trained on aligned sequences, and closing that gap was identified as an important challenge for future work.⁠[4] The difficulty is not that the architecture cannot represent such dependencies but that the training signal does not reliably push it to. A model can reconstruct sequences well by learning local patterns of amino acid usage while missing the interactions between distant positions that reflect the folded structure.

These limits are not separate problems so much as different faces of one tension. The loss asks the model to compress and to conform at once, and every failure above is a way that settlement can go wrong: too much conformity and the code goes unused, too much compression and the samples go soft, too little structure and the space cannot be read. Recognising this is what motivates the extensions covered later, which adjust the objective, the prior, or the architecture in an attempt to shift the settlement without giving up the model's advantages.

The model's weaknesses follow from its own objective: averaging blurs samples, an over-flexible decoder lets the latent code go unused, and the balance between the two loss terms has no universal setting.

Later developments

Variants and extensions

The basic variational autoencoder fixes a shape for its latent space and a way of measuring how well it fits the data, and most later variants change one of those choices while keeping the encoder-decoder arrangement intact. The changes are worth understanding together, because each one buys something and pays for it elsewhere. A variant that sharpens the latent space tends to cost reconstruction accuracy; a variant that improves reconstruction tends to cost time or interpretability. None of them replaces the original; each is a different settlement of the same tension between faithful rebuilding and an orderly, sampleable code.

Figure 1. Anomaly detection scores by method on the KPI dataset. F1 score of four time-series anomaly detection methods on the KPI dataset, where higher is better. The source states: “KPI LSTM-AE 0.9474 0.4737 0.6316 LSTM-VAE 0.76 0.5 0.6032 MAD-GAN 0.9444 0.4474 0.6071 LSTM-based VAE-GAN 0.95 0.5 0.6552” (Niu et al. (2020)).⁠[18]

The first family of variants attacks the training bound itself. The ordinary objective is a lower bound on the likelihood of the data, and a loose bound lets the model settle for simplified representations that fail to use the network's full capacity. The importance-weighted autoencoder keeps the same architecture but draws several samples from the encoder's distribution for each input and weights them, which yields a strictly tighter bound on the likelihood. The extra samples give the recognition network more flexibility to approximate complex posteriors that do not fit the usual simplifying assumptions, and models trained this way learn richer latent representations, with improved test likelihood on density-estimation benchmarks.⁠[13] The cost is computational: each training step now runs the encoder several times per input, so the tighter bound is bought with more work per example.

A second family goes after the organisation of the latent space rather than the tightness of the bound. Disentanglement is the goal of arranging the space so that individual axes correspond to individual factors of variation, which would make the code interpretable and allow one quality to be changed while the others are held fixed. A refinement decomposes the objective to expose a term measuring the total correlation between latent variables, the amount of redundancy among them, and uses that term to motivate the β-TCVAE, which targets disentanglement without requiring additional hyperparameters during training. That work also proposed a classifier-free measure of disentanglement, the mutual information gap, and found a strong relation between total correlation and disentanglement when the latent model is trained under the proposed framework.⁠[14] The trade is the one described earlier in general terms: leaning on the regularization term improves the tidiness of the space at some cost in reconstruction, and the balance has to be chosen for the task.

A third family changes what the model is asked to produce. The protein work described earlier used exactly this arrangement, training conditional versions of its models with solubility information attached and generating variants of the luxA protein with increased solubility without disrupting function. The same study found that 6 of 12 variants generated by the unconditional AR-VAE and 9 of 11 generated by the unconditional MSA VAE retained measurable luminescence, together with all 23 of the less distant variants generated by the conditional versions of the models.⁠[4] Conditioning narrows the search, but it also requires that the property be known for the training data, which is not always the case.

A fourth family extends the model to sequences, where each input is not an independent object but a stretch of data whose successive elements depend on one another. In the original VAE model, the input data vectors are processed independently. Dynamical variational autoencoders model both the latent space and the temporal dependencies within a sequence of data vectors and their corresponding latent vectors, relying on recurrent neural networks or state-space models to carry information from one step to the next. A review of this class presents seven such models in a common notation and benchmarks them on a speech analysis-resynthesis task.⁠[11]

Time-series anomaly detection shows the same extension put to practical use. A model that combines a variational autoencoder with an adversarial discriminator, using long short-term memory networks for the encoder, the generator, and the discriminator, was trained on normal time-series data and flagged anomalies by combining the reconstruction difference with the discriminator's judgement. Training the parts jointly means the mapping from data to latent space does not have to be recomputed at detection time, which the authors report makes detection faster and more accurate than reconstruction-based methods that require that optimisation step.⁠[18]

Set side by side, these variants make the underlying design space visible. The objective can be tightened by better estimating the bound, as the importance-weighted model does, or reshaped to favour particular properties of the latent space, as the disentanglement methods do. The input can be extended with a condition, which trades generality for control, or with a temporal structure, which trades simplicity for the ability to model sequences. Each choice shifts where the model sits on the same three-way trade between reconstruction quality, the interpretability and orderliness of the latent space, and computational cost. A practitioner selecting among them is really deciding which of those three matters most for the task at hand, and the answer differs between generating images, proposing protein variants, and monitoring a machine on a factory floor.

Variants of the variational autoencoder adjust the bound, the latent space, the conditioning, or the handling of time, and each adjustment moves the model along the same trade between reconstruction quality, disentanglement, and computational cost.

Key studies

YearStudySampleDesignFinding
2015Makhzani et al.⁠[10]MNIST, Street View House Numbers and Toronto Face datasetsmatching the autoencoder's aggregated posterior to a chosen prior through adversarial trainingAdversarial autoencoders achieved competitive results in generative modeling and semi-supervised classification.
2018Chen et al.⁠[14]decomposition of the training objective with a new disentanglement measureThe work showed a strong relation between total correlation among latent variables and disentanglement.
2019Simidjievski et al.⁠[2]heterogeneous breast cancer data, including clinical and mRNA datacomparison of four autoencoder architectures across 108 configurations eachMaximum mean discrepancy regularization gave better representations than Kullback-Leibler divergence, and higher-dimensional encodings gave better predictions.
2019Rampášek et al.⁠[3]26 Food and Drug Administration-approved drugs, up to 855 cell lines for sensitivity and up to 60 for perturbation datajoint probabilistic modeling with 100 train-validation-test splitsThe model did as well as or better than standard classifiers for 23 out of 26 drugs.
2019Winter et al.⁠[1]around 72 million compoundstranslation between chemical representations with a low-dimensional embeddingIn two ligand-based virtual screening tasks, the learned descriptor beat every baseline molecular fingerprint.
2020Niu et al.⁠[18]time-series data from the Yahoo and KPI datasetscomparison of four anomaly detection methodsThe combined model reached an F1 score of 0.8907 on Yahoo and 0.6552 on KPI, the best of the four methods on both.
2020Vahdat & Kautz⁠[5]MNIST, CIFAR-10, CelebA 64, CelebA HQ and FFHQ image datasetsdeep hierarchical architecture for image generationOn CIFAR-10, NVAE improved the best reported result from 2.98 to 2.91 bits per dimension.
2020Asperti & Trentin⁠[6]CIFAR-10 and CelebA image datasetsdeterministic balancing of reconstruction error and Kullback-Leibler divergenceThe technique outperformed previous variational autoencoder architectures with comparable parameter capacity.
2021Hawkins-Hooker et al.⁠[4]69,130 luciferase-like oxidoreductase sequencesgenerative protein design with laboratory validation6 of 12 raw-sequence variants and 9 of 11 aligned-sequence variants retained measurable luminescence, and all 23 conditional variants did.
2021Goffinet et al.⁠[15]vocalizations of laboratory mice and zebra finchesunsupervised feature learning and comparison with handpicked featuresThe 32 latent features beat handpicked features on common analysis tasks and showed that mouse ultrasonic vocalizations do not cluster as commonly believed.
2021Gayoso et al.⁠[17]immune cells from murine spleen and lymph nodes, over 100 surface proteinsjoint probabilistic modeling of paired RNA and protein measurementsThe model gave a 20-dimensional latent representation usable for dimensionality reduction, integration and differential expression testing.

See also

References

  1. Winter, R., Montanari, F., Noé, F., & Clevert, D. A. (2019). Learning continuous and data-driven molecular descriptors by translating equivalent chemical representations. Chemical Science, 10(6), 1692-1701. doi:10.1039/c8sc04175j
  2. Simidjievski, N., Bodnar, C., Tariq, I., Scherer, P., Andres Terre, H., Shams, Z., Jamnik, M., & Liò, P. (2019). Variational Autoencoders for Cancer Data Integration: Design Principles and Computational Practice. Frontiers in Genetics, 10. doi:10.3389/fgene.2019.01205
  3. Rampášek, L., Hidru, D., Smirnov, P., Haibe-Kains, B., & Goldenberg, A. (2019). Dr.VAE: improving drug response prediction via modeling of drug perturbation effects. Bioinformatics, 35(19), 3743-3751. doi:10.1093/bioinformatics/btz158
  4. Hawkins-Hooker, A., Depardieu, F., Baur, S., Couairon, G., Chen, A., & Bikard, D. (2021). Generating functional protein variants with variational autoencoders. PLOS Computational Biology, 17(2), e1008736. doi:10.1371/journal.pcbi.1008736
  5. Vahdat, A., & Kautz, J. (2020). NVAE: A Deep Hierarchical Variational Autoencoder. arXiv. doi:10.48550/arxiv.2007.03898 Free full text
  6. Asperti, A., & Trentin, M. (2020). Balancing Reconstruction Error and Kullback-Leibler Divergence in Variational Autoencoders. IEEE Access, 8, 199440-199448. doi:10.1109/access.2020.3034828
  7. Doersch, C. (2016). Tutorial on Variational Autoencoders. arXiv. doi:10.48550/arxiv.1606.05908 Free full text
  8. Bond-Taylor, S., Leach, A., Long, Y., & Willcocks, C. G. (2022). Deep Generative Modelling: A Comparative Review of VAEs, GANs, Normalizing Flows, Energy-Based and Autoregressive Models. IEEE Transactions on Pattern Analysis and Machine Intelligence, 44(11), 7327-7347. doi:10.1109/tpami.2021.3116668
  9. Asperti, A., Evangelista, D., & Loli Piccolomini, E. (2021). A Survey on Variational Autoencoders from a Green AI Perspective. SN Computer Science, 2(4). doi:10.1007/s42979-021-00702-9
  10. Makhzani, A., Shlens, J., Jaitly, N., Goodfellow, I., & Frey, B. J. (2015). Adversarial Autoencoders. arXiv. doi:10.48550/arxiv.1511.05644 Free full text
  11. Girin, L., Leglaive, S., Bie, X., Diard, J., Hueber, T., & Alameda-Pineda, X. (2022). Dynamical Variational Autoencoders: A Comprehensive Review. Foundations and Trends® in Machine Learning, 15(1-2), 1-175. doi:10.1561/2200000089
  12. Zhao, S., Song, J., & Ermon, S. (2017). InfoVAE: Information Maximizing Variational Autoencoders. arXiv. doi:10.48550/arxiv.1706.02262 Free full text
  13. Burda, Y., Grosse, R., & Salakhutdinov, R. (2015). Importance Weighted Autoencoders. arXiv. doi:10.48550/arxiv.1509.00519 Free full text
  14. Chen, R. T. Q., Li, X., Grosse, R., & Duvenaud, D. (2018). Isolating Sources of Disentanglement in Variational Autoencoders. arXiv. doi:10.48550/arxiv.1802.04942 Free full text
  15. Goffinet, J., Brudner, S., Mooney, R., & Pearson, J. (2021). Low-dimensional learned feature spaces quantify individual and group differences in vocal repertoires. eLife, 10. doi:10.7554/elife.67855
  16. Stahlschmidt, S. R., Ulfenborg, B., & Synnergren, J. (2022). Multimodal deep learning for biomedical data fusion: a review. Briefings in Bioinformatics, 23(2). doi:10.1093/bib/bbab569
  17. Gayoso, A., Steier, Z., Lopez, R., Regier, J., Nazor, K. L., Streets, A., & Yosef, N. (2021). Joint probabilistic modeling of single-cell multi-omic data with totalVI. Nature Methods, 18(3), 272-282. doi:10.1038/s41592-020-01050-x
  18. Niu, Z., Yu, K., & Wu, X. (2020). LSTM-Based VAE-GAN for Time-Series Anomaly Detection. Sensors, 20(13), 3738. doi:10.3390/s20133738

Cite this page: Atlas Nova editors. (2026). Variational autoencoder. Atlas Nova. https://velocer.io/atlas/variational-autoencoders/