<?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 Roshan Nayak on Medium]]></title>
        <description><![CDATA[Stories by Roshan Nayak on Medium]]></description>
        <link>https://medium.com/@roshannayak610?source=rss-93c6107e1856------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SD4mRVq3ZwIcj6QpVYMl1g.png</url>
            <title>Stories by Roshan Nayak on Medium</title>
            <link>https://medium.com/@roshannayak610?source=rss-93c6107e1856------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:56:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roshannayak610/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[All About Activation Functions Used In Neural Networks.]]></title>
            <link>https://medium.com/@roshannayak610/all-about-activation-functions-used-in-neural-networks-9a407d5977e3?source=rss-93c6107e1856------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a407d5977e3</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Roshan Nayak]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 23:39:46 GMT</pubDate>
            <atom:updated>2024-08-20T23:39:46.431Z</atom:updated>
            <content:encoded><![CDATA[<p>The linear activation function is used to make the necessary adjustments at the output layer of the network.</p><p>Non-linear activation functions are used to introduce <strong>non-linearity</strong> in the <strong>mathematical expressions</strong> of the model so that the network will be able <strong>to identify non-linear relationships</strong>.</p><h3>Types of Activation Function.</h3><h4>Binary Step Function</h4><p>If the input to the activation function is greater than a threshold, then the neuron is activated, else it is deactivated. <strong>Mathematically, output = 1 when input ≥ threshold, else output = 0. </strong>The derivative of this function is <strong>zero </strong>for all x.</p><h4>Linear Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*Pl2I29AAkmcp7yOReGbprA.png" /></figure><p>The output of this function is directly proportional to the value of the input. The proportion coefficient is the parameter to the function. <strong>Mathematically, output = alpha*input. </strong>The derivative of this function is the proportionality coefficient, <strong>alpha</strong>.</p><h4>Sigmoid Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*98SrkaPAzEmGgQnQYwzKPw.png" /></figure><p>The output of this function ranges from 0 to 1. <strong>Mathematically, output = 1/(1+e^(-x)). </strong>The derivative is sigmoid(x)*(1-sigmoid(x)). This function has a very less gradient for most of its values which is a cause for vanishing gradient problem. Hence the function is usually used at the output layer. Non-symmetric with respect to the origin.</p><h4>Tanh Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*ie7Fbe64Io292iAOWHxy4g.png" /></figure><p>The output ranges from -1 to 1. <strong>Mathematically, output = (e^(x)-e^(-x))/(e^(x)+e^(-x)). </strong>Even this function has vary less gradient for most of the values of x. But its symmetric with respect to the origin.</p><h4>ReLU Activation Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*A_TuQoRF9ogPPwW4CaR_fQ.png" /></figure><p>Neurons will only be deactivated if the output of the linear transformation is less than 0. <strong>Mathematically, output = max(0, x).</strong> The derivative is 1 for x &gt; 0 else 0 for all other values. As the derivative is 0 for x &lt; 0, this can lead to some neurons end up not getting updated during backpropagation. This problem continues throughout the training process as if at a particular neuron the derivative goes to zero then none of the other weights in the path to that neuron will get updated(chain rule). Hence the value of this neuron will never change and will remain to be negative, which makes the value zero and the derivative zero again. These neurons are called <strong>dead neurons (neurons that stop learning)</strong>. To solve this problem Parameterized ReLU is used.</p><h4>Parameterized ReLU</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*WTmNHcHntaYoUSQDL5auiQ.png" /></figure><p>Instead of having a constant value for x &lt; 0 having a small value dependent on x will prevent derivative go zero. Hence avoiding dead neurons. <strong>Mathematically, output = alpha*x for x &lt; 0 and x for x ≥ 0, where alpha is a very small value, eg. 0.01. </strong>The derivative is alpha for x &lt; 0 and 1 for x ≥ 0.</p><h4>Leaky ReLU</h4><p>When alpha = 0.01, the function Parameterized ReLU is called Leaky ReLU.</p><h4>Softmax Function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*llAvk9BboGAueAvflzaFqQ.png" /></figure><p>Calculates the probability of the data point belonging to each class. <strong>Mathematically, output = value/sum_of_values.</strong></p><h3>Choosing the right activation function for the problem.</h3><ul><li>Sigmoid and tanh generally work better in the case of classifiers.</li><li>Use the binary function to convert the output value to class 0 or 1 in case of the binary classification problem.</li><li>Use linear activation function for regression problems.</li><li>Sigmoids and tanh functions are sometimes avoided due to the vanishing gradient problem. This makes the model take a lot of time to learn.</li><li>ReLU function is a general activation function and is used in most cases these days.</li><li>If we encounter a case of dead neurons in our networks the leaky ReLU function is the best choice.</li><li>Always keep in mind that ReLU function should only be used in the hidden layers.</li><li>As a rule of thumb, you can begin with using ReLU function and then move over to other activation functions in case ReLU doesn’t provide optimum results.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a407d5977e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Focal Loss : A better alternative for Cross-Entropy]]></title>
            <link>https://medium.com/data-science/focal-loss-a-better-alternative-for-cross-entropy-1d073d92d075?source=rss-93c6107e1856------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d073d92d075</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[loss]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Roshan Nayak]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 14:51:07 GMT</pubDate>
            <atom:updated>2022-04-28T08:56:46.900Z</atom:updated>
            <content:encoded><![CDATA[<h3>Focal Loss: A better alternative for Cross-Entropy</h3><h4>Focal loss is said to perform better than Cross-Entropy loss in many cases. But why Cross-Entropy loss fails, and how Focal loss addresses those problems let us find out in this article</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QN3xznUDhgWeTihU" /><figcaption>Gradient Descent, Photo by <a href="https://unsplash.com/@ross_savchyn?utm_source=medium&amp;utm_medium=referral">Rostyslav Savchyn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Loss functions</strong> are mathematical equations that calculate how far the predictions deviate from the actual values. Higher loss values suggest that the model is making a significant error, whereas lower loss values imply that the predictions are rather accurate. The goal is to reduce the loss function as much as possible. The loss function is used by models to learn the trainable parameters, such as weights and biases. Because the weight updation equation of the parameters has the first derivative of the loss function with respect to the weights or biases, the behaviour of this function will have a significant impact on the gradient descent process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*f_mbKUol-luq3LiBAZueAw.png" /><figcaption>Weight updating formula, Image Source : Author</figcaption></figure><p>There are numerous loss functions available right now. Each of them has a different mathematical equation and a different method of penalising the model’s errors. There are also benefits and drawbacks to each, which we must weigh before deciding on the best function to use.</p><p>Now that we’ve defined the loss function, let’s go over the issues that Categorical Cross-Entropy loss causes and how Focal loss solves them.</p><h3>Categorical Cross-Entropy Loss</h3><p>Categorical Cross-Entropy loss is traditionally used in classification tasks. As the name implies, the basis of this is Entropy. In statistics, entropy refers to the disorder of the system. It quantifies the degree of uncertainty in the model’s predicted value for the variable. The sum of the entropies of all the probability estimates is the cross entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*qmPkvBxyn-Wo7f29er5QAA.png" /><figcaption>Expression for Cross Entropy, Image Source : Author</figcaption></figure><p>Where Y is the true label and p is the predicted probability.</p><p><strong>Note</strong>: The formula shown above is for a discrete variable. In the case of a continuous variable, the summation should be replaced by integration.</p><p>The <strong>logarithm graph</strong> clearly shows that the summation will be negative because probabilities range from 0 to 1. As a result, we add a minus to invert the sign of the summation term. The graph of log(x) and -log(x) is shown below (x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*ncYHP4vAeNadwytalsrYvQ.png" /><figcaption>Graphs for log(x) in red and -log(x) in blue, Image Source : Author. Graph plotted using Desmos.</figcaption></figure><h4>Cases where Cross-Entropy loss performs badly</h4><ul><li><strong>Class imbalance</strong> inherits bias in the process. The majority class examples will dominate the loss function and gradient descent, causing the weights to update in the direction of the model becoming more confident in predicting the majority class while putting less emphasis on the minority classes. <strong>Balanced Cross-Entropy</strong> loss handles this problem.</li><li>Fails to distinguish between <strong>hard</strong> and <strong>easy examples</strong>. Hard examples are those in which the model repeatedly makes huge errors, whereas easy examples are those which are easily classified. As a result, Cross-Entropy loss fails to pay more attention to hard examples.</li></ul><h3>Balanced Cross-Entropy Loss</h3><p>Balanced Cross-Entropy loss adds a weighting factor to each class, which is represented by the Greek letter alpha, [0, 1]. Alpha could be the inverse class frequency or a hyper-parameter that is determined by cross-validation. The alpha parameter replaces the actual label term in the Cross-Entropy equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*PKqXDLYUoCEr9H6xO8_JDA.png" /><figcaption>Expression for Balanced Cross Entropy, Image Source : Author</figcaption></figure><p>Despite the fact that this loss function addresses the issue of class imbalance, it cannot distinguish between hard and easy examples. The problem was solved by focal loss.</p><h3>Focal Loss</h3><p>Focal loss focuses on the examples that the model gets wrong rather than the ones that it can confidently predict, ensuring that predictions on hard examples improve over time rather than becoming overly confident with easy ones.</p><p><strong>How exactly is this done? </strong>Focal loss achieves this through something called <strong>Down Weighting</strong>. Down weighting is a technique that reduces the influence of easy examples on the loss function, resulting in more attention being paid to hard examples. This technique can be implemented by adding a modulating factor to the Cross-Entropy loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*0iU1aPrrEydcIxyeqHLobg.png" /><figcaption>Expression for Focal Loss, Image Source : Author</figcaption></figure><p>Where γ (Gamma) is the <strong>focusing parameter</strong> to be tuned using cross-validation. The image below shows how Focal Loss behaves for different values of γ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*zkWsCJPPtCKzkG1VdZ4atA.png" /><figcaption>Down weighting increases with an increase in γ, Image Source : Focal Loss Research Paper</figcaption></figure><h4>How gamma parameter works?</h4><ul><li>In the case of the misclassified sample, the pi is small, making the modulating factor approximately or very close to 1. That keeps the loss function unaffected. As a result, it behaves as a Cross-Entropy loss.</li><li>As the confidence of the model increases, that is, pi → 1, modulating factor will tend to 0, thus down-weighting the loss value for well-classified examples. The focusing parameter, γ ≥ 1, will rescale the modulating factor such that the easy examples are down-weighted more than the hard ones, reducing their impact on the loss function. For instance, consider predicted probabilities to be 0.9 and 0.6. Considering γ = 2, the loss value calculated for 0.9 comes out to be 4.5e-4 and down-weighted by a factor of 100, for 0.6 to be 3.5e-2 down-weighted by a factor of 6.25. From the experiments, γ = 2 worked the best for the authors of the Focal Loss paper.</li><li>When γ = 0, Focal Loss is equivalent to Cross Entropy.</li></ul><p>In practice, we use <strong>an α-balanced variant</strong> of the focal loss that inherits the characteristics of both the <strong>weighing factor </strong>α and the <strong>focusing parameter </strong>γ, yielding slightly better accuracy than the non-balanced form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*0SkPCd2Y2IGCh8z-9BWL7Q.png" /><figcaption>Expression for α-balanced Focal Loss, Image Source : Author</figcaption></figure><p>Focal Loss naturally solved the problem of class imbalance because examples from the majority class are usually easy to predict while those from the minority class are hard due to a lack of data or examples from the majority class dominating the loss and gradient process. Because of this resemblance, the Focal Loss may be able to solve both problems.</p><p>Thank you for reading the article 😃. Have a nice day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d073d92d075" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/focal-loss-a-better-alternative-for-cross-entropy-1d073d92d075">Focal Loss : A better alternative for Cross-Entropy</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands on Data Augmentation in NLP using NLPAUG Python Library]]></title>
            <link>https://medium.com/codex/hands-on-data-augmentation-in-nlp-using-nlpaug-python-library-ad323c22908?source=rss-93c6107e1856------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad323c22908</guid>
            <category><![CDATA[augmentation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Roshan Nayak]]></dc:creator>
            <pubDate>Thu, 07 Apr 2022 12:07:52 GMT</pubDate>
            <atom:updated>2022-04-08T16:05:19.186Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>A sentence with same meaning can be written in multiple ways.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jyDxXT-IK4JEeuq5" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article I will make a deep dive into how to actually use the amazing nlpaug library. I will assume that the reader has already got a good understanding of what Data Augmentation technique is and why its actually used. If not then here is my understanding of data augmentation,</p><blockquote>Data Augmentation is a regularization technique employed to enhance the data by generating new samples from the existing one’s. This adds variety to the data helping the model to generalize well and reduce overfitting.</blockquote><p>In order to have a better understanding, I had summarized a research paper in my previous article. Do give it a read, the link is <a href="https://medium.com/swlh/data-augmentation-in-natural-language-processing-756e942b42f3">here</a>.</p><h3>Data Augmentation in NLP</h3><p>Data augmentation in NLP refers to modifying an existing sentence to obtain a new sentence that resembles the existing sentence. The accuracy of the data augmentation technique is measured in terms of how close does the newly generated sentence resemble the sentence from which it is generated. Huge deviation in the meaning will have serious consequences. For instance over modifying the sentence could end up inverting the sentiment of the generated sentence in case of sentiment analysis task.</p><p><strong>Need for Data Augmentation in NLP</strong></p><ol><li>Having imbalanced dataset will not help the model generalized well. The learnings of the model will be influenced more by the majority class due to which the model will end up predicting the majority class most of the times. This model cannot be used in production. Hence in order to tackle this problem we can used data augmentation to generate new samples for the minority class. This technique is called <strong>over sampling</strong>.</li><li>Small datasets cannot be trained on heavy models like Bert, Roberta, etc. Since these models have millions of parameters they take a lot of data in order to generalize and get some meaningful insights from the data. We can generate new samples using data augmentation technique and expand our dataset.</li><li>Can be used to increase the variety of the data. Many a times the model has the tendency to overfit the training set. Increasing the variety of the data will help the model generalize better.</li></ol><p><strong>Exploring the Data Augmentation techniques for NLP</strong></p><p>Before jumping into the techniques there are several parameters that control the augmentation process and are common across all the techniques and are quite important to be understood.</p><ul><li><strong>lang</strong> (<em>str</em>) — Language of your text. Default value is ‘eng’.</li><li><strong>aug_p</strong> (<em>float</em>) — Percentage of words that will be augmented.</li><li><strong>aug_min</strong> (<em>int</em>) — Minimum number of words to be augmented augmented.</li><li><strong>aug_max</strong> (<em>int</em>) — Maximum number of words will be augmented. If None is passed, number of augmentation is calculated via aup_p. If calculated result from aug_p is smaller than aug_max, will use calculated result from aug_p. Otherwise, using aug_max.</li><li><strong>stopwords</strong> (<em>list</em>) — List of words which will be skipped from augment operation.</li></ul><p>Now that we are aware of the parameters that control the augmentation techniques lets dive into the implementation part. There is a plethora of ways in which sentences can be created starting from the existing ones. Let’s examine the most popular and intuitive ones and their implementation. I am going to use the NLPAUG library of python.</p><p>Install NLPAUG execute the command given below and import the necessary libraries.</p><pre>!pip install nlpaug</pre><pre>import nlpaug.augmenter.word as naw</pre><ul><li><strong>Synonym Replacement:</strong> Randomly choose <em>n</em> words from the sentence that are not stop words. Replace each of these words with one of its synonyms chosen at random.</li></ul><pre>syn_aug = naw.SynonymAug(aug_p=0.3)<br>sentence = &#39;climate change puts the squeeze on wine production&#39;<br>mod_sentence = syn_aug.augment(sentence, n=1)<br>print(&#39;Original text :&#39;, sentence)<br>print(&#39;Augmented text :&#39;, mod_sentence)</pre><p>Original text : <strong>climate</strong> change <strong>puts</strong> the squeeze on wine production</p><p>Augmented text : <strong>clime</strong> change <strong>position</strong> the squeeze on wine production</p><ul><li><strong>Random Swap:</strong> Randomly choose two adjacent words in the sentence and swap their positions.</li></ul><pre>sentence = &#39;climate change puts the squeeze on wine production&#39;<br>aug = naw.random.RandomWordAug(action=&#39;swap&#39;, aug_p=0.3)<br>mod_sentence = aug.augment(sentence, n=1)<br>print(&#39;Original text :&#39;, sentence)<br>print(&#39;Augmented text :&#39;, mod_sentence)</pre><p>Original text : <strong>climate change</strong> puts <strong>the squeeze</strong> on <strong>wine production</strong></p><p>Augmented text : <strong>change climate</strong> puts <strong>squeeze the</strong> on <strong>production wine</strong></p><ul><li><strong>Random Deletion:</strong> Randomly remove each word in the sentence.</li></ul><pre>sentence = &#39;climate change puts the squeeze on wine production&#39;<br>aug = naw.random.RandomWordAug(action=&#39;delete&#39;, aug_p=0.3)<br>mod_sentence = aug.augment(sentence, n=1)<br>print(&#39;Original text :&#39;, sentence)<br>print(&#39;Augmented text :&#39;, mod_sentence)</pre><p>Original text : climate <strong>change </strong>puts <strong>the squeeze </strong>on wine production</p><p>Augmented text : climate puts on wine production</p><ul><li><strong>Antonym Replacement: </strong>Randomly choose <em>n</em> words from the sentence that are not stop words. Replace each of these words with one of its antonyms chosen at random.</li></ul><pre>sentence = &#39;climate change puts the squeeze on wine production&#39;<br>aug = naw.AntonymAug(aug_p=0.3)<br>mod_sentence = aug.augment(sentence, n=1)<br>print(&#39;Original text :&#39;, sentence)<br>print(&#39;Augmented text :&#39;, mod_sentence)</pre><p>Original text : climate change <strong>puts </strong>the squeeze on wine production</p><p>Augmented text : climate change <strong>divest </strong>the squeeze on wine production</p><p>I have covered four techniques in this article. The only thing to keep in mind while augmenting is that the polarity of the sentence before and after augmenting remains the same. Do explore the official documentation of the library to get acquainted with many more techniques. Have shared the link in the reference section.</p><p>Thanks for reading the article. I hope you enjoyed the reading!</p><p><strong>References:</strong></p><ul><li><a href="https://www.kaggle.com/code/andypenrose/text-augmentation-with-nlpaug/notebook">https://www.kaggle.com/code/andypenrose/text-augmentation-with-nlpaug/notebook</a></li><li><a href="https://nlpaug.readthedocs.io/en/latest/augmenter/word/antonym.html">https://nlpaug.readthedocs.io/en/latest/augmenter/word/antonym.html</a></li><li><a href="https://medium.com/swlh/data-augmentation-in-natural-language-processing-756e942b42f3">https://medium.com/swlh/data-augmentation-in-natural-language-processing-756e942b42f3</a></li></ul><p>If you haven’t read my latest blog on how to implement word2vec, then check out the link given below!!</p><p><a href="https://medium.com/swlh/word2vec-in-practice-for-natural-language-processing-a179b3286a21">Word2Vec in Practice for Natural Language Processing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad323c22908" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/hands-on-data-augmentation-in-nlp-using-nlpaug-python-library-ad323c22908">Hands on Data Augmentation in NLP using NLPAUG Python Library</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random Forest: An Ensembling Technique in Scikit-Learn]]></title>
            <link>https://medium.com/@roshannayak610/random-forest-an-ensembling-technique-in-scikit-learn-c324ed63dbc4?source=rss-93c6107e1856------2</link>
            <guid isPermaLink="false">https://medium.com/p/c324ed63dbc4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Roshan Nayak]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 11:34:09 GMT</pubDate>
            <atom:updated>2020-07-06T19:19:16.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ensembling Technique and Random Forest</h3><blockquote>Teamwork is proved to have made better decisions than an individual.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bBoKF3HisHOx6iz-" /><figcaption>Forest Photo by <a href="https://unsplash.com/@szmigieldesign?utm_source=medium&amp;utm_medium=referral">Lukasz Szmigiel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The pre-requisites required before you read this post is to have a deeper understanding of how <strong>Decision Trees</strong> and <strong>Regression Trees</strong> work.</p><p><strong>In this post, I will be doing the following things:</strong></p><ol><li>What is Ensembling?</li><li>Types of Ensembling Techniques.</li><li>Overview of Random Forest(A model that uses the Bagging Technique).</li><li>Parameters that matters for a Random Forest.</li></ol><h3><strong>Ensemble Models for Better Results</strong></h3><p>Now, what does the term ensemble basically mean? Ensembling is a technique where the final prediction is made considering the predictions made by multiple models instead of just one. According to the idea of synergy, <strong>decisions</strong> made collectively tend to be <strong>more</strong> effective <strong>than decisions</strong> made by a single <strong>individual</strong>. Hence, they have the potential to be <strong>more</strong> creative and lead to a <strong>more</strong> effective <strong>decision</strong>. In fact, groups may sometimes achieve results beyond what they could have done as <strong>individuals</strong>. Using this idea its seen that most of the time ensembling multiple models to make a prediction worked out well. Individual models in an ensemble model are called “weak learners”.</p><h3>Two Types of Ensembling Techniques</h3><ol><li><strong>Bagging</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*a1Nxk8eQpUQ7J9zrBz4J_w.jpeg" /><figcaption>Visualize Bagging Technique.</figcaption></figure><p>Bagging gets its name because it combines <strong><em>B</em></strong>ootstrapping and <strong><em>Agg</em></strong>regation to form one ensemble model. Given a sample of data, a bootstrapped dataset is generated by pulling multiple subsamples from the given dataset. A model is then trained on each of the bootstrapped subsamples and a subset of features. After each model is done training on the subsamples and subset of features, an algorithm is used to aggregate over the Decision Trees to form the most efficient predictor.</p><p>2. <strong>Boosting:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Ez7JZ4XaZIDsPwnYV1gs9w.jpeg" /><figcaption>Visualize Boosting Technique.</figcaption></figure><p>In the case of Bagging all the models are trained individually irrespective of what the other model does. Boosting is a sequential process, where each subsequent model attempts to correct the errors of the previous model. The succeeding models are dependent on the previous model. In simple terms, the next model will be trained such that it will predict the errors of the previous model. The sequence is continued until it reaches max length or the errors to be predicted are very small.</p><h3>Random Forest</h3><p>With decision trees as a weak learner,<strong> Random forests</strong> or <strong>random decision forests</strong> are an ensemble learning method for classification, regression, and other tasks that works by constructing a number of decision trees at training time and outputting the class that is the mode of the classes for the classification problem or mean of all the predictions for the regression problem. How these are better than a decision tree? Decision Trees have the tendency to overfit the training data failing to generalize on the samples that the model may encounter in the future that it had never seen during the training process. Hence instead of relying on just one decision tree, a Random Forest will have multiple decision trees of different shapes that are all considered for the final prediction of the model.</p><h3>Parameters that matters for a Random Forest</h3><ol><li><strong>criterion: </strong>The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain. Note: this parameter is tree-specific.</li><li><strong>n_estimators: </strong>The number of trees in the forest. The default value is 100.</li><li><strong>max_depth: </strong>The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. The default value is None. Usually tuned when the model is overfitting.</li><li><strong>min_samples_split: </strong>The minimum number of samples required to split an internal node. The node will not be split further if samples less than min_samples_split is contained by the node. The default value is 2.</li><li><strong>min_samples_leaf: </strong>The minimum number of samples required to be at a leaf node. The leaf will be discarded if the samples are less than min_samples_leaf. The default value is 1.</li><li><strong>max_features: </strong>The number of features to consider when looking for the best split. The default value is the square root of the number of features in the dataset.</li><li><strong>bootstrap: </strong>Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. The default value is True.</li><li><strong>n_jobs: </strong>The number of jobs to run in parallel.</li><li><strong>random_state: </strong>Controls both the randomness of the bootstrapping of the samples used when building trees and the sampling of the features to consider when looking for the best split at each node.</li></ol><p>The parameters mentioned should be necessarily tuned for better accuracy and not end up overfitting the model.</p><p>This is how a Random Forest is built. This is it from this post. Do <strong>clap if you liked it. </strong>Also, connect me on <a href="https://www.linkedin.com/in/roshan-nayak-82a452174/">LinkedIn</a>. Thank you for reading this till the end. <strong>Do tell me if there are any corrections to be done from my side.</strong></p><h3><strong>References</strong></h3><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">RandomForestClassifier</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c324ed63dbc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Word2Vec in Practice for Natural Language Processing]]></title>
            <link>https://medium.com/swlh/word2vec-in-practice-for-natural-language-processing-a179b3286a21?source=rss-93c6107e1856------2</link>
            <guid isPermaLink="false">https://medium.com/p/a179b3286a21</guid>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[similarity]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Roshan Nayak]]></dc:creator>
            <pubDate>Fri, 29 May 2020 21:42:43 GMT</pubDate>
            <atom:updated>2020-07-03T11:56:41.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KHja9ewBsB2P-r7b" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post I would be taking you through:</p><ol><li>What is Word Embeddings?</li><li>Data Preprocessing for Word2Vec.</li><li>Training a Word2Vec model.</li><li>Word similarity.</li></ol><p>Before diving into Word2Vec we have to know what actually <strong>word embedding</strong> is and why is it actually required. So let&#39;s get started.</p><h3>What is Word Embeddings?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*-Md0SXZPy1yWzm4LR5vBHA.png" /><figcaption>Word embeddings plot on a 2D plane. Source of the image: shorturl.at/FHQSU</figcaption></figure><p>Word embeddings are a type of word representation that allows <strong>words with similar meaning</strong> to <strong>have a similar representation</strong>. As we cannot feed in the words directly into the neural networks we have to somehow represent them in the form of vectors of some length. The length of these vectors is basically a hyperparameter. There are a number of algorithms using which we can map the words to the vectors. One of those algorithms is <strong>Word2Vec</strong>. This algorithm performed well when compared with other algorithms that already had been existed and we in the use before.</p><p><strong>Now why Word2Vec is better when compared to Bag of Words and TF-IDF? </strong>When we refer to how actually Bag of words and TF-IDF work we can clearly see that they don&#39;t actually give the sense of where actually the word is being used or in which context the word is being used. They are just a vector having numbers that do not make much sense. Whereas the word embeddings done by word2vec are such that the words with similar meanings have almost the same embedding vector. This gives us a sense of where this particular will actually be used. Below you can see how the word embeddings using word2vec of some of the words would look like. The values are color-coded. Each color represents some value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hML1FAnEGMajIEpIyMPRw.png" /><figcaption>word embeddings of king and queen are almost similar also that of the man and woman. Source of the image is from the Jay Alammar blog: <a href="http://jalammar.github.io/images/word2vec/queen-woman-girl-embeddings.png">http://jalammar.github.io/images/word2vec/queen-woman-girl-embeddings.png</a></figcaption></figure><p>Now if you do some arithmetic like King — Man + Woman = Queen.</p><p>This could be explained as the word <strong>King </strong>would mean <strong>royalty </strong>and a <strong>male </strong>as the gender. If we <strong>subtract man </strong>from it the information related to gender is lost but the royalty still prevails. When you <strong>add Woman</strong> to it, which means now the embedding has the information of <strong>royalty </strong>and the <strong>female </strong>as the gender. Which is basically a <strong>Queen</strong>. In this way, each word vector will hold some meaning into it which gives a sense of its meaning. <strong>Hence words with similar meaning will have almost the same embedding.</strong></p><p>If you would like to learn more about what goes under the hood while learning these embeddings using Word2Vec you could read the following post:</p><p><a href="http://jalammar.github.io/illustrated-word2vec/">http://jalammar.github.io/illustrated-word2vec/</a></p><p>Now that we have got a sense of what word embedding is, let&#39;s look into how do we actually embed the words using Word2Vec.</p><p>At first, you need to install the Gensim library into your local machine if you do not have it. This could be done using simple <strong>pip </strong>or <strong>conda </strong>commands.</p><p>Now let&#39;s look into the data preprocessing part. The dataset I am using contains some simple sentences. I will later provide the GitHub link from where you can get the dataset.</p><h3>Data Preprocessing for Wore2Vec</h3><p>Genism word2vec requires that a format of ‘list of lists’ for training where every document is contained in a list and every list contains lists of tokens of that document. At first, we need to generate a format of ‘list of lists’ for training the make model word embedding. To be more specific its a list of lists of words. Something like this: [[‘I’, ‘am’, ‘here’], [‘yes’, ‘it&#39;s’, ‘correct’]]. The code to generate the list of lists is given below:</p><pre>#import the libraries<br>import pandas as pd<br>from nltk.tokenize import word_tokenize</pre><pre>#read the data from the excel/csv file.<br>data = pd.read_excel(file_path, names = [&#39;sentences&#39;])</pre><pre>sentences = list(data[&#39;sentences&#39;])<br>sentences = [sentence.lower() for sentence in sentences] #lower all the uppes case characters.<br>list_of_list = [word_tokenize(sentence) for sentence in sentences] #Create the required list of list format.</pre><pre>Output: Now the first two elements of the list would look something like this<br>&gt;&gt;&gt;list_of_list[0:2]<br>[[&#39;drunk&#39;,   &#39;bragging&#39;,   &#39;staffer&#39;,   &#39;started&#39;,   &#39;russian&#39;,   &#39;collusion&#39;,   &#39;investigation&#39;],  [&#39;sheriff&#39;,   &#39;david&#39;,   &#39;clarke&#39;,   &#39;becomes&#39;,   &#39;an&#39;,   &#39;internet&#39;,   &#39;joke&#39;,   &#39;for&#39;,   &#39;threatening&#39;,   &#39;to&#39;,   &#39;poke&#39;,   &#39;people&#39;]]</pre><p><strong>So basically a list of lists is nothing but a list containing the list of words.</strong></p><h3>Training a Word2Vec model</h3><p>Now let&#39;s look into the <strong>parameters</strong> of the word2vec model.</p><ol><li><strong>list_of_lists</strong>: This is the same list of lists that we generated during the preprocessing phase.</li><li><strong>min_count: </strong>The minimum count of words to consider when training the model; words with occurrence less than this count will be ignored. The default for min_count is 5.</li><li><strong>size</strong>: The size of the embedding vector for each word and the default is 100.</li><li><strong>workers</strong>: The number of partitions during training and the default workers is 3.</li><li><strong>window</strong>: The maximum distance between a target word and words around the target word. The default window is 5.</li></ol><p>Now to train the model code is given below:</p><pre>&gt;&gt;&gt; from gensim.models import Word2Vec<br>&gt;&gt;&gt; model = Word2Vec(list_of_list, min_count=1,size= 50,workers=3, window =4)</pre><p>Now to have a look at the word embeddings of any of the word with min_count = 1, you can just use indexing and the indexing value to be that word. An example is provided below.</p><pre>&gt;&gt;&gt; model[&#39;drunk&#39;]<br>array([ 0.00175025, -0.00631893, -0.00175   ,  0.00838332,  0.00280083,         0.00377184,  0.00183425, -0.00615874,  0.00777504,  0.00380259,        -0.00834231,  0.00379236,  0.00138776, -0.0038057 ,  0.00721396,         0.00163374,  0.00017319,  0.00034911,  0.00850956, -0.00258099,        -0.00646694,  0.00314683,  0.00375721, -0.00179866,  0.00040652,         0.00085937, -0.00172446,  0.00848798, -0.00937741, -0.00678314,         0.00155409,  0.00540033, -0.00324092,  0.0082706 ,  0.00548601,        -0.009266  ,  0.00593508,  0.00584892,  0.00901981,  0.00890178,        -0.00093049,  0.00156764,  0.00205584, -0.00097351,  0.00111838,         0.00421014, -0.00288082,  0.00719491, -0.00207634, -0.00019168],       dtype=float32)</pre><h3>The similarity between the words</h3><p>Before having a look at the similarity between two words, let&#39;s see how the similarity is actually calculated. As here the words are represented as vectors, we calculate the similarity between these vectors.</p><p><strong>How do we check the similarity between two vectors? </strong>Cosine <strong>similarity</strong> measures <strong>the similarity between two vectors of</strong> an inner product space. It is measured <strong>by the</strong> cosine <strong>of the</strong> angle <strong>between two vectors</strong> and determines whether <strong>two vectors</strong> are pointing in roughly <strong>the</strong> same direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*d-OgMuX7ofIcUnPrVUfjdw.png" /><figcaption>visualizing cosine similarity calculation. Source of the image: shorturl.at/tJKSZ</figcaption></figure><p>And the formula to calculate the similarity is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*CHTUjtaensX3H8pxh9lYLQ.png" /><figcaption>Mathematical expression to calculate cosine similarity. Source of the image: shorturl.at/fmMQ7</figcaption></figure><p>Now that we have a trained model, the similarity() method of the model would calculate the similarity between two words. Let&#39;s have a look at the similarity between some of the words:</p><pre>&gt;&gt;&gt; model.similarity(&#39;he&#39;, &#39;robert&#39;)<br>0.31170955300331116</pre><pre>&gt;&gt;&gt; model.similarity(&#39;he&#39;, &#39;handcuffs&#39;)<br>0.13632124662399292</pre><p>This shows that <strong>‘robert’</strong> is <strong>more similar</strong> to <strong>‘he’</strong> than <strong>‘handcuffs’</strong>.</p><p>The most_similar() method would give the top ten words that have very good similarity with the word under consideration.</p><pre>&gt;&gt;&gt; model.most_similar(&#39;republican&#39;)<br>[(&#39;investigation&#39;, 0.3500652015209198),<br>(&#39;going&#39;, 0.2938186824321747),<br>(&#39;racism&#39;, 0.21984194219112396),<br>(&#39;mocks&#39;, 0.2088545560836792),<br>(&#39;out&#39;, 0.20704494416713715),<br>(&#39;mueller&#39;, 0.19829972088336945),<br>(&#39;brutally&#39;, 0.18746031820774078),<br>(&#39;fbi&#39;, 0.1826065480709076),<br>(&#39;for&#39;, 0.17787611484527588),<br>(&#39;staffer&#39;, 0.17109911143779755)]</pre><h3>Summary</h3><p>We worked on a very small dataset so that you can understand better instead of working on a huge dataset in the beginning. I would request you work this on a larger dataset to get a better sense of word embeddings and the cosine similarity between the words.</p><p>This is it for this post. Thank you for reading. Have a great day ahead :) :) :) :).<strong> Do upvote if you like it and have learned something from this.</strong></p><p>GitHub link for the dataset and the code is given below:</p><p><a href="https://github.com/RosNayak/ECF/tree/master/temp">RosNayak/ECF</a></p><p><strong>References:</strong></p><ol><li>Word2Vec form Jay Alammar: <a href="http://jalammar.github.io/illustrated-word2vec/">http://jalammar.github.io/illustrated-word2vec/</a></li><li>A blog from Jason Brownlee: <a href="https://machinelearningmastery.com/what-are-word-embeddings/">https://machinelearningmastery.com/what-are-word-embeddings/</a></li></ol><p>Do connect me on LinkedIn. My LinkedIn profile link is given below:</p><p><a href="https://www.linkedin.com/in/roshan-nayak-82a452174/">Roshan Nayak - Student - BMS College of Engineering | LinkedIn</a></p><p>If you haven’t read my previous blog on Data Augmentation in Natural Language Processing, do read it.</p><p><a href="https://medium.com/swlh/data-augmentation-in-natural-language-processing-756e942b42f3">Data Augmentation in Natural Language Processing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a179b3286a21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/word2vec-in-practice-for-natural-language-processing-a179b3286a21">Word2Vec in Practice for Natural Language Processing</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Augmentation in Natural Language Processing]]></title>
            <link>https://medium.com/swlh/data-augmentation-in-natural-language-processing-756e942b42f3?source=rss-93c6107e1856------2</link>
            <guid isPermaLink="false">https://medium.com/p/756e942b42f3</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[generalization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Roshan Nayak]]></dc:creator>
            <pubDate>Mon, 18 May 2020 08:32:50 GMT</pubDate>
            <atom:updated>2020-08-13T17:26:01.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Augmentation in Natural Language Processing for Text Classification.</h3><blockquote><em>Improve the performance of your model by generating data on the go.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q4_WcWZPb9WlS2DN" /><figcaption>Photo by <a href="https://unsplash.com/@askkell?utm_source=medium&amp;utm_medium=referral">Andy Kelly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you worked with augmented images before? Augmenting images made your model generalize and perform a lot better by exposing it to much data when you had less of it. In this post, we will go through data augmentation in Natural Language Processing. This post is an overview of the paper</p><blockquote>Easy Data Augmentation for Boosting Performance on Text Classification from Jason Wei and Kai Zou.</blockquote><h3><strong>Why Data Augmentation?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*syAGlTdxtrBwD4vwy1V12w.jpeg" /><figcaption>Go through more examples to understand better!!</figcaption></figure><p>If you have never heard of this term before here is a <strong>brief description</strong> of <strong>what it is and why do we use it?</strong> Image data augmentation is a technique that can be used to artificially expand the size of a training dataset by creating modified versions of images in the dataset. Training deep learning neural network models on more data can result in more skillful models, and the augmentation techniques can create variations of the images that can improve the ability of the fit models to generalize what they have learned to new images. So in general data augmentation help us prevent overfitting and handle the imbalance between the categories in the dataset.</p><h3>Data Augmentation in NLP</h3><p>The paper spoke of four simple ideas of augmenting the texts for text classification problems. Yes, these ideas are as simple as editing the texts. Here they are:</p><ol><li><strong>Synonym Replacement:</strong> Randomly choose <em>n</em> words from the sentence that are not stop words. Replace each of these words with one of its synonyms chosen at random.</li><li><strong>Random Insertion:</strong> Find a random synonym of a random word in the sentence that is not a stop word. Insert that synonym into a random position in the sentence. Do this <em>n</em> times.</li><li><strong>Random Swap:</strong> Randomly choose two words in the sentence and swap their positions. Do this <em>n</em> times.</li><li><strong>Random Deletion:</strong> Randomly remove each word in the sentence with probability <em>p</em>.</li></ol><p>Here is a sense of what these augmented sentence may look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*XGW-14pm1QahThR6n2NGXA.png" /><figcaption>Original and augmented sentences in all four ways.</figcaption></figure><p><strong>Were these ideas actually successful? </strong>At first, it seems like only the first idea Synonym Replacement would work well. But experimenting on a dataset show that all the four ideas worked almost equally well. Exposing a model to augmented data even though they make less sense by applying some random operations to a small dataset worked really well which prevented the model from deeply learning of limited examples and ending up not generalizing. Below is an image that shows how EDA outperformed the normal process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*SEZE83KT37tFVIkVFNBl1A.png" /></figure><h3><strong>What about the labels of augmented data?</strong></h3><p>It&#39;s a valid question that what would happen to the labels of the augmented data? Would they remain the same or will they have changed? If the latter is true then this makes EDA <strong>not an effective way</strong> of Data Augmentation.</p><p>To figure it out, train a model using RNN’s on the dataset that is not augmented for the sake of sentiment analysis. Then, apply EDA to the test set by generating N augmented sentences per original sentence. These are fed into the RNN along with the original sentences. The output vectors of these examples are extracted from the last dense layer. After applying dimensionality reduction to these output vectors and plotting them in the latent space. The plot looked something like this….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*LWnx92GltxRklwyp5XUEFQ.png" /><figcaption>visualizing the outputs of the original and the augmented examples.</figcaption></figure><p>The plots of the augmented examples are quite close to the plots of their original examples. This proves that the augmented examples retain the labels of their original examples. But wait!! Is this true always? Read further.</p><h3><strong>Visualizing four ideas individually</strong></h3><p>How these ideas effect individually? To see this effect apply all the four one at a time. Here are the plots of how actually these ideas performed individually when applied to an RNN model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*1GDRKbyr9boZ3HE3JKRhMQ.png" /><figcaption>Performance Gain vs Alpha parameter.</figcaption></figure><p><strong>Alpha parameter: </strong>The size of the sentence varies a lot. Hence we cannot apply the same amount of augmentation to all the sentences. Like a bit sentences may require more augmentation. Performing the same amount of augmentation on the small sentence would prove to be a disaster!! To avoid this we make use of something called as <strong>Alpha parameter.</strong></p><p><strong>value of n</strong>, n = alpha_parameter*length_of_the_sentence</p><p>We see that for all four ideas having a high alpha value will have a negative impact on the accuracy which we want to seriously avoid. This is because making too many swaps, or changing words would change the identity of the sentence. Hence this proves that augmented sentences do not always retain the labels of the original sentence <strong>if the augmented sentences are significantly different from the original sentences</strong>.</p><h3>Size of the dataset vs alpha value?</h3><p>From the above plots, we see that <strong>EDA works really well on small datasets</strong> when compared to larger datasets. This makes sense right because having larger datasets the model will have already generalized well on real data. Hence augmenting the data and exposing the model to less meaningful and artificial sentences may mislead the model and the model may perform less good than it used to be. Look at the plot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*rUwo5oPgViKNGuy25jpcqw.png" /><figcaption>Performance Gain vs Naug for the dataset of different sizes.</figcaption></figure><p><strong>What do we infer from the pic above? </strong>The performance gain is high for small datasets with more number Naug per sentence. The value of Naug reduces from 16 to 2 as the size of the dataset increases from 500 to &gt;5000 for the max value of performance gain.</p><h3>Hyperparameters to be considered</h3><p>We have got two hyperparameters here.</p><ol><li>alpha -&gt; Percent of words to be altered in a sentence.</li><li>Naug -&gt; number of augmented sentences per original sentence.</li></ol><p>Based on these results, the recommended values for parameters usage are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*3ssn5g3yvMYgn3V8zH6g_Q.png" /><figcaption>Recommended values for parameters for datasets of different sizes.</figcaption></figure><p>This is it for this post…. <strong>Do clap if you liked it</strong>. Experienced people reading this post, please help me understand more by providing suggestions and deeper insights. Connect me on LinkedIn.</p><p><a href="https://www.linkedin.com/in/roshan-nayak-82a452174/">Roshan Nayak - Student - BMS College of Engineering | LinkedIn</a></p><p><strong>All credits</strong> to the paper released by <strong>Jason Wei</strong> and <strong>Kai Zou</strong>. Link of the paper given below. I learned a lot from it.</p><p><a href="https://arxiv.org/abs/1901.11196">EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks</a></p><p><strong>Link to another article by neptune.ai that covers many augmentation techniques for text data.</strong></p><p><a href="https://neptune.ai/blog/data-augmentation-nlp">Data Augmentation in NLP: Best Practices From a Kaggle Master - neptune.ai</a></p><p>If you haven&#39;t read my latest blog on how to implement word2vec, then check out the link given below!!</p><p><a href="https://medium.com/swlh/word2vec-in-practice-for-natural-language-processing-a179b3286a21">Word2Vec in Practice for Natural Language Processing</a></p><p>Thank you for reading this post. Have a great day ahead :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=756e942b42f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/data-augmentation-in-natural-language-processing-756e942b42f3">Data Augmentation in Natural Language Processing</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insights On Memory Efficient Linked List.]]></title>
            <link>https://medium.com/deep-code-life/insights-on-memory-efficient-linked-list-60be49d3ac28?source=rss-93c6107e1856------2</link>
            <guid isPermaLink="false">https://medium.com/p/60be49d3ac28</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[doubly-linked-list]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[memory-efficient-list]]></category>
            <dc:creator><![CDATA[Roshan Nayak]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 18:26:58 GMT</pubDate>
            <atom:updated>2020-03-24T18:52:56.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Start anything by looking a something good!!" src="https://cdn-images-1.medium.com/max/253/1*Gt1miskEESNsv7QZsoqI1Q.jpeg" /><figcaption><strong>Start anything by looking a something good!!</strong></figcaption></figure><p>In today&#39;s world, it is very much necessary to make the proper utilization of the resources to spend less and gain more out of anything. Hence being a software engineer, he should know how to process and manage the data more efficiently and consuming very less memory space. In this article, we will see how could one avoid using two pointers in a doubly-linked list and save a lot of memory.</p><h3><strong>Doubly Linked List</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*Q9IrkEpWjpN45qmY-0VhTQ.png" /></figure><p>Unlike a singly linked list, doubly linked lists have pointers pointing to both the node next to it and the node before it. This help us in traversing back and forth whenever there is a need to do so. We need not traverse the linked list from the beginning if there was a need for accessing a node before the node where we are currently pointing to.</p><p>The structure of a node of a doubly linked:</p><pre>struct Node{<br>    int data; //Data stored in the node.<br>    Node* next_node; //Pointer pointing to the next node.<br>    Node* prev_node; //Pointer pointing to the previous node.<br>};</pre><h3>Memory utilization</h3><p>Let us talk about the memory utilization of the doubly-linked list. Consider we have a doubly-linked list with 10 nodes where each node stores an integer value. Each node of the list contains an integer and two pointers. We know that an integer occupies 4 bytes in the memory. Each pointer occupies 4 bytes if your machine is using a 32-bit processor to store a 32-bit long address and occupies 8 bytes in case you are having a machine using a 64-bit processor. Let us assume your processor to be 64 bit. Hence two pointers occupy 16 bytes in the memory. Summing up totals to the memory occupied by a node which is 16 + 4 = 20 bytes. Ten nodes occupy 20*10 = 200 bytes of memory. Could we reduce this? Yes, let us see how we could reduce this in the next section of the article.</p><h3><strong>Memory Efficient Linked List</strong></h3><p>As the name suggests this linked list functions just like a doubly-linked list but will occupy less memory when compared to the same during runtime. A node in this linked list will have data and a pointer. Unlike the pointers in the nodes of the singly or doubly linked list, the pointer in the node of the memory-efficient linked list would not store the address of any nodes but will store the bitwise XOR of the addresses of the node next to it and the node previous to it. Thus instead of using two pointers, we get the job done with just one pointer.</p><pre>struct Node{<br>    int data; //Data stored in the node.<br>    Node *address_difference;<br>};<br>/*address_difference = next_node_addr ^ prev_node_addr */</pre><p>In the next two sections, we will look at why to avoid doubly-linked list and how do we traverse the Memory Efficient Linked List.</p><h3>Avoid Doubly-Linked List</h3><p>Let us assume that the doubly linked list used previously is now implemented as a memory-efficient linked list. The list was of size 10 and each node had a data of type int. The difference from the old implementation and the new one is that in the new implementation each node is having only one pointer which was two in the old case. Hence each node occupies only 4 + 8 = 12 bytes of space in the memory. The memory occupied by the list totals to 12 * 10 = 120 bytes of memory. We see a huge difference between the previous value and the value calculated now. That is memory-efficient linked list is occupying 80 bytes lesser than the doubly linked list.</p><p>This may seem very less but what if the list had 1000 nodes? The difference, in this case, would calculate to 8000 bytes. For the list having 1000000 nodes, the difference would be 8000000 bytes which are almost equal to 8MB!! Can you imagine? You have saved 8MB of your RAM from being used unnecessarily. This is why the memory-efficient linked list is preferred over the doubly-linked list.</p><h3><strong>Traversing Memory-Efficient Linked List</strong></h3><p>Traversing forward and backward of the linked list could be done using the properties of XOR.</p><pre>Properties of XOR<br>Let a and b be the addresses of the previous and next node respectively.<br>1) (a ^ b) ^ b = a<br>2) (a ^ b) ^ a = b</pre><p>Assume the linked list, head -&gt; A -&gt; B -&gt; C -&gt; D -&gt; E -&gt; null.</p><p>Consider we are at node C and want to get to node D. Pointer in node C has the value (addr_B ^ addr_D). Using this how do we get the address of node D? It’s actually simple. Looking at the property one in the box above we see that expression (addr_B ^ addr_D) ^ addr_B would give us the address of the node D. Hence while traversing in the forward direction its necessary that we use an extra pointer to remember the address of the previous node which would help us in calculating the address of the next node.</p><p>Similarly to traverse the list in the backward direction we must have the address of the next node to calculate the address of the previous node. Using the property two from the above box that is (addr_B ^ addr_D) ^ addr_D would give us the address of the node B.</p><p>I will provide the code snippet on how to traverse the linked list and insert a new node at the end of the list below. If you want a detailed implementation of then please check the link provided below. This would take you to my GitHub repository where I have written down the code for constructing a Memory-Efficient Linked List and printing all the contents in the list.</p><pre><br>struct Node{<br> int x;<br> Node *diff;<br>};</pre><pre>Node* CreateNode(Node *start){<br> Node *temp = new Node;         <br> std::cout&lt;&lt;&quot;Enter the element: &quot;;<br> std::cin&gt;&gt;temp-&gt;x;                     <br> <br> if(start == 0){<br>  start = temp;     <br>  temp-&gt;diff = 0;<br> }<br> else{<br>  Node *temp2 = start;   <br>  Node *prev = 0, *store; <br>  <br>  while((Node*)((uintptr_t)(temp2-&gt;diff)^(uintptr_t)(prev)) != 0){<br>   store = temp2;<br>   temp2 = (Node*)((uintptr_t)(temp2-&gt;diff)^(uintptr_t)(prev));<br>   prev = store;<br>  }<br>  <br>  temp2-&gt;diff = (Node*)((uintptr_t)(temp)^(uintptr_t)(prev));<br>  temp-&gt;diff = temp2;<br> }<br> return start;<br>}</pre><pre>int main(){<br> Node *start = 0;<br> <br> int size;<br> std::cout&lt;&lt;&quot;Enter the size of the list: &quot;;<br> std::cin&gt;&gt;size;<br> <br> for(int i=0; i&lt;size; i++)<br>  start = CreateNode(start);<br> <br> return 0;<br>}</pre><p><strong>GitHub Link to my Code:</strong></p><p><a href="https://github.com/RosNayak/C-/blob/master/MemoryEfficientList.cpp">https://github.com/RosNayak/C-/blob/master/MemoryEfficientList.cpp</a></p><p>Hope this post will help. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60be49d3ac28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deep-code-life/insights-on-memory-efficient-linked-list-60be49d3ac28">Insights On Memory Efficient Linked List.</a> was originally published in <a href="https://medium.com/deep-code-life">deep code life</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>