{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Deep Probabilistice Generative Models - Variational Auto-Encoders\n",
"\n",
"For this lab exercise, you have to use Pytorch.\n",
"If you don't know Pytorch or you don't know how to use it, please start by reading the following link:\n",
"\n",
"- https://pytorch.org/tutorials/beginner/nlp/pytorch_tutorial.html\n",
"\n",
"When you use Pytorch function, it is important to carefully read the documentation to understand how the different functions, what kind of transformation they apply etc.\n",
"Searching on stackoverflow is not enough. :) \n",
"You have to take time to read it carefully to understand what you are doing.\n",
"\n",
"- https://pytorch.org/docs/stable/torch.html\n",
"- https://pytorch.org/docs/stable/nn.html\n",
"- https://pytorch.org/docs/stable/nn.functional.html\n",
"\n",
"The most import tip: keep track of the dimension of your tensor and what information they contain!\n",
"\n",
"For examples, you can look at the GMM optimization via gradient descent notebook from the first course and at the MNIST classification example below. Don't just run them, try to understand them! Could you recode them from scratch without internet/example access?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 0. Preprocessing\n",
"\n",
"Import the libraries we will use.\n",
"You can download the file dataset_loader from the course website."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"import torch.optim\n",
"import torch.nn.functional as F\n",
"\n",
"import os\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import math\n",
"import matplotlib\n",
"import math\n",
"\n",
"# To load the data we will use the script of Gaetan Marceau Caron\n",
"# You can download it from the course webiste and move it to the same directory that contains this ipynb file\n",
"import dataset_loader\n",
"\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we download and preprocess the MNIST dataset, see http://yann.lecun.com/exdb/mnist/ .\n",
"Our observed random variables will be Bernoulli distributions, so we need to binarize the dataset, i.e. each pixel can either be black or white."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Download mnist dataset \n",
"if(\"mnist.pkl.gz\" not in os.listdir(\".\")):\n",
" !wget http://deeplearning.net/data/mnist/mnist.pkl.gz\n",
"\n",
"# if you have it somewhere else, you can comment the lines above\n",
"# and overwrite the path below\n",
"mnist_path = \"./mnist.pkl.gz\"\n",
"\n",
"# the dataset contains 3 splits (train/dev/test),\n",
"# each one containing two vectors (pixels and classes)\n",
"(train_data_pixels, train_data_classes), \\\n",
"(dev_data_pixels, dev_data_classes), _ = dataset_loader.load_mnist(mnist_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# to binarize, we just set to 1 pixels with a value >= 0.5, 0 otherwise\n",
"train_data_pixels = 1*(train_data_pixels >= 0.5)\n",
"dev_data_pixels = 1*(dev_data_pixels >= 0.5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# dataset_loader return numpy tensors,\n",
"# we convert them directly to pytorch tensors\n",
"train_data_pixels = torch.from_numpy(train_data_pixels).float()\n",
"train_data_classes = torch.from_numpy(train_data_classes).long()\n",
"\n",
"dev_data_pixels = torch.from_numpy(dev_data_pixels).float()\n",
"dev_data_classes = torch.from_numpy(dev_data_classes).long()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# there 50000 images, each image is of size 28x28\n",
"# each image as been reshaped as vector of size 784\n",
"print(\"Shape of the pixel tensor:\", train_data_pixels.shape)\n",
"print(\"Shape of the class tensor:\", train_data_classes.shape)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# we will use this function to print images generated by our network\n",
"# the parameter images must be a tensor of shape (n images, 784)\n",
"def display_images(images):\n",
" # convert to numpy tensor\n",
" images = images.detach().numpy()\n",
"\n",
" for i in range(images.shape[0]):\n",
" plt.imshow(images[i].reshape(28,28), cmap='Greys')\n",
" plt.show()\n",
" \n",
"# display the 5 first image in the dataset\n",
"display_images(train_data_pixels[:5])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. MNIST classification with Pytorch\n",
"\n",
"In this first part, you need to study the code to understand how Pytorch works. :)\n",
"The example is a simple classifier for MNIST data.\n",
"\n",
"**TODO**\n",
"\n",
"- can you write mathematically the function computed by this network?\n",
"- what are the dimensions of each parameter?\n",
"\n",
"It is very import that you are able to write that and understand what tensor operation it does.\n",
"This is the **root** of machine learning and especially deep learning.\n",
"To help you, draw the matrices/vectors!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# to create a neural network (or a part of a neural network),\n",
"# we create a class that extends nn.Module\n",
"class Classifier(nn.Module):\n",
" # the constructor, parameters are self-documented by their name :)\n",
" # input_dim: in our case it will the size of a single input image\n",
" # hidden_dim: the hidden representation dim\n",
" # output_dim: the number of class, in our case there are 10 digits\n",
" def __init__(self, input_dim, hidden_dim, output_dim, dropout_ratio=0.5):\n",
" super().__init__()\n",
" \n",
" # we have two projections in the network,\n",
" # the first one project the input in the hidden space,\n",
" # the second one project the hidden representation in the output space.\n",
" # have a look at the documentation of nn.Linear!\n",
" # nn.Linear extends nn.Module\n",
" self.proj1 = nn.Linear(input_dim, hidden_dim)\n",
" self.proj2 = nn.Linear(hidden_dim, output_dim)\n",
" \n",
" # dropout can be used to prevent overfitting,\n",
" # however, it may be better to start training VAE without!\n",
" # I just put it here for the example\n",
" \n",
" # let assume you create a network with:\n",
" # network = Classifier(10, 10, 10)\n",
" # then, to enable dropout you must call:\n",
" # network.train()\n",
" # and to disable dropout:\n",
" # network.eval()\n",
" # basically this calls set the network\n",
" # in training and evaluation modes, respectively\n",
" self.dropout = nn.Dropout(0.5)\n",
" \n",
" # this is the function that will be called\n",
" # when we pass data to the network to compute the output\n",
" # shape of batch: (n samples, output_dim)\n",
" # where n samples is the number of samples in the batch\n",
" def forward(self, batch):\n",
" hid = self.proj1(batch)\n",
" \n",
" # non-linearity, it could have been a nn.Module object stored in this module,\n",
" # here we use the functionnal version\n",
" hid = F.relu(hid)\n",
" \n",
" # note: dropout is used to prevent overfitting\n",
" hid = self.dropout(hid)\n",
" \n",
" # return the output, i.e. logits of each class for each sample in the batch\n",
" # shape: (n samples, output_dim)\n",
" return self.proj2(hid)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n_epoch = 20\n",
"batch_size = 100\n",
"\n",
"# build the network!\n",
"network = Classifier(28*28, 200, 10)\n",
"\n",
"# optimizer that will be used to update the parameters!\n",
"optimizer = torch.optim.Adam(network.parameters())\n",
"\n",
"all_epoch_losses = list()\n",
"all_epoch_accuracies = list()\n",
"for epoch in range(n_epoch):\n",
" # we keep track of the loss at each epoch\n",
" epoch_loss = 0\n",
" \n",
" # Note: one trick often used is to shuffle the data at each epoch,\n",
" # we won't do that here.\n",
" # if you want to do it, be carefull:\n",
" # you need to shuffle both train_data_pixels and train_data_classes\n",
" # so that they match, i.e. you cannot shuffle them independently!\n",
"\n",
" network.train() # set the network in train mode (i.e. enable dropout)\n",
" \n",
" # loop over the data\n",
" for i in range(0, train_data_pixels.shape[0], batch_size):\n",
" # IMPORTANT:\n",
" # we must always call zero_grad() because each call to .backward()\n",
" # will accumulate the gradient!\n",
" optimizer.zero_grad()\n",
" \n",
" # batch of data\n",
" # shape: (n samples, 784)\n",
" # do you understand why n samples can be different of batch_size?\n",
" batch = train_data_pixels[i:i+batch_size]\n",
" \n",
" # compute the weights associate with each class for each picture\n",
" # logits shape: (n samples, 10)\n",
" logits = network(batch)\n",
" \n",
" # compute the loss\n",
" # look at the documentation of the function!\n",
" loss = F.cross_entropy(\n",
" logits,\n",
" train_data_classes[i:i+batch_size],\n",
" reduction=\"mean\"\n",
" )\n",
" \n",
" # to accumulate to the epoch loss,\n",
" # we need to call loss.item() so the value\n",
" # will detached from the computational graph,\n",
" # i.e. loss.item() is python float, not a pytorch object.\n",
" # can you understand why we multiply by batch_size.shape[0] ?\n",
" epoch_loss += loss.item() * batch.shape[0]\n",
" \n",
" loss.backward() # compute the gradient\n",
" optimizer.step() # update parameters of the model\n",
" \n",
" # at the end of each epoch, we eval on the dev data\n",
" network.eval()\n",
" n_dev_correct = 0\n",
" \n",
" # we don't need gradient computation during evaluation,\n",
" # so we enclose computation with torch.no_grad(),\n",
" # this will makes computation more efficient\n",
" with torch.no_grad():\n",
" for i in range(0, dev_data_pixels.shape[0], batch_size):\n",
" batch = dev_data_pixels[i:i+batch_size]\n",
" logits = network(batch)\n",
" \n",
" # compute the class of maximum weight for each sample,\n",
" # look at the documentation of argmax!\n",
" # pred shape: (n samples,)\n",
" pred = logits.argmax(1)\n",
" \n",
" # compare prediction with gold classes\n",
" n_dev_correct += (pred == dev_data_classes[i:i+batch_size]).sum().item()\n",
" \n",
" all_epoch_losses.append(epoch_loss)\n",
" all_epoch_accuracies.append(n_dev_correct / dev_data_classes.shape[0]) \n",
" print(\n",
" epoch, \":\\t\",\n",
" epoch_loss,# / len(train_data[0]),\n",
" \"\\t / dev precision:\\t\",\n",
" n_dev_correct / dev_data_classes.shape[0],\n",
" flush=True\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# print graph to show how the loss and the accuracy evolve during training,\n",
"# for example to see if we overfit the training data.\n",
"# Note that MNIST is a really simple dataset, so its no really interesting in this case :)\n",
"plt.plot(np.arange(n_epoch), all_epoch_losses)\n",
"plt.show()\n",
"\n",
"plt.plot(np.arange(n_epoch), all_epoch_accuracies)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. VAE with continuous latent space and binary observed space\n",
"\n",
"The first VAE that we will develop is based on the following generative story:\n",
"\n",
"1. $z \\sim p(z)$\n",
"2. $x \\sim p(x | z ; \\theta)$\n",
"\n",
"where the latent random variable $Z$ takes value in $\\mathbb R^n$.\n",
"The prior ditribution $p(z)$ is a multivariate Gaussian where each coordinate is independent.\n",
"We fix the mean and variance of each coordinate to 0 and 1, respectively.\n",
"The conditional distribution $p(x | z ; \\theta)$ is parameterized by a neural network.\n",
"The random variables $X$ are $m$ independent Bernoulli random variables.\n",
"\n",
"Note: this kind of VAE will be quite bad at generating MNIST picture.\n",
"Therefore, when you do you experiments, you should both generate picture and show the distribution $p(x | z ; \\theta)$ as a picture.\n",
"This is a well known problem of VAE, you can try to play with the network architecture and the parameters to improve generation.\n",
"However, hyperparameter optimization is not the goal of this lab exercise. :)\n",
"Another solution would be to use Gaussian random variables for the output distribution, but we won't do that here."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### KL divergence\n",
"\n",
"The first function we have to implement is the one that compute the KL divergence with the prior.\n",
"You can find the formula in appendix B of the following paper: https://arxiv.org/pdf/1312.6114.pdf\n",
"\n",
"**WARNING:** In the paper they give the formula for the -KL, and here we want the KL, so don't forget to put a minus sign in front of their formula. :)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# the shapes of mu and log_sigma_squared are: (n batch, n latent)\n",
"# the return vector must be of shape: (n batch,)\n",
"def KL_with_gaussian_prior(mu, log_sigma_squared):\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
"# test for shape\n",
"mu = torch.rand((10, 30))\n",
"log_sigma_squared = torch.rand((10, 30))\n",
"\n",
"if KL_with_gaussian_prior(mu, log_sigma_squared).shape != (10, ):\n",
" raise RuntimeError(\"Invalid return dim!\")\n",
"else:\n",
" print(\"return dim is ok.\")\n",
" \n",
"# test for return value\n",
"# result should be 0 as it is equal to the prior\n",
"print(\"Should be 0:\", KL_with_gaussian_prior(torch.tensor([[0.]]), torch.tensor([[0.]])).item())\n",
"print(\"Should be 0.5:\", KL_with_gaussian_prior(torch.tensor([[1.]]), torch.tensor([[0.]])).item())\n",
"print(\"Should be 2.6945...:\", KL_with_gaussian_prior(torch.tensor([[1.]]), torch.tensor([[2.]])).item())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Network\n",
"\n",
"Next you need to code the encoder and the decoder.\n",
"The encoder should return a tuple of tensors (mu, log_sigma_squared),\n",
"both are unconstrained so they should be the output of a linear projection.\n",
"The term log_sigma_squared means that the standard deviation can be computed via sigma=exp(0.5 * log_sigma_squared).\n",
"Be sure you understand this.\n",
"\n",
"The structure of the encoder should be as follow:\n",
"\n",
"- one projection and non linearity (e.g. relu) to compute a hidden representation of the input,\n",
"- two projections to compute my and log_sigma_squared from the same hidden representation.\n",
"\n",
"The structure of the decoder shoud be similar to the classifier above.\n",
"Similarly to the encoder, the decoder should output unconstrained value, i.e. it does not directly return the mu parameters of the Bernoulli distribution, but values in R.\n",
"In your code, if you need to get the distribution, you can call sigmoid(mu) to transform the unconstrained values to the mu parameters.\n",
"\n",
"- one projection and non linearity (e.g. relu) to compute a hidden representation of the input,\n",
"- one projection to the output space\n",
"\n",
"The decode has two additional functions:\n",
"\n",
"- sample_distributions: it samples from the prior and return the conditional output distributions (so here it means that you **must** apply the sigmoid befaire returning)\n",
"- sample_images: call sample_distributions and then sample images from the output distributions.\n",
"\n",
"To sample from a Bernoulli you can use the following function: https://pytorch.org/docs/stable/generated/torch.bernoulli.html\n",
"To sample from the Gaussian prior, you can:\n",
"\n",
"- first create an empty tensor via https://pytorch.org/docs/stable/generated/torch.empty.html\n",
"- then fill values in the tensor via https://pytorch.org/docs/stable/tensors.html#torch.Tensor.normal_\n",
"\n",
"This second function change a tensor in-place (hence the _ at the end of the name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class GaussianEncoder(nn.Module):\n",
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
" super().__init__()\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" def forward(self, batch):\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class GaussianPriorDecoder(nn.Module):\n",
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
" super().__init__()\n",
" \n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" def forward(self, batch):\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" # n_samples: number of \"image output distribution\" to compute\n",
" def sample_distributions(self, n_samples):\n",
" # first you must sample from the prior,\n",
" # then you must pass the data through this network, i.e. self(z)\n",
" \n",
" # shape of z: (n_samples, input_dim)\n",
" z = # TODO....\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" \n",
" # sample images\n",
" def sample_images(self, n_samples, argmax=False):\n",
" # compute the output distributions for each image\n",
" # probs shae: (n_samples, output_dim)\n",
" probs = self.sample_distributions(n_samples)\n",
" \n",
" # then sample output pixels\n",
" # there are two modes:\n",
" # argmax=False: sample from the output distribution\n",
" # argmax=True: instead of sampling, return the most probable value for each random variable\n",
" # (check how the images are converted to binary images above!)\n",
" \n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Training loop\n",
"\n",
"I did most of the work, you just need to implement ont thing: the reparameterization trick! :)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dim_input = 28*28\n",
"latent_dim = 2 # we use only 2 dimensions so we can plot them!\n",
"hidden_dim = 400\n",
"n_epoch = 20\n",
"batch_dim = 256\n",
"\n",
"encoder = GaussianEncoder(dim_input, hidden_dim, latent_dim)\n",
"decoder = GaussianPriorDecoder(latent_dim, hidden_dim, dim_input)\n",
"\n",
"# we must pass both network parameters to the optimizer\n",
"# sometime its also useful to use two different optimizers,\n",
"# for example if we want to use different learning rates.\n",
"optimizer = torch.optim.Adam(list(encoder.parameters()) + list(decoder.parameters()))\n",
"\n",
"for epoch in range(n_epoch):\n",
" epoch_reconstruction = 0\n",
" epoch_kl = 0\n",
"\n",
" decoder.train()\n",
" encoder.train()\n",
" for i in range(0, train_data_pixels.shape[0], batch_dim): \n",
" optimizer.zero_grad()\n",
" \n",
" batch = train_data_pixels[i:i+batch_dim]\n",
" \n",
" # compute parameters of the approximate posterior\n",
" mu, log_sigma_squared = encoder(batch)\n",
" \n",
" # for MC sampling of the reconstruction loss,\n",
" # we use one sample from the approximate posterior.\n",
" # you need to use the reparameterization trick for this!\n",
" # in order to sample from the the N(0, 1) distribution,\n",
" # you can use:\n",
" # torch.empty_like(mu).normal_(mean=0.,std=1.)\n",
" # (check the documentation if you don't understand this!)\n",
" \n",
"\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" z = # TODO\n",
" \n",
" # reconstruction_logits: (batches, classes, output size)\n",
" # note that the output of the network is in R,\n",
" # to get Bernoulli parameters you must use the sigmoid.\n",
" # For the reconstruction loss, you can either use:\n",
" # - F.binary_cross_entropy_with_logits\n",
" # - F.entropy_with_logits\n",
" # Read the doc in order to understand the difference!\n",
" # Warning: use the reduction=\"none\" parameter\n",
" reconstruction_logits = decoder(z)\n",
" reconstruction_loss = F.binary_cross_entropy_with_logits(\n",
" reconstruction_logits,\n",
" batch,\n",
" reduction=\"none\"\n",
" )\n",
" \n",
" kl_div = KL_with_gaussian_prior(mu, log_sigma_squared)\n",
" \n",
" # loss shape: (batch dim,)\n",
" # do you understand why we sum along this dimension only?\n",
" # there is a minus sign before reconstruction because\n",
" # the loss formula is -log etc, but in the elbo its +log\n",
" elbo = -reconstruction_loss.sum(1) - kl_div\n",
" \n",
" epoch_reconstruction += -reconstruction_loss.sum().item()\n",
" epoch_kl += kl_div.sum().item()\n",
" \n",
" # we want to maximize the ELBO,\n",
" # but Pytorch does minimization,\n",
" # so we define our loss as -ELBO\n",
" # and we mean over instances in the dataset\n",
" loss = -elbo.mean()\n",
" loss.backward()\n",
" \n",
" # optimization trick :)\n",
" # gradient clipping, so we don't take too big updates\n",
" torch.nn.utils.clip_grad_norm_(encoder.parameters(), 5)\n",
" torch.nn.utils.clip_grad_norm_(decoder.parameters(), 5)\n",
" \n",
" optimizer.step()\n",
" \n",
" print(\n",
" epoch, \":\\t\",\n",
" epoch_reconstruction / train_data_pixels.shape[0],\n",
" \"\\t\",\n",
" epoch_kl / train_data_pixels.shape[0]\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now visualize the output distribution from random prior samples and generate new images."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"decoder.eval()\n",
"\n",
"with torch.no_grad():\n",
" # you can try true samples\n",
" # or useing argmax\n",
" samples = decoder.sample_distributions(5)\n",
" display_images(samples)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"decoder.eval()\n",
"\n",
"with torch.no_grad():\n",
" # you can try true samples\n",
" # or useing argmax\n",
" samples = decoder.sample_images(5, argmax=False)\n",
" display_images(samples)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using the approximate posterior, we can visualize the latent space, by assigning one color per digit.\n",
"What we display is the mean value.\n",
"For a well trained model, we should see all points close to 0 and each class should be well delimited, i.e. there must be clusters of the same color.\n",
"\n",
"If your samples and latent space are ugly, you could try to improve your model by:\n",
"\n",
"- change the learning hyperparameters\n",
"- add/remove dropout\n",
"- change the network structure (number and size of layers, dropout...)\n",
"\n",
"Note that if you want to visualize a latent space when its dimension is greater than two, you could project it in 2 dimensions using PCA (its already implemented in scikit-learn!)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"decoder.eval()\n",
"\n",
"# tensor that will contain all latent points\n",
"points = np.empty((train_data_pixels.shape[0], 2))\n",
"with torch.no_grad():\n",
" for i in range(0, train_data_pixels.shape[0], batch_dim): \n",
" batch = train_data_pixels[i:i+batch_dim]\n",
" mu, _ = encoder(batch)\n",
" points[i:i+batch_dim] = mu.numpy()\n",
"\n",
"plt.scatter(\n",
" points[:,0], points[:, 1],\n",
" # colormap is between 0 and 1, and we have 10 classes\n",
" # so we just divide by 10 :)\n",
" # https://matplotlib.org/3.1.1/tutorials/colors/colormaps.html\n",
" c=matplotlib.cm.get_cmap(\"tab10\")(train_data_classes / 10.)\n",
")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. VAE with binary latent space and binary observed space\n",
"\n",
"The second VAE that we will develop is based on the same generative story:\n",
"\n",
"1. $z \\sim p(z)$\n",
"2. $x \\sim p(x | z ; \\theta)$\n",
"\n",
"but where the latent variable $Z$ are independent Bernoulli random variables.\n",
"See the last video from the course to understand how this change the model.\n",
"\n",
"### Architecture\n",
"\n",
"How many values should the encoder return? What is the difference with the previous encoder?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class BernoulliEncoder(nn.Module):\n",
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
" super().__init__()\n",
"\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" def forward(self, batch):\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class BernoulliPriorDecoder(nn.Module):\n",
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
" super().__init__()\n",
" \n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" def forward(self, batch):\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" def sample_distributions(self, n_samples):\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" def sample_images(self, n_samples, argmax=False):\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### KL divergence\n",
"\n",
"We assume the prior are Bernoullis with parameter 0.5, i.e. the probability to sample 0 or 1 are equals (\"fait coin\" probability).\n",
"What the formula of the KL divergence? How does it simplify?\n",
"\n",
"Hint: you should see an entropy term in it that you can compute via https://pytorch.org/docs/stable/distributions.html#torch.distributions.bernoulli.Bernoulli.entropy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# the shapes of mu and log_sigma_squared are: (n batch, n latent)\n",
"# the return vector must be of shape: (n batch,)\n",
"import math\n",
"\n",
"def KL_with_bernoulli_prior(probs):\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
"# test for shape\n",
"probs = torch.rand((10, 30))\n",
"\n",
"if KL_with_bernoulli_prior(probs).shape != (10, ):\n",
" raise RuntimeError(\"Invalid return dim!\")\n",
"else:\n",
" print(\"return dim is ok.\")\n",
" \n",
"# test for return value\n",
"# result should be 0 as it is equal to the prior\n",
"print(\"Should be 0:\", KL_with_bernoulli_prior(torch.tensor([[0.5, 0.5]])).item())\n",
"print(\"Should be 0.693...:\", KL_with_bernoulli_prior(torch.tensor([[1.]])).item())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Training loop\n",
"\n",
"This time I let you on your own! :) \n",
"Remember that you need to use the Score Function Estimator trick! (see the last video of the course)\n",
"\n",
"You need to use a baseline to stabilize the variance of the estimator.\n",
"Here, we will rely on the average reconstruction value from all previous update.\n",
"You can easily store it and compute it using the running average trick:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n1 = 5\n",
"n2 = 10\n",
"n3 = 1\n",
"n4 = 12\n",
"\n",
"print((n1 + n2 + n3 + n4) / 4)\n",
"\n",
"running_average = 0\n",
"\n",
"# after the first parameter update\n",
"n_updates = 1\n",
"running_average += (n1 - running_average) / n_updates\n",
"\n",
"# after the second parameter update\n",
"n_updates += 1\n",
"running_average += (n2 - running_average) / n_updates\n",
"\n",
"# etc etc\n",
"n_updates += 1\n",
"running_average += (n3 - running_average) / n_updates\n",
"\n",
"n_updates += 1\n",
"running_average += (n4 - running_average) / n_updates\n",
"\n",
"# should be equal to the previous printed value!\n",
"print(running_average)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dim_input = 28*28\n",
"latent = 64\n",
"hidden_dim = 400\n",
"n_epoch = 50\n",
"batch_dim = 256\n",
"\n",
"encoder = BernoulliEncoder(dim_input, hidden_dim, latent)\n",
"decoder = BernoulliPriorDecoder(latent, hidden_dim, dim_input)\n",
"optimizer = torch.optim.Adam(list(encoder.parameters()) + list(decoder.parameters()))\n",
"\n",
"running_avg = 0 # to control the variance of the SFE\n",
"n_updates = 0\n",
"for epoch in range(n_epoch):\n",
" epoch_reconstruction = 0\n",
" epoch_kl = 0\n",
" \n",
" decoder.train()\n",
" encoder.train()\n",
" for i in range(0, train_data_pixels.shape[0], batch_dim): \n",
" optimizer.zero_grad()\n",
" \n",
" batch = train_data_pixels[i:i+batch_dim]\n",
" \n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
" \n",
" loss.backward()\n",
" torch.nn.utils.clip_grad_norm_(encoder.parameters(), 5)\n",
" torch.nn.utils.clip_grad_norm_(decoder.parameters(), 5)\n",
" optimizer.step()\n",
" n_updates += 1\n",
" \n",
" # update the running_avg\n",
" #\n",
" #\n",
" # TODO TODO TODO TODO TODO\n",
" #\n",
" #\n",
"\n",
" \n",
" print(\n",
" epoch, \":\\t\",\n",
" epoch_reconstruction / train_data_pixels.shape[0],\n",
" \"\\t\",\n",
" epoch_kl / train_data_pixels.shape[0],\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now visualize the trained model. :) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"decoder.eval()\n",
"\n",
"with torch.no_grad():\n",
" samples = decoder.sample_distributions(5)\n",
" display_images(samples)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"decoder.eval()\n",
"\n",
"with torch.no_grad():\n",
" # you can try true samples\n",
" # or useing argmax\n",
" samples = decoder.sample_images(5, argmax=True)\n",
" display_images(samples)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 4. Turning a Deterministic Auto-Encoder into a generative model\n",
"\n",
"Last exercise!\n",
"Here I want to show you a trick to turn a deterministic model into a probabilistic generative model.\n",
"This a two step process.\n",
"\n",
"First, you train an auto-encoder - not a VAE, just an encoder.\n",
"The encoder takes an image and project it in the latent space, here we will use a 2 dimension latent space.\n",
"It is a deterministic computation: the output of the encoder **is not** the parameters of the approximate posterior $q(z|x)$ distribution, it is a point in the $\\mathbb R^2$ space.\n",
"The decoder reconstruct the input image from the encoder output.\n",
"Therefore, during training, the main difference is that you don't have a KL divergence term! :)\n",
"\n",
"Second, we turn this deterministic model into a probabilistic generative model.\n",
"To do this, we look at where each training image of the training is mapped in the latent space.\n",
"You can train a Gaussian Mixture Model that will generate data that look like the latent space of the training set!\n",
"Then, to generate a new data point, you can:\n",
"\n",
"1. sample a cluster from the GMM: $y \\sim p(y)$\n",
"2. sample a point from the bivariate Gaussian associated with this cluster: $z \\sim p(z|y)$\n",
"3. use the decoder to sample an image: $x \\sim p(x | z)$\n",
"\n",
"To fit and sample from the GMM, use the scikit learn library!\n",
"https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html\n",
"\n",
"### Architecture and training loop of the auto-encoder"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# You are on your own! good luck :)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now visualize the latent space of the deterministic auto-encoder. How does it look like compared to the VAE one? Does it looks like we can fit it with a GMM?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"decoder.eval()\n",
"\n",
"# tensor that will contain all latent points\n",
"points = np.empty((train_data_pixels.shape[0], 2))\n",
"with torch.no_grad():\n",
" for i in range(0, train_data_pixels.shape[0], batch_dim): \n",
" batch = train_data_pixels[i:i+batch_dim]\n",
" mu, _ = encoder(batch)\n",
" points[i:i+batch_dim] = mu.numpy()\n",
"\n",
"plt.scatter(\n",
" points[:,0], points[:, 1],\n",
" # colormap is between 0 and 1, and we have 10 classes\n",
" # so we just divide by 10 :)\n",
" # https://matplotlib.org/3.1.1/tutorials/colors/colormaps.html\n",
" c=matplotlib.cm.get_cmap(\"tab10\")(train_data_classes / 10.)\n",
")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Turning the deterministic auto-encoder into a generative model\n",
"\n",
"Todo:\n",
"\n",
"1. fit the point from the encoder with a GMM (for example with 20 clusters, called components in scikit-learn): https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html\n",
"2. Sample many points from this GMM and plot them: does the resulting point cloud looks like the one above? (or, in other words, did the GMM correctly fit the latent space?)\n",
"3. Sample new data from the model! How does it looks like compared to VAE? how does the output distribution looks like? Does it work?\n",
"\n",
"Note: its an **unsupervised problem**, do not use class information in this part!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# I let you do this alone, again..."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}