<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Konstantin Georgiev on Medium]]></title>
        <description><![CDATA[Stories by Konstantin Georgiev on Medium]]></description>
        <link>https://medium.com/@kgeorgiev96?source=rss-aff91451f333------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*2HhmAkgYHmPjd2Ki6XqA5g.jpeg</url>
            <title>Stories by Konstantin Georgiev on Medium</title>
            <link>https://medium.com/@kgeorgiev96?source=rss-aff91451f333------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:25:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kgeorgiev96/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to debug your Deep Learning pipeline with TensorBoard]]></title>
            <link>https://medium.com/data-science/how-to-debug-your-deep-learning-pipeline-with-tensorboard-d27d3f8795e?source=rss-aff91451f333------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27d3f8795e</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[tensorboard]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Konstantin Georgiev]]></dc:creator>
            <pubDate>Fri, 19 Feb 2021 15:30:58 GMT</pubDate>
            <atom:updated>2021-02-19T22:42:19.100Z</atom:updated>
            <content:encoded><![CDATA[<h4>An interactive example on how to boost your Deep Learning experimental throughput.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*j-j1JYSTmBE0krFHuh5m6w.png" /><figcaption>UMAP segmentation of 10 Hiragana character classes using TensorBoard (Image by Author)</figcaption></figure><p>As we develop our Deep Learning models we often stumble upon various kinds of problems within our pipeline. This includes issues in the way we deal with our data, errors in the way this data is passed into our model or even at the evaluation stage. One of the main challenges for a Data Scientist is to make this data transparent (as much as possible) to ensure that the right tool in the toolbox is being used (preprocessing strategy, model layers, criteria for evaluation, etc.). However, in order to achieve this we often have to do a series of experiments on a <strong>trial-and-error</strong> basis, which involve displaying custom plots and tracking variables. This is where <strong>TensorBoard </strong>comes in to boost our workflow!</p><h3><strong>What exactly is TensorBoard?</strong></h3><p><strong>TensorBoard</strong> is an advanced profiling tool made specifically for Deep Learning pipelines that works with all kinds of data sources (image, video, audio, structured data, etc.). It allows us to debug our pipeline through automated visualization plots. It also <strong>tracks</strong> the history of our experiments so that we can run multiple versions and observe which model configuration has the best impact on the performance. This is especially useful for hyperparameter tuning. Another feature which I really like is the ability to <strong>project </strong>our model embeddings in 2D/3D space (through clustering methods) and observe the correlation between each individual data point.</p><p>In this tutorial, I’ll show you a standard <strong>Image Classification </strong>example using the <strong>K-MNIST </strong>(Kuzushiji-MNIST) dataset containing sets of Japanese Hiragana characters. We’ll use <strong>PyTorch</strong> to build and evaluate our model and send it over to <strong>TensorBoard </strong>for analysis, with just a simple 2–3 lines addition in our code!</p><h3>Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*GwyA3Ukcwdv7LSVZ.png" /><figcaption>KMNIST — 10 rows Hiragana candidate classes (Image by Clanuwat et al., <a href="https://arxiv.org/pdf/1812.01718.pdf">Deep Learning for Classical Architecture</a>, 2018)</figcaption></figure><p><strong>K-MNIST</strong> is a set of Japanese Kuzushiji characters, based on the classic <strong>MNIST</strong>. Except in this case, the targets are not numbers but each represent a set of Hiragana characters (each row in the example above). The first example in each row is the modern Hiragana counterpart of the character, while the rest are written in <strong>Kuzushiji</strong>-<strong>style</strong>, which was used in old Japanese manuscripts and books over 150 years ago. The story behind how this dataset was created is really fascinating, as it generally allows old pieces of Japanese literature written in this style to be translated in modern Kanji and used in education systems. You can read more about the work of Clanuwat et al. <a href="https://arxiv.org/pdf/1812.01718.pdf">here</a>.</p><p>We’ll use this dataset in our to build a basic <strong>PyTorch ConvNet</strong> for character recognition (don’t worry you don’t need to actually know Japanese, neither do I). So, let us begin :).</p><h4><strong>Dependencies</strong></h4><p>This example is was made on a Python 3.7 enviroment including the latest versions of the following packages:</p><ul><li><strong>torch and torchvision — modelling</strong></li><li><strong>standard plotting, computation packages — matplotlib, seaborn, numpy (should be already installed on Conda)</strong></li><li><em>Note: if you’ve also installed </em><strong><em>Tensorflow </em></strong><em>on your environment you can use this hack to clear any TensorBoard errors related to file handling.</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35fe3f7fc996b38e700e7bc703624297/href">https://medium.com/media/35fe3f7fc996b38e700e7bc703624297/href</a></iframe><p>Here’s also the other imports:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3b7272d04f6c64ccf7c6a903f85e634/href">https://medium.com/media/f3b7272d04f6c64ccf7c6a903f85e634/href</a></iframe><h4>Basic config</h4><p>Let’s also add a couple of default variables useful for later on. These include the class names of the characters, some hyperparameters, paths and the size of the images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4e8312f8fb0d066f365a0747a88f6b5/href">https://medium.com/media/e4e8312f8fb0d066f365a0747a88f6b5/href</a></iframe><h4>Initialize TensorBoard</h4><p>This is simply done with one call which will generate a <strong>runs/k-mnist </strong>directory where our data will be encoded by the <strong>TensorBoard API.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40bc120929e62317c4fdac748dfa27ca/href">https://medium.com/media/40bc120929e62317c4fdac748dfa27ca/href</a></iframe><h4><strong>Read the data</strong></h4><p>We can use the PyTorch DataLoader class to easily load our K-MNIST data for training and validation. We can also specify custom transformations to be performed after loading. In this case, we’ll convert the images to a PyTorch tensor and normalize the image channels (using the same parameters as the ones used for processing <strong>MNIST</strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69d0bac7800a9e515050e39c7cec25e2/href">https://medium.com/media/69d0bac7800a9e515050e39c7cec25e2/href</a></iframe><h4>Visualize some examples</h4><p>Before we actually get to the automated part of <strong>TensorBoard</strong>, let’s first look at how to profile some custom images. For this example, we’ll view the raw characters by loading them as <strong>numpy</strong> arrays from <strong>ubyte</strong> format. Next we’ll create two simple functions:</p><ul><li>one to display a 5x5 grid of the first 25 characters and their class index</li><li>one to display each of the 25 characters in a separate image</li></ul><p>We’ll log the output of both of these functions to <strong>TensorBoard</strong>. For the grid, we’ll temporarily save the matplotlib figure into a buffer and then transform it to a tensor using PIL and then pass it to <strong>TensorBoard. </strong>We do this because <strong>TensorBoard</strong> only deals with tensor inputs. For plotting the individual images, we can simply convert the numpy array to a tensor and pass each image with a different global step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12f2385a8b5856d2d0490af50d1947b8/href">https://medium.com/media/12f2385a8b5856d2d0490af50d1947b8/href</a></iframe><p>Now, in order to see the logged output, we need to launch the <strong>TensorBoard API </strong>in a separate terminal and host it in our local runtime. We can do this by changing into our <strong>project folder</strong> and running the following. The <strong>TensorBoard output</strong> will be located at <a href="http://localhost:6006/"><strong>http://localhost:6006</strong></a><strong>.</strong></p><p>tensorboard --logdir=runs/k-mnist --samples_per_plugin &quot;images=100, text=100&quot;</p><p>Here, the <strong>logdir</strong> is the directory we created when initializing the <strong>SummaryWriter</strong>. <em>Note: </em><em>--samples_per_plugin allows us to increase the amount of samples we can step over for a specific TensorBoard module. In our case we exceed this limit, in terms of images and text and increasing it gives us the full set of outputs.</em></p><p>After hosting <strong>TensorBoard </strong>we will see the following page:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2Ff2i1EK1%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2Ff2i1EK1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="700" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3ce8db387acaffd2dc36401008def57/href">https://medium.com/media/d3ce8db387acaffd2dc36401008def57/href</a></iframe><p>Visualizing image data in <strong>TensorBoard</strong> allows you to adjust contrast and brightness interactively, as well as scroll over multiple examples, which is quite useful for observing your data.</p><h4>Create the DataLoaders</h4><p>In order to make the model training more memory-efficient we need to use batch processing. This is easily done in PyTorch through <strong>DataLoaders. </strong>Simply specify the batch size and whether to shuffle the training/val sets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/813bcc85fe03c68ad2234c027000f34d/href">https://medium.com/media/813bcc85fe03c68ad2234c027000f34d/href</a></iframe><h4><strong>Create a simple CNN model and log the model summary</strong></h4><p>Next, we’ll create a baseline 3-layer CNN model to classify the Hiragana characters (this will be mostly based on the proposed network on the official K-MNIST <a href="https://github.com/rois-codh/kmnist">repo</a>). This will consist of two <strong>CONV-POOL-DROPOUT </strong>combinations and a fully-connected layer to reduce the output to 10-dimensions, the logits representing each class. As usual, we will calculate the loss using the <strong>Cross Entropy </strong>function and we will set a standard optimizer. In order to add the graph embedding to <strong>TensorBoard</strong>, we need to grab a batch of features and labels so that the input shapes can be saved as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25eb3da4d9a59e02aa2b01d88e7a5c4c/href">https://medium.com/media/25eb3da4d9a59e02aa2b01d88e7a5c4c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FVJQ6rxn%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FVJQ6rxn&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="700" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bd5175037e8824c4a8686fe597d4cf7/href">https://medium.com/media/2bd5175037e8824c4a8686fe597d4cf7/href</a></iframe><p>This helps us interactively trace our model structure, starting from the input shape and going all the way down to the predictions. Each arrow also describes the shape that comes out of each unit which is quite useful for identifying shape mismatches in our model. This is an easy example, but for larger, more deeper architectures the graphs save a lot of debugging time.</p><h4>Train the predictor</h4><p>Before we start training, we should make sure we are training on our GPU device (if available). This is done by setting the active PyTorch device:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9437fbd528724e558eb61b67679a1f3c/href">https://medium.com/media/9437fbd528724e558eb61b67679a1f3c/href</a></iframe><p>In order to make the code more readable and reproducible, let’s build a <strong>KMNISTPredictor</strong> class containing some input parameters and helper-functions. We’ll set the target number of epochs, batch size, loss function and the <strong>TensorBoard </strong>writer object. The <strong>loss_batch </strong>function will allow us to calculate the <strong>CrossEntropy</strong> loss, backprop and update the weights for a single batch. The <strong>get_correct_examples function </strong>is a simple one-liner for getting the number of correct samples in a single batch, which will help us compute the accuracy<strong>. </strong>In addition<strong>, </strong>we’ll also need to compute the probabilities for each class using the Softmax function, so we can just extract both the predicted classes and probabilities in a single step using<strong> get_probs</strong>. <em>Note: to(dev) ensures we send the batches to the correct device, otherwise we’ll get memory allocation errors.</em><strong><em> </em></strong>Finally, our <strong>fit()</strong> function will consist of two stages:</p><ul><li><strong>Training mode:</strong> iterate through each batch and sum the batch loss, correct and total examples in the epoch. This will continuously update the model weights. After that, just print them and log the <strong>train loss and accuracy</strong> as a <strong>TensorBoard</strong> scalar.</li><li><strong>Evaluation mode:</strong> iterate through each validation batch and sum the loss, correct and total examples in the epoch (do not specify an optimizer, the weights for this step should be frozen). Then similarly, log the <strong>validation loss and accuracy</strong> as a <strong>TensorBoard</strong> scalar.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc2d39fe6603f1bd53005f912674621c/href">https://medium.com/media/dc2d39fe6603f1bd53005f912674621c/href</a></iframe><p>We’ll also add a <strong>save() and load()</strong> method in order to preserve our model state for future uses. Now we can just train and save our model by running three lines of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45658af35bc0e0a788962fe85c120d08/href">https://medium.com/media/45658af35bc0e0a788962fe85c120d08/href</a></iframe><p>Now, we can automatically keep track of the model performance without having to do any kind of custom plots. Our tracked metrics will be logged on the <strong>Scalars </strong>tab where we can observe the loss/accuracy at each time step. This allows us to see potential problems with the current config (e.g. at which point our model starts to overfit).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FjCqQmvN%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FjCqQmvN&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="700" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bf4fb34f7bb44275946ece0e57e3515/href">https://medium.com/media/5bf4fb34f7bb44275946ece0e57e3515/href</a></iframe><p>In this example, we can see that our model converges quite nicely, as we reach <strong>95% validation accuracy </strong>and our <strong>validation loss curve</strong> smoothens out. However, we can still do further analysis in order to ensure that our model is stable.</p><h4><strong>Precision-Recall Curves</strong></h4><p>In order to visualize the per-class performance for each Hiragana character, we can easily use <strong>TensorBoard’s</strong> <strong>precision-recall</strong> curves module. First we load the validation data and extract the predicted classes and probabilities for each batch. Then, we stack them together in a list and log the outputs to TensorBoard. Iterating through each class, we need to pass a <strong>boolean array</strong>, specifying which outputs correspond to the respective class and the set of probabilities (also an increasing global step, so that we don’t overwrite any of the classes).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3da6bac774744093292d108a921a2724/href">https://medium.com/media/3da6bac774744093292d108a921a2724/href</a></iframe><p>In the <strong>prcurves </strong>tab, we can observe the precision-recall tradeoff for each Hiragana character. You will see that all the slopes are heavily shifted to the right as the model achieves good performance on all classes. If we highlight the upper-right region though we can zoom in and see the actual ratio of <strong>True Positives/Negatives</strong> and <strong>False Positives/Negatives</strong> for each class.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FXGYW8uP%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FXGYW8uP&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="700" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3498bcad73715717d7328d7eb1d4aef/href">https://medium.com/media/a3498bcad73715717d7328d7eb1d4aef/href</a></iframe><h4>Plot classification errors</h4><p>Similarly to the image grid we displayed before, we can also plot a custom error grid, in order to observe which characters have been <strong>misclassified</strong>. We just need to load the validation data again, get the predicted classes and append them to a list, saving the <strong>true/predicted</strong> classes individually (only when they are different), as well as the actual image. Then we can take the first <strong>25</strong> misclassified examples and create a grid, same as before. While, we’re at it, we can also add some text data to log to <strong>TensorBoard</strong>, like the <strong>predicted vs actual output</strong> of each example. We’ll add the image index, to correlate this information to the displayed grid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58778a14821e222cd6413cf0dec08054/href">https://medium.com/media/58778a14821e222cd6413cf0dec08054/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FfcSw13d%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FfcSw13d&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="700" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3dcb2d3bea5eb683a065f06e504e5fe/href">https://medium.com/media/a3dcb2d3bea5eb683a065f06e504e5fe/href</a></iframe><p>We will see our error grid at the <strong>Images</strong> tab, and our logged classes for each example on the <strong>Text</strong> tab.</p><h4>Hyperparameter tuning</h4><p>We can also easily leverage TensorBoard for tuning the hyperparameters of our <strong>K-MNIST</strong> predictor using <strong>hparams</strong>. First we need to modify our training class to support this by including a few more lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edbb256cbe24d249a940e6fbfc0aefd5/href">https://medium.com/media/edbb256cbe24d249a940e6fbfc0aefd5/href</a></iframe><p>We’ll first add the <strong>learning rate, optimizer name, batch size</strong> (targets for tuning), as well as the <strong>TensorBoard</strong> writer object. Then, at the end of our <strong>fit()</strong> function, we’ll simply add these parameters for monitoring:</p><ul><li>first argument: dictionary of hyperparameters (name:value)</li><li>second argument: dictionary of performance metrics for monitoring (name:value)</li></ul><p>In this case, we’ll log the epoch <strong>validation accuracy/loss</strong>. This will generate a performance table highlighting the change in these values for each combination of hyperparameters. Now, let’s define a search grid and an overall <strong>optimize()</strong> function to decorate our training pipeline. This will iterate over each <strong>learning rate/batch size/optimizer</strong> combination and generate a total of <strong>27</strong> model combinations (over a <strong>3x3</strong> grid). This may take some time to compute (in my case it took about 30 mins) so feel free to reduce the number of parameters. <em>Note: Some of the model combinations will have very poor performance as the choice of batch size and learning rate leads to an unstable configuration. For larger </em><strong><em>learning rates</em></strong><em>, the model is more likely to be initialized at a </em><strong><em>local minima</em></strong><em>, unable to get traction from the training data as the step size is too high. This is one example where tuning your </em><strong><em>learning rate/batch size</em></strong><em> is essential</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5def06059d74fe20e34f224b496776ff/href">https://medium.com/media/5def06059d74fe20e34f224b496776ff/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FjFe1uWF%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FjFe1uWF&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="700" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74bd58f493299e3e6864b414c83bb16/href">https://medium.com/media/d74bd58f493299e3e6864b414c83bb16/href</a></iframe><p>In the <strong>Table</strong> view, we can observe the performance metrics for each hyperparameter configuration. In our case, the best achieved performance was the one we initially had with (Adam, Batch Size: 32, Learning Rate: 0.001), reaching about <strong>95% validation accuracy</strong>. We can also better visualize this in the <strong>Parallel Coordinates</strong> view where we can change the scale of the metrics and track the performance for each model in our hyperparameter grid.</p><h4>Feature inspection / Dimensionality reduction</h4><p>Another really cool feature that <strong>TensorBoard</strong> supports is <strong>feature projection</strong> in 2D/3D space. This allows you to apply clustering methods such as PCA or T-SNE, in order to visualize the <strong>similarities</strong> between individual groups and <strong>identify patterns</strong> within certain classes of features. And the best part is, it is all interactive so you can observe it in real time.</p><p>Let’s see a quick example. We will pick out 16 random examples per batch from the validation data (images and labels), stack them together in one dimension and create a TensorBoard embedding to visualize this set of examples. The image will be squeezed in two dimensions (the batch dimension and the width*height*channels). This will build the feature vector that computes the similarities. For the visualization, the original PyTorch image tensor will be passed to <strong>label_img </strong>and the <strong>metadata</strong> will be the true class of the Hiragana character<strong>.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bde848b068e5ca65441964ee28a54c18/href">https://medium.com/media/bde848b068e5ca65441964ee28a54c18/href</a></iframe><p>The <strong>Projector</strong> tab will initially display the PCA of our random batches. This is a <strong>dimensionality reduction</strong> method which squeezes our input features into just 3 observable dimensions. You can then color the plot by class label, so you can distinguish between each character class. You can also run other simulations using methods such as <strong>T-SNE and UMAP</strong>. Feel free to experiment here by trying different methods, parameters and sampling strategies to see how the distributions change.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FQCZM3Fs%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FQCZM3Fs&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="700" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c7fabeac4d33fe16537fae414b29631/href">https://medium.com/media/8c7fabeac4d33fe16537fae414b29631/href</a></iframe><p><em>Note: if the projector tab does not appear, try rerunning TensorBoard from the command line and refresh the browser.</em></p><p>After finishing your work with TensorBoard, you should also always close your writer with <strong>writer.close() </strong>to release it from memory<strong>.</strong></p><h4>Final thoughts</h4><p><strong>TensorBoard</strong> is generally a great profiling tool to help debug your deep learning pipeline, both on the data and model-level. I can definitely say it saves a lot of time from having to create custom plots and track performance metrics by yourself. Thus, it’s a great tool to have at your disposal as you can generate and test more experiments/model configurations and immediately track what works and what doesn’t in your pipeline, as well as what needs to be fixed.</p><p>I hope you enjoyed this tutorial :). It’s been a while since I last wrote one, but I’m keen on writing more of these in the future, so please let me know if you have any suggestions/issues with the code or the information mentioned in the blog.</p><p>The repository (which is just a Jupyter Notebook essentially) is available on <a href="https://github.com/JadeBlue96/TensorBoard-Tutorial">GitHub</a> to clone locally.</p><h4><strong>References</strong></h4><ol><li><a href="https://www.tensorflow.org/tensorboard/image_summaries"><strong>Displaying Image Summaries in TensorBoard (Tensorflow)</strong></a></li><li><a href="https://becominghuman.ai/logging-in-tensorboard-with-pytorch-or-any-other-library-c549163dee9e"><strong>Logging with TensorBoard</strong></a></li><li><a href="https://towardsdatascience.com/a-complete-guide-to-using-tensorboard-with-pytorch-53cb2301e8c3"><strong>Another great TensorBoard Overview (PyTorch)</strong></a></li><li><a href="https://pytorch.org/tutorials/intermediate/tensorboard_tutorial.html"><strong>Official Tensorboard Tutorial with PyTorch</strong></a></li><li><a href="https://github.com/rois-codh/kmnist"><strong>The K-MNIST dataset</strong></a></li><li><a href="https://pytorch.org/vision/0.8/datasets.html"><strong>Torchvision dataset documentation (useful for creating DataLoaders)</strong></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27d3f8795e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-debug-your-deep-learning-pipeline-with-tensorboard-d27d3f8795e">How to debug your Deep Learning pipeline with TensorBoard</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DCGANs — Generating Dog Images with Tensorflow and Keras]]></title>
            <link>https://medium.com/data-science/dcgans-generating-dog-images-with-tensorflow-and-keras-fb51a1071432?source=rss-aff91451f333------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb51a1071432</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[dogs]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Konstantin Georgiev]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 17:06:55 GMT</pubDate>
            <atom:updated>2020-01-10T09:22:26.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>DCGANs — Generating Dog Images with Tensorflow and Keras</h3><h3>Based on Kaggle’s Generative Dogs competition (2019)</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTholYWKBIqQkfYf9Yr%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdogs-dcgans-generative-modelling-TholYWKBIqQkfYf9Yr&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FTholYWKBIqQkfYf9Yr%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b41be2466ff6be1353e21f1c9424d95/href">https://medium.com/media/9b41be2466ff6be1353e21f1c9424d95/href</a></iframe><p>This post is a tutorial on the basic ideas behind the effectiveness of <strong>DCGANs</strong>, as well as some methods/hacks to improve their performance. These methods are all based on my experience during <strong>Kaggle’s </strong><a href="https://www.kaggle.com/c/generative-dog-images"><strong>Generative Dogs Competition</strong></a><strong>. The tutorial is also available, either in notebook format on my original </strong><a href="https://www.kaggle.com/jadeblue/dcgans-and-techniques-to-optimize-them"><strong>kernel</strong></a><strong>, or on </strong><a href="https://github.com/JadeBlue96/DCGAN-Dog-Generator"><strong>GitHub</strong></a><strong>.</strong></p><p>To run this example locally or using <strong>Colab</strong>, you will need a <strong>Kaggle account</strong>, in order to retrieve its API key and use the provided datasets. Full tutorial is available <a href="https://medium.com/@yvettewu.dw/tutorial-kaggle-api-google-colaboratory-1a054a382de0"><strong>here</strong></a>.</p><h3>Generative Adversarial Networks (GANs)</h3><p>Unlike most popular neural network architectures, <strong>GANs</strong> are trained to solve two problems simultaneously — <strong>discrimination</strong> (effectively separating real from fake images) and <strong>“realistic” fake data generation</strong> (effectively generating samples considered as real). As we can see these tasks are complete polar opposites but what would happen if we separated them into different models?</p><p>Well, the general names for these models are <strong>Generator (G)</strong> and <strong>Discriminator (D)</strong> and are considered the building blocks behind the theory of <strong>GANs</strong>.</p><p>The <strong>Generator</strong> network takes as input a simple random noise N-dimensional vector and transforms it according to a learned target distribution. Its output is also N-dimensional. The <strong>Discriminator</strong> on the other hand models a probability distribution function (like a classifier) and outputs a probability that the input image is real or fake <strong>[0, 1]</strong>. With this in mind, we can define the two main goals of the generation task:</p><p><strong>1. Train G to maximise D’s final classification error.</strong> (So that the generated images are perceived as real).</p><p><strong>2. Train D to minimise the final classification error.</strong> (So that real data is correctly distinguished from fake data).</p><p>To achieve this, during <strong>backpropagation</strong>, <strong>G</strong>’s weights will be updated using <strong>Gradient Ascent</strong> to maximise the error, while <strong>D</strong> will use <strong>Gradient Descent</strong> to minimise it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*efj9Bgi86fdiyfDq.png" /><figcaption>GAN inputs and outputs — (note that the two networks don’t use the true distribution of images directly during training but instead use each other’s outputs to estimate their performance)</figcaption></figure><p>So how do we define a <strong>loss function</strong> that estimates the cumulative performance of the two networks? Well, we can use the <strong>Absolute Error</strong> to estimate <strong>D</strong>’s error and then we can reuse the same function for <strong>G</strong> but maximised:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*Ip0v_LDojrOQTX3ikMojNg.png" /><figcaption>Mean Absolute Error — the distance between the real and fake distributions of images</figcaption></figure><p>In this case, <strong><em>p_t</em></strong> represents the true distribution of images, while <strong><em>p_g</em></strong> is the distribution created from <strong>G</strong>.</p><p>We can observe that this theory is based on some key concepts of <strong>Reinforcement Learning</strong>. It can thought of as a two-player minimax game, where the two players are competing against each other and thus progressively improving in their respective tasks.</p><p>We saw the basic idea behind the theory of <strong>GANs</strong>. Now let’s take one step further and learn how <strong>DCGANs</strong> work by applying ideas and methods from <strong>Convolutional Neural Networks</strong>.</p><h3>Deep Convolutional Generative Adversarial Networks (DCGANs)</h3><p><strong>DCGANs</strong> utilize some of the basic principles of <strong>CNNs</strong> and have thus become one of the most widely used architectures in practice, due to their fast convergence and also due to the fact that they can be very easily adapted into more complex variants (using labels as conditions, applying residual blocks and so on). Here are some of the more important problems that <strong>DCGANs</strong> solve:</p><ul><li><strong>D is created so that it basically solves a supervised image classification task.</strong> (for this case dog or no dog)</li><li><strong>The filters learned by the GAN can be utilized to draw specific objects in the generated image.</strong></li><li><strong>G contains vectorized properties that can learn very complex semantic representations of objects.</strong></li></ul><p>Here are some of the core guidelines to consider when creating a stable <strong>DCGAN</strong>, as opposed to a standard <strong>CNN</strong>(taken from the official <a href="https://arxiv.org/pdf/1511.06434.pdf">paper</a>):</p><ul><li><strong>Replace Pooling functions with Strided convolutions.</strong> (this allows <strong>D</strong> to learn its own spatial downsampling and <strong>G</strong> its respective upsampling without adding any bias to the model)</li><li><strong>Use BatchNorm</strong> (it stabilizes learning by normalizing the input to each unit to have zero mean and unit variance, this also helps to create more robust deep models without having the gradients diverging)</li><li><strong>Avoid using Fully-Connected hidden layers (not output).</strong> (example for this is global average pooling which seems to hurt convergence speed)</li><li><strong>For G — use ReLU activations and Tanh for the output.</strong> (tanh is generally the more preffered activation when you have an image as an output as it has a range of [-1, 1])</li><li><strong>For D — use LeakyReLU activations (and a sigmoid function for the output probabilites).</strong> (this is tested empirically and seems to work well for modelling to a higher resolution)</li></ul><p>Here is the most standard structure of a <strong>DCGAN generator</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*QsYQLn7wfIIeZ49XU7SLuw.png" /><figcaption>DCGAN Generator structure</figcaption></figure><p>As we can observe, its initial input is simply a <strong>(1, 100)</strong> noise vector, which passes through <strong>4 Convolutional</strong> layers with upsampling and a stride of <strong>2</strong> to produce a result RGB image of size (64, 64, 3). To achieve this, the input vector is projected onto a 1024-dimensional output to match the input of the first <strong>Conv</strong> layer, which we will see more later on.</p><p>What would a standard discriminator look like? Well, about what you would expect, let’s take a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*bjMzwBibh-KAb_06QV32bA.png" /><figcaption>DCGAN Discriminator structure</figcaption></figure><p>This time around we have an input image of <strong>(64, 64, 3)</strong>, same as <strong>G</strong>’s output. We pass it to <strong>4 standard downsampling Conv layers</strong>, again with a stride of <strong>2</strong>. In the final output layer, the image gets flattened to a vector, which is usually fed to a sigmoid function, which then outputs <strong>D</strong>’s prediction for that image <strong>(a single value representing the probability in the range [0,1] — dog = 1 or no dog = 0)</strong>.</p><p>Well, now you saw the basic idea behind <strong>GANs</strong> and <strong>DCGANs</strong>, so now we can proceed to generate some dogs using <strong>Tensorflow and Keras </strong>:).</p><h3>Image preprocessing and EDA (Exploratory Data Analysis)</h3><p>Before we proceed with creating the <strong>GAN</strong> model let’s first do a quick exploration of the <strong>Stanford Dogs</strong> dataset, which we’ll be using. Because we also have the annotations for each image, we can use them to map each dog image to its respective breed. To do that, we can first make a dictionary that maps the breed code in the file name to the actual breed name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f685f2226551d5414a5b4bb7dd8ac668/href">https://medium.com/media/f685f2226551d5414a5b4bb7dd8ac668/href</a></iframe><p>Next, I’m going to use <strong>OpenCV</strong> for a quick function to read and transform the images to <strong>RGB</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f25b0efda6d8fb70d1df3a921a0e359/href">https://medium.com/media/3f25b0efda6d8fb70d1df3a921a0e359/href</a></iframe><p>If we look at the dataset, we can see that each annotation folder contains a list of <strong>xml</strong> files. These files are associated with a specific image and contain very useful information, mainly the bounding boxes around each dog in the image. There are also images with more than one dog in them and this allows us to accurately crop them and make a dataset that contains <strong>single dogs only</strong> images.</p><p>Here we can utilize the <strong>xml</strong> library to create a tree and find the relevant elements for that annotation. For each object we can extract the bounding box coordinates, crop the images and normalize the crop by <strong>shrinking</strong> or <strong>expanding</strong> it depending on the result <strong>image width</strong>. Finally, we’ll save the images in a numpy array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58b968c3f3e29e7ceaf462fb9b2c13ba/href">https://medium.com/media/58b968c3f3e29e7ceaf462fb9b2c13ba/href</a></iframe><pre>for o in objects:                           <br>   bndbox = o.find(&#39;bndbox&#39;)                            <br>   xmin = int(bndbox.find(&#39;xmin&#39;).text)                           <br>   ymin = int(bndbox.find(&#39;ymin&#39;).text)                           <br>   xmax = int(bndbox.find(&#39;xmax&#39;).text)                           <br>   ymax = int(bndbox.find(&#39;ymax&#39;).text)                                 .. Add some margins and adjust the width ..                             # Crop the image                           <br>   img_cropped = img[ymin:ymin+w, xmin:xmin+w, :]      # [h,w,c]                           .. Interpolation step ..                           <br># Resize the image                           <br>   img_cropped = cv2.resize(img_cropped, (image_width, image_height), interpolation=interpolation)<br># Save the images and labels<br>dog_images_np[curIdx,:,:,:] = np.asarray(img_cropped)<br>dog_breed_name = dog_breed_dict[dog_ann.split(&#39;_&#39;)[0]]<br>breeds.append(dog_breed_name)<br>curIdx += 1<br>                <br>return dog_images_np, breeds</pre><p><em>The features take about 2–3 mins to load.</em></p><p>By trial, we can figure out that the result images with single dogs only are <strong>22125</strong> and thus we can specify the exact size of our numpy array. There are <strong>120</strong> different dog breeds.</p><p>Now that we have the features and labels, we can plot them in a square grid to see what the crops look like and to make sure that they are labeled correctly.</p><pre>def plot_features(features, labels, image_width=image_width, image_height=image_height, image_channels=image_channels,<br>examples=25, disp_labels=True): <br>  <br>    if not math.sqrt(examples).is_integer():<br>        print(&#39;Please select a valid number of examples.&#39;)<br>        return<br>    imgs = []<br>    classes = []<br>    for i in range(examples):<br>        rnd_idx = np.random.randint(0, len(labels))<br>        imgs.append(features[rnd_idx, :, :, :])<br>        classes.append(labels[rnd_idx])</pre><pre>    fig, axes = plt.subplots(round(math.sqrt(examples)), round(math.sqrt(examples)),figsize=(15,15),<br>    subplot_kw = {&#39;xticks&#39;:[], &#39;yticks&#39;:[]},<br>    gridspec_kw = dict(hspace=0.3, wspace=0.01))<br>    <br>    for i, ax in enumerate(axes.flat):<br>        if disp_labels == True:<br>            ax.title.set_text(classes[i])<br>        ax.imshow(imgs[i])</pre><p>Note that we need to normalize the pixel values to make sure that the dogs are plotted correctly.</p><pre>plot_features(dog_images_np / 255., breeds, examples=25, disp_labels=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*9LwQfdpKPB_OvuQq92YMlg.png" /><figcaption>Visualizing the image features</figcaption></figure><h3>The model hyperparameters list</h3><p>Here we have a whole list of hyperparameters that you can tune and play around with to try and improve the model. I’ve mostly gathered these values from research papers and experimented a bit with tweaking them and this is what I ended up with. Here’s a list of things you could try out:</p><ul><li><strong>Sample size</strong> — the number of features</li><li><strong>Batch size</strong> — 64 or 32 could improve performance, but are computationally heavy and you can only run the model for a small amount of epochs</li><li><strong>Weight Init Std and Mean</strong> — these values are come from research papers and seem to stabilize model training</li><li><strong>Leaky ReLU slope</strong> — the threshold for <strong>D</strong>’s activations, also seems robust</li><li><strong>Downsize factor and Scale factor</strong> — set up so that <strong>G</strong>’s noise vector can be reshaped to (4, 4, 512), other combinations might also work</li><li><strong>Dropout</strong> — amount of dropout layers, their placement and their rate could improve performance.</li><li><strong>Learning rate and Learning rate decay</strong> — very important to model convergence, hard to tune precisely, <strong>G</strong> and <strong>D</strong> can have different learning rates.</li><li><strong>Noise vector shape</strong> — usually 128 or 100 seems to be sufficient</li></ul><h3>Creating the image dataset</h3><p>Now let’s use our numpy array of features to construct a <strong>Tensorflow</strong> dataset object. First, we can convert the data types to <strong>float32</strong>, which always helps to preserve some memory.</p><pre>dog_features_tf = tf.cast(dog_images_np, &#39;float32&#39;)</pre><p>We could also apply <strong>Data Augmentation</strong> to our dataset. This includes random <strong>horizontal flips</strong>, zooming and cropping the image in random regions. Out of these, I found only the first method to be somewhat useful for adding some more variance to the dataset, as the other methods introduce a lot of noise.</p><p>So in this case, there will be a <strong>50%</strong> chance that an image in our dataset will be flipped from left to right.</p><pre>def flip(x: tf.Tensor) -&gt; (tf.Tensor):<br>    x = tf.image.random_flip_left_right(x)<br>    return x</pre><p>Now we can use <strong>Tensorflow</strong> to create the dataset by shuffling it, applying some augmentation, and finally separating it into batches of the specified <strong>Batch size</strong>.</p><pre>dog_features_data = tf.data.Dataset.from_tensor_slices(dog_features_tf).shuffle(sample_size).map(flip).batch(batch_size, drop_remainder=True)</pre><h3>Normalization techniques</h3><p>Before we actually make the <strong>Generator</strong>, let’s see a few normalizations that can gradually speed up a <strong>DCGAN</strong>’s convergence.</p><h3>Weight Initialization</h3><p>One of these methods is <strong>Weight initialization</strong>. It turns out that it’s pretty important for training stable <strong>GANs</strong>. Firstly, the model weights need to be <strong>zero-centered</strong> with a slight increase of <strong>std</strong>(0.02). This stabilizes both <strong>D</strong> and <strong>G</strong> during training and prevents the model gradients from vanishing or exploding. This is a key step in every case, where we have to use random variables in our model (the random noise vector).</p><p>Here is an example of how <strong>Weight initialization</strong> can seriously affect the learning process of a Neural Network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaTir4OPRGRMpWCCwv6eXQ.png" /><figcaption>The impact of weight initialization on model training</figcaption></figure><p>We can also apply a <strong>Truncated Normal</strong> distribution using <strong>Keras</strong>, which will discard <strong>values more than 2 standard deviations from the mean</strong>. This could perhaps eliminate some outlier points during training.</p><pre>weight_initializer = tf.keras.initializers.TruncatedNormal(stddev=weight_init_std, mean=weight_init_mean, seed=42)</pre><h3>Spectral Normalization</h3><p><strong>Spectral Normalization</strong> is a new type of weight initialization, designed specifically for <strong>GANs</strong>, which seems to further stabilize model training (you can read more from this <a href="https://arxiv.org/pdf/1802.05957.pdf">paper</a>). For a more detailed explanation on <strong>Spectral Normalization</strong> and why it works it also worth to check out this <a href="https://christiancosgrove.com/blog/2018/01/04/spectral-normalization-explained.html">post</a>, it has very intuitive examples.</p><p><strong>Spectral Normalization</strong> of a single weight in our network can be defined as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*szrUCXyXqK5uIk1xUxKvfQ.png" /><figcaption>Applying Spectral Normalization on a single weight</figcaption></figure><p>Here <em>u</em> and <em>v </em>are simple random vectors of the same size. They are utilized to perform what’s called a <strong>power iteration</strong> operation on the specific weight, for each learning step and it proves to be a lot more computationally efficient than simply penalizing the gradients.</p><p>Afterwards, in the backpropagation step, we use <em>WSN(W)</em> to update the weights instead of <em>W</em>.</p><p>For this project, I will reuse some custom <strong>Keras</strong> layers implemented by <strong>IShengFang</strong> (<a href="https://github.com/IShengFang/SpectralNormalizationKeras">official code</a>), to apply <strong>Spectral Normalization</strong> on top of <strong>Conv</strong> and <strong>Dense</strong> layers.</p><p>Here is also a good example on the effect of <strong>Spectral Normalization</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*rd7XVN8zTgZB3gGgqFkC6w.png" /><figcaption>DCGAN training with SN</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*h80WCznlsGXifDDxrbUAow.png" /><figcaption>DCGAN training with standard layers</figcaption></figure><p>Let’s also define some template layers in <strong>Keras</strong>, so that we can create <strong>G</strong> and <strong>D</strong> more easily later on. The standard pattern for the layers will be:</p><p><strong>TP_Conv_Block = [(Conv(SN)2DTranspose (upsample)) -&gt; (BatchNorm) -&gt; (ReLU)]</strong></p><p><strong>Conv_Block = [(Conv(SN)2D (downsample)) -&gt; (BatchNorm) -&gt; (LeakyReLU)]</strong></p><p>For this example, I will be using standard <strong>Conv2DTranspose blocks in G and Spectral Normalized Conv2D layers in D.</strong></p><pre>def transposed_conv(model, out_channels, ksize, stride_size, ptype=&#39;same&#39;):<br>    model.add(Conv2DTranspose(out_channels, (ksize, ksize),<br>                              strides=(stride_size, stride_size), padding=ptype, <br>                              kernel_initializer=weight_initializer, use_bias=False))<br>    model.add(BatchNormalization())<br>    model.add(ReLU())<br>    return model<br><br>def convSN(model, out_channels, ksize, stride_size):<br>    model.add(ConvSN2D(out_channels, (ksize, ksize), strides=(stride_size, stride_size), padding=&#39;same&#39;,<br>                     kernel_initializer=weight_initializer, use_bias=False))<br>    model.add(BatchNormalization())<br>    model.add(LeakyReLU(alpha=leaky_relu_slope))<br>    #model.add(Dropout(dropout_rate))<br>    return model<br></pre><h3>The Generator</h3><p>We can finally define our generator. The model structure is mostly based on the official DCGAN <a href="https://arxiv.org/pdf/1511.06434.pdf">paper</a> with a few tweaks that I found beneficial to the performance. Here is the overall structure:</p><p><strong>[Input(128, 1) -&gt; Dense(2048,) -&gt; Reshape(4, 4, 128) -&gt; TP_Conv_Block(Depth=512, K=5x5, S=1x1) -&gt; Dropout(0.5) -&gt; TP_Conv_Block(Depth=256, K=5x5, S=2x2) -&gt; Dropout(0.5) -&gt; TP_Conv_Block(Depth=128, K=5x5, S=2x2) -&gt; TP_Conv_Block(Depth=64, K=5x5, S=2x2) -&gt; TP_Conv_Block(Depth=32, K=5x5, S=2x2) -&gt; Dense(Depth=3, Tanh)]</strong></p><pre>def DogGenerator():<br>    model = Sequential()<br>    model.add(Dense(image_width // scale_factor * image_height // scale_factor * 128,<br>                    input_shape=(noise_dim,), kernel_initializer=weight_initializer))<br>    #model.add(BatchNormalization(epsilon=BN_EPSILON, momentum=BN_MOMENTUM))<br>    #model.add(LeakyReLU(alpha=leaky_relu_slope))<br>    model.add(Reshape((image_height // scale_factor, image_width // scale_factor, 128)))<br>    <br>    model = transposed_conv(model, 512, ksize=5, stride_size=1)<br>    model.add(Dropout(dropout_rate))<br>    model = transposed_conv(model, 256, ksize=5, stride_size=2)<br>    model.add(Dropout(dropout_rate))<br>    model = transposed_conv(model, 128, ksize=5, stride_size=2)<br>    model = transposed_conv(model, 64, ksize=5, stride_size=2)<br>    model = transposed_conv(model, 32, ksize=5, stride_size=2)<br>    <br>    model.add(Dense(3, activation=&#39;tanh&#39;, kernel_initializer=weight_initializer))<br><br>    return model</pre><h3>The Discriminator</h3><p>The <strong>Discriminator</strong> is relatively easier to implement, since its basically a small <strong>CNN</strong> two-class classifier. We can choose whether to apply <strong>Spectral Normalization</strong> or not and see the performance effects. For this example, I will try to apply <strong>SN</strong> only in <strong>D</strong>. Here is <strong>D</strong>’s structure:</p><p><strong>[Input(128, 128, 3) -&gt; Conv(SN)2D(Depth=64, K=5x5, S=1x1, same) -&gt; LeakyReLU -&gt; Conv_Block(Depth=64, K=5x5, S=2x2) -&gt; Conv_Block(Depth=128, K=5x5, S=2x2) -&gt; Conv_Block(Depth=256, K=5x5, S=2x2) -&gt; Flatten -&gt; Dense(16384, Sigmoid)]</strong></p><p>Also note that all <strong>Conv</strong> and <strong>Dense</strong> layers are initialized with the <strong>Truncated Normal</strong> distribution defined above. Another thing is that the <strong>bias</strong> term is removed from the <strong>Conv</strong> layers, which also stabilizes the model a little bit.</p><pre>def DogDiscriminator(spectral_normalization=True):<br>    model = Sequential()<br>    if spectral_normalization:<br>        model.add(ConvSN2D(64, (5, 5), strides=(1,1), padding=&#39;same&#39;, use_bias=False,<br>                         input_shape=[image_height, image_width, image_channels], <br>                         kernel_initializer=weight_initializer))<br>        #model.add(BatchNormalization(epsilon=BN_EPSILON, momentum=BN_MOMENTUM))<br>        model.add(LeakyReLU(alpha=leaky_relu_slope))<br>        #model.add(Dropout(dropout_rate))<br>        <br>        model = convSN(model, 64, ksize=5, stride_size=2)<br>        #model = convSN(model, 128, ksize=3, stride_size=1)<br>        model = convSN(model, 128, ksize=5, stride_size=2)<br>        #model = convSN(model, 256, ksize=3, stride_size=1)<br>        model = convSN(model, 256, ksize=5, stride_size=2)<br>        #model = convSN(model, 512, ksize=3, stride_size=1)<br>        #model.add(Dropout(dropout_rate))<br><br>        model.add(Flatten())<br>        model.add(DenseSN(1, activation=&#39;sigmoid&#39;))<br>    else:<br>        ...<br>    return model</pre><pre>dog_discriminator = DogDiscriminator(spectral_normalization=True)</pre><h3>Label smoothing</h3><p>One regularization method that can be applied during training is called <strong>Label smoothing</strong>. What this does is that it essentially prevents <strong>D</strong> from being overconfident or underconfident in its predictions. If <strong>D</strong> becomes too certain that there is a dog in a specific image, <strong>G</strong> can exploit that fact and continuously start to generate only images of that sort and in turn, cease to improve. We can combat this, by setting the class labels to be in the range <strong>[0, 0.3]</strong> for the negative classes and <strong>[0.7, 1]</strong> for the positive ones.</p><p>This will prevent the overall probabilities from getting very close to the two thresholds.</p><pre># Label smoothing -- technique from GAN hacks, instead of assigning 1/0 as class labels, we assign a random integer in range [0.7, 1.0] for positive class<br># and [0.0, 0.3] for negative class<br><br>def smooth_positive_labels(y):<br>    return y - 0.3 + (np.random.random(y.shape) * 0.5)<br><br>def smooth_negative_labels(y):<br>    return y + np.random.random(y.shape) * 0.3</pre><h3>Introducing noise to the labels</h3><p>This technique is also called <strong>Instance Noise</strong>. By adding a small amount of error to the labels (let’s say 5%), this tends to make the true and predicted distributions more spread out and thus start to overlap with each other. This in turn makes fitting a custom distribution of generated images easier in the learning process.</p><p>Here is a good example of how the two distributions look like with these techniques:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EA95dVM9vFHBTxWjrwYJCQ.png" /><figcaption>The impact of Insance Noise and Label smoothing on the real and fake distributions of images</figcaption></figure><p>Here is how we can implement <strong>Instance Noise</strong>:</p><pre># randomly flip some labels<br>def noisy_labels(y, p_flip):<br>    # determine the number of labels to flip<br>    n_select = int(p_flip * int(y.shape[0]))<br>    # choose labels to flip<br>    flip_ix = np.random.choice([i for i in range(int(y.shape[0]))], size=n_select)<br>    <br>    op_list = []<br>    # invert the labels in place<br>    #y_np[flip_ix] = 1 - y_np[flip_ix]<br>    for i in range(int(y.shape[0])):<br>        if i in flip_ix:<br>            op_list.append(tf.subtract(1, y[i]))<br>        else:<br>            op_list.append(y[i])<br>    <br>    outputs = tf.stack(op_list)<br>    return outputs</pre><h3>Optimizers</h3><p>The best proven optimization algorithm for this task is <strong>Adam</strong> with a standard learning rate of <strong>0.0002</strong> for both models and a beta of <strong>0.5</strong>.</p><pre>generator_optimizer = tf.train.AdamOptimizer(learning_rate=lr_initial_g, beta1=0.5)<br>discriminator_optimizer = tf.train.AdamOptimizer(learning_rate=lr_initial_d, beta1=0.5)</pre><h3>Defining the loss function</h3><p>Another new trend in optimizing <strong>GANs</strong> recently has been applying a <strong>Relativistic</strong> loss function as opposed to the standard one. Those functions measure the probability that the real data is more “realistic” than the generated data. One of the more popular relativistic function choices include <strong>RaLSGAN (Relativistic Average Least Squares), RaSGAN (Relativistic Average Standard) and RaHinge (Relativistic Hinge loss)</strong>.</p><p>But before all of that, let’s define the standard <strong>GAN</strong> loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*o8VrOm7QexoDjOOoi_sHpg.png" /></figure><p>As we can observe, this is basically the standard <strong>Binary Crossentropy loss</strong> used for classification tasks or the <strong>Logistic Loss</strong> between the real and generated distributions. In <strong>Tensorflow</strong>, this can be defined as follows:</p><p>In comparison, here is what an <strong>RSGAN (Relativistic Standard)</strong> loss looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*vrDKykPN7Fwny5ffWvV6Ew.png" /></figure><p>In this case the task is different, to measure the similarity between the <strong>real (r)</strong> and <strong>fake (f)</strong> data distributions. RSGAN reaches the optimal point when D(x) = 0.5 (i.e. <em>C</em>(<em>xr</em>)=<em>C</em>(<em>xf</em>)). There are many relativistic loss function variants and they all contain different methods for measuring this similarity. In this project, I’ve tried out <strong>3</strong> of the variants that seemed to have the best documented <strong>MIFID</strong> score <strong>(RaLSGAN, RaSGAN and RaHinge)</strong>. Feel free to try out different losses for yourself to see if you can improve the performance ;).</p><p>Here’s a big list of the most commonly used ones:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*R6cGS9l48aQcT9SEDvLFlA.png" /><figcaption>Standard and Relativistic GAN losses</figcaption></figure><p>Throughout many trials for this particular problem, I didn’t find any increase in performance by switching to <strong>Relativistic</strong> losses, so I decided to stick with the standard <strong>GAN</strong> loss function, as it is much simpler to estimate, though in some cases these losses can really speed up convergence in your model.</p><p>Here is what the <strong>Discriminator</strong> loss function will look like with <strong>Label Smoothing and Instance Noise</strong> applied. It’s basically the sum of two sub-losses <strong>(Fake — in terms of G’s images, Real — in terms of the actual training images)</strong>.</p><pre>def discriminator_loss(real_output, fake_output, loss_func, apply_label_smoothing=True, label_noise=True):<br>    if label_noise and apply_label_smoothing:<br>        real_output_noise = noisy_labels(tf.ones_like(real_output), 0.05)<br>        fake_output_noise = noisy_labels(tf.zeros_like(fake_output), 0.05)<br>        real_output_smooth = smooth_positive_labels(real_output_noise)<br>        fake_output_smooth = smooth_negative_labels(fake_output_noise)<br>        if loss_func == &#39;gan&#39;: <br>            real_loss = cross_entropy(tf.ones_like(real_output_smooth), real_output)<br>            fake_loss = cross_entropy(tf.zeros_like(fake_output_smooth), fake_output)</pre><pre>        else:<br>... other loss function variants</pre><pre>        loss = fake_loss + real_loss<br>        return loss</pre><p>And the <strong>Generator</strong> loss function <strong>(with Label Smoothing applied) </strong>is just a standard <strong>Logistic Loss</strong>:</p><pre>def generator_loss(real_output, fake_output, loss_func, apply_label_smoothing=True):<br>    if apply_label_smoothing:<br>        fake_output_smooth = smooth_negative_labels(tf.ones_like(fake_output))<br>        if loss_func == &#39;gan&#39;:<br>            return cross_entropy(tf.ones_like(fake_output_smooth), fake_output)<br>        else:<br>... other loss function variants</pre><pre>    return loss</pre><h3>Main training loop</h3><p>Let’s also fix the number of epochs for training and the number of images to feed to the <strong>Generator</strong> for visualizing intermediate results.</p><pre>EPOCHS = 280<br>num_examples_to_generate = 64<br>seed = tf.random.normal([num_examples_to_generate, noise_dim])</pre><p>One training step of a <strong>DCGAN</strong> consists of three standard steps:</p><ol><li><strong>Forward prop</strong> — <strong>G</strong> creates a batch of fake images; this, alongside a batch of real images is fed to <strong>D</strong>.</li><li><strong>Calculate both G and D’s loss function</strong>.</li><li><strong>Backprop</strong> — compute gradients for <strong>G</strong> and <strong>D</strong> optimize the weights.</li></ol><pre>def train_step(images, loss_type=&#39;gan&#39;):<br>    noise = tf.random.normal([batch_size, noise_dim])<br><br>    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:<br>        generated_images = dog_generator(noise, training=True)<br>        <br>        real_output = dog_discriminator(images, training=True)<br>        fake_output = dog_discriminator(generated_images, training=True)<br>        <br>        gen_loss = generator_loss(real_output, fake_output, loss_type, apply_label_smoothing=True)<br>        disc_loss = discriminator_loss(real_output, fake_output, loss_type, <br>                                       apply_label_smoothing=True, label_noise=True)<br> <br>    gradients_of_generator = gen_tape.gradient(gen_loss, dog_generator.trainable_variables)<br>    gradients_of_discriminator = disc_tape.gradient(disc_loss, dog_discriminator.trainable_variables)<br><br>    generator_optimizer.apply_gradients(zip(gradients_of_generator, dog_generator.trainable_variables))<br>    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, dog_discriminator.trainable_variables))<br>    <br>    return gen_loss, disc_loss</pre><p>Let’s also define some functions to visualize the model losses by epoch and as a whole.</p><pre>def plot_losses(G_losses, D_losses, all_gl, all_dl, epoch):<br>    plt.figure(figsize=(10,5))<br>    plt.title(&quot;Generator and Discriminator Loss - EPOCH {}&quot;.format(epoch))<br>    plt.plot(G_losses,label=&quot;G&quot;)<br>    plt.plot(D_losses,label=&quot;D&quot;)<br>    plt.xlabel(&quot;Iterations&quot;)<br>    plt.ylabel(&quot;Loss&quot;)<br>    plt.legend()<br>    ymax = plt.ylim()[1]<br>    plt.show()<br>    <br>    plt.figure(figsize=(10,5))<br>    plt.plot(np.arange(len(all_gl)),all_gl,label=&#39;G&#39;)<br>    plt.plot(np.arange(len(all_dl)),all_dl,label=&#39;D&#39;)<br>    plt.legend()<br>    #plt.ylim((0,np.min([1.1*np.max(all_gl),2*ymax])))<br>    plt.title(&#39;All Time Loss&#39;)<br>    plt.show()</pre><p>We can also use the following function to plot a grid of the generated images.</p><pre>def generate_and_save_images(model, epoch, test_input, rows, cols):<br>    # Notice `training` is set to False.<br>    # This is so all layers run in inference mode (batchnorm).<br>    predictions = model(test_input, training=False)<br>    fig = plt.figure(figsize=(14,14))<br>    for i in range(predictions.shape[0]):<br>        plt.subplot(rows, cols, i+1)<br>        plt.imshow((predictions[i, :, :, :] * 127.5 + 127.5) / 255.)<br>        plt.axis(&#39;off&#39;) <br>        <br>    plt.subplots_adjust(wspace=0, hspace=0)<br>    plt.savefig(&#39;image_at_epoch_{:04d}.png&#39;.format(epoch))<br>    plt.show()</pre><p>To generate a single test image, we can also reuse the same method.</p><pre>def generate_test_image(model, noise_dim=noise_dim):<br>    test_input = tf.random.normal([1, noise_dim])<br>    # Notice `training` is set to False.<br>    # This is so all layers run in inference mode (batchnorm).<br>    predictions = model(test_input, training=False)<br>    fig = plt.figure(figsize=(5,5))<br>    plt.imshow((predictions[0, :, :, :] * 127.5 + 127.5) / 255.)<br>    plt.axis(&#39;off&#39;) <br>    plt.show()</pre><h3>Evaluating GANs</h3><p>We still haven’t mentioned how a <strong>GAN</strong> is usually evaluated. Most research papers that use benchmarks to estimate how well a <strong>GAN</strong> performs are usually based on what’s called the <strong>Inception Score</strong>. This measures two main characteristics of the input images:</p><ul><li><strong>The variety (for example generating different types of dog breeds)</strong></li><li><strong>The distinction (or quality of the image)</strong></li></ul><p>If both things are true, the score will be high. If either or both are false, the score will be low. A higher score is better. It means your GAN can generate many different distinct images. The lowest score possible is zero. Mathematically the highest possible score is infinity, although in practice there will probably emerge a non-infinite ceiling.</p><p>The <strong>Inception Score</strong> is derived from Google’s <a href="https://towardsdatascience.com/a-simple-guide-to-the-versions-of-the-inception-network-7fc52b863202">Inception Network</a>, which is one of the state-of-the-art deep architectures for classifying images. By passing the images from our GAN through the classifier, we can measure properties of our generated images. To produce the score, we need to calculate the similarity/distance between the real and fake distributions of images. This is done using the <strong>KL(Kullback–Leibler) divergence formula</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*S6Cp770aAUtMJBK66zLgFw.png" /></figure><p>Here, <strong>P and Q</strong> are the two measured distributions. In this case, <strong>higher KL divergence</strong> means better results — the quality of the images is similar and there is a wide variety of labels present. In the opposite case, the <strong>low KL divergence</strong> can be due to either low quality or low variety of labels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbPx_RCrZv0G7nRIA_cseg.png" /><figcaption>Measuring the performance with KL divergence</figcaption></figure><h3>FID (Frechet Inception Distance)</h3><p>One shortcoming for <strong>IS</strong> is that it can misrepresent the performance if it only generates one image per class. To combat this we can use the <strong>FID (Frechet Inception Distance)</strong>. This measure defines the two previous types of images as multivariate <strong>Gaussian distributions</strong> with mean <em>μ</em> and covariance Σ (Sigma). Let’s see how this distance is calculated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*c159Dp06UeZUzAj_5JKonw.png" /></figure><p>Here, <em>x</em> and <em>g</em> represent the real and fake distribution of images, while <em>Tr </em>is the sum of diagonal elements of the results.</p><blockquote><strong><em>Lower FID values mean better image quality and diversity.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYEKvgxy1WKo6Tn4EE624g.png" /><figcaption>Example of how the diversity factor impacts the scoring on different datasets</figcaption></figure><p>Here are also a few useful notes on why <strong>FID</strong> is a good measure:</p><ul><li><strong>FID is more robust to noise than IS.</strong></li><li><strong>If the model only generates one image per class, the distance will be high. So FID is a better measurement for image diversity.</strong></li><li><strong>By computing the FID between a training dataset and a testing dataset, we should expect the FID to be zero since both are real images. (although there is usually a small amount of error)</strong></li><li><strong>FID and IS are based on feature extraction (the presence or the absence of features).</strong></li></ul><h3>MIFID (Memorization Informed Frechet Inception Distance)</h3><p>Here is Kaggle’s official evaluation workflow for the Generative Dogs competition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*EPkyoJAjlDC2QHAKGyHcyg.png" /><figcaption>There are two stages of evaluation — public and private on different datasets. The MIFID metric is calculated using the standard FID, combined with a Memorization Score.</figcaption></figure><p>As we can see, in addition to the <strong>FID</strong> metric, there is an additional <strong>Memorization Score</strong> added to the calculation. This is basically a <strong>Cosine distance</strong> formula that measures the similarity between the real (images from a private dataset) and fake images. My guess is that this has been done to make sure that the images fed to the evaluation kernel have actually been generated by a <strong>GAN</strong> and not just replicated or modified from the real dataset.</p><p>Thankfully, the <strong>MIFID</strong> evaluator has been implemented by the Kaggle team <a href="https://www.kaggle.com/wendykan/demo-mifid-metric-for-dog-image-generation-comp">(here)</a> and we don’t have to worry about it.</p><h3>Image zipping and saving functions</h3><p>I’m just going to add two more for zipping the final <strong>10K</strong> images for submission and generating temporary images to calculate the <strong>MIFID</strong> in between certain epochs during training.</p><pre>def zip_images(filename=&#39;images.zip&#39;):<br>    # SAVE TO ZIP FILE NAMED IMAGES.ZIP<br>    z = zipfile.PyZipFile(filename, mode=&#39;w&#39;)<br>    for k in range(image_sample_size):<br>        generated_image = dog_generator(tf.random.normal([1, noise_dim]), training=False)<br>        f = str(k)+&#39;.png&#39;<br>        img = np.array(generated_image)<br>        img = (img[0, :, :, :] + 1.) / 2.<br>        img = Image.fromarray((255*img).astype(&#39;uint8&#39;).reshape((image_height,image_width,image_channels)))<br>        img.save(f,&#39;PNG&#39;)<br>        z.write(f)<br>        os.remove(f)<br>        #if k % 1000==0: print(k)<br>    z.close()<br>    print(&#39;Saved final images for submission.&#39;)<br>    <br>def save_images(directory=OUT_DIR):<br>    for k in range(image_sample_size):<br>        generated_image = dog_generator(tf.random.normal([1, noise_dim]), training=False)<br>        f = str(k)+&#39;.png&#39;<br>        f = os.path.join(directory, f)<br>        img = np.array(generated_image)<br>        img = (img[0, :, :, :] + 1.) / 2.<br>        img = Image.fromarray((255*img).astype(&#39;uint8&#39;).reshape((image_height,image_width,image_channels)))<br>        img.save(f,&#39;PNG&#39;)<br>        #if k % 1000==0: print(k)<br>    print(&#39;Saved temporary images for evaluation.&#39;)</pre><p>It’s finally time to implement the final training function that wraps up the whole process. There are also a few techniques used here that I haven’t mentioned yet. Let’s see what they are.</p><h3>Learning rate decay</h3><p>This one is experimental and doesn’t always help improve performance, but I don’t think it would hurt either way. The idea here is to decrease the <strong>learning rate</strong> by a very small amount for each training step/steps, in order to stabilize the training process and speed up convergence (and escape from local minima). For this project, I am using the <a href="https://www.tensorflow.org/api_docs/python/tf/train/cosine_decay"><strong>Cosine learning rate decay</strong></a><strong> </strong>in <strong>Tensorflow</strong> to reduce the learning rate for every decay_step iterations.</p><h3>Dealing with mode collapse</h3><p>Other than <strong>Non-convergence</strong> and <strong>Vanishing and Exploding gradients</strong>, <strong>GANs</strong> sometimes suffer from another major problem called <strong>Mode Collapse</strong>. This happens when <strong>G</strong> starts to produce limited varieties of samples. Here is a good example of <strong>Mode Collapse</strong> for a <strong>GAN</strong> trained on the <strong>MNIST</strong> dataset where <strong>G</strong> continuously produces only images for a single class label:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5Vr12P6BnrwiQbEbvpUfQ.png" /><figcaption>G learns to fool D by only generating samples from a single class, which causes the model to lose diversity</figcaption></figure><p>We’ve already seen some methods that can potentially eliminate <strong>Mode Collapse</strong> like <strong>Label smoothing</strong>, <strong>Instance Noise</strong>, <strong>Weight Initialization</strong> and so on. One other method that we could apply during training is called <strong>Experience Replay</strong>.</p><p><strong>Experience Replay</strong> preserves some of the recently generated images in memory. For every replay_step iterations, we train <strong>D</strong> on those previous images to &quot;remind&quot; the network of previous generations and thus decrease the chance of <strong>overfitting</strong> to a particular instance of data batches during training. In this example, I am using a slightly different form of <strong>Experience Replay</strong> in the sense that, I am generating a new extra image for each training step to store in a list, instead of feeding it actual generated images from previous iterations, since storing data during <strong>Eager execution</strong> isn&#39;t an easy task.</p><pre>&#39;&#39;&#39;<br>        generated_image = dog_generator(tf.random.normal([1, noise_dim]), training=False)<br>        exp_replay.append(generated_image)<br>        if len(exp_replay) == replay_step:<br>            print(&#39;Executing experience replay..&#39;)<br>            replay_images = np.array([p[0] for p in exp_replay])<br>            dog_discriminator(replay_images, training=True)<br>            exp_replay = []    <br>&#39;&#39;&#39;</pre><p><em>EDIT: As Kaggle was running into memory issues after ~7–8 hours of runtime, I decided against using experience replay. Let me know if you find a workaround for this :D.</em></p><h3><strong>The training function</strong></h3><p>All in all, the training process is fairly straight-forward. There are additional steps for displaying the intermediate results like the images, losses and calculating the <strong>MIFID</strong>. At the end of the learning process, we print out the final evaluation and a larger grid of the final images.</p><pre>display_results = 40<br>calculate_mifid = 100<br>replay_step = 50<br>decay_step = 50<br><br>def train(dataset, epochs):<br>    all_gl = np.array([]); all_dl = np.array([])<br>    for epoch in tqdm(range(epochs)):<br>        <br>        G_loss = []; D_loss = []<br>        <br>        start = time.time()<br>        new_lr_d = lr_initial_d<br>        new_lr_g = lr_initial_g<br>        global_step = 0<br>        <br>        for image_batch in dataset:<br>            g_loss, d_loss = train_step(image_batch)<br>            global_step = global_step + 1<br>            G_loss.append(g_loss); D_loss.append(d_loss)<br>            all_gl = np.append(all_gl,np.array([G_loss]))<br>            all_dl = np.append(all_dl,np.array([D_loss]))<br><br>        if (epoch + 1) % display_results == 0 or epoch == 0:<br>            plot_losses(G_loss, D_loss, all_gl, all_dl, epoch + 1)<br>            generate_and_save_images(dog_generator, epoch + 1, seed, rows=8, cols=8)<br>        <br>        if (epoch + 1) % calculate_mifid == 0:            <br>            OUT_DIR.mkdir(exist_ok=True)<br>            save_images(OUT_DIR)<br>            evaluator = MiFIDEvaluator(MODEL_PATH, TRAIN_DIR)<br>            fid_value, distance, mi_fid_score = evaluator.evaluate(OUT_DIR)<br>            print(f&#39;FID: {fid_value:.5f}&#39;)<br>            print(f&#39;distance: {distance:.5f}&#39;)<br>            print(f&#39;MiFID: {mi_fid_score:.5f}&#39;)<br>            shutil.rmtree(OUT_DIR)<br>            print(&#39;Removed temporary image directory.&#39;)<br>        <br>        # Cosine learning rate decay<br>        if (epoch + 1) % decay_step == 0:<br>            new_lr_d = tf.train.cosine_decay(new_lr_d, min(global_step, lr_decay_steps), lr_decay_steps)<br>            new_lr_g = tf.train.cosine_decay(new_lr_g, min(global_step, lr_decay_steps), lr_decay_steps)<br>            generator_optimizer = tf.train.AdamOptimizer(learning_rate=new_lr_d, beta1=0.5)<br>            discriminator_optimizer = tf.train.AdamOptimizer(learning_rate=new_lr_g, beta1=0.5)          <br><br>        print(&#39;Epoch: {} computed for {} sec&#39;.format(epoch + 1, time.time() - start))<br>        print(&#39;Gen_loss mean: &#39;, np.mean(G_loss),&#39; std: &#39;, np.std(G_loss))<br>        print(&#39;Disc_loss mean: &#39;, np.mean(D_loss),&#39; std: &#39;, np.std(D_loss))<br><br>    # Generate after the final epoch and repeat the process<br>    generate_and_save_images(dog_generator, epochs, seed, rows=8, cols=8)<br>    checkpoint.save(file_prefix = checkpoint_prefix)<br>   <br>    OUT_DIR.mkdir(exist_ok=True)<br>    save_images(OUT_DIR)<br>    evaluator = MiFIDEvaluator(MODEL_PATH, TRAIN_DIR)<br>    fid_value, distance, mi_fid_score = evaluator.evaluate(OUT_DIR)<br>    print(f&#39;FID: {fid_value:.5f}&#39;)<br>    print(f&#39;distance: {distance:.5f}&#39;)<br>    print(f&#39;MiFID: {mi_fid_score:.5f}&#39;)<br>    shutil.rmtree(OUT_DIR)<br>    print(&#39;Removed temporary image directory.&#39;)<br>    <br>  <br>    print(&#39;Final epoch.&#39;)</pre><p>Here are some of the generated dog images during training:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*ByRDA7N5DSEBEAyNGtGlGQ.png" /><figcaption>Epoch 120 — MIFID ~ 90.5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*u0XOmQ8_5nSBItT7f7HI7A.png" /><figcaption>Epoch 200 — MIFID ~ 64.8</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*SkG-eUZOBIiW0U6kWDdY3A.png" /><figcaption>Epoch 280 (final) — MIFID ~ 60.99</figcaption></figure><p>As we can observe, the MIFID steadily improves for 280 epochs (~ 8 hours). The best score that I achieved using this model during the competition was <strong>55.87</strong>. The learning process does tend to be somewhat random so I think a score around the region of <strong>[50, 65]</strong> should be realistic. Feel free to train this model for longer, if you have the time, as it has potential to keep improving :).</p><p>Finally, I’ll show you how to make a fun <strong>GIF</strong> to see a nice little simulation of the <strong>DCGAN</strong>’s learning process (code from Tensorflow’s <a href="https://www.tensorflow.org/beta/tutorials/generative/dcgan">DCGAN tutorial</a>).</p><pre>anim_file = &#39;dcgan.gif&#39;<br><br>with imageio.get_writer(anim_file, mode=&#39;I&#39;) as writer:<br>    filenames = glob.glob(&#39;image*.png&#39;)<br>    filenames = sorted(filenames)<br>    last = -1<br>    for i,filename in enumerate(filenames):<br>        frame = 1*(i**2)<br>        if round(frame) &gt; round(last):<br>            last = frame<br>        else:<br>            continue<br>        image = imageio.imread(filename)<br>        writer.append_data(image)<br>    image = imageio.imread(filename)<br>    writer.append_data(image)<br><br>import IPython<br>if IPython.version_info &gt; (6,2,0,&#39;&#39;):<br>    IPython.display.Image(filename=anim_file)</pre><h3>Conclusion</h3><p>To sum up, <strong>DCGANs</strong> seem to be extremely sensitive to hyperparameter choice and a lot of problems can arise during training, including <strong>Mode Collapse</strong>. They are also very computationally intensive and it is incredibly hard to build a high-scoring model for a runtime of <strong>~9 hours</strong>. Fortunately, there is a whole bucket list of possible methods and techniques that are well-documented and can be easily applied to your model to stabilize the training process.</p><p>For me personally, it was really fun to toy around with these techniques and break a few kernels in the process :D. Feel free to leave any suggestions down in the comments (for improving the model or fixing something that I messed up).</p><p>Big thanks to <strong>Chris Deotte, Nanashi, Chad Malla and Nirjhar Roy</strong> for their Kaggle kernels and examples during the competition. I’ll leave links to them down below.</p><p>Overall, this was the first <strong>Kaggle</strong> competition that I’ve ever entered and it was an extremely fun method for learning about <strong>GANs</strong> and playing around with them. This seems to be Kaggle’s first competition involving generative modelling and let’s hope that more exciting challenges like this will come in the future ;).</p><h3>References</h3><h3>Useful Kernels and notebooks</h3><p>[1]. My previous kernel on <a href="https://www.kaggle.com/jadeblue/dog-generator-starter-eda-preprocessing">EDA and image preprocessing</a></p><p>[2]. <a href="https://www.kaggle.com/paulorzp/show-annotations-and-breeds">Xml parsing and cropping to specified bounding box</a></p><p>[3]. <a href="https://www.kaggle.com/amanooo/wgan-gp-keras">Image cropping method with interpolation</a></p><p>[4]. <a href="https://www.kaggle.com/cmalla94/dcgan-generating-dog-images-with-tensorflow">Another great Keras-based DCGAN approach by Chad Malla</a></p><p>[5]. <a href="https://www.kaggle.com/c/generative-dog-images/discussion/98595">DCGAN hacks for improving your model performance</a></p><p>[6]. <a href="https://www.tensorflow.org/beta/tutorials/generative/dcgan">Tensorflow DCGAN tutorial</a></p><p>[7]. <a href="https://www.kaggle.com/jesucristo/introducing-dcgan-dogs-images">DCGAN Dogs Images by Nanashi</a></p><p>[8]. <a href="https://www.kaggle.com/phoenix9032/gan-dogs-starter-24-jul-custom-layers">GAN dogs starter 24-Jul -Custom Layers by Nirjhar Roy</a></p><p>[9]. <a href="https://www.kaggle.com/cdeotte/supervised-generative-dog-net">Supervised Generative Dog Net by Chris Deotte</a></p><p>[10]. <a href="https://www.kaggle.com/jadeblue/dogdcgan-v6-ksize">My best submission for this competition</a></p><h3>Research papers, posts and discussions</h3><p>[1]. Ian Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, S. Ozair, Y. Bengio<strong>, </strong><a href="https://arxiv.org/pdf/1406.2661.pdf">Generative Adversarial Networks</a> (2014)</p><p>[2]. J. Rocca, <a href="https://towardsdatascience.com/understanding-generative-adversarial-networks-gans-cd6e4651a29">Understanding Generative Adversarial Networks (GANs)</a></p><p>[3]. J. Brownlee, <a href="https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/">A Gentle Introduction to Generative Adversarial Networks (GANs)</a></p><p>[4]. A. Radford, L. Metz, S. Chintala, <a href="https://arxiv.org/abs/1511.06434">Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks</a> (2015)</p><p>[5]. J. Hui, <a href="https://medium.com/@jonathan_hui/gan-dcgan-deep-convolutional-generative-adversarial-networks-df855c438f">GAN — DCGAN (Deep convolutional generative adversarial networks)</a></p><p>[6]. S. Yadav, <a href="https://towardsdatascience.com/weight-initialization-techniques-in-neural-networks-26c649eb3b78">Weight Initialization Techniques in Neural Networks</a></p><p>[7]. T. Miyato, T. Kataoka, M. Koyama, Y. Yoshida, <a href="https://arxiv.org/pdf/1802.05957.pdf">Spectral Normalization for Generative Adversarial Networks</a> (2018)</p><p>[8]. IShengFang, <a href="https://github.com/IShengFang/SpectralNormalizationKeras">Spectral Normalization implemented in Keras</a></p><p>[9]. C. Cosgrove, <a href="https://christiancosgrove.com/blog/2018/01/04/spectral-normalization-explained.html">Spectral Normalization Explained</a></p><p>[10]. J. Hui, <a href="https://towardsdatascience.com/gan-ways-to-improve-gan-performance-acf37f9f59b">GAN — Ways to improve GAN performance</a></p><p>[11]. J. Brownlee, <a href="https://machinelearningmastery.com/how-to-code-generative-adversarial-network-hacks/">How to Implement GAN Hacks in Keras to Train Stable Models</a></p><p>[12]. Y. Jiao, <a href="https://lanpartis.github.io/deep%20learning/2018/03/12/tricks-of-gans.html">Tricks of GANS</a></p><p>[13]. C. K. Sønderby, <a href="https://www.inference.vc/instance-noise-a-trick-for-stabilising-gan-training/">Instance Noise: A trick for stabilising GAN training</a></p><p>[14]. J. Hui, <a href="https://medium.com/@jonathan_hui/gan-rsgan-ragan-a-new-generation-of-cost-function-84c5374d3c6e">GAN — RSGAN &amp; RaGAN (A new generation of cost function.)</a></p><p>[15]. D. Mack, <a href="https://medium.com/octavian-ai/a-simple-explanation-of-the-inception-score-372dff6a8c7a">A simple explanation of the Inception Score</a></p><p>[16]. J. Hui, <a href="https://medium.com/@jonathan_hui/gan-how-to-measure-gan-performance-64b988c47732">GAN — How to measure GAN performance?</a></p><p>[17]. <a href="https://www.kaggle.com/c/generative-dog-images/discussion/98595#latest-582912">All you need is GAN Hacks</a></p><p>[18]. <a href="https://www.kaggle.com/c/generative-dog-images/discussion/102155#latest-599429">How to train your touchy GANs — Things that seem to work.</a></p><p>[19]. <a href="https://www.kaggle.com/c/generative-dog-images/discussion/97809#latest-591866">Explaining the metric FID</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb51a1071432" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dcgans-generating-dog-images-with-tensorflow-and-keras-fb51a1071432">DCGANs — Generating Dog Images with Tensorflow and Keras</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>