<?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 Vikas Jha on Medium]]></title>
        <description><![CDATA[Stories by Vikas Jha on Medium]]></description>
        <link>https://medium.com/@jha-vikas?source=rss-e1b2c82684b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XxHHER8J78DLE2yplXv0lg.jpeg</url>
            <title>Stories by Vikas Jha on Medium</title>
            <link>https://medium.com/@jha-vikas?source=rss-e1b2c82684b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:22:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jha-vikas/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[Deep-dive into Variational Autoencoders]]></title>
            <link>https://medium.com/analytics-vidhya/deep-dive-into-variational-autoencoders-d66c4a3df236?source=rss-e1b2c82684b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d66c4a3df236</guid>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vikas Jha]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 16:45:32 GMT</pubDate>
            <atom:updated>2021-06-11T16:12:53.488Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In previous posts on autoencoders (<a href="https://medium.com/analytics-vidhya/under-and-over-autoencoders-3d695f428c1a">Part 1</a> &amp; <a href="https://medium.com/analytics-vidhya/implementing-under-over-autoencoders-using-pytorch-4ddaf458947e">Part 2</a>), we explored the intuition, theory and implementation of under and over-autoencoders. The autoencodes have two parts: encoder and decoder. The encoder moves the input to the latent space, while the decoder tries to get the input representation back from the latent space representation.</p><h4>The problem with classical autoencoders</h4><p>However, the encoder in these cases are deterministic in nature, i.e. the map a value in input to a point in latent space, which is subsequently mapped back to input space by decoder. However, a good autoencoder should not be learning point representation of input data, but more of a distribution of the latent space features owing to two reasons:</p><ul><li>The characteristics of data do not have a point representation. They have a distribution.</li><li>The manifold structure of the input data should be smooth and not disconnected.</li></ul><p>Varational autoencoders(VAE) try to address these issue by using a probabilistic model of latent representations which understands the underlying causal relations better, helping in more effective generalization.</p><h3>Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*-Rq74Gjw9F4vx2c7rD1niw.png" /></figure><p>Consider <em>z</em>, the latent space or hidden representation, and input <em>x</em>, and let <em>z </em>have a probability distribution <em>p(z)</em>.</p><p>For generalization, we would like to have <em>p(x). </em>We have access to only <em>x</em>, we would like to capture <em>p(z|x).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*7sVpsjYmQuaCalzkpiKxig.png" /></figure><p>So, to capture <em>p(x)</em>, we need <em>p(z).</em> However, as <em>z</em> is inaccessible, we cannot know the distribution of z and subsequently p(z), making this problem intractable.</p><p>However, there is another way to solve this issue. Latent variable z can be forced to follow a known distribution. This what VAE does. In VAE, we enforce Gaussian distribution on latent variable z. Gaussian distribution can be characterized by the mean and the variance, which are estimated by the input values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*AVIuncW8MA_bWTAOTx3Wgg.png" /><figcaption>VAE strucure. Source: author</figcaption></figure><p>VAE has 3 components:</p><ul><li>Encoder: It encodes the input vector in <em>n</em> dimensions into <em>2h</em> dimensions. <em>h</em> is the dimensions of the latent space. Here, <em>2h</em> dimensions represent the <em>h</em> means and <em>h</em> variances concatenated.</li><li>The sampler: It takes the <em>2h</em> dimensional long vector and creates Gaussian distribution based on the h means and h variances, from which the <em>z</em> value used for output is sampled.</li><li>The decoder: It takes the Gaussian distribution and outputs the reconstructed vector, which is compared to the input vector to calculate the loss.</li></ul><h4>How to enforce structure in latent variables distribution</h4><p>Let’s consider what the classical autoencoder loss function, i.e reconstruction loss does here. The distribution of z can be thought as bubbles in latent space. The reconstruction loss is minimized when the bubbles don’t overlap at all, as the overlap will bring a point of ambiguity. Hence, the reconstruction loss pushes the bubbles of z distribution as far as possible from each other. If there is no regulation on how far these bubbles can lie, the reconstruction loss would would push them too far apart, making the distribution negligible compared to the space in which bubbles are located, defeating the whole purpose of the getting the distribution in the first place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*QF84UzVP6Uf2XZuYF2UMXQ.png" /><figcaption>z distribution bubbles floating away thanks to reconstruction loss. Source: author</figcaption></figure><p>Hence, we need a term in loss which can tie the distribution bubbles down, and enforce the Gaussian distribution on individual bubbles. This role is done by KL divergence of the Gaussian distribution with respect to the normal distribution with zero mean and unit variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*xHif6Q0a81AGy7EgtSwY3w.png" /><figcaption>Loss in VAE. source: author</figcaption></figure><p>The KL divergence(or relative entropy) of the Gaussian with respect to a standard normal distribution is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*50knaAlYx5UZ7-kIqrwD3A.png" /><figcaption>KL divergence of Gaussian distribution with mean E(z) and variance V(z). source: author</figcaption></figure><p>The last term of the KL divergence puts a L2 penalty on the means of the latent variables, pulling them towards the origin, stopping them from wandering away. The rest of terms i.e. V(z)-log(V(z))-1 has a minima at V(z) at 1 which is obvious at we are finding the relative entropy with respect to the standard normal distribution. Hence, the composite loss term strikes a balance between reduction of reconstruction error and the difference from the standard normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*eMlpu1EVYoJv_cjNtXI1vQ.png" /><figcaption>V(z) vs V(z)-log(V(z))-1. source: author</figcaption></figure><h4>The reparameterisation trick</h4><p>We do the sampling from the Gaussian distribution for the latent variable (z) which is fed to the decoder. However, it creates a problem in backpropagation and consequently optimizing, because when we do gradient descent to train the VAE model, we don’t know how to do backpropagation through the sampling module.</p><p>Instead, we use reparameterisation trick to sample for <em>z</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*ZQQYsAemGKJ7aF71mUbDcQ.png" /></figure><p>Now, the backpropagation is possible, as the gradients with respect to <em>z</em> have to go through the sum and product functions only.</p><h3>Implementation using PyTorch</h3><p>We will be using the MNIST dataset for explanation.</p><p>The data loading and transformation steps are similar to the classical encoders. We will be focusing on the architecture of the VAE here.</p><p>We define a simple VAE in terms of 3 units, encoder, decoder and sampler. The sampler implements the reparameterisation trick discussed above.</p><h4>Base architecture</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb247dbdf9e58226bf9f3bf52576aded/href">https://medium.com/media/eb247dbdf9e58226bf9f3bf52576aded/href</a></iframe><p>The input dimensions(784) correspond to the MNIST image size of 28x28. The input data is moved from 784 dimensions to 400(<em>dxd</em>) dim, passed through non-linear layer (ReLU) and then moved to <em>2d</em> hyperspace, where d = 20. The latent space is <em>d</em>(20) dimensional. We need <em>2d</em> dimensions as it is concatenation of <em>d</em> means and <em>d</em> variances.</p><p>The decoder module is also very similar to classical autoencoder. It takes a d dimensional latent space vector, passes it through set of linear and non-linear layers and outputs final vector of size 784, same as input.</p><p>The magic happens in the sampler layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c4ccb14622a53860880d6906f91c82a/href">https://medium.com/media/8c4ccb14622a53860880d6906f91c82a/href</a></iframe><p>The sampler module takes the 2d vector and returns z based on reparameterisation trick. One thing to note here is that we do not input variance into the sampler layer, but log of variance. It is so as variance has to be positive, while log of variance can be negative too. It makes sure that the variance is always positive and we are able to use the full range of values as input. It makes the process more stable too.</p><p>Next we define the loss as sum of reconstruction loss and KL divergence. The training is similar to classical autoencoder and has been covered in earlier <a href="https://medium.com/analytics-vidhya/implementing-under-over-autoencoders-using-pytorch-4ddaf458947e">article</a>.</p><p>Before training, this is the reconstruction we are getting, where top row is the original, and bottom is reconstruction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5stT1UOGa1H7tjIWShSZug.png" /><figcaption>Reconstruction before training. source: author</figcaption></figure><p>After just 20 epochs, following are the results of the reconstruction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFDdfr1fDsFRSQ-6TsScSA.png" /><figcaption>Actual vs reconstruction by VAE after training. source: author</figcaption></figure><p>To look at the latent space vectors, we generate few random samples and use decoder to generate a sample:</p><p>z_sample = torch.randn((8, d)).to(device)<br>sample_out = model.decoder(z_sample)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpqp1x7Z3hlHP_1DINSMgQ.png" /><figcaption>Decoded data of latent space</figcaption></figure><p>We can see that the latent space has learnt the representation of the digits, though not complete. With more epoch of training, the latent layer can capture the input feature even better.</p><h4>Interpolation between two inputs</h4><p>We can use the latent space representations to interpolate between two inputs(images here), by taking the weighted mean of the latent space representation. Consider digits 0 &amp; 6. We can look at the gradual steps in turning a 0 to a 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*0mmN0c3Rh2lCgSzZm-OPag.png" /><figcaption>Turning a 0 to 6. source: author</figcaption></figure><p>Each step of the transformation defines the latent variable of interpolated image as:</p><p>z_interpolation = ((i/N)*z_6 + (1-i/N)*z_0) where i ranges from 0 to 8<br>output_interpolation = model.decoder(z_interpolation)</p><h3>Conclusion</h3><p>As we have seen, the Variational Autoencoders represent latent variables in terms of not points, but as probabilistic cloud or distribution. Not only it helps in making latent space representation more general, but also it makes the manifold more connected and smooth. The underlying concepts of the VAE simulates data generation process, which can be further used in GANs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d66c4a3df236" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/deep-dive-into-variational-autoencoders-d66c4a3df236">Deep-dive into Variational Autoencoders</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing under & over autoencoders using PyTorch]]></title>
            <link>https://medium.com/analytics-vidhya/implementing-under-over-autoencoders-using-pytorch-4ddaf458947e?source=rss-e1b2c82684b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ddaf458947e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vikas Jha]]></dc:creator>
            <pubDate>Thu, 20 May 2021 11:36:28 GMT</pubDate>
            <atom:updated>2021-05-21T18:25:08.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SyLW-TLN5NLKPEpo" /><figcaption>Photo by <a href="https://unsplash.com/@cebbbinghaus?utm_source=medium&amp;utm_medium=referral">Christopher Robin Ebbinghaus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Autoencoder is a neural network which converts data to a more efficient representation in latent space using encoder, and then tries to derive the original data back from the latent space using decoder. The bottleneck or the constraint applied to information flow obviates the direct copying of data between encoder and decoder, and so the network learn to keep the most general and efficient representation of the data, while ignoring the noise or temporary patterns.</p><p>Autoencoders can be implemented from scratch in python using numpy, which would require implementing the gradient framework manually. However, <a href="https://en.wikipedia.org/wiki/Differentiable_programming">differentiable programming</a> is available in python through efficient frameworks like <a href="https://en.wikipedia.org/wiki/PyTorch">PyTorch </a>which will be used for the current article.</p><h3>Brief visit to architecture</h3><p>As described in my <a href="https://medium.com/@jha-vikas/under-and-over-autoencoders-3d695f428c1a">article</a>, one of the many ways to look at the autoencoders is to characterize them based on the hidden/intermediate layer or latent space dimensions. If the information flow bottleneck in autoencoder is applied by restricting the dimension of the hidden/intermediate layer, then it is under-autoencoder, otherwise it is over-autoencoder. In latter case, the information bottleneck is applied by introducing noise in the input data, or modifying the loss function, reducing the effective space in which the latent space representations can lie.</p><h3>Data</h3><p><em>DataLoader </em>from torch is used to create iterable/map style over dataset for multiple batches. torchvision contains <em>transforms</em> module which contains transformation methods. They can be chained together to apply all transformations on the images in one go. The pixel values in MNIST dataset is scaled in range -1 to +1, from 0 to 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04c0fc164b4d5b471aef042051191da4/href">https://medium.com/media/04c0fc164b4d5b471aef042051191da4/href</a></iframe><p>PyTorch expects data in form (batch size, channel, height, width). In case the data is in some other form, proper transformations should be executed to bring it in the required form.</p><p>Also note that torch.nn.Functional(often imported as F) contains some useful functions like activation functions a convolution operations which can be used. However, these are<strong> not</strong> full layers. So, to specify a layer, torch.nn.module should be used.</p><h3>Fully connected and Convolution autoencoders</h3><p>The autoencoder will be implemented in two ways, fully connected network and Convulational network. Former has more weights, and can be implemented in most kind of data. CNNs are good for signals/inputs that come in the form of multidimensional arrays and have three major properties, locality(presence of strong local correlation between values), stationarity(properties of the signal repeat themselves, hence shared weights can be used) and<strong> </strong>compositionality(features compose image in hierarchical manner, justifying use of multiple layers to identify different level of detail).</p><h4>Model architecture: Fully connected autoencoder</h4><p>We define Autoencoder class inherited from parent class nn.Module. The input is tensor of size 28x28(as the MNIST images are of size 28x28). Encoder and decoder layers are specified inside the Autoencoder class. The forward pass is defined as data being passed via encoder followed by decoder. The output post the forward pass is compared with the input, giving the loss. Mean square error is taken as loss function here as the pixel intensity is continuous. For categorical data, loss functions like cross-entropy will be more suitable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6b1fd9bd1ab3e3b4580ff7bae15a630/href">https://medium.com/media/f6b1fd9bd1ab3e3b4580ff7bae15a630/href</a></iframe><h4>Model architecture: Convulational autoencoder</h4><p>The architecture of the convulational autoencoder is similar, except that instead of feeding a long single vector with specified channels and batch size(thus a 3-d vector), a 4-d vector is fed with batch size, channel, height and width as dimensions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d09be57205bc185f9f52893be716efc/href">https://medium.com/media/0d09be57205bc185f9f52893be716efc/href</a></iframe><h4>Training Loop</h4><p>It is a typical training loop used in training any neural network:</p><ul><li>The image is moved to device(CPU or GPU). The output is calculated.</li><li>Based on output, loss is calculated.</li><li>The gradients are zeroed.</li><li>Back-propagation and accumulation are implemented.</li><li>Optimizer.step() moves the weights opposite to the direction of gradients in magnitude guided by learning rate.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c898164fa100478511ac090408254a86/href">https://medium.com/media/c898164fa100478511ac090408254a86/href</a></iframe><h3>Results</h3><h4>Under-autoencoder</h4><p>For under-autoencoders with hidden layer/latent space dimension 30 compared to the input dimension of 28x28=784, after 20 epochs, we get following reduction in MSE:</p><pre>epoch [1/20], loss:0.1892<br>epoch [2/20], loss:0.1600<br>epoch [3/20], loss:0.1274<br>epoch [4/20], loss:0.1137<br>…..<br>epoch [18/20], loss:0.0520<br>epoch [19/20], loss:0.0558<br>epoch [20/20], loss:0.0574</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*32YtebG6-vTcVeqwVZPwDw.png" /><figcaption>Images from under-autoencoder</figcaption></figure><p>The top row shows the actual images, and the bottom row shows corresponding recreated image. As we see, in case of third and fourth column, the recreation is not very clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*X3G3Lfa_a5uIWxyV8s77bQ.png" /><figcaption>Weights in Linear layer of Encoder for under-autoencoder</figcaption></figure><p>Looking at the some of the weights of the linear layer of the encoding, it is clear that there are weights which seem to be just random noise(Fourth column of first row and third column of second row), with no pattern in activations. Other weights seem to be capturing some patterns.</p><p>Let’s compare them with the output of over-autoencoder.</p><h4>Over-autoencoder</h4><p>Consider over-autoencoder with hidden layer/latent space dimension as 500. However, as we know the input data dimension is 28x28=784, how can this be called an over-autoencoder? The answer lies in the the effective dimension of the input. More than 80% of the input image pixels do not contribute to the image of the numerical. Hence, the effective dimension of the input layer is only around 150, which is the average number of active pixels in the images. Surround area is mostly dark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*GUfNYv1rhqbEJva5Bx28NQ.png" /><figcaption>Images from over-autoencoder</figcaption></figure><p>There are three rows of images from the over-autoencoder. The top row is the corrupted input, i.e. image which was fed to the autoencoder (after adding the noise). Second row has the reconstructed image, and the third row shows the actual input image before corruption.</p><p>Even with visual inspection, it is apparent that over-autoencoder is performing better than under-autoencoder. The assertion becomes clearer if you look at the loss values:</p><pre>epoch [1/20], loss:0.0702<br>epoch [2/20], loss:0.0594<br>epoch [3/20], loss:0.0551<br>epoch [4/20], loss:0.0519<br>epoch [5/20], loss:0.0534<br>epoch [6/20], loss:0.0463<br>....<br>epoch [16/20], loss:0.0415<br>epoch [17/20], loss:0.0416<br>epoch [18/20], loss:0.0423<br>epoch [19/20], loss:0.0400<br>epoch [20/20], loss:0.0407</pre><p>The over-autoencoder converges faster than under-autoencoder. Even the final loss value is lower than under-autoencoder. It is because the input is expanded to higher dimensional space where it can move in much more number of ways to fit the model to actual manifold, even when there is constraint in terms of data flow. For under-autoencoders, we move from a higher dimensional hyperspace to lower dimensional one, where the movement is much more constrained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*yLpRHHLerLWXxYBdCGXHtA.png" /><figcaption>Weights in Linear layer of Encoder for over-autoencoder</figcaption></figure><p>The weights seemed to have learnt better representations too, with hardly any weight devoid of any patterns.</p><h4>Convulational autoencoder</h4><p>Convulational autoencoder presented here are also a type of over-autoencoder as 1 channel data is moved to 16 channels. Further, due to CNN layers being specialized for the image type data, they fit faster compared to the autoencoders mentioned above. Considering the loss value over epochs:</p><pre>epoch [1/20], loss: 0.0497<br>epoch [2/20], loss: 0.0227<br>epoch [3/20], loss: 0.0172<br>epoch [4/20], loss: 0.0143<br>epoch [5/20], loss: 0.0124<br>epoch [6/20], loss: 0.0114<br>epoch [7/20], loss: 0.0105<br>epoch [8/20], loss: 0.0088<br>...<br>epoch [16/20], loss: 0.0050<br>epoch [17/20], loss: 0.0045<br>epoch [18/20], loss: 0.0043<br>epoch [19/20], loss: 0.0040<br>epoch [20/20], loss: 0.0038</pre><p>As expected the loss quickly reduces and reaches much lower value compared to under and over-encoders based on conventional fully connected layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*tsdVsmgVa7w1-kpQPhR43g.png" /><figcaption>Images from convulational-autoencoder</figcaption></figure><p>Visual inspection of the images generated validates our hypothesis. The three rows represent the noisy data sent as input to encoder, the generated clean output and the actual clean input respectively.</p><h3>Conclusion</h3><p>Based on the implementation and the results on MNIST dataset, it is clear that over-autoencoder is outperforming the under-autoencoder due to bigger latent space where it gets the freedom to model the manifold more accurately. However, it is more to prone to over-fitting too.</p><p>On the other hand, convulational autoencoders(which are over-autoencoders too) outperform fully connected layer based autoencoders because they take the properties of images into account to extract better representation of the data in hand.</p><p>In all the autoencoders mentioned above, there is a flaw that they are mapping a point in input hyperspace to a point on manifold. However, it would be better to generalize by mapping points to a vector field in the manifold instead of discrete points which would give a smoother mapping of manifold. The Variational Autoencoders(VAE) achieve that by introducing a conditional distribution with mean as point value of the latent representation and some variance. We will be looking at VAEs in subsequent articles.</p><p>For the full script: <a href="https://github.com/jha-vikas/pyTorch-implementations">https://github.com/jha-vikas/pyTorch-implementations</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ddaf458947e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/implementing-under-over-autoencoders-using-pytorch-4ddaf458947e">Implementing under &amp; over autoencoders using PyTorch</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under and over autoencoders]]></title>
            <link>https://medium.com/analytics-vidhya/under-and-over-autoencoders-3d695f428c1a?source=rss-e1b2c82684b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d695f428c1a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[manifold]]></category>
            <category><![CDATA[autoencoder]]></category>
            <dc:creator><![CDATA[Vikas Jha]]></dc:creator>
            <pubDate>Fri, 14 May 2021 17:23:09 GMT</pubDate>
            <atom:updated>2021-05-25T17:49:09.802Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GPLwPoEu-wCr4Smu" /><figcaption>Cat &amp; Dog (source: Photo by <a href="https://unsplash.com/@tranmautritam?utm_source=medium&amp;utm_medium=referral">Tran Mau Tri Tam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>)</figcaption></figure><p>If a person is shown same size images of a dog and a cat, and asked what image would lie halfway between them, a sensible answer would not be to take the images’ pixel value and take mean of them. However ridiculous it might sound, the reasonable answer would be some sort of an image of an animal which is half cat and half dog.</p><p>Or as a more sensible example, consider an image of a building at night. If one wants to see how it looks in the day, the right approach would not be to take individual pixels and move the intensity more towards white. The target image should take care of the individual pixel’s response to sunlight, how the pixels in different location might respond to light differently, and multiple other factors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K5ECAuAPZ3Bq-HT4" /><figcaption>Photo by <a href="https://unsplash.com/@rachitchaudhary?utm_source=medium&amp;utm_medium=referral">Rachit Chaudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The common factor in both cases is that image reconstruction or modification, if performed in pixel space gives rather non-natural and bad result. However, humans are able to imagine and visualize in both the cases how the end result might look like. Humans are definitely not thinking in pixel space.</p><h3>Latent Space</h3><p>The reason humans are able to process the images and visualize what a non-existing mix of cat or dog will look like, or look at a building in night and picture what that building might look like in daylight is because human thinking seems to operate in latent space. Latent space is abstract multi-dimensional space containing latent variables, which are feature vectors that encode the useful generic information/representation of easily observable features. Latent space contains the internal hidden representation of the actual vector. It is not only applicable for images, but for any kind of information.</p><p>The real world high dimensional data is supposed to lie in low-dimensional (latent space) manifolds embedded within the high dimensional space(Manifold hypothesis). Capturing manifold capture the latent space characteristics which will help in learning the generalized features of the data. For example, consider Swiss Roll 3-d representation of data with multiple classes represented by different colours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*Tvl2neTlLsiRwCyT.png" /><figcaption>Fig 1. Swiss Roll Data representation (source: <a href="https://i.stack.imgur.com/pa1FR.png">https://i.stack.imgur.com/pa1FR.png</a>)</figcaption></figure><p>The real world data lies in 3 dimensions. No linear separator can separate the classes. However, if the actual manifold representation is understood, not only separating the different classes becomes easier, but also imputing is more effective.</p><p>On the same lines, the learning of latent space representation forces the system to learn a more efficient representation of the data.</p><h3>Autoencoders</h3><p><em>An autoencoder is a type of artificial neural network used to learn efficient data codings in an unsupervised manner.(Wikipedia)</em> The autoencoder filters the noise and learns the encodings(representation) of the data is lower dimensional hyperspace. As there is no target variable, the learning of the autoencoder is unsupervised. The output in autoencoder is produced from the encoded representation of the input.</p><h4>Why predict the output that we already know as input?</h4><p>The predict output produced by encoder is compared with the input. The difference between the two represented as loss is hence used to learn the weights inside the autoencoders. The function to calculate the loss depends on the input type and task at hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*qhMrxAfafAN_FAM1NtTAsQ.png" /><figcaption>Fig 2. Basic Autoencoder</figcaption></figure><p>Autoencoder has two parts:</p><ol><li>Encoder: It converts the input to the encodeded representation. The code ‘h’ in Fig 2 is the latent space.</li><li>Decoder: It takes the encoded representation and provides output based on that.</li></ol><h4>Little taste of mathematics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*PTm8LGWsOLJQo710eH3C0Q.png" /></figure><h4>Reconstruction loss</h4><p>Let loss be represented by <em>L</em>. Loss can be calculated as mean of individual losses over data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*QdE5bcykmYtHq0TLpYXrcg.png" /></figure><p>As we see in the calculations, input and output, both lie in the same dimensional(<em>n</em>) hyperspace. The encoded representation lies in a different dimension represented by <em>d</em>. Based on the dimension (<em>d</em>) of the latent space, we can have two types of autoencoders.</p><h3>Under and over-autoencoders</h3><p>When d &lt; n, the autoencoder is under-autoencoder. It forces the learning of efficient representation of the input by creating a bottleneck in the dimensions/ degree of freedom through which information can be passed and learnt.</p><p>However, when d ≥ n(over-autoencoder), the encoder and decoders can be just identity functions, resulting in the output which is same as input. It is because the loss function penalizes on the dissimilarity of the input and output. The simplest way to do that is to just copy the input without any changes, which is made possible by passing input signal through identity functions in encoder and decoder. The autoencoder here is overfitting. Autoencoder should be able to reconstruct the data which lives on the manifold, ignoring the points in data which represent noise. The enforce policy that autoencoder should only be able to reconstruct a small set of input which lies on the manifold. Autoencoder should not be able to reconstruct the data points which lie away from the manifold.</p><p>Under-autoencoder’s encoder and decoder layers cannot act as identity functions as the latent space/hidden layer does not have enough dimensions to copy the input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*LEzWpEqkw0pLT7zB.jpg" /><figcaption>Missing pixels (source: <a href="https://paperswithcode.com/task/facial-inpainting">https://paperswithcode.com/task/facial-inpainting</a>)</figcaption></figure><p>For instance, if an autoencoder is trained on images of faces, and a new face is given with a part removed(missing/masked image), the autoencoder should be reconstructing only those pixels which lie on facial manifold it has learnt. It is similar to how humans would impute the rest of face after observing a partial face. Any variation applied to input later is considered as noise by autoencoder and be ignored as network will be indifferent to those points.</p><h4>Then why take d ≥ n?</h4><p>If an over-autoencoder having hidden layer(latent space) dimension greater than input dimension is so prone to overfitting, and might end up with encoder and decoder both represented by identity matrices, what is the point of using it? The answer is that the larger intermediate representation i.e. expanded space compared to input space makes it easier to extract features and optimize because there is more space to move around.</p><p>However, to avoid the issue to identity matrix copying the input data to output directly, constraints in data flow has to be introduced. The constraints force the network to choose a selective subset of larger intermediate hidden space.</p><p>The constraints can be applied by introducing noise(<strong>Denoising autoencoder</strong>) in input, and learning the weights by comparing the output to actual clean input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*BgVfKyax-E_6wqZkExPOwQ.png" /><figcaption>Denoising autoencoder</figcaption></figure><p>Another way to add constraint is to regularization term.<strong> Contractive autoencoder</strong> adds ‘squared norm of the gradient of the hidden representation with respect to the input’ to the reconstruction loss. While reconstruction loss penalizes for insensitivity to reconstruction directions, the squared norm of the gradient penalizes for sensitivity to any direction. The added term to reconstruction loss reduces the variance in the hidden layer/latent space representation, by increasing bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lfckBRGz1A32AHnR.png" /><figcaption>Contractive autoencoder(source:<a href="https://atcold.github.io/pytorch-Deep-Learning/en/week07/07-3/">https://atcold.github.io/pytorch-Deep-Learning/en/week07/07-3/</a>)</figcaption></figure><p>As over-autoencoders are high variance models, introduction of constraints reduces variance increasing the bias. The aim here is to get to the sweet spot where the margin increase in bias becomes equal to marginal reduction in variance, eliminating the reason of any further tradeoff.</p><h3>Conclusion</h3><p>We have understood the fundamental idea behind how autoencoders work, i.e. by trying to find a latent space representation of the data which captures its actual generic and the most important features. The data is assumed to lie in a lower dimensional manifold, and the autoencoder tried to extract that represent from the data provided.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d695f428c1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/under-and-over-autoencoders-3d695f428c1a">Under and over autoencoders</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple perspectives of Linear Regression]]></title>
            <link>https://jha-vikas.medium.com/multiple-intuitive-perspective-of-linear-regression-65d3a2e242d2?source=rss-e1b2c82684b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/65d3a2e242d2</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Vikas Jha]]></dc:creator>
            <pubDate>Wed, 12 May 2021 17:17:07 GMT</pubDate>
            <atom:updated>2021-05-12T17:18:22.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4hmL4L7QswiYPzbG" /></figure><h3><strong>Introduction</strong></h3><p>As a student of econometrics or data science or statistics, one would come across Linear Regression as one of the first and fundamental algorithms. Linear Regression is an approach for supervised learning for a quantitative response or output. As the name suggests, linear regression approximates a quantitative response <strong><em>Y</em></strong> based on set of inputs or features, represented by <strong><em>X</em></strong>, assuming that a linear relationship exists between <strong><em>X</em></strong> and <strong><em>Y</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*h1av5mAZVOMStqqhwaz9tA.png" /><figcaption>Fig 1: Example of Simple Linear Regression (source: G. James et al., An Introduction to Statistical Learning: with Applications in R)</figcaption></figure><p>For instance, Fig 1 plots sales as a function of advertising budget. Individual data points are represented by red points. The grey line represents sales as a linear function of advertising budget in TV. The linear function is the best representation of the sales as function of TV advertising budget as it minimizes the squared sum of errors(represented by light grey vertical lines).</p><h3>Why multiple perspectives?</h3><p>A concept can be very well derived by mathematical manipulation of formulae. However, that might not lead to conceptual understanding of the intricacies. Visiting a problem from multiple perspectives helps in understanding the fundamental idea behind the concept, broadening the scope in which a concept can be applied.</p><h3>Multiple perspectives</h3><h4>1. Minimization of Mean Square Error</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*dRE85bGYdUrNmV61l1YkZA.png" /></figure><p>The minimization is performed analytically using calculus by differentiating error term with respect to coefficients.</p><h4>2. Using Projection</h4><p>Another perspective of linear regression is through projection of hyperplane formed by output, on the hyperspace formed by inputs. For simplicity, let us assume that we have two input variables(<em>x1 &amp; x2</em>), and an output variable <em>y</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*nEAQC4i6jJa6GGIdrZErDg.png" /><figcaption>Projection of y on hyperplane formed by X (source: G. James et al., An Introduction to Statistical Learning: with Applications in R)</figcaption></figure><p>The best possible estimate of <em>y</em>, using <em>x</em> is the projection of y on the hyperplane formed by x. In current case, it is the projection of y on the 2-d plane formed by <em>x1 &amp; x2</em>.</p><p>The error term is the normal from the 2d plane(x1-x2) to y. The concept can be generalized to higher dimensions. The combination vector whose dot-product with input variables of x which form the projection is the coefficient vector.</p><h4>3. As approximate Normal distribution</h4><p>The OLS can be also represented as:</p><p>y ~ N(<em>𝑋𝛽</em>, <em>e</em>)</p><p>Linear regression can be also thought of as approximating y in the form of a normal distribution with mean <strong><em>𝑋𝛽</em></strong><em> </em>and standard deviation as <strong><em>e</em></strong><em>.</em></p><p>For uni-variate case, if the inputs and outputs are centered by subtracting the mean, y is approximated by uni-variate normal distribution.</p><h3>Conclusion</h3><p>Although the three perspectives for Linear Regression might seem different on the surface, the underlying concept of approximating the output as a linear combination of inputs is same. The coefficients obtained are equal in all the three cases. In fact, if we derive the formulae for coefficients’ calculation analytically from methodologies 1 &amp; 2 (minimization of MSE &amp; projection), we arrive at the same result. Same can be verified for methodology 3 too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65d3a2e242d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning ver3 Lesson 4]]></title>
            <link>https://jha-vikas.medium.com/deep-learning-ver3-lesson-4-8f085a1e28ca?source=rss-e1b2c82684b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f085a1e28ca</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vikas Jha]]></dc:creator>
            <pubDate>Thu, 15 Nov 2018 10:00:13 GMT</pubDate>
            <atom:updated>2018-11-15T10:00:13.231Z</atom:updated>
            <content:encoded><![CDATA[<p>Refer notes: <a href="https://medium.com/@boy1729/deep-learning-ver3-lesson-1-99005e886132">Lesson 1</a>, <a href="https://medium.com/@boy1729/deep-learning-ver3-lesson-2-d69333b51253">Lesson 2</a>, <a href="https://medium.com/@boy1729/deep-learning-ver3-lesson-3-c9443ff3b264">Lesson 3</a></p><p>This article is compiled based on my notes on Lesson 4 of Deep Learning for Coders ver3.</p><p>· Caution: Update the fastai library and course material before running any code.</p><p>Jeremy started with IMDB Reviews Dataset analysis.</p><h3>IMDB Reviews Dataset</h3><p>Continued from lesson3</p><p>· During Numericalization, every word requires a row in weight matrix. However, this would lead matrix to become too large and sparse. Hence, we limit he matrix to 60000 rows. Anything which does not appear more than 2 times is put in unknown token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QftDBgTm-VXrJIXf0k5OA.jpeg" /><figcaption>Use pretrained model. Image courtesy: <a href="https://twitter.com/jeremyphoward">Jeremy Howard</a> &amp; <a href="https://twitter.com/math_rachel">Rachel Thomas</a></figcaption></figure><p>· The model is based on transfer learning from WikiText103. Instead of starting from scratch with random weight, start with pretrained weight based on training on a big dataset(a cleaned subset of wikipedia called wikitext-103).<br>· The model is further fine-tuned according to the imdb dataset as the English language used on IMDB reviews are not same as those on wikipedia. The model is pretrained to guess what the next word is, with input being all the previous word. This has a recurrent structure (RNN: Recurrent Neural Network).</p><p>· Data object inputs are:<br> — all the text files in path<br> — split ratio to create validation dataset.<br> — model label</p><p>· TextDataBunch object: For the language model, the TextDataBunch ignores the labels are shuffles the texts each epoch and sends batches that read text in order with targets (next word in sentence).</p><p>· Language Model Learner inputs:<br> — TextDataBunch object<br>— Pretrained model<br> — Dropout: To avoid overfitting.<br>· Further steps: Learning rate estimation, fitting with ‘fit_one_cycle’ (refer previous lesson notes for details), unfreezing and refitting.<br>· The accuracy obtained is around 30% i.e. 1 out of 3 next words is correctly guessed.</p><p>· Next, a new classification data object is created, which keeps the labels (unlike previous language model). Fitting steps are same as previous model. During the second run, all but last 2 layers are frozen. Similarly, during the third run, all but last 3 layers are frozen up.<br>The accuracy obtained in the classification model is more than 94% with 3 epochs.</p><h3>Tabular Data</h3><p>· Deep learning is currently not much used for tabular data analysis. However, tabular data is analysis is at root for most of the use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nq0shFCO6ncoXuiTRCfgdg.jpeg" /><figcaption>Tabular data use cases. Image courtesy: <a href="https://twitter.com/jeremyphoward">Jeremy Howard</a> &amp; <a href="https://twitter.com/math_rachel">Rachel Thomas</a></figcaption></figure><p>· Using Deep learning reduces requirement of feature engineering (does not remove completely). As it more generalizable, maintenance requirement is less.<br>· Pandas is used to import tabular data. Pandas can read and import data from most of the sources.</p><p>· Tabular module from fastai library is used to analyse. tabular_data_from_df converts DataFrame to a DataBunch for modelling using Datablock API.<br>· Continuous variables can be used as it is post pre-processing (called so as it is done ahead of time, once unlike Transformation for images). It involves filling missing values, categorifying, and normalization. Missing data is replaced with median. Training data is the template for missing imputation, and same process is repeated with Test data.<br>· For categorical variables, embeddings are used.<br>· 84% accuracy is obtained after 1 epoch.</p><h3>Collaborative Filtering</h3><p>· Collaborative filtering is used in recommendation systems. It works on preferences of several users.</p><p>· There are two ways to represent data for the purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ft4jr83emQwaThsJKxF9Sw.jpeg" /><figcaption>Two ways to represent data for Collaborative filtering</figcaption></figure><p>· Second way of representing data leads to a big sparse matrix. Data is not storedlike this usually.<br>· Data used in this case is <a href="https://grouplens.org/datasets/movielens/">Movielens dataset</a>.<br>· Collaborative learner from fastai is used.<br>· Cold start problem: if there is a new user or a new movie, there is no rating available from/for respectively. In such case, collaborative filtering cannot work. Metadata driven model from cold start can be one of the solution.</p><h3>Embeddings</h3><p>· As mentioned above, if the second way of representing data for collaborative filtering is used, the resulting matrix is very big and sparse. Processing this huge matrix is computationally challenging. Further, it is tough to represent meaningful relationships between vectors (rating for a movie, or by a user).</p><p>· As solution to above sparsity, embeddings are employed. The convert sparse vectors lying in N dimensional hyperspace to a lower dimensional denser space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*leYCPEWYtX3PDRy4KdVNQg.jpeg" /><figcaption>Embeddings example (courtesy:<a href="https://developers.google.com/machine-learning/crash-course/embeddings/obtaining-embeddings"> Google ML crash course</a>)</figcaption></figure><p>· In the lecture, Jeremy shows an example of movies vs users, where, each sparse vector for a user, which is N1x1 (N1 being the number of movies) vector is condensed into 4x1 vector (without bias), and 5x1 vector (with bias). Similarly, ratings for movies by each user, which is a N2x1 (N2 being the number of users) is condensed into 4x1 vector (without bias), and 5x1 vector (with bias). Taking dot product of embeddings for a user and a movie gives us the rating for the move by that user.</p><p>· Using the actual rating available, the randomly initiated embeddings can be solved iteratively to the optimal value, which reduces the mean sum of squared errors (MSE) in excel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f085a1e28ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning ver3 Lesson 3]]></title>
            <link>https://jha-vikas.medium.com/deep-learning-ver3-lesson-3-c9443ff3b264?source=rss-e1b2c82684b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9443ff3b264</guid>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vikas Jha]]></dc:creator>
            <pubDate>Sat, 10 Nov 2018 21:15:58 GMT</pubDate>
            <atom:updated>2018-11-15T09:38:45.447Z</atom:updated>
            <content:encoded><![CDATA[<p>Refer notes: <a href="https://medium.com/@boy1729/deep-learning-ver3-lesson-1-99005e886132">Lesson 1</a>, <a href="https://medium.com/@boy1729/deep-learning-ver3-lesson-2-d69333b51253">Lesson 2</a></p><p>This article is compiled based on my notes on Lesson 3 of Deep Learning for Coders ver3.</p><p>· Caution: Update the fastai library and course material before running any code.</p><p>Deploying models in production is as important as development of machine learning models. Zeit is one such platform suggested by Jeremy, and the guidelines are available on course website (will be made available after course is over).</p><h3><strong>Great applications created by students</strong>:</h3><p>· ‘Which car’ by Edward Ross: Identifies 400 Australian cars based on images. Application works on phone too. As model is deployed as web app, it works even with mobile.<br>· Guitar classifier by C Werner.<br>· Humming bird classifier for Trinidad and Tobago.<br>· Face image to dynamic smiley<br>· <a href="https://github.com/keyurparalkar/ASL-live-predictor">American sign language translator</a><br>· ‘<a href="http://yourcityfrom.space/">Your city from space</a>’ by Henri Palacci: Identifies the country based on satellite image.<br>· ‘Time Series learning with CNN’ by Ignacio Oguiza. Refer ‘https://aaai.org/ocs/index.php/WS/AAAIW15/paper/viewFile/10179/10251’ for details on encoding Time Series as Images using CNN.</p><h3><strong>Multilevel Prediction with Planet Amazon Dataset (Kaggle)</strong></h3><p>· Multilevel data: Each image is not labelled with a single label, but multiple labels like ‘Cloudy+Rainforest’, ‘Dry+Desert’ etc.<br>· Data comes from Kaggle: Kaggle provides <a href="https://github.com/Kaggle/kaggle-api">API </a>tool to download data.<br>· Data Structure: csv files with tags for images.<br>· The trickiest step is to create DataBunch object: Data Block API in fastai provides the way to create DataBunch object as per requirements. Refer docs for guidelines.<br>· Required PyTorch objects to be known:<br> — Dataset: Defines indexing (get item) and length(len).<br> — Data Loader: Takes a dataset, grabs items in random, combines them into minibatch and pops them on GPU for modelling.<br> — DataBunch: Combines training data loader and validation dataloader.</p><p>·Parts to convert to Databunch:<br> — ImageFileList folder: where to find data.<br> — Labels: from csv file.<br> — Random split/test folder.<br> — Datasets: How to convert to datasets.<br> — Transform: Data transformations/ augmentation.</p><p>· Image transformations &amp; augmentation:<br> — Flipping: Horizontal flipping applies for dog/cat classification data. For satellite images, vertical flipping is also done.<br> — Warping: Images can be wrapped due perspective changes. Should be included in usual images. However, is not applicable for satellite images, astronomical maps.</p><p>· create_cnn: basic requirements are data, architecture and metric:<br> — Metric: It does not affect the training of model. It is just outputted to track the performance of the model training by user.</p><p>· Threshold in fbeta: In multilabel classification, argmax function cannot be used as argmax chooses the index with highest probability value. Instead, threshold value is set for probability, and all the indices (and respective labels) with probability higher than the threshold are returned.</p><p>· To create customized functions, concept of python partial functions is used: refer ‘https://www.geeksforgeeks.org/partial-functions-python/’</p><p>· Process of training model: Train the model without unfreezing layers &gt; Run LR rate finder &gt; Unfreeze all layers &gt; Train using a range of LR (Check Lesson1 &amp; 2 for details of differential LR for different layers)</p><p>· How to choose LR when LR ranger plot is flat: Use Learning rate which is around 10 times lower than the point where Losses start rising steeply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*K4Ew0s3eWlAsQn5TvboJ9Q.jpeg" /><figcaption>Courtesy: <a href="https://twitter.com/jeremyphoward">Jeremy Howard</a> &amp; <a href="https://twitter.com/math_rachel">Rachel Thomas</a></figcaption></figure><p>· Progressive resizing: Model is initially trained on small image size, and subsequently on larger images, and so on. It helps model to generalize better and use transfer learning. However, a new DataBunch object should be created every time image size is changed.</p><h3>Cam video image segmentation</h3><p>· Data source: ‘http://mi.eng.cam.ac.uk/research/projects/VideoRec/CamVid/’<br>· The description at site reads: “The Cambridge-driving Labeled Video Database (CamVid) is the first collection of videos with object class semantic labels, complete with metadata. The database provides ground truth labels that associate each pixel with one of 32 semantic classes.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*2vYKl6ZezGkkO6Y5W6iavA.jpeg" /><figcaption>Courtesy: <a href="http://mi.eng.cam.ac.uk/research/projects/VideoRec/CamVid/">http://mi.eng.cam.ac.uk/research/projects/VideoRec/CamVid/</a></figcaption></figure><p>· The images are labelled with pixel based colours. Such images are encountered in medical video frames/images, self-driving cars etc.<br>· Marked files are provided as bunch of numbers. Use ‘open_mask’ instead of ‘open_image’ to open them.<br>· Codes text file provides labels respective to each code.</p><p>· Accuracy for pixel data case: Void pixels are ignored.<br>· Model architecture used is <a href="http://deeplearning.net/tutorial/unet.html">u-net</a>.<br>· Other steps are same as previous model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*-Ii_sYOJXAYgy-CvokMlVA.jpeg" /><figcaption>Cycles vs Loss. Image courtesy: <a href="https://twitter.com/jeremyphoward">Jeremy Howard</a> &amp; <a href="https://twitter.com/math_rachel">Rachel Thomas</a></figcaption></figure><p>Plot of loss over cycles shows that the loss initially increases then goes down. settling in flat stable minima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*rKmeL1_XcPQCfGzZwWnNnw.jpeg" /><figcaption>‘Fit 1 cycle’ varying LR helping overcome the coefficient values stuck in non-optimal valley</figcaption></figure><p>It is because of ‘fit one cycle’ is used to fit the model to data. As, initially the learning rate is low, so during fitting one can get stuck in local minima. However, with the high LR part of ‘fit 1 cycle’, it jumps over the hurdle, with temporary increase in loss, ultimately.</p><p>· If memory is an issue, lower precision point numbers (like 16bit, use fp_16 in the end of Learner) can be used. Surprisingly, it can even improve performance as it can reduce overfitting and help generalize better.</p><h3>IMDB Reviews Dataset</h3><p>· Dataset contains movie reviews, in the form of text data. Classify them as positive or negative.<br>· To create the DataBunch, following steps are followed:<br> — Tokenization: Each unit represents a single linguistic concept.<br> — Numericalization: Convert tokens to numbers.<br>· Datablock API: It gives much more flexibility than default methods.<br>· Model training: The model is not trained from scratch, but a pretrained model trained on a bigger dataset is used. This pretrained model is trained to guess next word.<br>· Next same steps are repeated as in previous models. (Details to be covered in Lesson 4)</p><h3>Behind the scenes in Deep Learning</h3><p>· The layers of the network are linear, connected to each other by Activation functions.<br>· If activation functions are linear too, the whole network will be linear.<br>· Introducing non-linear activation function introduces non-linearity in the network.<br>· Universal Approximation Theorem: <a href="http://neuralnetworksanddeeplearning.com/chap4.html">Any shape can be approximated by a combination of linear layers and non linear activation functions</a>.<br>· Earlier sigmoid was the most used activation function. Currently, ReLU(Rectified Linear Unit) or leaky-ReLU is generally used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9443ff3b264" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning ver3 Lesson 2]]></title>
            <link>https://jha-vikas.medium.com/deep-learning-ver3-lesson-2-d69333b51253?source=rss-e1b2c82684b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d69333b51253</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vikas Jha]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 11:56:09 GMT</pubDate>
            <atom:updated>2018-10-31T12:04:39.834Z</atom:updated>
            <content:encoded><![CDATA[<p>Refer notes: <a href="https://medium.com/@boy1729/deep-learning-ver3-lesson-1-99005e886132">Lesson 1</a></p><p>This article is compiled based on my notes on Lesson 2 of Deep Learning for Coders ver3.</p><p>· Caution: Update the fastai library and course material before running any code.</p><h3><strong>Creative applications of CNN</strong></h3><p>— Cleaning up whatsapp folder<br> — Deep CNN &amp; Data Augmentation for Environment Sound Classification (Converting sound to images and subsequent processing). <br>— <a href="https://gist.github.com/suvash/d9fe3aa8d570d42ab65175a057d402a4">Suvash Thapaliya: Identifying Devnagari script using deep learning</a>.<br>— The Mystery of the Origin — <a href="https://medium.com/@alenaharley/the-mystery-of-the-origin-cancer-type-classification-using-fast-ai-libray-212eaf8d3f4e">Cancer Type Classification using Fast.AI Library</a>. <br>— New vs Old bus in Panama classifier. <br>— <a href="https://github.com/henripal/maps">Identifying cities’ location based on satellite images</a></p><p>· Jeremy stressed again on getting hands on experience. This article by James Dellinger is inspirational: <a href="https://medium.com/@jamesdell/if-i-can-you-can-and-you-should-a470d7aea89d">https://medium.com/@jamesdell/if-i-can-you-can-and-you-should-a470d7aea89d</a>. Learning ‘Deep learning’ should be taken as learning soccer/football. One does not attempt understand initially gravity, friction, airflow, but starts kicking ball.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1Nm34sbCvnbMuvkJe-j-g.jpeg" /><figcaption>Credits: <a href="https://twitter.com/jeremyphoward">Jeremy Howard</a> &amp; <a href="https://twitter.com/math_rachel">Rachel Thomas</a>.</figcaption></figure><h3><strong>Creating new datasets based on Google image search</strong></h3><p>— Go to google image search: Search what you want images of.<br> — Press Ctrl+shift+J and Paste the javascript command for getting all the images url in the form of text file. <br>— Upload the text file in the server. Make new folder for downloading images. Use ‘download_images()’ to download the images in the folder. <br>— Repeat the steps for any other keyword.</p><h3><strong>Model</strong></h3><p>· The model being attempted tries to classify Teddy, Black and Grizzly bears. So, 3 folders with respective images have been made.</p><p>· Some images are corrupt/irrelevant/cartoonish: Use verify_images() to remove them.</p><p>· Now, ‘ImageDataBunch’ is prepared: <br> — There is separate validation set. Hence, 20% of the images are reserved for the same, and not used in training.<br> — Normalization of the images is done(refer lesson 1 notes for details).</p><p>· Training model:<br> — Model: Resnet34, metric: error rate, 5 epochs.<br> — Model accuracy is around 98%.</p><p>· Unfreezing the layers:<br> — It allows for modification of weights of all layers. However, the choice of learning rate becomes crucial here as lower layers need very fine tuning compared to upper layers, where higher learning rates can be used. Using same learning rate can lead to loss of accuracy.<br> — Learning rate finder is used to reach the appropriate learning rate. ‘Look out for the strongest downward slope which sticks around for a while.’ If there are multiple such slopes, consider all and see which works best.<br> — Learning rates in unfrozen layers are provided as range of values, with lower end for lower layers and upper end for higher layers.<br>— With 2 epochs, error rate is around 1.4% compared to 2% earlier.<br> — The low accuracy can be because of model, for which more cycles will help(as noise is random here). Or it can be because of biased/garbage data, where the further training of model will be pointless.</p><p>· Model in production<br> — For inference/prediction, models can be run on CPU.<br> — Load weight &gt; Load image for prediction &gt; Predict.<br> — Can be easily deployed using web app</p><h3><strong>Things which can go wrong</strong></h3><p>— Validation error goes high: Learning rate might be high.<br>— Slow convergence: Validation error goes down, but convergence takes lot of time.<br>— Training loss &gt; Validation loss: Underfitting. More training/epochs required.<br>— Validation error reduces for a while, then shoots up: Overfitting may be an issue.</p><h3><strong>Behind the scene Concepts</strong></h3><p>· Tensor vs Matrix vs Vector: Tensor is a generalized matrix. Usual parlance, is 1-D is called Vector, 2-D is called matrix and more than 2 dimensions, it is called Tensor.<br>· For difference between matrix and tensor, refer: <a href="https://medium.com/@quantumsteinke/whats-the-difference-between-a-matrix-and-a-tensor-4505fbdc576c">https://medium.com/@quantumsteinke/whats-the-difference-between-a-matrix-and-a-tensor-4505fbdc576c</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*6UcQdP-1yFoUotb-QnDWsg.gif" /><figcaption>(courtesy: Adam Geitgey (<a href="https://medium.com/@ageitgey/machine-learning-is-fun-part-3-deep-learning-and-convolutional-neural-networks-f40359318721">https://medium.com/@ageitgey/machine-learning-is-fun-part-3-deep-learning-and-convolutional-neural-networks-f40359318721</a>).</figcaption></figure><p>· Greyscale images are represented by matrix which tells about the intensity of individual pixels in 2-D plane. If images are coloured, the 3rd dimension represents the colour and representation becomes a Tensor.<br>· In bear identification problem (referred above), the pixels are processed into 3 probability values, and subsequently passed through argmax function, which returns the index of the category with maximum probability. It can be extrapolated for more than 3 categories.</p><h3><strong>Process of Optimization</strong></h3><p>· Linear regression: Trying to fit a line in a bunch of points, the metric being the MSE (Mean Square Error).<br>· Y = X(dot)a<br> where Y is matrix of output(s), X is matrix of input(s). The intercept is taken care by including a column of 1(s) in X matrix, and a is matrix of coefficients. Refer <a href="http://matrixmultiplication.xyz/">http://matrixmultiplication.xyz</a> for dot product.<br>· Solving equation for coefficients which minimizes the optimizing metric (MSE here) gives up the fitted line.<br>· Matplotlib plot can be animated to visualize the process of fitting curve.<br>· Two ways to solve: Analytically and iteratively (Gradient descent).</p><h3><strong>Iterative method</strong></h3><p>· Weight(updated) = weight — LR*grad.<br>· Gradient descent calculates gradient at the current coefficient/weight locations to decide on which way to move to reach the minima. Uses whole data to update the coefficients/weights.<br>· Stochastic Gradient descent: Updates the weights by calculating the gradient in batches, not taking whole data simultaneously. For instance, if batch size is ‘64’, only 64 images at a time in a batch are used to update the weights.<br>· Minibatch: random group of points are used to update weights.</p><h3><strong>Overfitting vs Underfitting</strong></h3><p>· Refer: <a href="https://qr.ae/TUhvtz">https://qr.ae/TUhvtz</a>.<br>· Overfitting can be avoided with large number of coefficients using regularization</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d69333b51253" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning ver3 Lesson 1]]></title>
            <link>https://jha-vikas.medium.com/deep-learning-ver3-lesson-1-99005e886132?source=rss-e1b2c82684b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/99005e886132</guid>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vikas Jha]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 11:08:08 GMT</pubDate>
            <atom:updated>2018-10-31T04:03:59.655Z</atom:updated>
            <content:encoded><![CDATA[<p>Following suggestion by a friend in Jan 2018, I started with Deep learning for coders v2. The non-conventional top-down approach followed by Jeremy and Rachel seemed counter intuitive at first. However, it does seem to work. Nevertheless, I did a blunder of watching videos at 2x, and not practising enough coding, a mistake which Jeremy has warned enough times during his lecture.</p><p>In v3, I plan to work on as many datasets as possible and going by the advice from Rachel (<a href="https://medium.com/@racheltho/why-you-yes-you-should-blog-7d2544ac1045">https://medium.com/@racheltho/why-you-yes-you-should-blog-7d2544ac1045</a>), I also plan to write brief blog posts on each of the 7 lessons based on my notes taken during the live session.</p><h3><strong>The course</strong></h3><p>Disclaimer: I missed initial 20min of lecture due to internet issues.</p><p><strong>·</strong> The course is taught by:<a href="https://twitter.com/jeremyphoward"> Jeremy Howard</a> &amp; <a href="https://twitter.com/math_rachel">Rachel Thomas</a>.</p><p><strong>·</strong> Pre-requisites for this course is ‘High school mathematics + 1 year of coding experience’. Python coding knowledge is an advantage.</p><p><strong>·</strong> The course consists of 7 lessons, each around 1.5 to 2 hours long, with expected 8–10 hours work each week. It is recommended that one goes through full lesson/video, without trying to understand/google everything.</p><h3><strong>Setting up the virtual machine</strong></h3><p>· The deep learning setup requires Nvidia GPU (<a href="https://www.quora.com/Why-are-GPUs-well-suited-to-deep-learning">https://www.quora.com/Why-are-GPUs-well-suited-to-deep-learning</a>). It is possible to use personal computers/servers for the course. However, it would be slower (as high-end machines are not easy/cheap to come by) and setting up the computer would take time and energy. It is highly recommended to rent access to servers which have everything preinstalled.</p><p>· On course website , 5 options are suggested. While Paperspace , Salamander , and Sagemaker provide easy ready to run option, some installation is required for Google Compute Platform, and AWS EC2.</p><h3><strong>The approach</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*lcE3mqBW_Z6F4E3OmGPyCg.jpeg" /></figure><p>Top down approach: ‘Learn how it works before you learn why it works. Get hands dirty coding as much as possible.’</p><h3><strong>Getting started</strong></h3><p>· Jupyter notebook is recommended as it is interactive and can show plots/images. Use ‘Shift+Enter’ to run the cell contents.</p><p>· First cell contains the magic commands: %matplotlib inline, %reload_ext autoreload, %autoreload 2 (read more at: <a href="https://towardsdatascience.com/the-top-5-magic-commands-for-jupyter-notebooks-2bf0c5ae4bb8">https://towardsdatascience.com/the-top-5-magic-commands-for-jupyter-notebooks-2bf0c5ae4bb8</a>). These commands ensure that matplotlib plots are shown in Jupyter notebook, and the autoreload extension is loaded.</p><p>· Next cell loads the <a href="http://docs.fast.ai/">fastai </a>library. Fastai library sits on top of PyTorch. It is faster and uses less lines of code then Keras. It supports vision, text, tabular, and collab (collaborative filtering) models.</p><p>· Import of all (‘import *’) is used, and coding recommendations are not followed as this is a research/practice environment, and all components should be readily available. During production environment, proper coding guidance may be followed.</p><h3><strong>Data and processing</strong></h3><p>· Data is taken from two sources: Kaggle datasets &amp; academic datasets. These datasets provide strong baselines/benchmark for performance to which models can be compared to.</p><p>· The Oxford-IIIT Pet Dataset(<a href="http://www.robots.ox.ac.uk/~vgg/data/pets/">http://www.robots.ox.ac.uk/~vgg/data/pets/</a>): 37 category pet dataset with roughly 200 images for each class. It has 12 cat &amp; 25 dog breeds. Previous versions of this course used ‘cats vs dogs’ datasets, which had become too easy to work on over the years with easily available models. Oxford-IIIT Pet Dataset classification is a problem of fine grained classification (i.e. classification between similar categories).</p><p>· Path = untar_data(URL.PETS), where URL.PETS is the url of the dataset. Path lib is used instead of strings, as it works across platforms (needs more explanation)</p><p>· The labels are the target which are the goal of the prediction process. In the dataset, the names of the individual images are in format: ‘path_label_extension.jpg’. Regular expressions are used to extract the labels from the text.</p><p>· Size of images: In this course, the images used are square (i.e. height = width), and of size 224 x 224. Images which are of different shape/size are resized and cropped accordingly. It is one of the drawback of deep learning models that they need images of same size. Variable size images are in scope of part 2 of the course.</p><p>· databunch object: contains training, and validation data</p><p>· Normalization of images: Individual pixel values range from 0 to 255. They are normalized to bring the value with mean 0 and standard deviation 1. Image augmentation: Generate new images from existing ones. Helps to avoid over-fitting. Padding : Concepts to be discussed in coming classes.</p><h3><strong>Model</strong></h3><p>· CNN (Convolutional Neural Network), requires 2 things to train: Data &amp; Architecture</p><p>· ResNet architecture:<br> — Why ResNet? Works generally well in most cases<br> — 34-layer architecture: 50 layer needs more memory to run. 34 works fine for current problem<br> — Metric: Printed for validation set</p><p>· 1st run: takes time as ResNet initial weights are downloaded. These weights are not random but based on training the model on a number of images. So, model does not start with nothing/random weights. It is further trained for the specific problem which is being targeted, with additional data. For instance, with ResNet-34, 30 images were enough to train a world class model to differentiate between Cricket and Baseball images.</p><p>· fit_one_cycle: Based on paper released in March 2018??. It fit a model following the 1cycle policy. (Need more explanation). It works better than fit.</p><p>· First model gives around 94% accuracy, compared to 2012 research paper (source??) where problems specific model gave only 59% accuracy.</p><p>· ResNet vs Inception: ResNet scores higher in <a href="https://dawn.cs.stanford.edu/benchmark/">Stanford Dawnbench</a>. Inception is also not as resilient.</p><p>· Lower layers vs higher layers:</p><p>— Lower the layer, more basic is the pattern which it captures. First layer may be capturing horizontal, vertical and diagonal lines.</p><p>— Second layer learns from the combination of features from first layer, and so on.</p><p>— As basic patterns/geometrical shapes are almost similar everywhere, there is no need to train lower layers heavily.</p><p>— Unfreezing all layers leads to loss of accuracy compared to even untrained model, as lower layer weights are disturbed. Different layers tell different semantic complexity. Unlearning and training all layers at same rate leads to lower accuracy. Hence, earlier layers should be either left untouched or very fine tuning with very low learning rate should be done.</p><p>— <a href="http://www.matthewzeiler.com/wp-content/uploads/2017/07/arxive2013.pdf">Zeiler and Fergus paper on visualizing CNN</a>: shows the patterns captured by different layers.</p><p>— Learning rate finder: Tells how quickly parameters be updated. To capture the different learning rate requirements, a range of learning rates are passed.</p><h3><strong>Good work by fastai students:</strong></h3><p>· Hamel Husain: Towards Natural Language Semantic Code Search (Enables semantic search of codes: <a href="https://githubengineering.com/towards-natural-language-semantic-code-search/">https://githubengineering.com/towards-natural-language-semantic-code-search/</a>)</p><p>· Sara Hooker: Model to alert Forest rangers based on Chain saw sound &lt;could not find link&gt;</p><p>· Christine Mcleavey Payne: Combined Deep learning with Music (<a href="http://christinemcleavey.com/">http://christinemcleavey.com/</a>)</p><p>· Alexandre Cadrin-Chênevert: Radiologist. Deep learning applied to radiology. Pointed out overfitting &lt;link??&gt;</p><p>· Melissa Fabros: first round winners of the “AI For Everyone” Challenge. Built system to identify faces less represented in the conventional training datasets (dark skinned). (<a href="https://www.crowdfundinsider.com/2017/09/121836-crowdflower-names-kiva-engineer-first-round-winner-1-million-ai-everyone-challenge/">https://www.crowdfundinsider.com/2017/09/121836-crowdflower-names-kiva-engineer-first-round-winner-1-million-ai-everyone-challenge/</a>)</p><p>· Karthik: phone based object identification for visually challenged.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99005e886132" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>