<?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 Sudeep Das on Medium]]></title>
        <description><![CDATA[Stories by Sudeep Das on Medium]]></description>
        <link>https://medium.com/@sudeepdas27?source=rss-3b6d022742a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WUqekAVAMuR-LelFJsjIPA.jpeg</url>
            <title>Stories by Sudeep Das on Medium</title>
            <link>https://medium.com/@sudeepdas27?source=rss-3b6d022742a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:30:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sudeepdas27/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[StyleGAN (Style Generative Adversarial Network)]]></title>
            <link>https://sudeepdas27.medium.com/stylegan-style-generative-adversarial-network-e1d4c84e138a?source=rss-3b6d022742a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1d4c84e138a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[stylegan2]]></category>
            <category><![CDATA[stylegan]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Sudeep Das]]></dc:creator>
            <pubDate>Sat, 17 Jul 2021 12:35:24 GMT</pubDate>
            <atom:updated>2021-07-17T12:35:24.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rYhzw0uiATPlfAmOp9B_Ag.gif" /></figure><p>This is the final part of the series “All about GANs” where we will be focusing more upon the StyleGAN. In this particular article, we will be exploring the architecture of StyleGAN in-depth.</p><p>And also, if you aren’t very familiar with the working of GAN (or) are interested to know about other variants of GANs and their in-depth working then you can refer to my previous blogs on GAN which are mentioned below.</p><p>Blog 1: <a href="https://sudeepdas27.medium.com/introduction-to-gan-generative-adversarial-networks-9f96ab80de0b"><strong>Introduction to GAN (Generative Adversarial Networks)</strong></a></p><p>Blog 2:<strong> </strong><a href="https://sudeepdas27.medium.com/all-about-gans-part-1-84547262ab38"><strong>All about GANs (Part 1)</strong></a></p><p>Blog 3:<strong> </strong><a href="https://sudeepdas27.medium.com/all-about-gans-part-2-ba104334d2cf"><strong>All about GANs (Part 2)</strong></a></p><p>Blog 4: <a href="https://medium.com/nerd-for-tech/scraping-instagram-to-artificially-create-sneaker-designs-dcgan-pytorch-c449c5ebfad0"><strong>Scraping Instagram to Artificially create Sneaker Designs (DCGAN PyTorch)</strong></a></p><p>Before understanding StyleGAN, there are other few concepts one must be aware of as.</p><h3><strong>Basic Concepts (Pre-requisites)</strong></h3><p>1. <strong>Fidelity</strong>: It represents how realistic &amp; clear the images are. And in other words, how different the real image is from the generated image as it’s important to maintain consistency.</p><p>2. <strong>Diversity</strong>: Variety of images produced from the generator. It helps in covering the entire range of the distribution. And if the generator produces only one realistic image with high fidelity and not others then it is not a well-performing GAN which is similar to mode collapse</p><h3><strong>Evaluation Metrics</strong></h3><h4><strong>A. Pixel distance</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BlybBU7IAyKVGrEovkfbQ.png" /></figure><p>It’s not much reliable as if there’s a subtle change in pixel values of an image, then the difference between pixel values would be too high. And as resolution increases, the number of pixels also increases. At a higher resolution even though the images look similar, their pixel distance may be too high.</p><h4><strong>B. Feature Distance</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*iBaM_Hc2RouPRcEuZrdbSg.png" /><figcaption><strong>Source: </strong><a href="https://bit.ly/2TggMR8"><strong>https://bit.ly/2TggMR8</strong></a></figcaption></figure><p>Instead of pixel distance, this is another way where we compare the high-level features or semantic features instead of comparing pixels at a granular level.</p><p>For feature extraction, we need to extract the features using a classifier model. We generally use transfer learning to use pre-trained weights of CNN models. In it, the last layer isn’t considered as it’s used to represent class outputs that may not be of our use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecJMxRKDqVCwX_O5qVppLg.png" /><figcaption><strong>Source: </strong><a href="https://morioh.com/p/cca080900a78"><strong>https://morioh.com/p/cca080900a78</strong></a></figcaption></figure><p>The earlier pooling layers tend to hold important features that represent the entire set and they are also called a <strong>feature layer</strong>.</p><p>The classifier for StyleGAN was Inception v3 which was trained on 14 million images called <strong>ImageNet</strong>. The features extracted from ImageNet are called ImageNet embeddings/feature space/embedding space.</p><h4><strong>C.</strong> <strong>Fréchet Inception Distance (FID)</strong></h4><p>It indicates the distance of the distribution, the smaller the value closer is the distribution between real &amp; fake distribution, or in other words, the generated image looks similar to the real image.</p><p><strong>Lower FID = closer distributions and the number of samples do affect the FID score as the noise reduces as samples increases.</strong></p><p>The FID metric is the squared Wasserstein metric between two multidimensional Gaussian distributions</p><p>i) Distribution of real images used to train of feature-wise mean &amp; covariance matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*gbvICTp8x_Tq3ZEqWvoPyQ.png" /></figure><p>ii) Distribution of images generated by the GAN of feature-wise mean &amp; covariance matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*EhTu85HiadeR55t2FeliaA.png" /></figure><p>It compares the mean and standard deviation of one of the deeper layers in a convolutional neural network named Inception v3. It’s a better alternative to the Inception Score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*XE1Qsp_IIv132n8eBq8hSA.png" /></figure><h4><strong>D.</strong> <strong>Perceptual path length</strong></h4><p><strong>Perceptual Path Length (PPL)</strong> is the difference between two images while it’s interpolating &amp; that change occurs smoothly along the perceptual path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*uzV5NFDL9I8TZ0ehoEbUaA.png" /><figcaption><strong>Source: </strong><a href="https://medium.com/analytics-vidhya/from-gan-basic-to-stylegan2-680add7abe82"><strong>https://medium.com/analytics-vidhya/from-gan-basic-to-stylegan2-680add7abe82</strong></a></figcaption></figure><p>As in the above diagram, the two images of dogs are two endpoints that have different colors and majorly share similar semantic features generated from two different latent variables. The blue line between them is the PPL.</p><p>We subdivide a latent space interpolation path into linear segments, where the total perceptual length of this segmented path is the sum of perceptual differences over each segment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vh0ol2xFn2iF1_vpDw2uSw.png" /></figure><p>z1, z2 ∼ P(z), t ∼ U(0, 1), and ‘d’ evaluates the perceptual distance between the resulting images. <strong>Slerp</strong> denotes spherical interpolation, which is the most appropriate way of interpolating in our normalized input latent space.</p><p>Their intermediate value would produce something of the mixture of features of two images by computing the average perceptual path length in W. While taking two latent variables i.e. (z1 &amp; z2), they are mixed together at a ratio ‘t+ε’. <strong>Lerp </strong>denotes linear interpolation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_A-7g2Lzh0XIspfXVlIhA.png" /></figure><p>The shorter the perceptual path length between two images, the more similar they look, and the larger the perceptual path length the more dissimilar they look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*mOdGpumWZOAcVBbgdp_Q4w.png" /><figcaption><strong>Source: </strong><a href="https://arxiv.org/pdf/1912.04958.pdf"><strong>https://arxiv.org/pdf/1912.04958.pdf</strong></a></figcaption></figure><h3><strong>StyleGAN (Style Adversarial Network)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__Wse5H9ttLeTMpTJaMYrw.png" /><figcaption><strong>Source: </strong><a href="https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431"><strong>https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431</strong></a></figcaption></figure><p>The above figure represents the entire architecture of StyleGAN that consists of various components and all those components/techniques have been broadly listed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*Ex55mL6TEWgWofzv6gcJbA.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1812.04948.pdf">https://arxiv.org/pdf/1812.04948.pdf</a></figcaption></figure><p>The researcher experimented with various techniques to gauge over changes in performance on two different datasets and their Fréchet inception distance (FID) is given. The lower the FID, the better.</p><blockquote><strong><em>A:</em></strong><em> The StyleGAN uses the Progressive Growing technique from ProGAN</em></blockquote><blockquote><strong><em>B:</em></strong><em> Bilinear sampling technique used for upsampling &amp; downsampling.</em></blockquote><blockquote><strong><em>C:</em></strong><em> Addition of 8-layer MLP (Noise Mapping network) to disentangle the features. AdaIN is then used to apply styles</em></blockquote><blockquote><strong><em>D:</em></strong><em> Input constant matrix with dimension 4×4×512 to the first layer of G</em></blockquote><blockquote><strong><em>E:</em></strong><em> Addition of Stochastic Variation</em></blockquote><blockquote><strong><em>F:</em></strong><em> Style mixing &amp; Mixing Regularization using AdaIN (coarse, medium, fine details)</em></blockquote><h3><strong>Progressive Growing &amp; Upsampling/Downsampling</strong></h3><p>StyleGAN is trying to make it so it’s easier for the generator to generate higher resolution images by gradually training it from lower resolution images to those higher resolution images.</p><p>It uses one of the techniques from ProGAN (Progressive GANs). It also lets you get more control of the features that can be added to the images. And it also helps to add features/styles to the images and hence it’s known as StyleGAN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*xvglzrUGtCcngwxtjRM3LA.gif" /><figcaption><strong>Source: </strong><a href="https://towardsdatascience.com/progan-how-nvidia-generated-images-of-unprecedented-quality-51c98ec2cbd2"><strong>https://towardsdatascience.com/progan-how-nvidia-generated-images-of-unprecedented-quality-51c98ec2cbd2</strong></a></figcaption></figure><p>Progressive growing takes place gradually where a double-sized image is produced by upsampling it using its nearest neighbor filters. After that, when 99% of upsampling is done, the rest 1% is taken to produce an 8x8 image from a 4x4 image</p><p><strong>Generator</strong></p><p>In the case of upsampling since we use the nearest neighbor filter (in the case of StyleGAN, Bilinear sampling technique is used) it consists of unlearned parameters so initially, it is used and from that final generated image, 1% is passed through convolution layer to contribute to the final image and this is because it consists of learnable parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*6VFuSPJyk9kpJ8J5QkmvLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*vZVMYyI1bIU5OPO_0D_bCQ.png" /><figcaption><strong>Source: </strong><a href="https://bit.ly/2TggMR8"><strong>https://bit.ly/2TggMR8</strong></a></figcaption></figure><p>Gradually over time, we shift our upsampling process to convolutional layers that have learned the weights, which are represented by a parameter α.</p><p><strong>Discriminator</strong></p><p>In the case of the discriminator, a similar principle takes place where instead of upsampling we downsample it by 0.5x. Similarly, learnable parameters are present to gradually learn over time where overtime for downsampling, the discriminator relies on the convolutional layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*xYk0RwqK52f8scIVZ_rUNA.png" /><figcaption><strong>Source: </strong><a href="https://bit.ly/2TggMR8"><strong>https://bit.ly/2TggMR8</strong></a></figcaption></figure><p>And this is how the block looks of progressive growing where it consists of a sample layer and two convolution layers for learning more parameters and to capture more features from the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*V5KMDjGV6FsbvytrYCjS9Q.png" /></figure><h3><strong>Noise Mapping Network</strong></h3><p>Takes ‘z’ from latent vector or noise vector of size 4×4×512 which is passed through mapping network to produce ‘w’. The mapping network consists of 8 Fully Connected neural network layers (MLP Multi-Layer Perceptron).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*73NiSKuOlWBdxJMhBtM1eg.png" /></figure><p><strong>Z-space entanglement</strong></p><p>The features from z-space are entangled in nature which means ‘z’ doesn’t map onto output features in a one-on-one manner as it’s highly entangled so changing one feature would change the feature of others. The reason for this is because there’s a p.d.f. (probability distribution function) of the real image. And it becomes hard for z to map individually to the features.</p><p>Altering one value would alter the values of other features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*McSHjPp5vjZo1_ayi8emhA.png" /><figcaption><strong>Source: </strong><a href="https://bit.ly/2TggMR8"><strong>https://bit.ly/2TggMR8</strong></a></figcaption></figure><p>The mapping network converts the latent z into an intermediate latent space w. To achieve this disentangled connection, it’s passed through the 8 MLP/Mapping Network to disentangle it which gives more control over the features. This lets you control the styles that can be added to the outcome.</p><p>And this is how ‘z’ is passed through the mapping network to turn into ‘w’. Instead of adding ‘z’ to the progressive growing layer, <strong>a fixed value is given of size 4x4x512</strong> because there wasn’t much noticeable difference on adding ‘z’ which existed in previous GAN models. A separate learned affine operation A is applied to transform w<em> </em>in each layer so it acts as the style information.</p><h3><strong>Addition of Styles using AdaIN (Adaptive instance normalization)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*VnD1Y9sEZZ1ph_1jMRJ2UA.png" /><figcaption><strong>Source: </strong><a href="https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431"><strong>https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431</strong></a></figcaption></figure><p>The ‘w’ obtained from the noise mapping layer is fed to the progressive growing layer and also as well it’s added to the AdaIN layer that exists between the convolution layers as that can be seen in the above diagram. AdaIN majorly consists of 2 concepts that makes it up which are as below:</p><blockquote>1. Instance Normalization over Batch Normalization</blockquote><blockquote>2. Adaptive Instance Normalization</blockquote><h4><strong>Instance Normalization vs Batch Norm</strong></h4><p>In the instance normalization, the convolution outputs are normalized where they are transformed in a normal distribution with a mean 0 and an std of 1. It does it by taking the mean and std of the instance instead of the entire batch.</p><p>In batch norm, it looks over the height &amp; width of the image highlighted by blue over the entire batch of images. But in the case of images, every image is different so it’s important to look over an instance (one example &amp; one channel) of the batch.</p><p>So that is represented by an instance ‘i’ over some instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*EJpetFrL5myfo4npKuYZqg.png" /></figure><h4><strong>AdaIN (Adaptive Instance Normalization)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*TN-bnfUWz2Ypm228-5llkw.png" /></figure><p>‘w’ is applied over multiple layers via the AdaIN layer, to apply adaptive styles to the images. The adaptive styles obtained from ‘w’ are sent through 2 learnable parameter networks which is y(s) <strong>(scale)</strong> &amp; y(b) <strong>(bias)</strong>. These are then added to the AdaIN layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*1EMlGPl6inQKnH5NS4TvuA.png" /></figure><p>The ‘w’ that is being added to the progressive generator block at the earlier stage defines most of the coarser features and with time its addition to the later stages defines all the finer details and it also helps us having control over most of the features on a different scale as coarser, medium &amp; finer details.</p><blockquote><strong>Note:</strong></blockquote><blockquote>It’s important to understand that most of the styles of images can be presented in terms of their mean, std, scale &amp; bias. Ex: Painting of a human or landscape may variate from artist to artist as they have their different styles but the main object tends to remain the same i.e., human/scenery, etc.</blockquote><h3><strong>Style Mixing &amp; Mixing Regularization</strong></h3><p>‘w’ that was obtained from the noise mapping network is added to all the layers in the progressive growing block which gives us more control. Here we can mix multiple values of ‘w’ value such as w1, w2, w3 … etc obtained from different ‘z’ values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*7qpfvxUAe8X3tfh10IRzaA.png" /><figcaption><strong>Source: </strong><a href="https://jonathan-hui.medium.com/gan-stylegan-stylegan2-479bdf256299"><strong>https://jonathan-hui.medium.com/gan-stylegan-stylegan2-479bdf256299</strong></a></figcaption></figure><p>‘w’ that is being added at the earlier stage defines most of the coarser features because that defines the basic structure of formation and with time its addition to the later stages defines all the finer details.</p><p>Since all the values can be controlled, we can obtain different images by adding different layers and one such of them is given below where w1 belongs to one style and w2 belongs to the other style. It also helps in producing a lot of diversity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*17kw9ulKm6iQQuN_nQnfLg.png" /><figcaption><strong>Source: </strong><a href="https://bit.ly/2TggMR8"><strong>https://bit.ly/2TggMR8</strong></a></figcaption></figure><h3><strong>Stochastic Variation</strong></h3><p>To add some degree of variation in the details of the images, noise is added at different levels to obtain different degrees of variation in the output. As you can see below, noise added in the earlier layers produces major changes in hair curls, etc whereas noise added later defines the fine layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*Sy7ZA9XQS0DbLu6tFQXZ5Q.png" /></figure><p>The noise that is added is taken from a normal distribution and it is then concatenated into ‘x’ that is later added just before the AdaIN layer. <strong>The degree to which it affects is defined by lambda λ.</strong> Since it’s being added to two different convolutional layers at every layer, it’s given as λ1 &amp; λ2. And this can help in controlling extremely minute details.</p><h3><strong>Truncation Trick</strong></h3><p>The images that are generated from a normal distribution where the generated images at the peak tend to have higher fidelity and lower diversity and the ones near the edge tend to have higher diversity but lower fidelity. It can be noticed that images on top are quite similar apart from colors and have the same background whereas, the images present near the tail end have higher diversity but they don’t look authentic and real.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*tMiGiAG6iK1yT9RBzU-JaQ.png" /><figcaption><strong>Source: </strong><a href="https://bit.ly/2TggMR8"><strong>https://bit.ly/2TggMR8</strong></a></figcaption></figure><p>Hence the images that are present in the bottom end areas are truncated as they have low probability density and they won’t be enough for the model to train &amp; learn from.</p><p>Its equation is given below where <strong>ψ</strong> is called the <strong>style scale. </strong>Generally, truncation is done at lower resolution layers while coarser styles are being defined as it doesn’t affect details in the high-resolution layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*ruHyvioP_FnwOvYSZO8nEg.png" /></figure><p>w’ = Truncated w</p><p>w = Actual w</p><p>ψ = Style scale</p><h3><strong>Issues</strong></h3><p><strong>Blob-like effects:</strong> The AdaIN used in StyleGAN causes blob-like artifacts as it’s used for style transfer as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*njXfXSgEFpbyiZS4hX4ywQ.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1912.04958.pdf">https://arxiv.org/pdf/1912.04958.pdf</a></figcaption></figure><p><strong>Phase artifacts: </strong>In the below figure the teeth do not follow the pose but stay aligned to the camera, as indicated by the blue line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*y4WXg5rZpo600RMrPQInkA.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1912.04958.pdf">https://arxiv.org/pdf/1912.04958.pdf</a></figcaption></figure><h3>AUTHOR</h3><blockquote><strong><em>Sudeep Das</em></strong><em> : </em><a href="https://www.linkedin.com/in/sudeepdas27/"><strong><em>https://www.linkedin.com/in/sudeepdas27/</em></strong></a></blockquote><h3><strong>References</strong></h3><p>[1] A Style-Based Generator Architecture for Generative Adversarial Networks; <a href="https://arxiv.org/pdf/1812.04948.pdf">https://arxiv.org/pdf/1812.04948.pdf</a></p><p>[2] From GAN basic to StyleGAN2; <a href="https://medium.com/analytics-vidhya/from-gan-basic-to-stylegan2-680add7abe82">https://medium.com/analytics-vidhya/from-gan-basic-to-stylegan2-680add7abe82</a></p><p>[3] Build Better Generative Adversarial Networks (GANs); <a href="https://www.coursera.org/learn/build-better-generative-adversarial-networks-gans">https://www.coursera.org/learn/build-better-generative-adversarial-networks-gans</a></p><p>[4] Explained: A Style-Based Generator Architecture for GANs — Generating and Tuning Realistic Artificial Faces; <a href="https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431">https://towardsdatascience.com/explained-a-style-based-generator-architecture-for-gans-generating-and-tuning-realistic-6cb2be0f431</a></p><p>[5] GAN — StyleGAN &amp; StyleGAN2; <a href="https://jonathan-hui.medium.com/gan-stylegan-stylegan2-479bdf256299">https://jonathan-hui.medium.com/gan-stylegan-stylegan2-479bdf256299</a></p><p>[6] Analyzing and Improving the Image Quality of StyleGAN; <a href="https://arxiv.org/pdf/1912.04958.pdf">https://arxiv.org/pdf/1912.04958.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1d4c84e138a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping Instagram to Artificially create Sneaker Designs (DCGAN PyTorch)]]></title>
            <link>https://sudeepdas27.medium.com/scraping-instagram-to-artificially-create-sneaker-designs-dcgan-pytorch-c449c5ebfad0?source=rss-3b6d022742a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c449c5ebfad0</guid>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[generative-art]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[dcgan]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <dc:creator><![CDATA[Sudeep Das]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 18:07:25 GMT</pubDate>
            <atom:updated>2021-07-12T01:49:17.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nIOhmBGbNrYz31pISoBlA.png" /></figure><p>In this particular blog which is the 3rd part of the series “<strong>All about GANs</strong>” where I will be discussing the architecture &amp; working of DCGAN (Deep Convolution Generated Adversarial Network) and its implementation.</p><p>Here we will be implementing DCGAN using the PyTorch framework to generate sneaker images on our own dataset that was scraped from Instagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*DAS094w3j8NuluklUbeaPg.png" /><figcaption>Generated Image from DCGAN</figcaption></figure><p>So, this article will be divided majorly into 3 parts:</p><ul><li><strong>What is DCGAN? How DCGAN works?</strong></li><li><strong>Scraping images from Instagram to create our Dataset</strong></li><li><strong>Actual Implementation of DCGAN using PyTorch</strong></li></ul><p>If in case you are familiar with the working of DCGAN, then you can directly skip to the actual implementation section.</p><p>And also, if you aren’t very familiar with the working of GAN (or) are interested to know about other variants of GANs and their in-depth working then you can refer to my previous blogs on GAN which are mentioned below.</p><p>Blog 1: <a href="https://sudeepdas27.medium.com/introduction-to-gan-generative-adversarial-networks-9f96ab80de0b"><strong>Introduction to GAN (Generative Adversarial Networks)</strong></a></p><p>Blog 2:<strong> </strong><a href="https://sudeepdas27.medium.com/all-about-gans-part-1-84547262ab38"><strong>All about GANs (Part 1)</strong></a></p><p>Blog 3:<strong> </strong><a href="https://sudeepdas27.medium.com/all-about-gans-part-2-ba104334d2cf"><strong>All about GANs (Part 2)</strong></a></p><p>I would highly recommend you to go through them before as I have explained in detail about the working of GAN. So, let’s get started!</p><h3><strong>DCGAN (Deep Convolutional Generative Adversarial Network)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aozft_1JijDhuuItH3UAlA.png" /><figcaption>DCGAN Architecture</figcaption></figure><p>DCGAN is another variant of GAN that consists of two blocks i.e. Generator &amp; Discriminator. The discriminator block can be made up of any CNN classifier architecture that uses strided convolutional layers, whereas in the case of generator block, it takes up values from a noise/latent vector and then converts it into a 64x64x3 output/image by using transpose convolution operation.</p><h4><strong>Generator</strong></h4><p>The generator consists of convolutional-transpose layers. In the generator, the input is taken from a latent vector (normal distribution of dimension 100x1) and produces an output of dimension 64x64x3 image by performing transposed convolutional operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*2Qguc3B4JfukFXFCvWb7xA.png" /></figure><p>The formula for Transpose convolution is:</p><p><strong>Output dim = stride * (input dim — 1) + filter size — 2 * padding</strong></p><p>From the diagram we can see the conversion in dimensions takes place as:</p><p>100x1 → 4x4x1024 → 8x8x512 → 16x16x256 → 32x32x128 → 64x64x3</p><p><strong>4x4x1024 → 8x8x512</strong></p><p>stride = 2, padding = 1, filter size = 4</p><p>Output dim (height): 2 * (4–1) + 4–2*1 = 8</p><p>Output dim (weight): 2 * (4–1) + 4–2*1 = 8</p><p>There are 512 filters and hence the output is: 8x8x512</p><p><strong>8x8x512 → 16x16x256</strong></p><p>stride = 2, padding = 1, filter size = 4</p><p>Output dim (height): 2 * (8–1) + 4–2*1 = 16</p><p>Output dim (weight): 2 * (8–1) + 4–2*1 = 16</p><p>There are 256 filters and hence the output is: 16x16x256</p><p>That’s how the transpose convolution operation works which is also known as and fractional-strided convolutions. It also includes batch norm layers, and ReLU activation is used.</p><h4><strong>Discriminator</strong></h4><p>The discriminator consists of strided convolutional layers. It discriminates between samples ‘x’ taken from real distribution and output from generator ‘G(x)’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*6iGAGp5fhgdciTH4L2UTSg.png" /></figure><p>Formula for Convolution operation is:</p><p><strong>Output dim = (input dim + 2 * padding — filter size)/stride +1</strong></p><p>From the diagram we can see the conversion in dimensions takes place as:</p><p>64x64x3 → 32x32x64 → 16x16x128 → 8x8x256 → 4x4x512 → 1x1</p><p><strong>64x64x3 → 32x32x64</strong></p><p>Stride = 2, padding = 1, filter size = 4</p><p>Output dim (height): (64 + 2*1–4)/2 + 1 = 32</p><p>Output dim (weight): (64 + 2*1–4)/2 + 1 = 32</p><p>There are 64 filters and hence the output is: 32x32x64</p><p><strong>32x32x64 → 16x16x128</strong></p><p>Output dim (height): (64 + 2*1–4)/2 + 1 = 32</p><p>Output dim (weight): (64 + 2*1–4)/2 + 1 = 32</p><p>There are 128 filters and hence the output is: 32x32x128</p><p>Similarly, this strided convolution operation is performed on other layers. It also includes batch normalization layers, and LeakyReLU activation is used.</p><h4><strong>Loss Functions and Optimizers</strong></h4><p>In the case of DCGAN, we tend to use the Binary Cross Entropy loss function which is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fkdsd7sNPsviMmkbxz-_rw.png" /><figcaption>Binary Cross-Entropy Loss</figcaption></figure><p>The loss is calculated and accordingly, the weights and other parameters are updated with multiple epochs till we obtain the minimum loss. In DCGAN, we tend to use the Adam Optimizer for optimization with a learning rate of 0.0002 and beta1 = 0.5.</p><p>As per the <a href="https://arxiv.org/pdf/1511.06434.pdf"><strong>paper</strong></a>, there are few other important things to keep in mind while implementing a stable DCGAN and they are:</p><ul><li>Replace any pooling layers with strided convolutions (discriminator) and fractional-strided convolutions (generator)</li><li>Use batch norm in both the generator and the discriminator</li><li>Remove fully connected hidden layers for deeper architectures</li><li>Use ReLU activation in a generator for all layers except for the output, which uses Tanh</li><li>Use LeakyReLU activation in the discriminator for all layers.</li></ul><h3><strong>Scraping Data from Instagram</strong></h3><p>For our project, we decided to generate or say artificially create images of Sneakers. And for that to happen we need to train our model over various sneaker images. This is where Instagram comes into the picture as it’s a platform where multiple talented people across the globe put their content.</p><p>I used the “<a href="https://github.com/arc298/instagram-scraper"><strong>instagram-scraper</strong></a>” to scrape off the photos that were uploaded by the users whose accounts were public. I have hyperlinked their git repo and the scrapper does an amazing job in scraping the data.</p><p>After installation execute the command in cmd as mentioned in their repository and it downloads all the media content. Below is a snapshot of my cmd while scrapping data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*W7-7cMTOHrMclDYe7kQqiw.png" /><figcaption>cmd (instagram-scraper)</figcaption></figure><p>For my project, I decided to scrape the media of these talented artists and a sneaker page as:</p><ul><li><a href="https://www.instagram.com/chenchicharo/">@chenchicharo</a></li><li><a href="https://www.instagram.com/kah__bane/">@kah__bane</a></li><li><a href="https://www.instagram.com/sneakerslabour/">@sneakerslabour</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9ulVspHn8NmzXBeawkZNg.png" /></figure><p>After downloading all the files, collate them all together in one folder and filter out relevant images that will be used for training our model.</p><h3><strong>DCGAN Implementation using PyTorch</strong></h3><p>The first step would be to install all the dependencies and then import all the images and transform them all to the same dimension that will be fed to our model by using a data loader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*h7SlM1bYM5HWBxqzo7SjHg.png" /><figcaption>Transform &amp; Dataloader</figcaption></figure><p>Then we define our generator block as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7c3ULPYxp0M5sqLnC287Jw.png" /><figcaption>Generator Block</figcaption></figure><p>Then we define our discriminator block as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*CFmdDGf8_7v4NjmN4tFSug.png" /><figcaption>Discriminator Block</figcaption></figure><p>Once we have defined our generator &amp; discriminator block, the next step would be to train them over a certain number of epochs by defining few other parameters such as optimizer, learning rate, batch size, and loss function (Binary Cross-Entropy Loss) a.k.a. Criterion.</p><p>The model was trained over 100 epochs. And I did try working on the TensorFlow framework too using TPU &amp; GPU separately which was way slower than PyTorch. It took over 10mins to execute 100 epochs in PyTorch whereas, the same operation took me over 2hrs to execute in TensorFlow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*BkwpASQUDIYQOYpn8YUNdQ.png" /><figcaption>Training Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*5pVmeU1y9ChhsY1uypyv7g.gif" /><figcaption>Images over epochs</figcaption></figure><p>The above gif shows how the model generates realistic images of sneakers that are very similar to the actual shoes from our dataset. And below is the comparison between the real &amp; fake images of sneakers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYytfAxWOOSO1yd7saM5yA.png" /><figcaption>Comparison between real &amp; fake images</figcaption></figure><h3><strong>Conclusion</strong></h3><p>DCGAN is comparatively easier to understand compared to other variants of GAN and this is what makes it really popular and also apart from that, it&#39;s effective too. It overcomes multiple barriers as compared to previous variants of GANs.</p><p>PyTorch especially makes it really easy and fun to play around with DCGAN!</p><h3>AUTHOR</h3><blockquote><strong><em>Sudeep Das</em></strong><em> : </em><a href="https://www.linkedin.com/in/sudeepdas27/"><strong><em>https://www.linkedin.com/in/sudeepdas27/</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c449c5ebfad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about GANs (Part 2)]]></title>
            <link>https://sudeepdas27.medium.com/all-about-gans-part-2-ba104334d2cf?source=rss-3b6d022742a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba104334d2cf</guid>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[bidirectional]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[cyclegan]]></category>
            <dc:creator><![CDATA[Sudeep Das]]></dc:creator>
            <pubDate>Sat, 03 Jul 2021 08:43:09 GMT</pubDate>
            <atom:updated>2021-07-03T09:00:53.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*006MyE6oaVn8BNCrt1uvSw.png" /></figure><p>Welcome to the second blog of the entire series “<strong>All about GANs</strong>”. The entire blog series is broken down into 4 parts and this is the 2nd blog. In this blog we will be discussing other variants of GANs mainly:</p><ol><li>InfoGAN (Information GAN)</li><li>BiGAN (Bidirectional GAN)</li><li>CycleGAN</li></ol><p>In the previous blogs, we introduced the concept of GAN and its working and also discussed different variants of GAN. If you are interested to understand more about the basics and working of GAN then please go through these previous blogs.</p><ul><li>Blog 1: <a href="https://sudeepdas27.medium.com/introduction-to-gan-generative-adversarial-networks-9f96ab80de0b">Introduction to GANs (Generative Adversarial Networks)</a></li><li>Blog 2: <a href="https://sudeepdas27.medium.com/all-about-gans-part-1-84547262ab38">All about GANs (Part 2)</a></li></ul><p>Before we discuss the working of the InfoGAN, it’s important to understand the concept of Information Theory that will be used to derive its loss function.</p><h3><strong>Information Theory</strong></h3><p>Information theory is that learning of an unlikely event is more informative than learning that a likely event has occurred. E.g. “The sun rose from the east”, this statement doesn’t hold any unlikely information as it happens on a regular basis and is a universal truth. An example of “Today solar eclipse will take place” is an unlikely event as this happens rarely and is uncommon. In the context of ML, it’s used to quantify the similarity between distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Lz30qNJMNtFeXP7fCneWg.png" /><figcaption><strong>Source: </strong><a href="https://staging.news.st-chris.net/pi-1-jamie-odowd/#.YN3oAegzZPY"><strong>https://staging.news.st-chris.net/pi-1-jamie-odowd/#.YN3oAegzZPY</strong></a></figcaption></figure><p>There are three properties stated under the information theory,</p><blockquote>1. Likely events should have low information content that is guaranteed to happen</blockquote><blockquote>2. Unlikely events should have higher information content</blockquote><blockquote>3. Independent events should have additive information</blockquote><p>These are the properties that need to be sufficed for an event ‘ x ’ to have <strong>self-information </strong>which is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*38-lxbg-f_kdwNvONbTdIQ.png" /></figure><p>Self-information deals only with a single outcome. We can quantify the amount of uncertainty in an entire p.d.f. (probability distribution function) using the <strong>Shannon entropy </strong>as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*U8g58NmCeLCTJFgy5plpVw.png" /><figcaption><strong>Shannon Entropy</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTOUx_lffKtqNlNQAJc3pw.png" /></figure><p>Distributions that are nearly deterministic (where the outcome is nearly certain) have low entropy &amp; distributions that are closer to uniform have high entropy.</p><h4><strong>Joint Entropy</strong></h4><p>The combined entropy of two discrete variables ‘X’ &amp; ‘Y’ is given as the entropy of their pair (X, Y) known as joint entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*RR2-50c2zG67hNw0iidJpw.png" /></figure><h4><strong>Conditional Entropy</strong></h4><p>The conditional entropy of ‘X’ given ‘Y’ is the average conditional entropy of ‘Y’ is given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*Hq5NsuNQxiFf0v1AUHmQ7A.png" /></figure><p>On solving the above equation, we obtain,</p><p><strong>H(X|Y) = H(X, Y) - H(X)</strong> (<strong>Chain Rule</strong>)</p><p><strong>H(X|Y) = 0</strong>; if value of ‘X’ is completely determined by ‘Y’</p><p><strong>H(X|Y) = 1</strong>; if X &amp; Y are independent random variables</p><h4><strong>Mutual Information</strong></h4><p>The amount of information that can be obtained from a random variable by observing another. It gives the measure of the correlation between two random variables ‘X’ &amp; ‘Y’ such that the more independent they are, the lesser is the mutual information among them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xm8hULx0SQH9LOJ4tUEt8A.png" /><figcaption>Entropy Venn Diagram</figcaption></figure><p>The mutual information is given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*NLiIf0ae_E9A8Qs7RU5cdw.png" /></figure><p><strong>I(X;Y) = -H(X,Y) + H(X) + H(Y)</strong></p><p>Using the chain rule it can be written in two ways,</p><p><strong>I(X;Y) = H(X) — H(X|Y)</strong></p><p><strong>(or)</strong></p><p><strong>I(X;Y) = H(Y) — H(Y|X)</strong></p><h3><strong>InfoGAN</strong></h3><p>InfoGAN is unsupervised learning used for information maximization of disentangled representation of the image. Here labels aren’t provided and the InfoGAN learns from the images as it learns patterns among images in an unsupervised manner and produces images by following the patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*prUiwgbEWyETe90DEE4SSQ.png" /><figcaption><strong>Source: </strong><a href="https://www.researchgate.net/figure/The-architectures-of-InfoGAN-and-SCGAN-InfoGAN-attempts-to-separate-the-condition-which_fig1_327949545"><strong>https://www.researchgate.net/figure/The-architectures-of-InfoGAN-and-SCGAN-InfoGAN-attempts-to-separate-the-condition-which_fig1_327949545</strong></a></figcaption></figure><p>In the InfoGAN, the latent vector ‘ z ’ provided is <strong>highly entangled</strong> in nature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*bDWLFofYVJr6HSF_lnquYw.png" /></figure><p>So, a different algorithm is run to capture the salient semantic features from the real samples and assign them labels that ensure the entangled features of ‘z’ is converted into disentangled features {c, z} where ‘ c ’ is labels/attributes. And the generated output from the generator is ‘G(z, c)’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*bxq_uSa-fUSr-RTE_zPRKQ.png" /></figure><p>The output from generator G(z, c) is represented by ‘x̂’ that is fed to another neural network implementing ‘Q(c/x)’ that produces an output of “ <strong>c’</strong> ”. This particular network’s working is similar to a <strong>Reverse</strong> <strong>autoencoder</strong>.</p><p><strong>InfoGAN maximizes the mutual information</strong> between latent code ‘ c ’ and generated output ‘G(z, c)’, so the generator learns the important features. And the role of the discriminator is ensuring that the generator just doesn’t copy ‘c’ that makes it recognizable but to ensure that it infuses/encodes it in the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*23oNEnDqxjHPAto9CAWEnw.png" /></figure><p>Here λ&lt;1 as mentioned in the paper and,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*eUpanTdODUbpcb5Qh-Ul7A.png" /></figure><p>Lambda is the regularization constant and is typically just set to one or below one. To find the regularization value, we generally estimate the <strong>likelihood</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*E_zd5WNhPBEP49_1fGUd7Q.png" /></figure><h4><strong>Minimization of G*</strong></h4><p>To obtain the minimum value for G* we have to maximize “ λ I( c; G(z,c)) ”</p><p>λ I( c; G(z,c)) = H(c) - H(c|G(z,c)) → A</p><p>To obtain the maximum value of equation A, we have to minimize H(c|G(z,c)) to 0.</p><p>[ ⸪ H(X|Y) = 0; if value of ‘X’ is completely determined by ‘Y’ ]</p><blockquote><strong>N O T E :</strong></blockquote><blockquote>It’s difficult almost intractable to directly maximize the value of I( c; G(z,c) ) as it needs to access the posterior P(c|x) and instead the <strong>lower</strong> <strong>bound</strong> of it is obtained i.e. <strong>Q(c|x) which is an auxiliary distribution approximating P(c|x)</strong>. This technique is known as <strong>Variational Information Maximization Technique.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HCSofrOwTrifiJOeizOUg.png" /><figcaption><strong>Source: </strong><a href="https://arxiv.org/pdf/1606.03657.pdf">https://arxiv.org/pdf/1606.03657.pdf</a></figcaption></figure><p>Using the above technique we obtain the final equation as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*1736yS-kN_OGC95dUvsiCg.png" /></figure><h3><strong>BiGAN (Bi-directional GAN)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*ipeaFHlgqF_URje7m2wtNg.png" /><figcaption><strong>Source: </strong><a href="https://arxiv.org/pdf/1605.09782.pdf">https://arxiv.org/pdf/1605.09782.pdf</a></figcaption></figure><p>The above diagram is the architecture of BiGAN. The working principles of the BiGAN are very much similar to the working of autoencoders. Autoencoders have an encoder block and a decoder block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*3U_s7A-m3vn2LE-f3JepzQ.png" /><figcaption><strong>Source: </strong><a href="https://www.compthree.com/blog/autoencoder/"><strong>https://www.compthree.com/blog/autoencoder/</strong></a></figcaption></figure><p>In the case of BiGAN, the encoder and the decoder block are present differently and there’s no connection between them. It can be given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFY4rcMz4X8omdveTYufWA.png" /></figure><p>‘ x ’ is the sample taken from the distribution of the real images and ‘ z ’ is taken from the latent coded distribution. According to the paper, the decoder is also called the generator. Then both the images are sent to the discriminator that takes the joint distribution. It produces an output of ‘1’ to images that come from the encoder block as they belong to real images and ‘0’ to the decoder block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*TC7SH6jSNm4vJ1s8FQ3_EQ.png" /></figure><p>Now, once the discriminator can identify between real and generated images then the encoder, decoder, and discriminator block can be trained so that the joint distribution between (x, z’) and (z, x’) can be optimized.</p><p>The BiGAN training objective is defined as a minimax objective is given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*TqNRey1jA73OclY_5BRSvA.png" /></figure><p>where,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*rbkBJpPwL3fEw5iyeoM11g.png" /></figure><p>For a detailed understanding, kindly go through the blog by Hamaad Shah and an explanatory video by Ahlad Kumar.</p><p>Blog: <a href="https://towardsdatascience.com/using-bidirectional-generative-adversarial-networks-to-estimate-value-at-risk-for-market-risk-c3dffbbde8dd">Using Bidirectional Generative Adversarial Networks to estimate Value-at-Risk for Market Risk Management</a></p><p>Video: <a href="https://www.youtube.com/watch?v=4NTIqxxENBM">Objective function of BiGAN (Bidirectional GAN) / ALI architecture</a></p><h3><strong>CycleGAN</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9YKv4PulSppvDO2IIjGkg.png" /><figcaption>Source: <a href="https://link.springer.com/article/10.1007/s12194-019-00520-y/figures/2">https://link.springer.com/article/10.1007/s12194-019-00520-y/figures/2</a></figcaption></figure><p>CycleGAN is used for image-to-image translation that is used to convert one image into another by keeping the attributes of the original image the same. Below is the diagram is given of image-to-image translation. CycleGAN comes under the unpaired approach unlike the paired approach and there are other GANs too that work similarly under the unpaired approach such as DiscoGAN and Dual GAN.</p><p>CycleGAN is an augmentation of the GAN design that includes the synchronous preparing of two generator models and two discriminator models.</p><p>The generator inputs samples(images) from the 1st domain to generates images for the 2nd domain, and the other generator inputs images from the 2nd domain to generate images for the 1st domain. Whereas discriminator is used for discriminating between real &amp; fake images and the loss is calculated to update the generators.</p><p>CycleGAN uses a <strong>cycle consistency loss</strong> to enable training without the need for paired data. In other words, it can translate from one domain to another without a one-to-one mapping between the source and target domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cSnjqdiu5LopsX4QYydTg.png" /><figcaption><strong>Source: </strong><a href="https://arxiv.org/pdf/1703.10593.pdf">https://arxiv.org/pdf/1703.10593.pdf</a></figcaption></figure><p>The architecture of CycleGAN is basically divided into two networks that are connected together and they are as follows:</p><p><strong>1st Network</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CI0L39sjUb_cwDgJoAbDzg.png" /><figcaption><strong>Source: </strong><a href="https://blog.jaysinha.me/train-your-first-cyclegan-for-image-to-image-translation/"><strong>https://blog.jaysinha.me/train-your-first-cyclegan-for-image-to-image-translation/</strong></a></figcaption></figure><p>The above diagram represents the working of the 1st network where a real image is taken from distribution A and is passed through the generator(A2B) that generates a fake image B. Then again, it’s passed through another generator(B2A) that generates a reconstructed image. The working is very similar to the working of an autoencoder.</p><p>After this, the L1 loss metric is used for optimization to reduce the distance between the two distributions, and this is called the <strong>cycle-consistency loss.</strong></p><p>The below diagram represents the 1st network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4V2T648CJkYa-HcD-T0seg.png" /><figcaption><strong>Source: </strong><a href="https://arxiv.org/pdf/1703.10593.pdf"><strong>https://arxiv.org/pdf/1703.10593.pdf</strong></a></figcaption></figure><p>‘ x ’ represents a sample taken from the real image distribution and that’s converted into ‘Ŷ’ using the generator ‘G’ which is later passed through another generator ‘F’ to produce ‘x̂’ which is the estimate of the actual image and then the cycle consistency loss is calculated.</p><h4><strong>Objective function</strong></h4><p>We will be having two losses here i.e. Adversarial loss and the Cycle consistency loss. These loss functions will be used for deriving the final objective function of CycleGAN.</p><p><strong>Adversarial Loss</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*4ApcNVoXv-AvjUEoKCuIhw.png" /></figure><p><strong>Cycle Consistency Loss</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*ySeT503iEUXqmqYJNb9GMg.png" /></figure><p><strong>2nd Network</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjtSlHY5GOssMIAPWdPfRg.png" /></figure><p>Similarly, like the 1st network, the 2nd network is similar but with few changes in it. In 2nd network where a real image is taken from distribution B and is passed through the generator(B2A) that generates a fake image A. Then again, it’s passed through another generator(A2B) that generates a reconstructed image.</p><p>The below diagram represents the 2nd network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*Ygj3Lb_qamPZCjKTe44a0g.png" /></figure><p>‘y’ represents a sample taken from the real image distribution and that’s converted into ‘X̂’ using the generator ‘F’ which is later passed through another generator ‘G’ to produce ‘ ŷ’ which is the estimate of the actual image and then the cycle consistency loss is calculated.</p><h4><strong>Objective function</strong></h4><p>We will be having two losses here i.e. Adversarial loss and the Cycle consistency loss. These loss functions will be used for deriving the final objective function of CycleGAN.</p><p><strong>Adversarial Loss</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*xtOEq3zyE3diX-GquWhZ4w.png" /></figure><p><strong>Cycle Consistency Loss</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*InmW2RZLTmYOTR_jpmqRjw.png" /></figure><h3><strong>CycleGAN Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiBNC7zkVZZXBE9xIshGDA.png" /></figure><p>The above two networks (1st &amp; 2nd) that were mentioned are combined together to form a CycleGAN network given above and their equations mentioned are all together combined to obtain the final objective function of the CycleGAN i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*J1yimKeELltZ72suGVtNIg.png" /></figure><p>And it’s optimization function is given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*6d8cqRld8daPahebd_-w2w.png" /></figure><p>CycleGAN has multiple applications and they are as follows:</p><blockquote>• Style Transfer</blockquote><blockquote>• Object Transfiguration</blockquote><blockquote>• Photograph generation from Painting</blockquote><blockquote>• Photograph Enhancement</blockquote><blockquote>• Image colorization</blockquote><h3><strong>Conclusions</strong></h3><p>In case if you have followed the readings so far, you must be having a very clear idea about the working of GANs and their variants that were explained in depth. I would strongly recommend you to go through the actual papers and also other works mentioned in the references.</p><p>In the upcoming blogs on GANs, we will be focusing more on the actual implementation of DCGAN for image generation. And in the last part, we will be discussing the architecture of StyleGAN and StyleGAN2 and their implementation using TensorFlow.</p><h3>AUTHOR</h3><blockquote><strong>Sudeep Das</strong>: <a href="https://www.linkedin.com/in/sudeepdas27/"><strong>https://www.linkedin.com/in/sudeepdas27/</strong></a></blockquote><h3><strong>References</strong></h3><p>[1] Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks <a href="https://arxiv.org/pdf/1703.10593.pdf">https://arxiv.org/pdf/1703.10593.pdf</a></p><p>[2] Ahlad Kumar <a href="https://www.youtube.com/channel/UCP9YJJ24w6g38VMVMm6Thtg">https://www.youtube.com/channel/UCP9YJJ24w6g38VMVMm6Thtg</a></p><p>[3] InfoGAN: Interpretable Representation Learning by Information Maximizing Generative Adversarial Nets <a href="https://arxiv.org/pdf/1606.03657.pdf">https://arxiv.org/pdf/1606.03657.pdf</a></p><p>[4] Bidirectional GAN <a href="https://paperswithcode.com/method/bigan">https://paperswithcode.com/method/bigan</a></p><p>[5] Adversarial Feature Learning <a href="https://arxiv.org/pdf/1605.09782.pdf">https://arxiv.org/pdf/1605.09782.pdf</a></p><p>[6] Goodfellow, I., Bengio, Y. and Courville A. (2016). Deep Learning (MIT Press)</p><p>[7] A Gentle Introduction to CycleGAN for Image Translation <a href="https://machinelearningmastery.com/what-is-cyclegan/">https://machinelearningmastery.com/what-is-cyclegan/</a></p><p>[8] Implementation of CycleGAN using TensorFlow <a href="https://www.tensorflow.org/tutorials/generative/cyclegan">https://www.tensorflow.org/tutorials/generative/cyclegan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba104334d2cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about GANs (Part 1)]]></title>
            <link>https://sudeepdas27.medium.com/all-about-gans-part-1-84547262ab38?source=rss-3b6d022742a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/84547262ab38</guid>
            <category><![CDATA[stylegan]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[wasserstein]]></category>
            <dc:creator><![CDATA[Sudeep Das]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 19:54:48 GMT</pubDate>
            <atom:updated>2021-07-02T18:19:43.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPKt6MsynWGI-sz2100emQ.png" /></figure><p>In this blog, we will be discussing other popular variants of GAN such as:</p><ol><li>cGAN (Conditional GAN)</li><li>WGAN (Wasserstein GAN)</li><li>InfoGAN (Information GAN)</li><li>BiGAN (Bidirectional GAN)</li><li>CycleGAN</li><li>DCGAN (Deep convolutional GAN)</li><li>BigGAN, StyleGAN &amp; StyleGAN2</li></ol><blockquote><strong>NOTE</strong></blockquote><blockquote>“<strong>All about GANs</strong>” blog series will be broken down into 4 parts. In this blog which is PART-1 we will mainly discussing about cGAN &amp; WGAN. We will discuss other variants in upcoming parts.</blockquote><p>In our previous blog, we introduced the GAN (Generative Adversarial Networks) and its working and mathematics. We also looked at its limitation and problems.</p><p>I would strongly recommend reading the previous blog to understand things in-depth:</p><blockquote><strong>Blog</strong> <strong>1:</strong> <a href="https://sudeepdas27.medium.com/introduction-to-gan-generative-adversarial-networks-9f96ab80de0b">Introduction to GAN (Generative Adversarial Networks)</a></blockquote><p>This blog is similarly more focused on discussing various types of GANs and their working. In upcoming blogs, we will be discussing the implementation of StyleGAN2 to generate photorealistic human face images trained on the FFHQ dataset.</p><h3><strong>Conditional GAN (cGAN)</strong></h3><p><strong>cGANs (Conditional Generative Adversarial Networks) </strong>improve basic GAN by adding a condition ‘<strong>c</strong>’ into the Generator and Discriminator networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*S-MlszgTs5d4mWJio6FUUA.png" /><figcaption>Source: <a href="https://www.researchgate.net/figure/a-Standard-GAN-and-b-conditional-GAN-architectures_fig1_330593980">https://www.researchgate.net</a></figcaption></figure><p>While using the basic GAN, we encountered a problem, that it tends to produce random images of objects/classes. In the case of the fashion MNIST dataset, GAN generated images randomly of boots, or shirts, or trousers. In short, we didn’t have any <strong>control</strong> over the objects we produced. This is where we use the cGANs where we have control over the objects that can be generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jO69GmYz1YV8ntD4UYe-lA.png" /><figcaption>Source: <a href="https://bit.ly/3xiVj8E">https://www.researchgate.net</a></figcaption></figure><p>In the case of the architecture of GAN &amp; cGAN, we can notice that it’s pretty much similar apart from ‘<strong>c</strong>’ which is the <strong>label information. </strong>It’s fed along with ‘z’ to the generator and also it’s provided along with ‘x’ to the discriminator.</p><p>The conditions are passed along with the ‘<strong>z’</strong> vector (latent space) represented by ‘<strong>c’</strong> which are the <strong>labels</strong>. The objective equation we derived in the <a href="https://sudeepdas27.medium.com/introduction-to-gan-generative-adversarial-networks-9f96ab80de0b"><strong>previous blog</strong></a> for the GAN was given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmJQ95u24X_hpv8dcadZkQ.png" /></figure><p>In the case of cGANs, we tend to use the “<strong>conditional probability”</strong> where ‘<strong>c</strong>’ represents the<strong> label information. </strong>Label information consists of different labels for different classes of objects present in that dataset. In cGANS, we use conditional probability instead of a single probability having all the functionalities same as GAN, and the equation is then written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Icpsh3pgWR33agN0sWbpA.png" /></figure><h3><strong>Wasserstein GAN (WGAN)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfDszBS6X0_TW3Y7X73LoA.png" /><figcaption>Source: <a href="https://jonathan-hui.medium.com/gan-wasserstein-gan-wgan-gp-6a1a2aa1b490">https://jonathan-hui.medium.com/gan-wasserstein-gan-wgan-gp-6a1a2aa1b490</a></figcaption></figure><p>Before we discuss WGAN, we need to understand few other concepts.</p><ul><li><strong>Kullback-Leibler Divergence</strong></li><li><strong>Jensen-Shannon Divergence</strong></li></ul><p>KL (Kullback-Leibler) divergence and JSD (Jensen-Shannon divergence) are used while deriving the objective function of the auto-encoders &amp; GAN respectively and they have certain limitations and hence in WGAN, we use the <strong>Wasserstein distance</strong> as a metric in the function.</p><h4><strong>(Kullback-Leibler) KL Divergence</strong></h4><p>KL Divergence is a measure of how one probability distribution is different from a second. It’s used while deriving the objective functions in VAE (Variational auto-encoders) to<strong> minimize the distance between two different probability distributions</strong> and are of two types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhBYYmGixJmmUHIQjFO6Bw.png" /></figure><p><strong>Forward KL Divergence</strong></p><p>Let’s take an example of two distributions P and Q where P is a known distribution and Q is unknown distribution. We try to approximate them by minimizing the distance this is how it forms in <strong>Case-1</strong>.</p><p><strong>Case-1 (Underestimation)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*MoUTVjXwhfsl0A1Iud7nYg.png" /><figcaption>Mode seeking behavior</figcaption></figure><p>In this scenario of <strong>underestimation,</strong> there is a region where <strong>Q(X) = 0</strong>, due to which while substituting these values in the forward KL it becomes as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*gNoSzcBsMqKlx-TtlpHUcw.png" /></figure><p>When the denominator is ‘0’ the equation tends to be infinity and maximizes which is opposite to its actual objective.</p><p><strong>Case-2 (Overestimation)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*VHymOj3-JjCxmaHYe6p2wg.png" /><figcaption>Mean seeking behavior</figcaption></figure><p>In this scenario, all the region is covered where <strong>Q(X) ≠ 0</strong>, but here <strong>P(X) = 0 </strong>as the green lines tend to extend even further due to which while substituting these values in the forward KL it becomes as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*60MHRGVTlNzTfQbM90fh4Q.png" /></figure><p>Hence for the forward KL, <strong>overestimation</strong> is used that tends to ignore the problem of Q(X) = 0 leading KL divergence to blow up and for this reason, it’s known as a <strong>zero-avoiding situation</strong>.</p><p><strong>Reverse KL Divergence</strong></p><p>Similarly, we take the above two cases of underestimation and overestimation and substitute values in the reverse KL equation.</p><p><strong>Case-1 (Underestimation)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*MoUTVjXwhfsl0A1Iud7nYg.png" /><figcaption>Mode seeking behavior</figcaption></figure><p>In case of underestimation, we get obtain values as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*C_NYWvm19b543rIJwGYFTg.png" /></figure><p><strong>Case-2 (Overestimation)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*VHymOj3-JjCxmaHYe6p2wg.png" /><figcaption>Mean seeking behavior</figcaption></figure><p>In case of overestimation, we get obtain values as;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*U4QtXuq_2GLuYoiIsvcIIA.png" /></figure><blockquote><strong>NOTE</strong></blockquote><blockquote>And generally, <strong>underestimation is chosen over overestimation</strong> because at times it tends to estimate a lot of area. And hence we choose Reverse KL divergence as in it’s case underestimation produces a value of 0.</blockquote><p><strong>But, in few cases both the forward &amp; reverse KL tend to blow up and end up producing infinity value</strong> e.g. Let’s consider two probability distributions P at 0 and Q at 0.5 as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*R-zKf2WLqAKDlPCOOtYvIA.png" /></figure><p>In the above diagram, their distributions are given and their KL divergence will be as,</p><p>At x = 0,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*jn765C7YvjHrAwh6S2R6hg.png" /></figure><p>At x = 0.5,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*2ZI9p3llUsjlVwa96UX-8Q.png" /></figure><blockquote><strong>NOTE</strong></blockquote><blockquote>From the above scenario we can notice that when two probability distributions do not overlap, the KL divergence tends to blow up giving a value of infinity.</blockquote><p>To overcome this problem, we use <strong>JSD (Jensen-Shannon divergence).</strong></p><h4><strong>JSD (Jensen-Shannon divergence)</strong></h4><p>Jensen-Shannon divergence is a method of measuring the similarity between two probability distributions. It is given as,</p><p>JSD(P||Q) = 1/2 * { KL(P||M) + KL(Q||M) }</p><p>where, [⸪ M = (P+1)/2]</p><p>On using the above case discussed in the KL divergence, we obtain the JSD as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZHVvI5t-fbIaJR7X9XC2g.png" /></figure><p>Hence, JSD helps in overcoming the problem we encountered in the KL divergence as it produces a value “log2” when two probability distributions aren’t overlapping.</p><h4><strong>Alternate method</strong></h4><p>Hence, researchers have come up with a better metric to approximate two probability distribution function by minimizing the distance that doesn’t blow up like JSD &amp; KLD known as the <strong>Wasserstein metric</strong>.</p><h3><strong>Wasserstein Metric</strong></h3><p>It is a metric used to calculate the <strong>horizontal distance</strong> or <strong>Wasserstein distance (Wd)</strong> between two different probability distributions denoted by “θ” [ 0 &lt; θ&lt; 1 ]. It’s also known as the Earthmover distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*K3QsNPJfanphVy1xteF0qw.png" /><figcaption>Shifting away of distribution Q</figcaption></figure><p>Let’s consider a scenario in which P &amp; Q are two probability distributions where Q keeps shifting away from the mean of P such that the distance between them keeps increasing as shown in the above figure.</p><p>As the distance keeps increasing between the mean of P &amp; Q as the mean of Q keeps shifting away represented by the x-axis in the below diagram the divergence graphs are given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*l5Ninj7crewPqdF9aH_SgA.png" /><figcaption>Source: <a href="https://jonathan-hui.medium.com/gan-wasserstein-gan-wgan-gp-6a1a2aa1b490">https://jonathan-hui.medium.com/gan-wasserstein-gan-wgan-gp-6a1a2aa1b490</a></figcaption></figure><p>As the distance increases and they don’t further overlap, KL divergence outputs ‘0’ &amp; JSD outputs value log2.</p><p>JSD produces a value of log2 which is represented by a logline and there the derivate/slope is close to ‘0’ causing a vanishing gradient problem hence, as the distance increases between two probability distributions both KL &amp; JS divergence produce a value of 0 i.e. the generator learns nothing from the gradient descent.</p><p>Therefore, <strong>Wasserstein distance</strong> is a better distance metric. It’s given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*ASxa5fWgR9vT2bXBjgUdkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBu8zgtlC7SS9zu8oWNXWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*kSSUzuZsq3BqpSBqNzSGpg.png" /><figcaption>Real &amp; generated distributions</figcaption></figure><p>We can also write the final objective function as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*1ObGQZlwB4DLXoi1CRCAZw.png" /></figure><p>The equation we derived is intractable and to make it tractable we use the “<strong>Kantorovich-Rubinstein duality</strong>” from which we obtain the equation as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*iKb-T9rkMwbApVBd7OssMA.png" /></figure><p><strong>Supremum</strong> (maximum) is taken over all <strong>1-Lipschitz continuity function</strong>.</p><blockquote><strong>1-Lipschitz continuity function : </strong>It means that the slope of the curve shouldn’t exceed 1 in the neighborhood of the point of interest.</blockquote><h4><strong>Quick Recap (k-Lipschitz continuity)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*1hOMffYTkhC3n8eiI6LtJQ.png" /></figure><p>In the above diagram, the point of interest lies between x and y.</p><p>x and y are the neighborhood of the point of interest. Perpendicular lines are drawn from x &amp; y whose corresponding functions f(x) and f(y) are drawn on the curve from which the <strong>slope</strong> is extracted.</p><p>If slope ≤ k, then it’s called <strong>k-Lipschitz continuity</strong>. If k=1, it’s called 1-Lipschitz continuity.</p><p>The equation we obtained was,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*nfe4Vk4VrgDGlfT0YCJruQ.png" /></figure><p>Here, we replace the supremum with the parameterized function of Dw as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*DtpYLi2GjrqoZ2uvvBlArA.png" /></figure><blockquote>Note</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*b3EE76-c7PQirFfr711K2w.png" /></figure><blockquote>To enforce the above condition, we use the <strong>clipping concept</strong> i.e. clipping of the parameters (weights, biases) of neural network between a range of (-c, c) which act as the neighbourhood discussed during the Lipschitz continuity function.</blockquote><h4>Limitations</h4><p>There are few limitations while using the clipping concept to enforce the Lipschitz constraint on the discriminator’s model to find Wasserstein distance.</p><p>If the clipping parameter is large, then it can take a long time for any weights to reach optimality, thereby making it harder to train. If the clipping parameter is small, this leads to a vanishing gradient problem.</p><h3><strong>What makes WGAN different?</strong></h3><ol><li>In WGAN, the discriminator acts as a critic which finds out the closeness between two distributions rather than discriminating/classifying between real &amp; fake. This makes it act as a regression problem.</li><li>Discriminator works as a regressor instead of a classifier.</li><li>As it doesn’t classify between real and fake images like regular GAN, hence it doesn’t use a sigmoid function in the last layer.</li><li>The optimization method chosen in WGAN is RMSprop.</li><li>There is no logarithmic term in the loss function.</li><li>Clipping of ‘W’ lies between a range of (-c, c) to satisfy the k-Lipschitz condition.</li></ol><h4>Conclusion</h4><p>That’s all about cGAN &amp; WGAN which is definitely a step-up from the previous basic GANs. Still, they have their limitations and in the upcoming blogs, we will be dealing with better and advanced GAN variants.</p><p>For any queries, or discussion you can contact me on LinkedIn and my details are given below.</p><h3>AUTHOR</h3><blockquote><strong><em>Sudeep Das</em></strong><em>: </em><a href="https://www.linkedin.com/in/sudeepdas27/"><strong><em>https://www.linkedin.com/in/sudeepdas27/</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84547262ab38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to GAN (Generative Adversarial Networks)]]></title>
            <link>https://sudeepdas27.medium.com/introduction-to-gan-generative-adversarial-networks-9f96ab80de0b?source=rss-3b6d022742a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f96ab80de0b</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <dc:creator><![CDATA[Sudeep Das]]></dc:creator>
            <pubDate>Sun, 30 May 2021 10:50:30 GMT</pubDate>
            <atom:updated>2021-05-31T08:56:27.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*4z-4lHxMzb_5dcuF2KeEqQ.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1812.04948.pdf">https://arxiv.org/pdf/1812.04948.pdf</a></figcaption></figure><p>All those people that you can see in the image above do not exist in person and are all created using StyleGAN 2. GANs have been lately too popular because of their wide applications in several fields such as computer vision, gaming, medical science, artificial intelligence, etc.</p><p>Their ability to generate such high-quality photorealistic images is something that has astonished many people over the globe. It’s too hard to differentiate between the images that they generate whether they are real or fake!</p><p>Just take some time to analyze the below gif of people who do not exist in reality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuUNd7sgZa7r-5wT1XrgIg.gif" /><figcaption>Source: <a href="https://syncedreview.com/2018/12/14/gan-2-0-nvidias-hyperrealistic-face-generator/">https://syncedreview.com/2018/12/14/gan-2-0-nvidias-hyperrealistic-face-generator/</a></figcaption></figure><p>In this article, I will be discussing the functioning of a basic GAN and its mathematics. In my upcoming articles, I will further discuss different types of GAN and its implementation using TensorFlow and PyTorch.</p><h3>Generative Adversarial Networks</h3><p>GAN is a type of neural networks used in deep learning for both supervised &amp; unsupervised learning that consists of two neural networks which keep competing among themselves and it mainly comprises of these two components:</p><p>1. Discriminator</p><p>2. Generator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xhrEDbl-Blgr0Yk1YcL7g.png" /></figure><p>They are trained in an adversarial manner to generate data that are similar to the given distribution and they consist of two models as:</p><p>1. <strong>Discriminator model</strong>: It distinguishes between real and fake samples and fine-tunes its parameters through backpropagation.</p><p><strong>0 </strong>— fake</p><p><strong>1 </strong>— original</p><p>It works similarly to the classifier models as it differentiates between different classes.</p><p>2. <strong>Generative model</strong>: The role of it is to produce fake samples which are similar to the real sample such that it fools the discriminator.</p><p><strong>Note: Each is held constant while the other is trained.</strong></p><h4>Training GAN</h4><ol><li>At first, the discriminator is trained by keeping the generator fixed (no forward &amp; backward propagation is done).</li><li>Once the discriminator is trained, then the generator is trained to generate fake images to fool the discriminator.</li><li>Step 1 &amp; 2 are repeated to a point where the discriminator cannot distinguish between real(1) &amp; fake(0) images and outputs a value of 0.5</li></ol><h3><strong>Notations</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*Z6kirYOKV4h7S6M1YF6LVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKTq8o58kebbzWuDGc7_xQ.png" /></figure><h3><strong>Loss function in GANs</strong></h3><p>The binary cross-entropy loss is given as:</p><p>L(ŷ,y) = [ y*log(ŷ) + (1-y)*log(1- ŷ) ]</p><p>Data coming from the real distribution pdata(x) have label value 1 for y &amp; data of ŷ is D(x). Plugging them into binary cross-entropy loss we derive:</p><p>L(D(x), 1) = log(D(x)) → <strong>A</strong></p><p>And, for data coming from generator have label value 0 and data of ŷ is G(D(z)). Plugging them into binary cross-entropy loss we derive:</p><p>L(D(G(z)), 0) = log(1- D(G(z))) → <strong>B</strong></p><h3><strong>Objective of Generator &amp; Discriminator</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*iiMhpPS0jlQU7tWt6ARuQA.gif" /><figcaption>Source: <a href="https://syncedreview.com/2018/12/14/gan-2-0-nvidias-hyperrealistic-face-generator/">https://syncedreview.com/2018/12/14/gan-2-0-nvidias-hyperrealistic-face-generator/</a></figcaption></figure><p>Discriminator’s objective is to distinguish between fake &amp; real data and for that it should maximize the loss by maximizing the values for the above two equations <strong>A</strong> &amp; <strong>B</strong> written as:</p><p>max{ log(D(x)) + log(1- D(G(z))) }</p><p>The generator’s objective is to fool the discriminator and for that it should minimize the loss by minimizing the values for<strong> A </strong>&amp; <strong>B</strong> as:</p><p>min{ log(D(x)) + log(1- D(G(z))) }</p><p>The combined equation from the above 2 equation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRRfkCkCchhtaODxq5F3DA.png" /></figure><p>So far, we have considered just one data point, now we take even other data points and for that, we need to calculate the expectation given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3RO0EpebIFtxQuZL3vczw.png" /></figure><h4><strong>Optimal Discriminator</strong></h4><p>When G is fixed, the optimal discriminator is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFAwWWupvgfVM6LbUCwCMA.png" /></figure><p><strong>Derivation</strong></p><p>The criterion of the discriminator is to maximize the loss from the actual equation when G is kept constant and be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-tBPBzksAWY6L2XPTantQ.png" /></figure><p>Now we will work on this particular equation and for that, we need to know 1 concept which is “<strong>change of variable</strong>”.</p><blockquote><strong>Change of variable</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmWRJLHqWva-dq4I6trOjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yi-hz8xDju8JOQgg26tuPA.png" /></figure><h4><strong>Optimal Generator</strong></h4><p>After obtaining the value for optimal discriminator the role of the optimal generator G* is to generate fake values which would be very similar to the real values i.e <strong>pg = pdata </strong>and we get the function as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEpmlPMqAu1Z3KgibpDr_g.png" /></figure><h4>Diagrammatically</h4><p>As we can see in the diagram the distributions generated aren’t similar to the true distribution from discriminator so with every iterations weights and biases are adjusted and accordingly the generated distribution becomes as close to the discriminators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsfYWxiKu62mA6T0Lb902A.png" /><figcaption>Source: <a href="https://arxiv.org/abs/1406.2661">https://arxiv.org/abs/1406.2661</a></figcaption></figure><p>a) Poorly fit model</p><p>b) After updating D</p><p>c) After updating G</p><p>d) Both are similar</p><p>After a while, they both become similar and look the same.</p><h3><strong>Optimization of Loss Function</strong></h3><p>Optimization of the loss function is necessary to adjust the weights and biases of the generator and discriminator during the backpropagation. According to the paper published by Ian Goodfellow 2014, minibatch stochastic gradient descent is used and the equations are as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dy3tdi_5O_hiJQuHApSotA.png" /></figure><blockquote><strong>Note: Refer to the notations mentioned in the top and here we take it for multiple points hence it’s it’s x(i) &amp; z(i).</strong></blockquote><h3><strong>Limitations of GANs</strong></h3><h4><strong>1. Vanishing Gradients</strong></h4><p>Initially, the generator hasn’t learned all the parameters so the discriminator easily distinguishes between real and fake data. Discriminator gets too robust that the generator can’t further fool it and learns nothing as a derivative of the generator function is close to 0 i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzYvNulY8yVo5zJ0DmVDAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*w3O5tcoipdPe7EclRGpHxg.png" /></figure><p>Due to minimization, it can’t learn much, and also the rate at which it learns is slow. Hence, we take the maximization of the generator function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOovvF_T7QRfPX4UWGKPnw.png" /></figure><h4>2. <strong>Mode Collapse</strong></h4><p>While training, the generator may get stuck with a setting where it keeps on producing the same output over and over again. In the below diagram we can see it starts producing similar-looking images of the same tone, lighting, posture, hair color, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*2qUozEFtof-ww1xMNfaqnw.png" /><figcaption>Source: <a href="https://cutt.ly/ensn4XR">https://www.researchgate.net/figure/Examples-for-mode-collapse-in-BEGAN-trained-on-CelebA-showing-three-over-allocated-bins_fig2_325484013</a></figcaption></figure><h4><strong>3. Hard to attain Nash Equilibrium</strong></h4><p>There exists no relation between discriminator &amp; generator while updating their own weights due to which their gradients can’t guarantee a convergence. The “<strong>min max</strong>” operation causes the generator &amp; disciminator to undermine the other leading to the zero-sum non-cooperative game where one’s loss is the other’s win and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tfUe81MlDXGmAukyDtl-Mg.png" /><figcaption>Source: <a href="https://lilianweng.github.io/lil-log/2017/08/20/from-GAN-to-WGAN.html">https://lilianweng.github.io/lil-log/2017/08/20/from-GAN-to-WGAN.html</a></figcaption></figure><p>Due to this, after certain iterations, huge oscillations take place along with a lot of instability.</p><p>For info kindly refer to this: <a href="https://cutt.ly/DnsmKeD">https://lilianweng.github.io/lil-log/2017/08/20/from-GAN-to-WGAN.html</a></p><h4><strong>4. Problem with Counting, Perspective &amp; Global Structure</strong></h4><p>GAN has a hard time understanding the number of objects present in the image and might generate weird artifacts.</p><p>They also have problems with understanding the 3D perspective of the image and tend to generate 2D perspective images.</p><p>Lastly, they can’t understand the global structure of the image which means that there are other objects too in the image like trees, leaves, etc. and they have a tough time generating images with such structures.</p><p>That’s all about the GAN and in upcoming articles, we will further look at different types of GAN along with their implementation using TensorFlow and PyTorch. As well as, understand better methodologies to overcome the shortcomings of GAN.</p><h3>AUTHOR</h3><blockquote><strong><em>Sudeep Das</em></strong> : <a href="https://www.linkedin.com/in/sudeepdas27/"><strong><em>https://www.linkedin.com/in/sudeepdas27/</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f96ab80de0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convolutional Neural Network]]></title>
            <link>https://sudeepdas27.medium.com/convolutional-neural-network-76909e869d52?source=rss-3b6d022742a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/76909e869d52</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Sudeep Das]]></dc:creator>
            <pubDate>Mon, 17 May 2021 05:05:56 GMT</pubDate>
            <atom:updated>2021-05-17T05:10:11.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QB0OdbglenNPjFfW8m4nLw.jpeg" /></figure><h3><strong>CNN/CONVNET</strong></h3><p><strong>Convolutional Neural Networks (CNN) </strong>are mostly used for images and videos. These tend to perform better than the feed-forward network as the image is nothing but matrices of different values that represent different values that range from 0–255. For e.g.: A black and white image of dimension 100×100 would have around 10000 values in it when flattened. Similarly, an HD image of resolution 1920x108x3 would generate around 6 million values. These 6million values belong to a single image and a bunch of these are would be required to train the machine and model on would round up to a very large amount that would be computationally heavy for the machine. So, this is the major reason we opt for CNN over a feed-forward network.</p><p>There are various operations that take place in the CNN and some of the most important that take place often in them are as follows:</p><ol><li>Convolutional Layer</li><li>Pooling</li><li>1×1 Convolution Layer</li><li>Fully Connected Layer</li></ol><p>Before, we deep dive into the functioning of the CNN, let’s understand how the image looks like in matrix form. A black and white image can be represented in a form of matrix where it consists value ranging from [0–255] where 0 represents black color and 255 represents a white color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*RamAxWUGdeyXBt9SuJ7nfA.png" /><figcaption>Source: <a href="https://ai.stanford.edu/">https://ai.stanford.edu</a></figcaption></figure><p>This is how a black and white image looks like and a color image is nothing but a combination of different shades and values of Red, Green, and Blue color, or say the RGB. And due to that, the image is split into 3 channels/layers representing a different color of RGB. Those 3 channels are Red channel, Green channel and Blue channel which is given below as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3mtfIUBcvHO5J2nW-rtiw.jpeg" /></figure><p>After understanding how the images are split into matrices, it’s time to understand how the CNN functions and how the operations take place in it. Before we try to understand how padding works, it’s important to understand how a convolutional layer is formed.</p><h3><strong>CONVOLUTIONAL LAYER</strong></h3><p>In the convolution; we actually perform a correlation operation as in convolution we flip the kernel but instead, it’s called a convolution. It requires 3 important things in it and they are as:</p><ul><li><strong>Padding(p)</strong></li><li><strong>Stride(s)</strong></li><li><strong>Filter/Kernel(f)</strong></li></ul><p>Let’s say an image of dimension 6×6 is given then we multiply with a filter of size 3×3 and the role of the filter is to detect the edges that exist within an image. The final image that’s formed when a filter is applied in this case would be of 4×4 size. All the values that exist within the red box are multiplied with the filter size and a matrix multiplication takes place and the size of the red box is the same as that of the filter and the final value obtained from it is stored in the final result box in the first box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*MzbgMLX2S6Xo4y8tqAfbhg.png" /><figcaption>Source: <a href="http://indoml.com/">http://indoml.com</a></figcaption></figure><p>In this given example the value of stride is given as 1 and padding as 0. So the obtained matrix size can be denoted in the formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*SzmtinMSMMv7isLyvWZBZA.png" /></figure><p>The final matrix dimension are = [(n +2p -f)/s + 1] x [(n +2p -f)/s + 1]</p><p>Stride is basically the number of units the red box shifts/moves towards after multiplication with the filter size values. That can be represented here below where the yellow box represents the values that are multiplied with the filter and then moves horizontally till the last value is covered and then it moves below by 1 unit as assigned to the stride value and then it moves horizontally and this operation is carried out till the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*MIfCEje3dtG4cr0cV_SEeA.gif" /></figure><p>In this operation we can clearly notice one thing that the numbers that exist on the outer region(corners) are generally counted once and this means that a lot of amount of data is being discarded as it’s not being counted and hence to tackle this issue, we use a concept of Padding. The role of padding is to add a no. of units around edges which consists of value 0 and due to this, the values that were existing around the edges are now contributing a significant amount of data. And one more thing to notice is that the image size reduces and padding is used here to ensure that the image size remains the same after performing the operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*nrVti7XhCaXffOG7mWDtsg.png" /><figcaption>Source: <a href="http://indoml.com/">http://indoml.com</a></figcaption></figure><p>Padding is generally given as:</p><p><strong>p = (f-1)/2</strong></p><p>And generally, padding is of two types and are:</p><ul><li><strong>Valid</strong></li><li><strong>Same</strong></li></ul><p>In the valid padding, the image on which the operation is executed has no padding due to which the size of the matrix reduces, and in the same padding, the size remains the same after operation by adding a layer of padding around the matrix. This ensures that the corner edge values contribute while performing operations and nothing is missed.</p><p>One more thing to keep in mind is that while assigning a value to stride the size of the matrix reduces and in case a non-integer value is obtained for example 3.7 then its lower value is taken. And the filter is also known as kernel and its role is to identify edges that may exist in different directions as horizontal, vertical or of any angle.</p><h3><strong>CONVOLUTION ON VOLUME</strong></h3><p>So far, we have been performing convolution operations on a single matrix or a single channel image which is of a greyscale image. As explained before, the color images generally consist of 3 channels of red, green, and blue RGB. Here the matrix consists of the 3 layers and the filters to which they are multiplied are of 3 layers too. The values obtained from all three layers are added together to form a single-layer matrix. This is also known as the convolution on volume.</p><p>And a similar process is carried out of padding, striding, and here in the diagram below the red represents the red channel and respectively for others of a total of 3 layers. We can also see that how striding takes place where the mask shifts by 1 unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*6KfykAhmg2bGsYHQMDVzCw.gif" /></figure><p>Let’s understand the neural network given below in the diagram and how the number of layers is formed passing through different operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*IlkFNq_PbhSauALBiGk3aw.png" /></figure><p>Now let’s try to understand the above concept with the things we have learned so far. At first, an image of dimension 39x39x3 is taken. On which we perform a convolution operation of filter size 3, padding 0, stride 1, and a total of 10 filters. Mathematically,</p><p>f = 3; s =1; p = 0; n =39</p><p>The obtained matrix will be of dimension,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*fSI1bbRV8ZlkryWOtEUlZA.png" /></figure><p>And, there are a total of 10 filters.</p><p>So, the obtained matrix after the operation is: 37x37x10</p><p>Similarly, the second convolutional layer will be of the dimension =&gt; (37 + 2*0–5)/2 + 1 = 17</p><p>Hence here the dimension obtained is: 17x17x20</p><p>For the third convolutional layer will be of the dimension =&gt; (17 + 2*0–5)/2 + 1 = 7</p><p>Hence the size of the matrix after operations is: 7x7x40</p><p>And after that, they are flattened into a single layer which consists of values 7*7*40 = 1960 values in it. From which one more layer is made of a number of neurons that represent the total number of classes from which the SoftMax operation is carried on to classify the types of the objects or mathematically speaking it returns the value of the object that tends to have the highest probability. This demonstrates a basic function of the convolutional neural network. But there are other concepts also that exist and that will be explained now and now we deal with the concept of Pooling and the types of pooling that exist and their importance.</p><h3><strong>POOLING</strong></h3><p>Pooling is another concept that is performed and the reason behind carrying out this operation to select those particular features that important and also it reduces the dimension of the matrix making it easier for computation. Here there exist three parameters that are:</p><ul><li>Size</li><li>Stride</li><li>Types</li></ul><p>And generally, there are three types of pooling operation that are carried out and they are as:</p><blockquote><strong><em>Max Pooling</em></strong></blockquote><blockquote><strong><em>Min Pooling</em></strong></blockquote><blockquote><strong><em>Average Pooling</em></strong></blockquote><p>Let’ discuss how pooling works and these types of pooling operations are carried out. The given matrix is given below which consists of certain values in it. The size is basically the mask of the region that is taken on which pooling is performed very much similar to the filter size mask. And after pooling operation is carried out on it the masks shift by certain units mentioned in the stride. Consider the matrix given below of dimension 4×4 where the size of the mask of pooling operation is 2 and stride 2. So, the mask shifts right by 2 units and then down by 2 units. So those different areas taken are represented by 4 different colors for representation purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*PU5p53XEMezRtyE0IuhbeQ.png" /></figure><p><strong>Max pooling </strong>is carried out when it has to choose the biggest amount of value present in that mask and this is generally used to pick the brighter pixels/value from the matrix and which is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/74/1*_qrfJkyxjT-YkNmTT4KVcg.png" /></figure><p>Similarly, <strong>min pooling</strong> is carried out to pick the lowest values in that mask which generally picks the darkest spot on the image and is given below as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/74/1*FvP8w_mytDqxCphHC3xbkA.png" /></figure><p>And then <strong>average pooling</strong> is carried out to pick the average of that mask region which is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/74/1*pJ-7DN6Alyo7FOhWpkqLuQ.png" /></figure><p>Similarly, a pooling operation is carried out for a color image where it consists of 3 layers representing 3 different channels of RGB. Below is a diagram of a color image on which max pool operation takes place and we can clearly see that the size of the matrix reduces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*DsiBY1B-lbPzx5rNFkLebg.png" /><figcaption>Source: <a href="http://indoml.com/">http://indoml.com</a></figcaption></figure><p>In pooling as well the similar formula is applicable as we learned before and the dimension of the matrix obtained after performing the operations is given as:</p><blockquote><em>[(n +2p -f)/s + 1] x [(n +2p -f)/s + 1] x (no. of filters)</em></blockquote><h4><strong>1×1 CONVOLUTION</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*2BF2TORoL92zii7BiHMj1Q.png" /></figure><p><strong>1×1 Convolution </strong>or very well known as a network in the network used to decrease no. of channels in a multi-channel matrix. This doesn’t perform a dimensionality reduction but helps in decreasing the number of filters which is represented below. We can see that a volume of 32x32x192 got reduced to a volume of dimension 28x28x32.</p><h4><strong>FULLY CONNECTED LAYER</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*_4_FVg4jFlZdN7H7twA98Q.png" /><figcaption>Fully connected layer</figcaption></figure><p>And lastly, after performing all the operations the matrix obtained consisting of different values are completely flattened out in a single layer that is given below on which SoftMax operation is carried out that can be used to classify the object or for any other operations.</p><p>The SoftMax layer consists of neurons as the no. of classes. In MNIST dataset there are 10 neurons in the SoftMax layer.</p><p>The image below depicts how the operations are carried on as discussed before and ends up generating a fully connected layer. And here there exist generally two fully connected layers in which the 1st one is an FC and the 2nd one is the SoftMax layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DDCLwDTXWBBjaClmR1DVpA.png" /><figcaption>Source: <a href="https://adeshpande3.github.io/">https://adeshpande3.github.io</a></figcaption></figure><h3><strong>FORWARD AND BACKWARD PROPAGATION</strong></h3><p><strong>Forward Propagation: </strong>To train the model both the forward and backward propagation is carried on alternatively. Now we will be mathematically understanding the functioning of the CNN and how both forward propagation and backward propagation take place. Generally, in this neural network, the trainable parameters are the weights of the filter that are multiplied during the convolution and the weights assigned in the fully connected layer. Here we do not consider the weights of max pooling as trainable parameters.</p><p>And here the loss can be calculated using L1 loss, L2 loss, or the cross-entropy loss and in the case of CNN, we use the cross-entropy loss. Here, we represent the output <strong>ẑ </strong>calculated during the forward propagation can be represented as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*bBwmqjUPLjNDlFyIiqVTiA.png" /></figure><blockquote>w = [w1, w2, w3, …. wn]; weights consist of the weights</blockquote><p><strong>‘b’ </strong>consists of all the biases that exist equally to the number of filters that exist.</p><p>This forms the first layer obtained and then a maxpool operation is done on it: maxpool( ẑ)</p><p>And after the similar process is carried on till we obtained an FC from which a similar operation is carried on with sending it through the SoftMax layer. In the final output layer, we obtain the predictions after the first pass as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*PrgLya9kgL8ZQkwOWwtzXQ.png" /></figure><p>From this, we calculate the loss and according to that, the weights are adjusted such that predicted values are close to the actual values. And for that to happen they are sent to the backward propagation.</p><p><strong>Backward Propagation: </strong>In the backward propagation we calculate the derivatives of loss w.r.t weights and biases and they are adjusted along with the learning rate which is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*L5zDUtsG7oX7SOMeoKvuHg.png" /></figure><p>where, α = learning rate</p><p>Here we tend to use the cross-entropy loss instead of using L1 loss and L2 loss. Just to give a recap L1 loss is also known as the least absolute deviation and L2 loss is known as the least square error given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kJPx6puOZd5t-O8x" /></figure><p>Cross-entropy loss for ‘c’ classes is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GCiIFRLtERRTNGjb" /></figure><p>‘z’ represents the logits and now we will derive the trainable parameters: ꝺL/ꝺw, ꝺL/ꝺb</p><p><strong>Derivatives w.r.t weight:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*a4Ef9Af7ndrwiRDd7m85xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*V_F6a3ezOsRz8NcjpwaWfQ.png" /></figure><p><strong>Case 1</strong>: ( i = l )</p><p>We calculate the derivative of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M-Ng_HGipJGmoHJ7" /></figure><p>Here we use the quotient rule which is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2W8TKAP4z98b34px" /></figure><p><strong>Case 2</strong>: ( i ≠ l )</p><p>In this case ‘i’ is not equal to ‘l’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i7TKCqbjdsJdjEB_" /></figure><p>And now our next objective is to calculate the derivative of loss w.r.t ‘z’ given as : ꝺL/ꝺzl</p><ul><li><strong>Now our objective is to calculate the derivative of cross-entropy loss and the cross-entropy loss is given as:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wrN5QmNh6shxzxTG" /></figure><p>Since we calculated the derivative before, we substitute the values here and we obtain,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*sdGtf9R6cEVl3xyCi6rBSg.png" /></figure><p>After this equation is calculated, we apply gradient descent to the derivative during the backpropagation and the weights are updated.</p><p>Now we need to calculate the derivatives of loss w.r.t to inputs:<strong> ꝺL/ꝺx</strong>. This derivative is calculated for the backpropagation on the maxpool layer. In the back propagation the highest values are retained at their location and the rest of all values are assigned a 0 value and according to this, the weights are adjusted in the convolution layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*MYu8lUAWA7a2_pX_Ck0e1A.png" /><figcaption>Maxpool in forward propagation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*zVtr0z9GigP-xj4QZaKRUQ.png" /><figcaption>Maxpool in backward propagation</figcaption></figure><p>Now this matrix is obtained from the backward propagation is taken as:<strong> ꝺL/ꝺx’</strong></p><p>The next objective is to calculate the partial derivate of loss w.r.t weight<strong> ꝺL/ꝺw</strong>. When an image is passed it produces an output by getting multiplied with the filter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*mNb3r8OUT_OPY0apxrGB8w.png" /><figcaption>Source: <a href="https://indoml.com/">https://indoml.com</a></figcaption></figure><p>We can clearly see that from the derivative of ꝺL/ꝺw, we can calculate the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*G6XR12rUTbyn_LK2t0WAXQ.png" /></figure><p>And hence we have calculated the partial derivative of loss w.r.t weights and inputs. And this totally describes the functioning of the convolutional neural network layer. And the diagram of the architecture/structure of a CNN is given below in the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*fyxhGgZL9UyjPp5GRiZGnA.png" /><figcaption>Source: <a href="https://www.sciencedirect.com/science">https://www.sciencedirect.com/science</a></figcaption></figure><p>This is how a convolutional neural network looks like but in general, they contain a lot of layers in it and that could stack around few hundreds of layers to a thousand layers and some of the other famous CNN architectures are given below as:</p><ol><li>LeNet-5 (1998)</li><li>AlexNet (2012)</li><li>VGG-16</li><li>VGG-19</li><li>ResNet50 (2015)</li><li>Inception — V4 (2016)</li></ol><p>And some of their architectures are given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*sNg77inu6OQnBa32dY74kw.png" /><figcaption>Inception’s Architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/0*6cztNQC4-P2opXRw" /><figcaption>VGG-16 Architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*J0XH18QRjNs2Jd-Tz8hQPA.png" /><figcaption>ResNet50 Architecture</figcaption></figure><p>And now we will be working on CNN where we will be building a CNN right from scratch.</p><h4>CNN Architecture from Scratch</h4><p>Currently, we discussed in depth how CNN functions and all the mathematics that goes behind it. Now our aim is to build a CNN right from scratch without any deep learning framework.</p><p>Our main objective here is to define functions and explain in a simple manner how the CNN will function and for that purpose we will be working on the famous example of Lena. At first, we install all the dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2ba797bf5bef63a94e4bff0f5f5f522/href">https://medium.com/media/d2ba797bf5bef63a94e4bff0f5f5f522/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*nxGBK5iA8GbMimtXoxC_gg.png" /></figure><p>As it can be clearly noticed that we are just using NumPy, cv2, and MatPlot library. Then our objective is to define a convolution layer block or say a class that takes care of both forward propagation and also as well backward propagation as functions that can be seen below.</p><p>On passing the Lena image it detects all the edges by using the filters where the weights and biases are assigned at random. This block defines the working of the convolution operation and then we build other blocks. The next block that we make is for carrying out the maxpool operations and that is given below along with the outputs from the previous block and the output of the current block.</p><p>After the maxpool operation is carried out the important features in the images are selected and used. And finally, after the maxpool is done the final connected layer (FC) is formed and that is passed via the softmax layer which is given in the below diagram. Hereafter the maxpool is done, the image is completely flattened out, and then it’s passed through a neural network which is finally passed a softmax activation and after that, the loss is calculated by the entropy loss. And then the weights are adjusted during the backpropagation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f847ec0d9b0fe0d91db114beb3b482c5/href">https://medium.com/media/f847ec0d9b0fe0d91db114beb3b482c5/href</a></iframe><p>In the above snippet of the code, you can see how the mathematics that we derived earlier has been used here to calculate the loss and update the weights and biases. For carrying on such operation NumPy is used. While working with deep learning frameworks there are wrappers defined that make the coding and understanding really easy. And for the ease of understanding, we haven’t carried on few operations here like padding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*uYdGAT45k3MMpvNOmpeROQ.png" /></figure><p>Our next aim is to use this neural network that we have developed on the MNIST dataset to understand how well the code is working that we have developed.</p><p><strong>MNIST DATASET</strong></p><p>Here we will import the dataset from the Keras datasets and that is given below as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a59a6f2b8d503f4e1403d819bc4b73b5/href">https://medium.com/media/a59a6f2b8d503f4e1403d819bc4b73b5/href</a></iframe><p>After that, we define three blocks that care of the forward prop, backward prop, and also the adjustment of weights that is carried on by running over multiple epochs. After which we get the output with an accuracy of nearly 83% on the training data is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*N9Q3Sc1ObUbtkBJVl4wGng.png" /></figure><p>That’s all from my side on CNN and I would highly appreciate your support on it. If you have any queries or doubts related to anything in the below-mentioned blog then feel free to contact me on my mentioned LinkedIn profile. Thank you!</p><h3>AUTHOR</h3><blockquote><strong>Sudeep Das</strong>: <a href="https://www.linkedin.com/in/sudeepdas27/"><strong>https://www.linkedin.com/in/sudeepdas27/</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76909e869d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network: Uncovering the Black Box]]></title>
            <link>https://sudeepdas27.medium.com/neural-network-uncovering-the-black-box-5053ad00d7f0?source=rss-3b6d022742a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5053ad00d7f0</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Sudeep Das]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 15:00:17 GMT</pubDate>
            <atom:updated>2021-05-17T05:09:22.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*FN8Pg209crqPsFRTyGUfQg.gif" /></figure><p>Neural network’s under-the-hood mathematics has baffled many aspiring data scientists and mathematicians for a pretty long time. Our objective here is to discuss how exactly the neural network functions and how the gradient descent and backpropagation works which is the most important function of any neural network that defines the entire working of the neural network. Here we will try to uncover the work that goes inside a black box and inspect every process and step that takes place using Excel and simple mathematics. Some of the important steps that take place in a neural network are:</p><p>- Assigning of weights, biases, and activation functions</p><p>- Forward Propagation</p><p>- Cost function to calculate error</p><p>- Back Propagation</p><p>- Adjusting of Weights(Optimization)</p><p>These steps are repeated till the right amount of weights are obtained where the cost generated from the cost function is the least.</p><blockquote><strong>Note</strong> : The weights are randomly assigned for convinent understanding.</blockquote><p>Without any further a due, let’s dive into the functioning of a neural network and for this purpose, we will begin with an extremely simple neural network and slowly build upon it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*QUA-yfaFkD7AS59FKoCknw.png" /></figure><p>In the above diagram, we have an example of a neural network that has only one input layer and one output layer and the input is represented by <strong>‘i’ </strong>and the weight by ‘w’ assigned, and the output generated here is represented by <strong>‘a’</strong> which is the product of input and weight.</p><blockquote><strong>Note</strong> : Here we aren’t considering bias and activation functions.</blockquote><p>a = i*w</p><p>Let’s assign them values;</p><p>i = 1 ; w = 4 ; Target value(y) = 2</p><p>So, the output obtained here is: a = 4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*GR3wXCVs_xdWpLR7Q9sfyA.png" /></figure><p>But we have to train the weights such that the output generated should be ‘2’ instead of ‘4’. So, our goal is to adjust the weight such that the output generated should be 2 or very close to it, and this process is known as optimization.</p><p>Let’s denote the equation of Cost function or also known as the cost function which is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryn7ZArnbOIOf2aWMGXHTQ.png" /><figcaption>Cost Function</figcaption></figure><p>ŷ = output obtained/ predicted output</p><p>y = target value/ expected output<br> So here we can notice that the cost function C is: (4–2)2 = 4</p><p>This means that we need to change the output such that the cost function decreases and that can be done by adjusting the weights. Let’s understand the equation in a mathematical form. The cost function that is given can be expressed in a graphical form too as it’s in form of x² and the diagram for that is given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*YBhJLZ1IorIktCEk_h7omg.gif" /><figcaption>Graph of equation y=x²</figcaption></figure><p>Since the graph of the cost function looks very similar to this in the case of the neural network we have taken, our role is to adjust the weight such that the point comes to the minima which can be represented below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*hxnqRIxiyCgDToM5hXb09Q.gif" /></figure><p>To understand it other words our role is to find the change in every unit of output with every unit change in the weight which can be denoted as <strong>ꝺa/ꝺw.</strong></p><h3><strong>Chain Rule of Differentiation:</strong></h3><p>We need to understand one of the basic rules of differentiation to understand how these partial derivatives work which is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6h5Ap6FTG9cqTKTjTvqh8Q.png" /><figcaption>Chain rule of differentiation</figcaption></figure><h3><strong>Back Propagation:</strong></h3><p>This rule is used a lot during the backpropagation while adjusting the weights and this is one of the most important formulas that is responsible for the backpropagation. And hence the derivative of the change in cost function due to change in weights can be shown as the product of derivate of cost function or<strong> ‘loss’</strong> w.r.t to<strong> ‘a’</strong> and derivate of <strong>‘a’</strong> w.r.t weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meB_4fYFLoKzCF_wpPao9w.png" /></figure><p>Let’s calculate for our network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QA23UgI-9s_V5vFgmauMlA.png" /></figure><p>Here, we take a small value for the learning parameter of 0.2, and later we will be experimenting with the learning parameter of different values too. Now the newly adjusted weight is given as:</p><p>w = w - (0.2) *( 4)</p><p>w = 4 - (0.2) * 4</p><p>w = 3.2</p><p>Hence the new adjusted weight is 3.2 and the output generated is: i*new weight = 1*3.2 = 3.2</p><p>But still, the new output generated isn’t close to our desired output so the same process is carried on for few more times till we get close to our expected output. In other words, the process keeps iterating again and again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CK_eWg2DKuOEHNRJ5E2w4g.png" /></figure><p>Similarly, this process is repeated till we get close to our desired output and that can be performed on excel too and the table is given below for different learning rates too. In excel we have tried for 4 different learning parameters and their weights are adjusted for every iteration. Note: At times, for different learning rate parameters certain problems can take place like Vanishing and Exploding gradient problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0zFGGX5ak6dF9NQlPuh2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zk2hpy5OPotMONrqG3WIPw.png" /></figure><p><strong>Vanishing Gradient Problem:</strong> When the learning parameter is too small as we have taken of 0.0001 the changes that take place in the weights are too small that it remains almost the same even after a lot of iterations. The problem can be seen in the above diagram where the learning rate is 0.001.</p><p><strong>Exploding Gradient Problem:</strong> When the learning parameter is a bit high then we never reach the minima and instead the values obtained are so large that it becomes computationally too heavy exploding up the calculations in the literal meaning. In the above diagram, we can see for a learning rate of 1.8 the adjusted weights after observation is too large.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*5IXnXxMmCWnV08OEF88Zmg.png" /><figcaption>Vanishing and Exploding Gradient Problem</figcaption></figure><p>But we can see that for learning rates 0.2 and 0.4 the weights are adjusted soon which helps us deriving the output very close to our expected output. And this is how a neural network works in general. So far, we have discussed taking neural networks where there are no bias and activation function and the neural networks are of a simple structure. Let’s work with few more neural networks to understand it better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*e1O5KMtIcDfBK-wbi2vG3g.png" /></figure><p>Let’s take an example of the above neural network and then adjust the weights till we get our obtained output. We will be using excel to solve the above neural network. So, let’s assign some values to the inputs and weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cb2mqOtHr0pf-I-Iy4LXyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mALXAtRRY9TouaWv55op1g.png" /></figure><p>Our main objective to train the weights or in other words, adjust the weights till the point we tend to reach the minima of the curve where the cost function error generated is of a very low value obtaining an output close to or the same as the expected output. For the given diagram let’s calculate the cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zP1znk-aucMKaurWHHRtFw.png" /></figure><p>…now the process is repeated till we get an output that is close to target values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiaJg869OW83C7S13BATTg.png" /></figure><p>… now the process is repeated till we get an output that is close to target values. And iterations are carried on and that can be calculated in an excel sheet given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*8ZmRAfA7oYFIp39vUL8otQ.png" /></figure><p>Here, we have taken two different learning rates for both the output layers, and the weights are adjusted till we obtain output similar or close to our expected outputs, and the result is presented below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJySyDIN48pskojGkFMTxg.png" /></figure><p>Now, let’s focus on a simple neural network that includes an activation function and also a bias. And we will be using a simple sigmoid activation function after we obtain the output ‘a’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*K-AvWJ0hO5TEQ2az9LKZDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNV5RiDP3hZ9653t8tOAKA.png" /></figure><p>So, for the first iteration:</p><p>w = 4 + (0.2)*[ 2(0.947) — 4(0.964) + 2(0.982) ] =&gt; 4.0001</p><p>And a similar process is carried out which can be shown in excel with different amounts of weights since here learning parameter causes a very minute change so we used weight to see a drastic change in it. We have taken two different weights at ‘w’ at 4 and the other at -0.5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*JTtE-SXioHWP5FGDiq5XLw.png" /></figure><p>In the bottom diagram, we can see the obtained output stays almost the same in the first case but for the second case, we can see how different weight and learning rates are changing causes a change in the final output which gets closer to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1tGIqOyFeOGECViSGd-cQ.png" /></figure><h3><strong>Complete Neural Network:</strong></h3><p>Now our objective is to apply all the concepts we have learned so far is a complete neural network and understand every step that is carried on in it. Here we have taken both the biases and activation function to compute values that should be close to our target value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*n0A0tRmm06BatPckUdvjoA.png" /></figure><p>Now let’s assign some values to the parameters mentioned above and carryout the forward propagation whose formulas are mentioned below:</p><p><strong>Forward Propagation</strong>: Once the weights are assigned we compute all the mentioned calculations till we obtain some outputs and then the cost function is used to calculate the error/loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZ-29Xjj4daIU1ZRk426Xg.png" /><figcaption>Forward Propagation</figcaption></figure><p><strong>Back Propagation</strong>: Now we carry one of the most crucial step that is to adjust the weights by calculating the derivatives of loss w.r.t individual weights present in both the output and hidden layer. We will first adjust the weights in the output layer and then in the hidden layer.</p><p><strong>Output Layer: </strong>The equations for the output layer are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4XSvb1GpzgScV9Pc-Qqjg.png" /><figcaption>Output Layer</figcaption></figure><p><strong>Hidden Layer: </strong>Once the weights are adjusted in the output layer then the weights in the hidden layer are adjusted and the equations for the hidden layer are shown below along with a diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*rs1m4Khgpeyb5uyquXtqkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbXO_zmqgJGIRQl67s2s-A.png" /></figure><p>Our next objective is to present that in an equation form which is given below in an unexpanded form after plugging in the above two values in Eqn. as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Ai6H8-bKEr4MTH5rOUlow.png" /></figure><p>Once, the values are obtained then they are multiplied with the learning parameter and adjusted with the actual weights, and again the similar process is repeated for multiple iterations till the point we obtain weights that produce ‘ŷ’ close to y or in other words that generate the least amount of error/loss.</p><p>In the upcoming blogs, we will be building up a neural network right from the scratch without using Keras, PyTorch, or any deep learning frameworks using only NumPy with python. And I hope my in-depth analysis and work would have brought you more clarity and an intrinsic understanding of the working of a neural network.</p><p>You can connect with me at : <a href="https://www.linkedin.com/in/sudeepdas27/"><strong>https://www.linkedin.com/in/sudeepdas27/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5053ad00d7f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Tree (CART)]]></title>
            <link>https://sudeepdas27.medium.com/decision-tree-cart-1a93a9d3cef2?source=rss-3b6d022742a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a93a9d3cef2</guid>
            <category><![CDATA[gini-index]]></category>
            <category><![CDATA[entropy]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sudeep Das]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 05:15:59 GMT</pubDate>
            <atom:updated>2021-02-07T05:35:57.041Z</atom:updated>
            <content:encoded><![CDATA[<p>Decision tree is one of the most important models as it lays out an important concept that is used for other machine learning models like Random Forest, XGBoost, bagging &amp; boosting, etc which all together come under the ensemble methods. It’s a tree-shaped model consisting of root nodes, branches, and internal &amp; leaf nodes which are mostly used for supervised learning. So, it’s really important to understand the concept of a decision tree and here we have explained the functioning of decision trees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*90M9ZYC8DVtMs-QJodwTBg.png" /></figure><p>A decision tree can be broadly categorized into — <strong>Regressors</strong> &amp; <strong>Classifiers</strong> and hence this is where it has received its name <strong>Classification and Regression Trees (CART).</strong> They both play a different function like the classification trees have the role of classifying targets e.g., Customers being loyal vs fraud. Whereas, decision tree regressors are mostly used to predict and find the continuous values e.g., Changing prices of houses.</p><blockquote>Some of the important parameters in the decision tree are <strong>Gini Index, Entropy, Information Gain, Purity.</strong></blockquote><p>i) <strong>Purity</strong>: Purity can be of two types and they are pure &amp; impure. Pure means that the leaf holding data has all the data belonging to the same particular class and impure means that the leaf holding the data has a mixture of different classes.</p><p>ii) <strong>Entropy</strong>: Entropy is used to calculate the purity of the branch and nodes and the mathematical formula for it is given below. Here “p” stands for probability of a particular class in that total class of variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*mk1jM4Cz368_jyOq8yyQoA.png" /></figure><p>iii) <strong>Gini Index: </strong>Gini index is similar to the entropy apart from the fact that it doesn’t consider the logarithmic values and is computationally less heavy as compared to the entropy. It’s used to find the probability of a particular class out of the total classes being classified correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*kL2BvZXTMTl-ndPKc1LsRw.png" /><figcaption>Gini Index</figcaption></figure><p>iv) <strong>Information gain:</strong> Information gain is generally used to find out the tree that produces less entropy or Gini index value. The tree that produces the highest information gain, that tree is considered for further splitting and then that tree is chosen and the same process repeats till the end, and that way accuracy increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*_xke5CUq1Nk50St-29xFeA.gif" /></figure><h3><strong>Entropy vs Gini Index</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Rj8jVJBzSUwy3NYMEXZREA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*a_CG5vnztpwAAIEmaU3ZHA.png" /></figure><p>The <strong>entropy </strong>lies within a range of 0 to 1 with its max impurity index in the range of 0 to 1. Whereas, Gini index lies within a range of 0 to 1 and the impurity index of 0 to 0.5 since it doesn’t consider the logarithmic expressions. Calculating entropy is computationally heavy as compared to the Gini index and for that reason, the Gini index is opted over entropy. Generally, the entropy at a leaf node where its data classes are split into equal parts leads to the highest entropy.</p><h3><strong>Pruning</strong></h3><p>At times the tree obtained can be of a larger size and can include those branches and leaf nodes that have low importance so they are pruned to decrease the size of the tree and to increase the accuracy. A few of the pruning techniques are:</p><p>1. Reduced error pruning</p><p>2. Cost complexity pruning</p><p>3. Weakest link pruning</p><p>We picked up a dataset on breast cancer where we test out our algorithms of decision trees and random forest which goes through multiple parameters to predict whether the patient has breast cancer or not. Then after applying our model we check for the accuracy of our model to see how correctly our model predicts the values. Then we apply <strong>cost complexity pruning </strong>as it uses a parameter of <strong>alpha</strong> which is called <strong>learning parameter</strong> and the alpha rate that generates the highest accuracy is taken for the pruning step. One more important point is that in the case of decision trees, the outliers don’t impact the metrics(accuracy) as they use probability and for such outlier, the probability would be so small that it wouldn’t be considered.</p><p>And here we have explained the decision tree algorithm using python.</p><p>We at first import the dataset of breast cancer and install are the prerequisite packages that are needed. The breast cancer dataset holds up to 31 parameters including the target. All the 30 parameters are loaded into the X except the target variable which is loaded in y.</p><p>Then, the dataset is split into a ratio of 20% for tests and 80% for training. The Decision tree classifier is called as clf and the values from the dataset are fit upon the model which later on predicts the values from which we receive an accuracy of <strong>94.73%</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erCXBt-axKq4S5nSjxTXog.png" /></figure><p>And this is how the decision tree looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gio6Jseg1Ikyf1fu8dGvw.png" /></figure><p>Since the tree we received is of a very large shape and it also consists of nodes whose value is too less and then to avoid such a problem we use the Cost Complex Pruning method to further increase our accuracy and to decrease the size of the tree by removing the nodes and branches that are of low importance.</p><p>After assigning the alphas we get these values of alphas and impurities are calculated as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*onEcz0t_z5sTQ2YW1G7SVQ.png" /></figure><p>After receiving the different values of alphas, we iterate our classifier over different values of alphas and then we plot a graph of train scores and test scores between accuracy on different alpha values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjNkRuZADYRTebJ_tH7RGA.png" /></figure><p>These are accuracies that we receive after iterating it over different alpha values and the graph we plot is given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*viFHSQrXU5lKtHE4NXW_iQ.png" /></figure><p>And after once we obtain the graph, we choose the alpha rate for which the accuracy is the highest and that is the same for a few of the 5 values. On computing the accuracy from those values, we receive an accuracy percentage of <strong>95.61% </strong>post pruning as compared to the <strong>94.73%</strong> obtained before the pruning of the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*Iv0opSYAbyU0CmlmJVUlRA.png" /></figure><p>And here is the tree we receive after the pruning is done and the figure is given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STRqMByJ0Nceheo3klhsTA.png" /></figure><p>You can connect with me at : <a href="https://www.linkedin.com/in/sudeepdas27/"><strong>https://www.linkedin.com/in/sudeepdas27/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a93a9d3cef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>