2 lines
46 KiB
Plaintext
2 lines
46 KiB
Plaintext
{"cells":[{"cell_type":"markdown","metadata":{"id":"u2U7TIRdKNGu"},"source":["# [Autoencoders](https://arxiv.org/abs/2201.03898)"]},{"cell_type":"markdown","metadata":{"id":"it5nmu_-c5-E"},"source":["When training CNNs, one of the problems is that we need a lot of labeled data. In the case of image classification, we need to separate images into different classes, which is a manual effort.\n","\n","However, we might want to use raw (unlabeled) data for training CNN feature extractors, which is called **self-supervised learning**. Instead of labels, we will use training images as both network input and output. The main idea of **autoencoder** is that we will have an **encoder network** that converts input image into some **latent space** (normally it is just a vector of some smaller size), the then **decoder network**, whose goal would be to reconstruct the original image.\n","\n","Since we are training autoencoder to capture as much of the information from the original image as possible for accurate reconstruction, the network tries to find the best **embedding** of input images to capture the meaning.\n","\n","\n","\n","Let's create simplest autoencoder for MNIST!"]},{"cell_type":"code","execution_count":125,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:29:06.172141Z","iopub.status.busy":"2022-04-07T23:29:06.171876Z","iopub.status.idle":"2022-04-07T23:29:06.179468Z","shell.execute_reply":"2022-04-07T23:29:06.178621Z","shell.execute_reply.started":"2022-04-07T23:29:06.172113Z"},"id":"6n8fzzN-2T1h","trusted":true},"outputs":[],"source":["import torch\n","import torchvision\n","import matplotlib.pyplot as plt\n","from torchvision import transforms\n","from torch import nn\n","from torch import optim\n","from tqdm import tqdm\n","import numpy as np\n","import torch.nn.functional as F\n","torch.manual_seed(42)\n","np.random.seed(42)"]},{"cell_type":"code","execution_count":56,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:08:18.678524Z","iopub.status.busy":"2022-04-07T22:08:18.677978Z","iopub.status.idle":"2022-04-07T22:08:18.682963Z","shell.execute_reply":"2022-04-07T22:08:18.682107Z","shell.execute_reply.started":"2022-04-07T22:08:18.678485Z"},"id":"bjL-jOgi3gmG","trusted":true},"outputs":[],"source":["device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n","train_size = 0.9\n","lr = 1e-3\n","eps = 1e-8\n","batch_size = 256\n","epochs = 30"]},{"cell_type":"code","execution_count":57,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:08:19.781260Z","iopub.status.busy":"2022-04-07T22:08:19.781001Z","iopub.status.idle":"2022-04-07T22:08:19.786750Z","shell.execute_reply":"2022-04-07T22:08:19.785852Z","shell.execute_reply.started":"2022-04-07T22:08:19.781233Z"},"id":"g2Eo43713Sxb","trusted":true},"outputs":[],"source":["def mnist(train_part, transform=None):\n"," dataset = torchvision.datasets.MNIST('.', download=True, transform=transform)\n"," train_part = int(train_part * len(dataset))\n"," train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_part, len(dataset) - train_part])\n"," return train_dataset, test_dataset"]},{"cell_type":"code","execution_count":87,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:10.615629Z","iopub.status.busy":"2022-04-07T22:34:10.615306Z","iopub.status.idle":"2022-04-07T22:34:10.619693Z","shell.execute_reply":"2022-04-07T22:34:10.619011Z","shell.execute_reply.started":"2022-04-07T22:34:10.615594Z"},"id":"K7FaPscQ4kd4","trusted":true},"outputs":[],"source":["transform = transforms.Compose([\n"," transforms.ToTensor(),\n","])"]},{"cell_type":"code","execution_count":88,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:10.622595Z","iopub.status.busy":"2022-04-07T22:34:10.621696Z","iopub.status.idle":"2022-04-07T22:34:10.659892Z","shell.execute_reply":"2022-04-07T22:34:10.659237Z","shell.execute_reply.started":"2022-04-07T22:34:10.622558Z"},"id":"jPaRjZEK18lW","trusted":true},"outputs":[],"source":["train_dataset, test_dataset = mnist(train_size, transform)"]},{"cell_type":"code","execution_count":89,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:10.661312Z","iopub.status.busy":"2022-04-07T22:34:10.660992Z","iopub.status.idle":"2022-04-07T22:34:10.669417Z","shell.execute_reply":"2022-04-07T22:34:10.668728Z","shell.execute_reply.started":"2022-04-07T22:34:10.661275Z"},"id":"jAI3uK86_zHM","trusted":true},"outputs":[],"source":["train_dataloader = torch.utils.data.DataLoader(train_dataset, drop_last=True, batch_size=batch_size, shuffle=True)\n","test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False)\n","dataloaders = (train_dataloader, test_dataloader)"]},{"cell_type":"code","execution_count":61,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:08:22.882317Z","iopub.status.busy":"2022-04-07T22:08:22.880010Z","iopub.status.idle":"2022-04-07T22:08:22.894982Z","shell.execute_reply":"2022-04-07T22:08:22.893986Z","shell.execute_reply.started":"2022-04-07T22:08:22.882274Z"},"id":"LdyQz4092fRV","trusted":true},"outputs":[],"source":["def plotn(n, data, noisy=False, super_res=None):\n"," fig, ax = plt.subplots(1, n)\n"," for i, z in enumerate(data):\n"," if i == n:\n"," break\n"," preprocess = z[0].reshape(1, 28, 28) if z[0].shape[1] == 28 else z[0].reshape(1, 14, 14) if z[0].shape[1] == 14 else z[0]\n"," if super_res is not None:\n"," _transform = transforms.Resize((int(preprocess.shape[1] / super_res), int(preprocess.shape[2] / super_res)))\n"," preprocess = _transform(preprocess)\n","\n"," if noisy:\n"," shapes = list(preprocess.shape)\n"," preprocess += noisify(shapes)\n","\n"," ax[i].imshow(preprocess[0])\n"," plt.show()"]},{"cell_type":"code","execution_count":74,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:16:44.659930Z","iopub.status.busy":"2022-04-07T22:16:44.659661Z","iopub.status.idle":"2022-04-07T22:16:44.665194Z","shell.execute_reply":"2022-04-07T22:16:44.664502Z","shell.execute_reply.started":"2022-04-07T22:16:44.659902Z"},"id":"FjpCEs-oWu6_","trusted":true},"outputs":[],"source":["def noisify(shapes):\n"," return np.random.normal(loc=0.25, scale=0.25, size=shapes)"]},{"cell_type":"code","execution_count":90,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:10.671163Z","iopub.status.busy":"2022-04-07T22:34:10.670898Z","iopub.status.idle":"2022-04-07T22:34:11.195124Z","shell.execute_reply":"2022-04-07T22:34:11.194396Z","shell.execute_reply.started":"2022-04-07T22:34:10.671129Z"},"id":"NeWJoiFC4A6J","outputId":"e680eb07-bf94-4301-8742-852103885624","trusted":true},"outputs":[],"source":["plotn(5, train_dataset)"]},{"cell_type":"code","execution_count":91,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:11.197716Z","iopub.status.busy":"2022-04-07T22:34:11.196275Z","iopub.status.idle":"2022-04-07T22:34:11.206490Z","shell.execute_reply":"2022-04-07T22:34:11.205773Z","shell.execute_reply.started":"2022-04-07T22:34:11.197674Z"},"id":"NnI2YvOg4DbT","trusted":true},"outputs":[],"source":["class Encoder(nn.Module):\n"," def __init__(self):\n"," super().__init__()\n"," self.conv1 = nn.Conv2d(1, 16, kernel_size=(3, 3), padding='same')\n"," self.maxpool1 = nn.MaxPool2d(kernel_size=(2, 2))\n"," self.conv2 = nn.Conv2d(16, 8, kernel_size=(3, 3), padding='same')\n"," self.maxpool2 = nn.MaxPool2d(kernel_size=(2, 2))\n"," self.conv3 = nn.Conv2d(8, 8, kernel_size=(3, 3), padding='same')\n"," self.maxpool3 = nn.MaxPool2d(kernel_size=(2, 2), padding=(1, 1))\n"," self.relu = nn.ReLU()\n","\n"," def forward(self, input):\n"," hidden1 = self.maxpool1(self.relu(self.conv1(input)))\n"," hidden2 = self.maxpool2(self.relu(self.conv2(hidden1)))\n"," encoded = self.maxpool3(self.relu(self.conv3(hidden2)))\n"," return encoded"]},{"cell_type":"code","execution_count":92,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:11.208243Z","iopub.status.busy":"2022-04-07T22:34:11.207603Z","iopub.status.idle":"2022-04-07T22:34:11.218984Z","shell.execute_reply":"2022-04-07T22:34:11.218304Z","shell.execute_reply.started":"2022-04-07T22:34:11.208207Z"},"id":"mZGB4Vr47478","trusted":true},"outputs":[],"source":["class Decoder(nn.Module):\n"," def __init__(self):\n"," super().__init__()\n"," self.conv1 = nn.Conv2d(8, 8, kernel_size=(3, 3), padding='same')\n"," self.upsample1 = nn.Upsample(scale_factor=(2, 2))\n"," self.conv2 = nn.Conv2d(8, 8, kernel_size=(3, 3), padding='same')\n"," self.upsample2 = nn.Upsample(scale_factor=(2, 2))\n"," self.conv3 = nn.Conv2d(8, 16, kernel_size=(3, 3))\n"," self.upsample3 = nn.Upsample(scale_factor=(2, 2))\n"," self.conv4 = nn.Conv2d(16, 1, kernel_size=(3, 3), padding='same')\n"," self.relu = nn.ReLU()\n"," self.sigmoid = nn.Sigmoid()\n","\n"," def forward(self, input):\n"," hidden1 = self.upsample1(self.relu(self.conv1(input)))\n"," hidden2 = self.upsample2(self.relu(self.conv2(hidden1)))\n"," hidden3 = self.upsample3(self.relu(self.conv3(hidden2)))\n"," decoded = self.sigmoid(self.conv4(hidden3))\n"," return decoded"]},{"cell_type":"code","execution_count":93,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:11.220928Z","iopub.status.busy":"2022-04-07T22:34:11.220360Z","iopub.status.idle":"2022-04-07T22:34:11.228411Z","shell.execute_reply":"2022-04-07T22:34:11.227831Z","shell.execute_reply.started":"2022-04-07T22:34:11.220891Z"},"id":"SDGiAPhbBBLY","trusted":true},"outputs":[],"source":["class AutoEncoder(nn.Module):\n"," def __init__(self, super_resolution=False):\n"," super().__init__()\n"," if not super_resolution:\n"," self.encoder = Encoder()\n"," else:\n"," self.encoder = SuperResolutionEncoder()\n"," self.decoder = Decoder()\n","\n"," def forward(self, input):\n"," encoded = self.encoder(input)\n"," decoded = self.decoder(encoded)\n"," return decoded"]},{"cell_type":"code","execution_count":94,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:11.231510Z","iopub.status.busy":"2022-04-07T22:34:11.230756Z","iopub.status.idle":"2022-04-07T22:34:11.242940Z","shell.execute_reply":"2022-04-07T22:34:11.242317Z","shell.execute_reply.started":"2022-04-07T22:34:11.231476Z"},"id":"nZyG_mNu_Pnc","trusted":true},"outputs":[],"source":["model = AutoEncoder().to(device)\n","optimizer = optim.Adam(model.parameters(), lr=lr, eps=eps)\n","loss_fn = nn.BCELoss()"]},{"cell_type":"code","execution_count":68,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:08:36.364247Z","iopub.status.busy":"2022-04-07T22:08:36.363981Z","iopub.status.idle":"2022-04-07T22:08:36.381955Z","shell.execute_reply":"2022-04-07T22:08:36.380758Z","shell.execute_reply.started":"2022-04-07T22:08:36.364218Z"},"id":"iiIy87v2_rUr","trusted":true},"outputs":[],"source":["def train(dataloaders, model, loss_fn, optimizer, epochs, device, noisy=False, super_res=None):\n"," tqdm_iter = tqdm(range(epochs))\n"," train_dataloader, test_dataloader = dataloaders[0], dataloaders[1]\n"," noisy_tensor = None\n"," test_noisy_tensor = None\n","\n"," for epoch in tqdm_iter:\n"," model.train()\n"," train_loss = 0.0\n"," test_loss = 0.0\n","\n"," for batch in train_dataloader:\n"," imgs, labels = batch\n"," shapes = list(imgs.shape)\n","\n"," if super_res is not None:\n"," shapes[2], shapes[3] = int(shapes[2] / super_res), int(shapes[3] / super_res)\n"," _transform = transforms.Resize((shapes[2], shapes[3]))\n"," imgs_transformed = _transform(imgs)\n"," imgs_transformed = imgs_transformed.to(device)\n","\n"," imgs = imgs.to(device)\n"," labels = labels.to(device)\n","\n"," if noisy and noisy_tensor is None:\n"," noisy_tensor = torch.FloatTensor(noisify(shapes)).to(device)\n"," else:\n"," noisy_tensor = torch.zeros(tuple(shapes)).to(device)\n","\n"," if super_res is None:\n"," imgs_noisy = imgs + noisy_tensor\n"," else:\n"," imgs_noisy = imgs_transformed + noisy_tensor\n","\n"," imgs_noisy = torch.clamp(imgs_noisy, 0., 1.)\n","\n"," preds = model(imgs_noisy)\n"," loss = loss_fn(preds, imgs)\n","\n"," optimizer.zero_grad()\n"," loss.backward()\n"," optimizer.step()\n","\n"," train_loss += loss.item()\n","\n"," model.eval()\n"," with torch.no_grad():\n"," for batch in test_dataloader:\n"," imgs, labels = batch\n"," shapes = list(imgs.shape)\n","\n"," if super_res is not None:\n"," shapes[2], shapes[3] = int(shapes[2] / super_res), int(shapes[3] / super_res)\n"," _transform = transforms.Resize((shapes[2], shapes[3]))\n"," imgs_transformed = _transform(imgs)\n"," imgs_transformed = imgs_transformed.to(device)\n","\n","\n"," imgs = imgs.to(device)\n"," labels = labels.to(device)\n","\n"," if noisy and test_noisy_tensor is None:\n"," test_noisy_tensor = torch.FloatTensor(noisify(shapes)).to(device)\n"," else:\n"," test_noisy_tensor = torch.zeros(tuple(shapes)).to(device)\n","\n"," if super_res is None:\n"," imgs_noisy = imgs + test_noisy_tensor\n"," else:\n"," imgs_noisy = imgs_transformed + test_noisy_tensor\n","\n"," imgs_noisy = torch.clamp(imgs_noisy, 0., 1.)\n","\n"," preds = model(imgs_noisy)\n"," loss = loss_fn(preds, imgs)\n","\n"," test_loss += loss.item()\n","\n"," train_loss /= len(train_dataloader)\n"," test_loss /= len(test_dataloader)\n","\n"," tqdm_dct = {'train loss:': train_loss, 'test loss:': test_loss}\n"," tqdm_iter.set_postfix(tqdm_dct, refresh=True)\n"," tqdm_iter.refresh()"]},{"cell_type":"code","execution_count":95,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:11.246183Z","iopub.status.busy":"2022-04-07T22:34:11.245971Z","iopub.status.idle":"2022-04-07T22:41:00.353349Z","shell.execute_reply":"2022-04-07T22:41:00.352609Z","shell.execute_reply.started":"2022-04-07T22:34:11.246159Z"},"id":"PMqO8eOxCemz","trusted":true},"outputs":[],"source":["train(dataloaders, model, loss_fn, optimizer, epochs, device)"]},{"cell_type":"code","execution_count":96,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:41:00.355694Z","iopub.status.busy":"2022-04-07T22:41:00.354744Z","iopub.status.idle":"2022-04-07T22:41:01.345106Z","shell.execute_reply":"2022-04-07T22:41:01.344413Z","shell.execute_reply.started":"2022-04-07T22:41:00.355654Z"},"id":"kR3n0EnjOts0","trusted":true},"outputs":[],"source":["model.eval()\n","predictions = []\n","plots = 5\n","for i, data in enumerate(test_dataset):\n"," if i == plots:\n"," break\n"," predictions.append(model(data[0].to(device).unsqueeze(0)).detach().cpu())\n","plotn(plots, test_dataset)\n","plotn(plots, predictions)"]},{"cell_type":"markdown","metadata":{"id":"1JUmf9i1dg2i"},"source":["> **Task 1**: Try to train autoencoder with very small latent vector size, eg. 2, and plot the dots corresponding to different digits. *Hint: Use fully-connected dense layer after the convoluitonal part to reduce the vector size to the required value.*\n","\n","> **Task 2**: Starting from different digits, obtain their latent space representations, and see what effect adding some noise to the latent space has on the resulting digits."]},{"cell_type":"markdown","metadata":{"id":"tjdFt03rULX-"},"source":["## Denoising\n","\n","Autoencoders can be effectively used to remove noise from images. In order to train denoiser, we will start with noise-free images, and add artificial noise to them. Then, we will feed autoencoder with noisy images as input, and noise-free images as output.\n","\n","Let's see how this works for MNISТ:"]},{"cell_type":"code","execution_count":75,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:17:04.340030Z","iopub.status.busy":"2022-04-07T22:17:04.339488Z","iopub.status.idle":"2022-04-07T22:17:04.722138Z","shell.execute_reply":"2022-04-07T22:17:04.721381Z","shell.execute_reply.started":"2022-04-07T22:17:04.339991Z"},"id":"1Yj9ZRDmUPxX","outputId":"7e3a1624-4326-41a2-8f94-3d41e11cd411","trusted":true},"outputs":[],"source":["plotn(5, train_dataset, noisy=True)"]},{"cell_type":"code","execution_count":76,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:17:19.192439Z","iopub.status.busy":"2022-04-07T22:17:19.192168Z","iopub.status.idle":"2022-04-07T22:17:19.201586Z","shell.execute_reply":"2022-04-07T22:17:19.200834Z","shell.execute_reply.started":"2022-04-07T22:17:19.192408Z"},"id":"qxo8NDLLUvut","trusted":true},"outputs":[],"source":["model = AutoEncoder().to(device)\n","optimizer = optim.Adam(model.parameters(), lr=lr, eps=eps)\n","loss_fn = nn.BCELoss()"]},{"cell_type":"code","execution_count":77,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:17:25.541867Z","iopub.status.busy":"2022-04-07T22:17:25.540974Z","iopub.status.idle":"2022-04-07T22:26:30.268786Z","shell.execute_reply":"2022-04-07T22:26:30.268076Z","shell.execute_reply.started":"2022-04-07T22:17:25.541820Z"},"id":"JAYzgfoTUBHM","trusted":true},"outputs":[],"source":["train(dataloaders, model, loss_fn, optimizer, 40, device, noisy=True)"]},{"cell_type":"code","execution_count":81,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:27:12.268888Z","iopub.status.busy":"2022-04-07T22:27:12.268406Z","iopub.status.idle":"2022-04-07T22:27:13.034069Z","shell.execute_reply":"2022-04-07T22:27:13.033393Z","shell.execute_reply.started":"2022-04-07T22:27:12.268848Z"},"id":"IaPfyJ0SV7XY","trusted":true},"outputs":[],"source":["model.eval()\n","predictions = []\n","noise = []\n","plots = 5\n","for i, data in enumerate(test_dataset):\n"," if i == plots:\n"," break\n"," shapes = data[0].shape\n"," noisy_data = data[0] + torch.FloatTensor(noisify(shapes))\n"," noise.append(noisy_data)\n"," predictions.append(model(noisy_data.to(device).unsqueeze(0)).detach().cpu())\n","plotn(plots, noise)\n","plotn(plots, predictions)"]},{"cell_type":"markdown","metadata":{"id":"MyvmZEHzdoJT"},"source":["> **Exercise:** See how denoiser trained on MNIST digits works for different images. As an example, you can take [Fashion MNIST](https://pytorch.org/vision/stable/generated/torchvision.datasets.FashionMNIST.html#torchvision.datasets.FashionMNIST) dataset, which has the same image size. Note that denoiser works well only on the same image type that is was trained on (i.e. for the same probability distribution of input data)."]},{"cell_type":"markdown","metadata":{"id":"yxFKm_OxdqfO"},"source":["## Super-Resolution\n","\n","Similarly to denoiser, we can train autoencoders to increase the resolution of the image. To train super-resolution network, we will start with high-res images, and automatically downscale them to produce network inputs. We will then feed autoencoder with small images as inputs and high-res images as outputs.\n","\n","For that let's downscale image to 14x14 at train."]},{"cell_type":"code","execution_count":82,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:27:26.148045Z","iopub.status.busy":"2022-04-07T22:27:26.147775Z","iopub.status.idle":"2022-04-07T22:27:26.528086Z","shell.execute_reply":"2022-04-07T22:27:26.527399Z","shell.execute_reply.started":"2022-04-07T22:27:26.148016Z"},"id":"trida5guu9js","outputId":"3dd13ba4-0351-4982-c162-578735af23f8","trusted":true},"outputs":[],"source":["super_res_koeff = 2.0\n","plotn(5, train_dataset, super_res=super_res_koeff)"]},{"cell_type":"code","execution_count":83,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:27:26.613377Z","iopub.status.busy":"2022-04-07T22:27:26.613175Z","iopub.status.idle":"2022-04-07T22:27:26.620037Z","shell.execute_reply":"2022-04-07T22:27:26.619230Z","shell.execute_reply.started":"2022-04-07T22:27:26.613352Z"},"id":"9vC57e-rei4p","trusted":true},"outputs":[],"source":["class SuperResolutionEncoder(nn.Module):\n"," def __init__(self):\n"," super().__init__()\n"," self.conv1 = nn.Conv2d(1, 16, kernel_size=(3, 3), padding='same')\n"," self.maxpool1 = nn.MaxPool2d(kernel_size=(2, 2))\n"," self.conv2 = nn.Conv2d(16, 8, kernel_size=(3, 3), padding='same')\n"," self.maxpool2 = nn.MaxPool2d(kernel_size=(2, 2), padding=(1, 1))\n"," self.relu = nn.ReLU()\n","\n"," def forward(self, input):\n"," hidden1 = self.maxpool1(self.relu(self.conv1(input)))\n"," encoded = self.maxpool2(self.relu(self.conv2(hidden1)))\n"," return encoded"]},{"cell_type":"code","execution_count":84,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:27:27.713826Z","iopub.status.busy":"2022-04-07T22:27:27.713074Z","iopub.status.idle":"2022-04-07T22:27:27.722103Z","shell.execute_reply":"2022-04-07T22:27:27.721327Z","shell.execute_reply.started":"2022-04-07T22:27:27.713789Z"},"id":"d78J288qe5qJ","trusted":true},"outputs":[],"source":["model = AutoEncoder(super_resolution=True).to(device)\n","optimizer = optim.Adam(model.parameters(), lr=lr, eps=eps)\n","loss_fn = nn.BCELoss()"]},{"cell_type":"code","execution_count":85,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:27:28.959163Z","iopub.status.busy":"2022-04-07T22:27:28.958701Z","iopub.status.idle":"2022-04-07T22:34:09.817260Z","shell.execute_reply":"2022-04-07T22:34:09.816576Z","shell.execute_reply.started":"2022-04-07T22:27:28.959126Z"},"id":"CJ_zcN5Je6I-","outputId":"2311bd2a-55c6-4fdf-c4d2-37f0426fb61c","trusted":true},"outputs":[],"source":["train(dataloaders, model, loss_fn, optimizer, epochs, device, super_res=2.0)"]},{"cell_type":"code","execution_count":86,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:34:09.819386Z","iopub.status.busy":"2022-04-07T22:34:09.818889Z","iopub.status.idle":"2022-04-07T22:34:10.614124Z","shell.execute_reply":"2022-04-07T22:34:10.613402Z","shell.execute_reply.started":"2022-04-07T22:34:09.819345Z"},"id":"YsVfcCKKfjv1","outputId":"e7e029b0-b403-4feb-f869-d6367957741a","trusted":true},"outputs":[],"source":["model.eval()\n","predictions = []\n","plots = 5\n","shapes = test_dataset[0][0].shape\n","\n","for i, data in enumerate(test_dataset):\n"," if i == plots:\n"," break\n"," _transform = transforms.Resize((int(shapes[1] / super_res_koeff), int(shapes[2] / super_res_koeff)))\n"," predictions.append(model(_transform(data[0]).to(device).unsqueeze(0)).detach().cpu())\n","plotn(plots, test_dataset, super_res=super_res_koeff)\n","plotn(plots, predictions)"]},{"cell_type":"markdown","metadata":{"id":"-aZqFJthfu9-"},"source":["> **Exercise**: Try to train super-resolution network on [CIFAR-10](https://pytorch.org/vision/stable/generated/torchvision.datasets.CIFAR10.html) for 2x and 4x upscaling. Use noise as input to 4x upscaling model and observe the result."]},{"cell_type":"markdown","metadata":{"id":"A3DOJU1-gTJV"},"source":["# [Variational Auto-Encoders (VAE)](https://arxiv.org/abs/1906.02691)\n","\n","Traditional autoencoders reduce the dimension of the input data somehow, figuring out the important features of input images. However, latent vectors ofter do not make much sense. In other words, taking MNIST dataset as an example, figuring out which digits correspond to different latent vectors is not an easy task, because close latent vectors would not necessarily correspond to the same digits. \n","\n","On the other hand, to train *generative* models it is better to have some understanding of the latent space. This idea leads us to **variational autoencoder** (VAE).\n","\n","VAE is the autoencoder that learns to predict *statistical distribution* of the latent parameters, so-called **latent distribution**. For example, we can assume that latent vectors would be distributed as $N(\\mathrm{z\\_mean},e^{\\mathrm{z\\_log}})$, where $\\mathrm{z\\_mean}, \\mathrm{z\\_log} \\in\\mathbb{R}^d$. Encoder in VAE learns to predict those parameters, and then decoder takes a random vector from this distribution to reconstruct the object.\n","\n","To summarize:\n","\n"," * From input vector, we predict `z_mean` and `z_log` (instead of predicting the standard deviation itself, we predict it's logarithm)\n"," * We sample a vector `sample(z_val in code)` from the distribution $N(\\mathrm{z\\_mean},e^{\\mathrm{z\\_log\\_sigma}})$\n"," * Decoder tries to decode the original image using `sample` as an input vector\n","\n"," <img src=\"images/vae.png\" width=\"50%\">"]},{"cell_type":"code","execution_count":35,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T21:58:49.985541Z","iopub.status.busy":"2022-04-07T21:58:49.985283Z","iopub.status.idle":"2022-04-07T21:58:49.996198Z","shell.execute_reply":"2022-04-07T21:58:49.995415Z","shell.execute_reply.started":"2022-04-07T21:58:49.985513Z"},"id":"aT_GEWeU409I","trusted":true},"outputs":[],"source":["class VAEEncoder(nn.Module):\n"," def __init__(self, device):\n"," super().__init__()\n"," self.intermediate_dim = 512\n"," self.latent_dim = 2\n"," self.linear = nn.Linear(784, self.intermediate_dim)\n"," self.z_mean = nn.Linear(self.intermediate_dim, self.latent_dim)\n"," self.z_log = nn.Linear(self.intermediate_dim, self.latent_dim)\n"," self.relu = nn.ReLU()\n"," self.device = device\n","\n"," def forward(self, input):\n"," bs = input.shape[0]\n","\n"," hidden = self.relu(self.linear(input))\n"," z_mean = self.z_mean(hidden)\n"," z_log = self.z_log(hidden)\n","\n"," eps = torch.FloatTensor(np.random.normal(size=(bs, self.latent_dim))).to(device)\n"," z_val = z_mean + torch.exp(z_log) * eps\n"," return z_mean, z_log, z_val"]},{"cell_type":"code","execution_count":36,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T21:58:51.180232Z","iopub.status.busy":"2022-04-07T21:58:51.179476Z","iopub.status.idle":"2022-04-07T21:58:51.187153Z","shell.execute_reply":"2022-04-07T21:58:51.185336Z","shell.execute_reply.started":"2022-04-07T21:58:51.180193Z"},"id":"XWi4oCcq409p","trusted":true},"outputs":[],"source":["class VAEDecoder(nn.Module):\n"," def __init__(self):\n"," super().__init__()\n"," self.intermediate_dim = 512\n"," self.latent_dim = 2\n"," self.linear = nn.Linear(self.latent_dim, self.intermediate_dim)\n"," self.output = nn.Linear(self.intermediate_dim, 784)\n"," self.relu = nn.ReLU()\n"," self.sigmoid = nn.Sigmoid()\n","\n"," def forward(self, input):\n"," hidden = self.relu(self.linear(input))\n"," decoded = self.sigmoid(self.output(hidden))\n"," return decoded"]},{"cell_type":"code","execution_count":37,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T21:58:58.410064Z","iopub.status.busy":"2022-04-07T21:58:58.409811Z","iopub.status.idle":"2022-04-07T21:58:58.416646Z","shell.execute_reply":"2022-04-07T21:58:58.415810Z","shell.execute_reply.started":"2022-04-07T21:58:58.410038Z"},"id":"WukDYQ9f409p","trusted":true},"outputs":[],"source":["class VAEAutoEncoder(nn.Module):\n"," def __init__(self, device):\n"," super().__init__()\n"," self.encoder = VAEEncoder(device)\n"," self.decoder = VAEDecoder()\n"," self.z_vals = None\n","\n"," def forward(self, input):\n"," bs, c, h, w = input.shape[0], input.shape[1], input.shape[2], input.shape[3]\n"," input = input.view(bs, -1)\n"," encoded = self.encoder(input)\n"," self.z_vals = encoded\n"," decoded = self.decoder(encoded[2])\n"," return decoded\n"," \n"," def get_zvals(self):\n"," return self.z_vals"]},{"cell_type":"markdown","metadata":{},"source":["Variational auto-encoders use complex loss function that consists of two parts:\n","* **Reconstruction loss** is the loss function that shows how close reconstructed image is to the target (can be MSE). It is the same loss function as in normal autoencoders.\n","* **KL loss**, which ensures that latent variable distributions stays close to normal distribution. It is based on the notion of [Kullback-Leibler divergence](https://www.countbayesie.com/blog/2017/5/9/kullback-leibler-divergence-explained) - a metric to estimate how similar two statistical distributions are."]},{"cell_type":"code","execution_count":41,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T21:59:39.022178Z","iopub.status.busy":"2022-04-07T21:59:39.021647Z","iopub.status.idle":"2022-04-07T21:59:39.029102Z","shell.execute_reply":"2022-04-07T21:59:39.028326Z","shell.execute_reply.started":"2022-04-07T21:59:39.022140Z"},"trusted":true},"outputs":[],"source":["def vae_loss(preds, targets, z_vals):\n"," mse = nn.MSELoss()\n"," reconstruction_loss = mse(preds, targets.view(targets.shape[0], -1)) * 784.0\n"," temp = 1.0 + z_vals[1] - torch.square(z_vals[0]) - torch.exp(z_vals[1])\n"," kl_loss = -0.5 * torch.sum(temp, axis=-1)\n"," return torch.mean(reconstruction_loss + kl_loss)"]},{"cell_type":"code","execution_count":42,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T21:59:39.390807Z","iopub.status.busy":"2022-04-07T21:59:39.390555Z","iopub.status.idle":"2022-04-07T21:59:39.405174Z","shell.execute_reply":"2022-04-07T21:59:39.404462Z","shell.execute_reply.started":"2022-04-07T21:59:39.390779Z"},"trusted":true},"outputs":[],"source":["model = VAEAutoEncoder(device).to(device)\n","optimizer = optim.RMSprop(model.parameters(), lr=lr, eps=eps)"]},{"cell_type":"code","execution_count":43,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T21:59:39.718068Z","iopub.status.busy":"2022-04-07T21:59:39.717856Z","iopub.status.idle":"2022-04-07T21:59:39.727781Z","shell.execute_reply":"2022-04-07T21:59:39.726792Z","shell.execute_reply.started":"2022-04-07T21:59:39.718043Z"},"trusted":true},"outputs":[],"source":["def train_vae(dataloaders, model, optimizer, epochs, device):\n"," tqdm_iter = tqdm(range(epochs))\n"," train_dataloader, test_dataloader = dataloaders[0], dataloaders[1]\n","\n"," for epoch in tqdm_iter:\n"," model.train()\n"," train_loss = 0.0\n"," test_loss = 0.0\n","\n"," for batch in train_dataloader:\n"," imgs, labels = batch\n"," imgs = imgs.to(device)\n"," labels = labels.to(device)\n","\n"," preds = model(imgs)\n"," z_vals = model.get_zvals()\n"," loss = vae_loss(preds, imgs, z_vals)\n","\n"," optimizer.zero_grad()\n"," loss.backward()\n"," optimizer.step()\n","\n"," train_loss += loss.item()\n","\n"," model.eval()\n"," with torch.no_grad():\n"," for batch in test_dataloader:\n"," imgs, labels = batch\n"," imgs = imgs.to(device)\n"," labels = labels.to(device)\n","\n"," preds = model(imgs)\n"," z_vals = model.get_zvals()\n"," loss = vae_loss(preds, imgs, z_vals)\n","\n"," test_loss += loss.item()\n","\n"," train_loss /= len(train_dataloader)\n"," test_loss /= len(test_dataloader)\n","\n"," tqdm_dct = {'train loss:': train_loss, 'test loss:': test_loss}\n"," tqdm_iter.set_postfix(tqdm_dct, refresh=True)\n"," tqdm_iter.refresh()"]},{"cell_type":"code","execution_count":44,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T21:59:40.174195Z","iopub.status.busy":"2022-04-07T21:59:40.173962Z","iopub.status.idle":"2022-04-07T22:04:29.373590Z","shell.execute_reply":"2022-04-07T22:04:29.372894Z","shell.execute_reply.started":"2022-04-07T21:59:40.174168Z"},"trusted":true},"outputs":[],"source":["train_vae(dataloaders, model, optimizer, epochs, device)"]},{"cell_type":"code","execution_count":50,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T22:06:02.195473Z","iopub.status.busy":"2022-04-07T22:06:02.195214Z","iopub.status.idle":"2022-04-07T22:06:03.098105Z","shell.execute_reply":"2022-04-07T22:06:03.097411Z","shell.execute_reply.started":"2022-04-07T22:06:02.195445Z"},"trusted":true},"outputs":[],"source":["model.eval()\n","predictions = []\n","plots = 5\n","for i, data in enumerate(test_dataset):\n"," if i == plots:\n"," break\n"," predictions.append(model(data[0].to(device).unsqueeze(0)).view(1, 28, 28).detach().cpu())\n","plotn(plots, test_dataset)\n","plotn(plots, predictions)"]},{"cell_type":"markdown","metadata":{},"source":["> **Task**: In our sample, we have trained fully-connected VAE. Now take the CNN from traditional auto-encoder above and create CNN-based VAE."]},{"cell_type":"markdown","metadata":{},"source":["# [Adversarial Auto-Encoders (AAE)](https://arxiv.org/abs/1511.05644)"]},{"cell_type":"markdown","metadata":{},"source":["Adversarial Auto-Encoders is a **combination** of Generative Adversarial Networks and Variational Auto-Encoders. \n","\n","Encoder will be the generator, discriminator will learn to distinguish the real images encoder output from generated ones. Encoder output is a distribution, from this output decoder will try decode image.\n","\n","In this approach we have **three loss functions**: generator loss, discriminator loss from GAN's and reconstruction loss from VAE.\n","\n"," <img src=\"images/aae.png\" width=\"50%\">"]},{"cell_type":"code","execution_count":169,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:29.048789Z","iopub.status.busy":"2022-04-07T23:42:29.048510Z","iopub.status.idle":"2022-04-07T23:42:29.057368Z","shell.execute_reply":"2022-04-07T23:42:29.056579Z","shell.execute_reply.started":"2022-04-07T23:42:29.048761Z"},"trusted":true},"outputs":[],"source":["class AAEEncoder(nn.Module):\n"," def __init__(self, input_dim, inter_dim, latent_dim):\n"," super().__init__()\n"," self.linear1 = nn.Linear(input_dim, inter_dim)\n"," self.linear2 = nn.Linear(inter_dim, inter_dim)\n"," self.linear3 = nn.Linear(inter_dim, inter_dim)\n"," self.linear4 = nn.Linear(inter_dim, latent_dim)\n"," self.relu = nn.ReLU()\n"," \n"," def forward(self, input):\n"," hidden1 = self.relu(self.linear1(input))\n"," hidden2 = self.relu(self.linear2(hidden1))\n"," hidden3 = self.relu(self.linear3(hidden2))\n"," encoded = self.linear4(hidden3)\n"," return encoded"]},{"cell_type":"code","execution_count":170,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:29.868218Z","iopub.status.busy":"2022-04-07T23:42:29.867956Z","iopub.status.idle":"2022-04-07T23:42:29.877232Z","shell.execute_reply":"2022-04-07T23:42:29.875007Z","shell.execute_reply.started":"2022-04-07T23:42:29.868183Z"},"trusted":true},"outputs":[],"source":["class AAEDecoder(nn.Module):\n"," def __init__(self, latent_dim, inter_dim, output_dim):\n"," super().__init__()\n"," self.linear1 = nn.Linear(latent_dim, inter_dim)\n"," self.linear2 = nn.Linear(inter_dim, inter_dim)\n"," self.linear3 = nn.Linear(inter_dim, inter_dim)\n"," self.linear4 = nn.Linear(inter_dim, output_dim)\n"," self.relu = nn.ReLU()\n"," self.sigmoid = nn.Sigmoid()\n"," \n"," def forward(self, input):\n"," hidden1 = self.relu(self.linear1(input))\n"," hidden2 = self.relu(self.linear2(hidden1))\n"," hidden3 = self.relu(self.linear3(hidden2))\n"," decoded = self.sigmoid(self.linear4(hidden3))\n"," return decoded"]},{"cell_type":"code","execution_count":171,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:30.613336Z","iopub.status.busy":"2022-04-07T23:42:30.613083Z","iopub.status.idle":"2022-04-07T23:42:30.622002Z","shell.execute_reply":"2022-04-07T23:42:30.621267Z","shell.execute_reply.started":"2022-04-07T23:42:30.613308Z"},"trusted":true},"outputs":[],"source":["class AAEDiscriminator(nn.Module):\n"," def __init__(self, latent_dim, inter_dim):\n"," super().__init__()\n"," self.latent_dim = latent_dim\n"," self.inter_dim = inter_dim\n"," self.linear1 = nn.Linear(latent_dim, inter_dim)\n"," self.linear2 = nn.Linear(inter_dim, inter_dim)\n"," self.linear3 = nn.Linear(inter_dim, inter_dim)\n"," self.linear4 = nn.Linear(inter_dim, inter_dim)\n"," self.linear5 = nn.Linear(inter_dim, 1)\n"," self.relu = nn.ReLU()\n"," self.sigmoid = nn.Sigmoid()\n"," \n"," def forward(self, input):\n"," hidden1 = self.relu(self.linear1(input))\n"," hidden2 = self.relu(self.linear2(hidden1))\n"," hidden3 = self.relu(self.linear3(hidden2))\n"," hidden4 = self.relu(self.linear4(hidden3))\n"," decoded = self.sigmoid(self.linear4(hidden4))\n"," return decoded\n"," \n"," def get_dims(self):\n"," return self.latent_dim, self.inter_dim\n"," "]},{"cell_type":"code","execution_count":173,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:35.303062Z","iopub.status.busy":"2022-04-07T23:42:35.302489Z","iopub.status.idle":"2022-04-07T23:42:35.307122Z","shell.execute_reply":"2022-04-07T23:42:35.306088Z","shell.execute_reply.started":"2022-04-07T23:42:35.303023Z"},"trusted":true},"outputs":[],"source":["input_dims = 784\n","inter_dims = 1000\n","latent_dims = 150"]},{"cell_type":"code","execution_count":174,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:36.281582Z","iopub.status.busy":"2022-04-07T23:42:36.280891Z","iopub.status.idle":"2022-04-07T23:42:36.341758Z","shell.execute_reply":"2022-04-07T23:42:36.341059Z","shell.execute_reply.started":"2022-04-07T23:42:36.281520Z"},"trusted":true},"outputs":[],"source":["aae_encoder = AAEEncoder(input_dims, inter_dims, latent_dims).to(device)\n","aae_decoder = AAEDecoder(latent_dims, inter_dims, input_dims).to(device)\n","aae_discriminator = AAEDiscriminator(latent_dims, int(inter_dims / 2)).to(device)"]},{"cell_type":"code","execution_count":175,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:36.966785Z","iopub.status.busy":"2022-04-07T23:42:36.966433Z","iopub.status.idle":"2022-04-07T23:42:36.973600Z","shell.execute_reply":"2022-04-07T23:42:36.972878Z","shell.execute_reply.started":"2022-04-07T23:42:36.966750Z"},"trusted":true},"outputs":[],"source":["lr = 1e-4\n","regularization_lr = 5e-5"]},{"cell_type":"code","execution_count":176,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:37.935003Z","iopub.status.busy":"2022-04-07T23:42:37.934685Z","iopub.status.idle":"2022-04-07T23:42:37.941516Z","shell.execute_reply":"2022-04-07T23:42:37.940603Z","shell.execute_reply.started":"2022-04-07T23:42:37.934966Z"},"trusted":true},"outputs":[],"source":["optim_encoder = optim.Adam(aae_encoder.parameters(), lr=lr)\n","optim_encoder_regularization = optim.Adam(aae_encoder.parameters(), lr=regularization_lr)\n","optim_decoder = optim.Adam(aae_decoder.parameters(), lr=lr)\n","optim_discriminator = optim.Adam(aae_discriminator.parameters(), lr=regularization_lr)"]},{"cell_type":"code","execution_count":177,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:38.761534Z","iopub.status.busy":"2022-04-07T23:42:38.760934Z","iopub.status.idle":"2022-04-07T23:42:38.783970Z","shell.execute_reply":"2022-04-07T23:42:38.782836Z","shell.execute_reply.started":"2022-04-07T23:42:38.761498Z"},"trusted":true},"outputs":[],"source":["def train_aae(dataloaders, models, optimizers, epochs, device):\n"," tqdm_iter = tqdm(range(epochs))\n"," train_dataloader, test_dataloader = dataloaders[0], dataloaders[1]\n"," \n"," enc, dec, disc = models[0], models[1], models[2]\n"," optim_enc, optim_enc_reg, optim_dec, optim_disc = optimizers[0], optimizers[1], optimizers[2], optimizers[3]\n"," \n"," eps = 1e-9\n","\n"," for epoch in tqdm_iter:\n"," enc.train()\n"," dec.train()\n"," disc.train()\n","\n"," train_reconst_loss = 0.0\n"," train_disc_loss = 0.0\n"," train_enc_loss = 0.0\n"," \n"," test_reconst_loss = 0.0\n"," test_disc_loss = 0.0\n"," test_enc_loss = 0.0\n","\n"," for batch in train_dataloader:\n"," imgs, labels = batch\n"," imgs = imgs.view(imgs.shape[0], -1).to(device)\n"," labels = labels.to(device)\n"," \n"," enc.zero_grad()\n"," dec.zero_grad()\n"," disc.zero_grad()\n"," \n"," encoded = enc(imgs)\n"," decoded = dec(encoded)\n"," \n"," reconstruction_loss = F.binary_cross_entropy(decoded, imgs)\n"," reconstruction_loss.backward()\n"," \n"," optim_enc.step()\n"," optim_dec.step()\n"," enc.eval()\n","\n"," latent_dim, disc_inter_dim = disc.get_dims()\n"," real = torch.randn(imgs.shape[0], latent_dim).to(device)\n"," \n"," disc_real = disc(real)\n"," disc_fake = disc(enc(imgs))\n"," \n"," disc_loss = -torch.mean(torch.log(disc_real + eps) + torch.log(1.0 - disc_fake + eps))\n"," disc_loss.backward()\n"," \n"," optim_dec.step()\n"," enc.train()\n"," \n"," disc_fake = disc(enc(imgs))\n"," enc_loss = -torch.mean(torch.log(disc_fake + eps))\n"," enc_loss.backward()\n"," \n"," optim_enc_reg.step()\n","\n"," train_reconst_loss += reconstruction_loss.item()\n"," train_disc_loss += disc_loss.item()\n"," train_enc_loss += enc_loss.item()\n","\n"," enc.eval()\n"," dec.eval()\n"," disc.eval()\n","\n"," with torch.no_grad():\n"," for batch in test_dataloader:\n"," imgs, labels = batch\n"," imgs = imgs.view(imgs.shape[0], -1).to(device)\n"," labels = labels.to(device)\n","\n"," encoded = enc(imgs)\n"," decoded = dec(encoded)\n","\n"," reconstruction_loss = F.binary_cross_entropy(decoded, imgs)\n","\n"," latent_dim, disc_inter_dim = disc.get_dims()\n"," real = torch.randn(imgs.shape[0], latent_dim).to(device)\n","\n"," disc_real = disc(real)\n"," disc_fake = disc(enc(imgs))\n"," disc_loss = -torch.mean(torch.log(disc_real + eps) + torch.log(1.0 - disc_fake + eps))\n","\n"," disc_fake = disc(enc(imgs))\n"," enc_loss = -torch.mean(torch.log(disc_fake + eps))\n","\n"," test_reconst_loss += reconstruction_loss.item()\n"," test_disc_loss += disc_loss.item()\n"," test_enc_loss += enc_loss.item()\n","\n"," train_reconst_loss /= len(train_dataloader)\n"," train_disc_loss /= len(train_dataloader)\n"," train_enc_loss /= len(train_dataloader)\n"," \n"," test_reconst_loss /= len(test_dataloader)\n"," test_disc_loss /= len(test_dataloader)\n"," test_enc_loss /= len(test_dataloader)\n","\n"," tqdm_dct = {'train reconst loss:': train_reconst_loss, 'train disc loss:': train_disc_loss, 'train enc loss': train_enc_loss, \\\n"," 'test reconst loss:': test_reconst_loss, 'test disc loss:': test_disc_loss, 'test enc loss': test_enc_loss}\n"," tqdm_iter.set_postfix(tqdm_dct, refresh=True)\n"," tqdm_iter.refresh()"]},{"cell_type":"code","execution_count":178,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:39.548719Z","iopub.status.busy":"2022-04-07T23:42:39.548152Z","iopub.status.idle":"2022-04-07T23:42:39.554618Z","shell.execute_reply":"2022-04-07T23:42:39.552145Z","shell.execute_reply.started":"2022-04-07T23:42:39.548682Z"},"trusted":true},"outputs":[],"source":["models = (aae_encoder, aae_decoder, aae_discriminator)\n","optimizers = (optim_encoder, optim_encoder_regularization, optim_decoder, optim_discriminator)"]},{"cell_type":"code","execution_count":179,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:42:40.199497Z","iopub.status.busy":"2022-04-07T23:42:40.198669Z","iopub.status.idle":"2022-04-07T23:51:58.463843Z","shell.execute_reply":"2022-04-07T23:51:58.463128Z","shell.execute_reply.started":"2022-04-07T23:42:40.199453Z"},"trusted":true},"outputs":[],"source":["train_aae(dataloaders, models, optimizers, epochs, device)"]},{"cell_type":"code","execution_count":181,"metadata":{"execution":{"iopub.execute_input":"2022-04-07T23:53:14.587179Z","iopub.status.busy":"2022-04-07T23:53:14.586912Z","iopub.status.idle":"2022-04-07T23:53:16.255114Z","shell.execute_reply":"2022-04-07T23:53:16.254415Z","shell.execute_reply.started":"2022-04-07T23:53:14.587150Z"},"trusted":true},"outputs":[],"source":["aae_encoder.eval()\n","aae_decoder.eval()\n","predictions = []\n","plots = 10\n","for i, data in enumerate(test_dataset):\n"," if i == plots:\n"," break\n"," pred = aae_decoder(aae_encoder(data[0].to(device).unsqueeze(0).view(1, 784)))\n"," predictions.append(pred.view(1, 28, 28).detach().cpu())\n","plotn(plots, test_dataset)\n","plotn(plots, predictions)"]},{"cell_type":"markdown","metadata":{},"source":["## Additional Materials\n","\n","* [Blog post on NeuroHive](https://neurohive.io/ru/osnovy-data-science/variacionnyj-avtojenkoder-vae/)\n","* [Variational Autoencoders Explained](https://kvfrans.com/variational-autoencoders-explained/)"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":[]}],"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.12"}},"nbformat":4,"nbformat_minor":4}
|