Back to paper library

Semi-Supervised VAE

A Hundred Labels

Original paper

Semi-Supervised Learning with Deep Generative Models

Paper authors

Diederik P. Kingma · Danilo J. Rezende · Shakir Mohamed · Max Welling

Publication
NeurIPS 2014Conference
First submitted to arXiv
arXiv:1406.5298
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{imagegenerationsemisupervisedvae2014,
  title = {{Semi-Supervised Learning with Deep Generative Models}},
  author = {Diederik P. Kingma and Danilo J. Rezende and Shakir Mohamed and Max Welling},
  year = {2014},
  eprint = {1406.5298},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1406.5298}
}
On this page

Fifty thousand handwritten digits, and only a hundred of them come with answers, ten for each digit.

Trained on just those hundred, a nearest-neighbor classifier gets 25.81% wrong on the MNIST test set; AtlasRBF, the best semi-supervised method of the time in the paper's table, gets 8.10% wrong. This paper's best result is 3.33%.

There are four authors. Kingma and Welling had finished the VAE only half a year earlier; Rezende and Mohamed of DeepMind had, almost simultaneously and independently, proposed stochastic backpropagation, built on the same idea. This time the two pairs wrote a single paper together and took on a different question. Can a generative model do work for a classifier?

Defining the problem

In semi-supervised classification, there is a lot of data on hand, and only a small part of it is labeled. Image search, genomics, and speech are all like this; data are easy to come by, while labeling is expensive and slow. The question is whether the unlabeled data can help the classifier draw a better decision boundary than it would with the labeled data alone.

The paper's introduction surveys the methods of the time:

  • Self-training: take the model's own most confident predictions as new labels and keep expanding the training set. It is a heuristic, and wrong predictions get reinforced right along with the rest.
  • Transductive SVM (TSVM): maximize the margin while keeping unlabeled points away from the margin as much as possible. It becomes hard to optimize once there is a lot of unlabeled data.
  • Graph-based methods: connect similar samples into a graph and let the labels propagate along it. The results are sensitive to the structure of the graph, and they require an eigenanalysis of the graph Laplacian, which limits their scale.
  • Neural network methods: add an unsupervised penalty, such as an autoencoder, on top of the classifier. Among them, the Manifold Tangent Classifier (MTC) first learns the data manifold with a contractive autoencoder, then makes the classifier invariant to small perturbations along the manifold; AtlasRBF combines manifold learning with kernel methods and was among the best-performing methods of the time.

Generative approaches to semi-supervised learning had in fact been around for a long time. They treat the missing labels as missing values and fill them in with a density model of the data. The difficulty was that the models were too weak; Gaussian mixture models or HMMs needed many components to be good enough, and nonparametric models such as trees or Gaussian processes couldn't keep up in scalability or inference accuracy.

The VAE had just shown that a deep network used as a density model can be trained with minibatch gradients, with approximate inference handed off to an encoder. What this paper wants to know is whether, once labels are put into such a model, the 49,900 images without answers can really help the hundred that have them.

Solving the problem

The paper proposes three models, shown together here:

Three rows, M1, M2, and M1+M2, each with the generative model on the left and the inference model on the right. M1: in generation, z points to x; in inference, x points to z, and z goes to a TSVM that predicts y. M2: in generation, y and z both point to x; in inference, x points to y, and x and y together point to z. M1+M2: in generation, y and z₂ point to z₁, and z₁ points to x; in inference, x points to z₁, z₁ points to y, and z₁ and y together point to z₂. Gray circles are observed variables, and the y in a dashed circle is observed for only part of the data.
Drawn for this note from Section 2 and Eqs. (2) and (4) of the paper.

M1: features first, then classify

M1 is just an ordinary VAE, with the generative model of Eq. (1):

p(z)=N(z ∣ 0,I),pθ(x∣z)=f(x;z,θ)p(z)=\mathcal N(z\,|\,0,I),\quad p_\theta(x|z)=f(x;z,\theta)

ff is a likelihood function whose parameters are given by a deep network; for MNIST it is Bernoulli. Training ignores the labels entirely and uses all fifty thousand images to maximize the VAE bound (Eq. 5). After training, each image goes through the encoder qϕ(z∣x)q_\phi(z|x), the inferred zz serves as its features, and the features of the hundred labeled images are then used to train a classifier; the paper uses a TSVM.

In the MNIST experiments, zz has 50 dimensions, and the encoder and decoder each have two layers of 600 softplus units. Going from 784 pixel dimensions down to 50 leaves the classifier a much smaller space to deal with; the authors' argument is that these low-dimensional representations come from Gaussian posteriors produced by a chain of nonlinear transformations, so the classes should be easier to separate.

M1's limitation is just as clear. Feature learning knows nothing about the classification task, and the labels show up only once, in the final classifier.

M2: labels as a latent variable

M2 writes the class directly into the generative model. An image is produced by two latent variables, the class yy and a continuous zz (Eq. 2):

p(y)=Cat(y ∣ π),p(z)=N(z ∣ 0,I)pθ(x∣y,z)=f(x;y,z,θ)\begin{aligned} &p(y)=\mathrm{Cat}(y\,|\,\pi),\qquad p(z)=\mathcal N(z\,|\,0,I) \\ &p_\theta(x|y,z)=f(x;y,z,\theta) \end{aligned}

Cat\mathrm{Cat} is the categorical distribution, and yy is fed into the decoder as a one-hot vector. yy and zz are independent in the prior, so to generate a "7," you can fix y=7y=7, draw a zz from N(0,I)\mathcal N(0,I) to decide the writing style, such as stroke thickness and slant, and the decoder combines the two into an image.

For labeled data, yy is observed; for unlabeled data, yy is a latent variable just like zz and has to be inferred. Classification thus becomes part of the inference problem, since guessing an image's yy is computing its posterior to begin with.

The inference model has two parts (Eq. 4):

qϕ(y∣x)=Cat(y ∣ πϕ(x))qϕ(z∣y,x)=N(z ∣ μϕ(y,x), diag(σϕ2(x)))\begin{aligned} q_\phi(y|x)&=\mathrm{Cat}\big(y\,|\,\pi_\phi(x)\big) \\ q_\phi(z|y,x)&=\mathcal N\big(z\,|\,\mu_\phi(y,x),\ \mathrm{diag}(\sigma^2_\phi(x))\big) \end{aligned}

qϕ(y∣x)q_\phi(y|x) is an MLP that outputs probabilities for 10 classes, and once trained, it is the classifier we're after; qϕ(z∣y,x)q_\phi(z|y,x) infers the image's writing style given its class. The official code feeds the image and the one-hot yy together into the encoder's first hidden layer, and the decoder likewise feeds yy and zz together into its first layer. In the MNIST experiments, M2 uses a 50-dimensional zz and networks with one layer of 500 softplus units each.

The labeled bound

With a label, both xx and yy are observed, and only zz remains to be inferred. Taking log⁡pθ(x,y)\log p_\theta(x,y) apart the way the VAE derivation does gives Eq. (6). Below, the θ\theta and ϕ\phi subscripts are dropped:

−L(x,y)=Eq(z∣x,y)[ log⁡p(x∣y,z)+log⁡p(y)+log⁡p(z)−log⁡q(z∣x,y)]\begin{aligned} -\mathcal L(x,y) = \mathbb E_{q(z|x,y)}\Big[\,&\log p(x|y,z) \\ &+ \log p(y) + \log p(z) \\ &- \log q(z|x,y)\Big] \end{aligned}

log⁡p(x,y)≥−L(x,y)\log p(x,y)\ge-\mathcal L(x,y). The paper defines L\mathcal L as the negative of the bound, that is, the loss to be minimized. Compared with the VAE, there is just one extra term, log⁡p(y)\log p(y); when the prior is uniform (which is how the official code sets it), it is the constant −log⁡10-\log 10 and doesn't affect the gradient. The expectation of log⁡p(z)−log⁡q(z∣x,y)\log p(z)-\log q(z|x,y) is the negative of the VAE's Gaussian KL and uses the same closed form; the reconstruction term is sampled with the reparameterization, as before.

The unlabeled bound

Without a label, yy has to be inferred as well. Treat yy and zz as one set of latent variables and factor the approximate posterior as q(y,z∣x)=q(y∣x) q(z∣x,y)q(y,z|x)=q(y|x)\,q(z|x,y); the bound becomes:

log⁡p(x)≥Eq(y,z∣x)[log⁡p(x,y,z)q(y,z∣x)]=∑yq(y∣x)(−L(x,y)−log⁡q(y∣x))=∑yq(y∣x)(−L(x,y))+H(q(y∣x))\begin{aligned} &\log p(x) \ge \mathbb E_{q(y,z|x)}\left[\log\frac{p(x,y,z)}{q(y,z|x)}\right] \\ &\quad= \sum_y q(y|x)\big(-\mathcal L(x,y) - \log q(y|x)\big) \\ &\quad= \sum_y q(y|x)\big(-\mathcal L(x,y)\big) + \mathcal H\big(q(y|x)\big) \end{aligned}

The second step takes the expectation over zz first and then sums over yy. The log⁡q(y,z∣x)\log q(y,z|x) in the denominator splits into log⁡q(y∣x)+log⁡q(z∣x,y)\log q(y|x)+\log q(z|x,y); in the expectation over zz, the log⁡p(x,y,z)−log⁡q(z∣x,y)\log p(x,y,z)-\log q(z|x,y) part is exactly the labeled −L(x,y)-\mathcal L(x,y), while log⁡q(y∣x)\log q(y|x) doesn't depend on zz and stays as it is. The third step writes −∑yq(y∣x)log⁡q(y∣x)-\sum_y q(y|x)\log q(y|x) as the entropy H\mathcal H of q(y∣x)q(y|x). This is Eq. (7), written −U(x)-\mathcal U(x).

This expression says that an unlabeled image has to try all 10 classes. Compute the labeled bound once for each yy, weight the results by the probabilities the classifier gives, and finally add the entropy.

Where does this push the classifier? Let's work it out for one unlabeled image. Suppose the decoder has already learned something, and this image's bound is −95-95 for y=7y=7, −101-101 for y=9y=9, and −120-120 for y=1y=1, with the other classes much lower.

  • If the classifier puts all its probability on 7, −U=−95-\mathcal U=-95, and the entropy is 0.
  • If the classifier gives 0.5 each to 7 and 9, −U=−98+log⁡2≈−97.31-\mathcal U=-98+\log 2\approx-97.31.

The best allocation can be computed directly. Let ay=−L(x,y)a_y=-\mathcal L(x,y); the maximum of ∑yq(y) ay+H(q)\sum_y q(y)\,a_y+\mathcal H(q) over qq is log⁡∑yeay\log\sum_y e^{a_y}, reached at q(y)∝eayq(y)\propto e^{a_y}, that is, a softmax over aya_y. Plugging in this example, the best classifier gives about 0.9975 to 7 and about 0.0025 to 9, with −U≈−94.998-\mathcal U\approx-94.998.

So maximizing the unlabeled bound pushes q(y∣x)q(y|x) toward "whichever class's generative model best explains this image." −L(x,y)-\mathcal L(x,y) is a lower bound on log⁡p(x,y)\log p(x,y), so q(y∣x)∝e−L(x,y)q(y|x)\propto e^{-\mathcal L(x,y)} amounts to approximating the true class posterior p(y∣x)p(y|x).

There's a chicken-and-egg problem here. The decoder has to know "what a 7 looks like" before the unlabeled data can help the classifier; and which dimension of yy corresponds to the digit 7 is something only the hundred labeled images can tell.

Adding the classification term

Adding the two kinds of bound together gives the objective for the whole dataset (Eq. 8):

J=∑(x,y)∼p~lL(x,y)+∑x∼p~uU(x)\mathcal J = \sum_{(x,y)\sim\tilde p_l}\mathcal L(x,y) + \sum_{x\sim\tilde p_u}\mathcal U(x)

p~l\tilde p_l and p~u\tilde p_u are the empirical distributions of the labeled and unlabeled data.

The authors point out a flaw in this objective. q(y∣x)q(y|x) appears only in U\mathcal U, so the labeled data never train the classifier directly, because with a label the true yy is used and q(y∣x)q(y|x) isn't needed at all. So in Eq. (9) they add a classification loss:

Jα=∑(x,y)∼p~lL(x,y)+∑x∼p~uU(x)+α⋅Ep~l(x,y)[−log⁡q(y∣x)]\begin{aligned} \mathcal J^\alpha = {}&\sum_{(x,y)\sim\tilde p_l}\mathcal L(x,y) + \sum_{x\sim\tilde p_u}\mathcal U(x) \\ &+ \alpha\cdot\mathbb E_{\tilde p_l(x,y)}\big[-\log q(y|x)\big] \end{aligned}

All experiments use α=0.1⋅N\alpha=0.1\cdot N. With NN at fifty thousand, α\alpha is 5,000; the expectation after it averages over the hundred labeled images, so spread over each image, the cross-entropy carries a weight of 50. The first two terms are sums of fifty thousand bounds, each on the order of a hundred nats or more; with a weight of just 1, the classification term would be drowned out.

The paper also gives this term a second origin. Put a symmetric Dirichlet prior on the parameters π\pi of the categorical distribution and do variational inference on them, and an objective of the same form comes out.

How much does this term matter? The official Pyro tutorial implements M2 following this paper and compares three versions:

LabelsSample yySum yySum + class. termLabeled only
10020.122.593.277.1
300019.889.395.891.1

Compiled for this note from the table in Pyro's "The Semi-Supervised VAE"; test accuracy in %, mean over five random samplings.

"Sample yy" draws one class from q(y∣x)q(y|x) at each step, and "Sum yy" computes all 10 classes one by one as in Eq. (7); neither has the classification term. With Eq. (8) alone, accuracy with 100 labels is only about 20%; adding the classification term is what brings it to 93.2%, 16 percentage points above a classifier trained on the hundred labeled images alone. The tutorial says the third version reproduces the paper's results. Its setup isn't quite the same as the paper's; the images aren't binarized, and the weight of the classification term is chosen on a validation set.

Training and cost

Just as in the VAE, every term in Eqs. (6) through (9) can have its gradient estimated with the reparameterization, and θ\theta and ϕ\phi are updated together. Algorithm 2 is M2's training loop; each iteration draws a minibatch, infers yy and zz for the unlabeled data, computes the gradient of Jα\mathcal J^\alpha, and updates the parameters.

The pseudocode of Algorithm 2 says to draw one yy from q(y∣x)q(y|x); Eq. (7) and the official code both compute all 10 classes one by one and then weight them. When implementing it, follow Eq. (7); the Pyro table above already shows the difference.

The price is computation. Section 3.3 puts the cost of each M1 update at M⋅S⋅CMLPM\cdot S\cdot C_{\mathrm{MLP}} (minibatch size, number of samples, and the cost of a forward pass through the network), and M2 at LL times that, where LL is the number of classes. With only 10 classes, MNIST is manageable, but with many classes it gets expensive, and the authors list this as the main limitation.

M1+M2: stacking two layers

The last model stacks the two. First train M1 to get a 50-dimensional representation z1z_1 for each image; then move M2 wholesale onto z1z_1, so that M2 generates z1z_1 instead of generating pixels directly. The generative model now has two layers of random variables:

p(x,y,z1,z2)=p(y) p(z2)⋅pθ(z1∣y,z2) pθ(x∣z1)\begin{aligned} p(x,y,z_1,z_2) ={}& p(y)\,p(z_2) \\ &\cdot p_\theta(z_1|y,z_2)\,p_\theta(x|z_1) \end{aligned}

z2z_2 plays the role of zz in the original M2, and z1z_1 is the representation learned by M1; in the official code, pθ(z1∣y,z2)p_\theta(z_1|y,z_2) is a Gaussian. M2 operates in a space of at most 50 dimensions, which costs less than working on 784-dimensional pixels.

The paper doesn't say much about why stacking works. M1's features alone already cut the TSVM's error rate from 16.81% to 11.82% (with 100 labels), and with M2 stacked on top, both the classifier and the generative model work in a space that is easier to separate; this is this note's inference.

The official code also has a step the paper doesn't mention. Before M1's features go into M2, the code takes a thousand unlabeled images, computes the standard deviation of the encoder mean in each dimension, and keeps only the dimensions whose standard deviation exceeds 0.1. Some latent dimensions in a VAE collapse entirely back onto the prior and record no information, and this step weeds them out up front. In addition, the z1z_1 that M2 sees in each minibatch is freshly sampled from q(z1∣x)q(z_1|x), not a fixed mean.

Discussion

Experimental setup

MNIST's fifty thousand training images are split into a labeled part and an unlabeled part, with 100, 600, 1000, or 3000 labels and the same number of labels for each class; each label count is redrawn several times, and the mean and standard deviation are reported.

Section 4.4 initializes the parameters from N(0,0.0012I)\mathcal N(0,0.001^2I) with the biases set to 0, and optimizes with "a variant of RMSProp with momentum and initialization bias correction," using a learning rate of 0.0003, a first-moment decay of 0.1, and a second-moment decay of 0.001. MNIST pixels are first normalized to between 0 and 1 and then treated as Bernoulli probabilities, with a fresh binary image sampled for each minibatch, so that the Bernoulli likelihood lives up to its name. M2 also adds weight decay, corresponding to an N(0,I)\mathcal N(0,I) prior on the parameters.

Converted, that "RMSProp variant" has β1=0.9\beta_1=0.9 and β2=0.999\beta_2=0.999. In December of the same year, Kingma and Ba put it on arXiv under the name Adam.

The header of the official adam.py also says that this initialization bias correction is "not yet published at the time of writing." The update line, however, uses self.alpha, and the corrected step size alpha_t, computed on the line just above, is never used (issue #4 asked about exactly this in June 2015; replies so far: zero). By the calculation in the Adam note, with β1=0.9\beta_1=0.9 and β2=0.999\beta_2=0.999 and no correction, the first step is 3.16 times the configured value.

Main MNIST results

First, the baselines of the time; the numbers are test error rates:

LabelsNNTSVMCAEMTCAtlasRBF
10025.8116.8113.4712.038.10
60011.446.166.35.13–
100010.75.384.773.643.68
30006.043.453.222.57–

Compiled from Table 1 of the paper; test error rate in %. The original table also has a CNN column (22.98, 7.68, 6.45, 3.35).

Then the paper's three models:

LabelsM1+TSVMM2M1+M2
10011.8211.973.33
6005.724.942.59
10004.243.602.40
30003.493.922.18

Compiled from Table 1 of the paper; test error rate in %.

  1. M1+TSVM ties MTC. With 100 labels, it is 11.82 versus 12.03. The same TSVM gets 16.81% wrong on raw pixels and 11.82% on M1's features.
  2. M2 alone is about as good as M1, but unstable. With 100 labels it gets 11.97%, with a standard deviation of 1.71; with 3000 labels it gets 3.92%, which is actually worse than the 3.60% with 1000 labels, with a standard deviation of 0.63. No other model in the table gets a higher error rate from more labels.
  3. Stacking is what counts. M1+M2 is the lowest at all four label counts; with 100 labels it gets 3.33% (standard deviation 0.14), less than half of AtlasRBF's 8.10%. The more labels, the smaller the gap; with 3000 labels it is 2.18 versus MTC's 2.57.

The authors also trained M1+M2 with all the labels and got 0.96% error, among the best published results at the time for permutation-invariant MNIST classification, which uses no prior knowledge of image structure.

Class and style, separated

A 10-by-10 grid for each of the handwritten digits 2, 3, and 4. Each grid fixes the class and varies a 2D z; the same position in the three grids has a similar writing style, with more upright characters on the left and characters slanting to the right on the right.
Original Figure 1(a), Kingma et al., from PDF page 7, arXiv license, scholarly quotation.

M2 keeps class and style in two separate variables, and this can be plotted directly. The authors train an M2 whose zz has only 2 dimensions, fix yy at 2, 3, and 4, and step zz across a grid from −5 to 5.

Characters at the same position in the three grids are written alike. The paper describes the left region as "upright writing styles" and the right as "slanted styles," independent of the class. Compare the VAE's 2D latent space in the previous note, where digit class and handwriting were mixed together in one map; here the class is handed to yy, and zz is left with only the style.

On the left, MNIST analogies: the leftmost column holds 10 handwritten digits from the test set, and each row to the right shows digits generated from the same z with y from 0 to 9, matching the stroke thickness and slant of the leftmost image. On the right, SVHN analogies: the leftmost column holds photos of house numbers, and each row to the right keeps the original's colors, background, and font while the digit in the middle changes in turn to 1 through 9 and then 0.
Original Figure 1(b)(c), Kingma et al., from PDF page 7, arXiv license, scholarly quotation.

The second experiment uses a high-dimensional zz. Take a test image, pass it through the inference network to get its zz, fix zz, and generate one image for each yy from 0 to 9.

In the MNIST panel on the left, the ten digits in each row all carry the handwriting of the leftmost image; in the thick-stroked row every digit is thick, and in the right-slanting row every digit slants. On the right, SVHN consists of house numbers photographed in street scenes; each row keeps the original's background, font, and colors and swaps only the digit in the middle. Look closely, and the neighboring digits cut off at the edges are kept as well. The authors say these were the best simulations a generative model had achieved on these two datasets at the time.

SVHN and NORB

SVHN and NORB had no existing semi-supervised results to compare against, so the authors ran nearest neighbors (KNN) and a TSVM with an RBF kernel themselves, comparing each on raw features and on M1 features. Both datasets use only 1000 labels and go through PCA before entering the model.

DatasetKNNTSVMM1+KNNM1+TSVMM1+M2
SVHN77.9366.5565.6354.3336.02
NORB78.7126.0065.3918.79–

The SVHN row is compiled from Table 2 of the paper and the NORB row from Table 3; test error rate in %.

M1's features improve the TSVM on both datasets, from 66.55% to 54.33% on SVHN and from 26.00% to 18.79% on NORB. On SVHN, M1+M2 gets 36.02% wrong, far below the other columns, but that is still more than one wrong in every three; the NORB row has no M1+M2 result.

The official code

The authors put nips14-ssl, written in Theano, on GitHub, with the last push in January 2015. For the M1+M2 experiments, the README says "Each experiment will run for 3000 epochs; since this code is not GPU-optimized, running many epochs might take a few days to complete."

Compared with the paper, a few settings differ:

  • The paper says M1 uses two layers of 600 units, but learn_yz_x_ss.py loads an M1 with two layers of 500 units;
  • The paper says M2 uses 500 units, but run_2layer_ssl.py switches to 300 with 100 labels;
  • The step mentioned earlier, dropping the dimensions with a standard deviation below 0.1, isn't in the paper;
  • The bias correction in adam.py is computed but never used.

None of these are big, but anyone trying to reproduce the 3.33% from the paper should go by the code.

What came later

That number didn't stand for long. In 2015, the Ladder Network reached 1.06% error with 100 labels on the same permutation-invariant MNIST; in its comparison table, this paper is listed above it under the name "DGN," at 3.33%.

This paper itself lists a few directions in Section 5, namely variational inference over the parameters as well, convolutional networks, and dealing with the linear slowdown as the number of classes grows.

Conclusion

M2 writes the label as a latent variable in the generative model, treated as an observation when the label is there and summed over all classes with weights when it isn't, which makes the classifier part of the inference model. On its own it is about as good as M1 and not very stable; stacked on the representation learned by M1, it brings the MNIST error rate with 100 labels down to 3.33%, far ahead of everything in the comparison table of the time.

When implementing M2, compute the bound once for every class on unlabeled data and weight the results, rather than drawing one class from q(y∣x)q(y|x) and calling it done; always add the classification term, with a weight on the same scale as the whole bound (the paper uses 0.1⋅N0.1\cdot N); and take a look at whether your optimizer's bias correction is actually in effect.

The version in the Pyro tutorial that follows only Eq. (8) and draws one class per step gets about 20% accuracy with 100 labels. Guessing at random among ten classes gets 10%.