<?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 Raj Sangani on Medium]]></title>
        <description><![CDATA[Stories by Raj Sangani on Medium]]></description>
        <link>https://medium.com/@rajbsangani?source=rss-7e3aebe20c71------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3wicJbtMpyXD8G4BH2gZKw.jpeg</url>
            <title>Stories by Raj Sangani on Medium</title>
            <link>https://medium.com/@rajbsangani?source=rss-7e3aebe20c71------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:49:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajbsangani/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[Advanced Recipes for Contrastive Learning]]></title>
            <link>https://pub.towardsai.net/advanced-recipes-for-contrastive-learning-fa7e2d802fc0?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa7e2d802fc0</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 01:50:02 GMT</pubDate>
            <atom:updated>2024-09-11T04:46:25.645Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to maximize batch size and choose in-batch negatives smartly to get the most out of your retrieval and search systems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Onxsefo6uyANIOax" /><figcaption>Photo by <a href="https://unsplash.com/@olloweb?utm_source=medium&amp;utm_medium=referral">Agence Olloweb</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Note : This blog assumes familiarity with basic knowledge about dense retrievers, RAG systems and contrastive learning. A very solid introduction to this can be found in the </em><a href="https://arxiv.org/pdf/2004.04906"><em>original DPR paper</em></a><em> from FAIR.</em></p><h3>Table of Contents</h3><ol><li>Possible issues with traditional training methods for retrievers</li><li>Massively increasing batch size using gradient caching (<strong>by a factor of 1000 on modern GPUs!</strong>)</li><li>Further increasing batch size in multi-GPU settings</li><li><strong>FURTHER </strong>increasing the number of in-batch negatives through an alternative loss function</li><li>Are in-batch negatives REALLY negatives? Filtering out false in-batch negatives</li></ol><h3>Terminology</h3><p>For consistency, here are some terms that will appear in later sections</p><p><strong>Query or Anchor</strong> — The question for which we are retrieving documents</p><p><strong>Positive</strong> — The document which correctly answers the query</p><p><strong>Negative</strong> — Any unrelated document that does not answer the query</p><p><strong>Hard Negative</strong> — A document which is very similar to the query but does not contain the correct answer.</p><p><strong>In-batch negatives — </strong>For every query, positive pair in a batch, all positive documents corresponding to the other queries can be used as negatives since they are unrelated.</p><h3>1. Issues with Dense Contrastive Learning</h3><p>The objective we optimize in dense retrieval looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hApgVNri1Z5GdUToY4p63Q.png" /><figcaption>Source : <a href="https://arxiv.org/pdf/2402.16829">https://arxiv.org/pdf/2402.16829</a></figcaption></figure><p>The summation term in the denominator contains documents which are positive documents for other queries in the batch but are used as negatives for the given query, positive pair in the numerator.</p><p>Several studies show that having a large batch <strong><em>B</em></strong> allows the use of more in-batch negatives and hence learns a better metric space.</p><p><strong>Unfortunately, when using transformer models to embed long documents, we run out of GPU memory quickly since long sequences take up huge activation memory. </strong><a href="https://erees.dev/transformer-memory/"><em>Here</em></a><em> is a great blog that details memory usage in decoder models.</em></p><p>As a result of this, we have to resort to smaller batches which is not helpful. Even turning to techniques such as <a href="https://aman.ai/primers/ai/grad-accum-checkpoint/#:~:text=Gradient%20accumulation%20is%20a%20technique,after%20each%20batch%20of%20data.">gradient accumulation</a> is of no use since we need all the negatives in memory at once as our loss is inseparable (due to the denominator).</p><h3>2. Enter Gradient Caching</h3><p>The authors of the paper <a href="https://arxiv.org/pdf/2101.06983"><em>Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup</em></a><em> </em>identify this problem and solve it.</p><p>They observe that we can separate the backpropagation process of contrastive loss into two independent parts with respect to batch examples</p><ol><li>from loss to representation,</li><li>from representation to model parameters</li></ol><p><strong>I would strongly encourage the mathematically curious readers to refer to section 3.2 in the paper for a detailed analysis on the independence.</strong></p><p>Based on these observations, they list the following steps to compute the gradients</p><h4>1. <strong>Graph-less Forward</strong></h4><p>Before gradient computation, run an extra forward pass for each batch instance to get its representation. Importantly, this forward pass runs without constructing the computation graph. Collect and store all representations computed.</p><h4><strong>2. Representation Gradient Computation and Caching</strong></h4><p>Compute the contrastive loss for the batch based on the representation from Step1 and have a corresponding computation graph constructed. A backward pass is then run to populate gradients for each representation. <strong>Note that the retriever model is not included in this gradient computation.</strong></p><h4>3. Sub-batch Gradient Accumulation</h4><p>Construct sub-batches of the batch (could be as small as a batch of 1 instance). Run model forward one sub-batch at a time to compute representations and build the corresponding computation graph. We take the sub-batch’s representation gradients from the cache and run back propagation through the encoder. Gradients are accumulated for model parameters across all sub-batches.</p><h4>4. Optimization</h4><p>When all sub-batches are processed, step the optimizer to update model parameters as if the full batch is processed in a single pass</p><p>At the cost of some training time due to the extra forward passes, we can now fit extremely large batches onto a GPU. <strong>I have personally used this method to increase batch size by a factor of 1024 with a sub-batch size of 1!</strong></p><h3>3. Further increasing batch size through multiple GPUs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*mlzWtFu3ZUlZ6dFtzteQPA.png" /><figcaption>Source : <a href="https://arxiv.org/pdf/2010.08191">https://arxiv.org/pdf/2010.08191</a></figcaption></figure><p>With the availability of multiple GPUs, say A GPUs, we can further increase batch size by a factor of A.</p><p>For each query, positive pair in a batch we have B-1 in-batch negatives. As we can see in the figure, if we compute representations on each GPU and then share them across GPUs, we are utilizing the same amount of memory but increasing the number of negatives by a factor equivalent to the number of available GPUs!</p><h3>4. Bidirectional Contrastive Loss</h3><p>In-batch sampling is a very smart way of saving on memory but can we do better? <strong>ABSOLUTELY</strong>!</p><p>The authors of the paper <a href="https://arxiv.org/pdf/2308.03281"><em>Towards General Text Embeddings with Multi-stage Contrastive Learning</em></a><em> </em>cleverly<em> </em>utilize the whole batch to effectively increase the number of negatives.</p><p>They propose the following loss</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4f_hsHEyTeJU-ItqUuIkNg.png" /><figcaption>Source : <a href="https://arxiv.org/pdf/2308.03281">https://arxiv.org/pdf/2308.03281</a></figcaption></figure><p><strong>where Z is :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*TrbuRbD9VZXBlVSKWfLxFA.png" /><figcaption>Source : <a href="https://arxiv.org/pdf/2308.03281">https://arxiv.org/pdf/2308.03281</a></figcaption></figure><p>For a given query, positive pair, they not only use traditional in-batch negatives, but also</p><ul><li>similarities between the given query and all other queries in the batch</li><li>similarities between the given positive and all other positives in the batch</li><li>similarities between current positive and all other queries in the batch</li></ul><p>to enhance the effective number of negatives.</p><p><strong>This modified objective yields improvements in scores on the MTEB benchmark.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*TqW2qQ73p7dU0qmqwfxNkQ.png" /><figcaption>Source : <a href="https://arxiv.org/pdf/2308.03281">https://arxiv.org/pdf/2308.03281</a></figcaption></figure><h3>5. Can in-batch negatives be considered as REAL negatives?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HeCzM7rB1_rWjrSd" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So far, we have focused on increasing batch size and finding more negatives in a batch but there are often cases when the documents that we sample for a query, positive pair within the batch are actually not unrelated to the query.</p><p><strong>This makes them false negatives!</strong></p><p>Thankfully the author of <a href="https://arxiv.org/pdf/2402.16829"><em>GISTEmbed: Guided In-sample Selection of Training Negatives for Text Embedding Fine-tuning</em></a><em> </em>has a very simple fix for this.</p><p><strong>The goal is to discard the similarity scores for those items in equation 5 (in the above section) that have a higher similarity than the given query, document pair.</strong></p><p>One can use a stronger guide model <strong>(a pre-trained encoder model used as a cross-encoder)</strong> to calculate the similarity scores for all the candidates in our partition function <strong>(equation 6 in the above section) and mask out all those scores that are more similar than the query,positive pair because these candidate pairs can’t be interpreted as negatives.</strong></p><h3><strong>Closing Thoughts</strong></h3><p>Note that the ideas mentioned above are intended to squeeze out every bit of performance from your retrieval system, but the core power of such a system always lies in the question: document pairs itself.</p><p>Training with a dataset that has a diverse set of questions and documents that are clean and unambiguous is the bread and butter for any retrieval system!</p><p>On a personal note, I really enjoyed writing this blog since this is my first blog after almost two years! I hope you enjoyed reading it!</p><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><p>If you liked this here are some more!</p><ul><li><a href="https://medium.com/towards-data-science/a-comprehensive-guide-on-model-calibration-part-1-of-4-73466eb5e09a">A Comprehensive Guide on Model Calibration: What, When, and How</a></li><li><a href="https://towardsdatascience.com/overfitting-is-not-the-only-problem-regularisation-can-help-with-6fcdbfdb9384">Overfitting is not the only problem Regularisation can help with</a></li><li><a href="https://towardsdatascience.com/dealing-with-features-that-have-high-cardinality-1c9212d7ff1b">Dealing with features that have high cardinality</a></li></ul><h3>References</h3><ol><li>Dense Passage Retrieval for Open-Domain Question Answering <a href="https://arxiv.org/abs/2004.04906">https://arxiv.org/abs/2004.04906</a></li><li>RocketQA: An Optimized Training Approach to Dense Passage Retrieval for Open-Domain Question Answering <a href="https://arxiv.org/abs/2010.08191">https://arxiv.org/abs/2010.08191</a></li><li>Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup <a href="https://arxiv.org/abs/2101.06983">https://arxiv.org/abs/2101.06983</a></li><li>GISTEmbed: Guided In-sample Selection of Training Negatives for Text Embedding Fine-tuning <a href="https://arxiv.org/pdf/2402.16829">https://arxiv.org/pdf/2402.16829</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa7e2d802fc0" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/advanced-recipes-for-contrastive-learning-fa7e2d802fc0">Advanced Recipes for Contrastive Learning</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide on Model Calibration: What, When, and How]]></title>
            <link>https://medium.com/data-science/a-comprehensive-guide-on-model-calibration-part-1-of-4-73466eb5e09a?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/73466eb5e09a</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 19:56:43 GMT</pubDate>
            <atom:updated>2024-03-08T17:16:18.374Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Part 1: Learn about calibrating machine learning models to obtain sensible and interpretable probabilities as outputs</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y2VoeGF9NGks4f0j" /><figcaption>Photo by <a href="https://unsplash.com/@adigold1?utm_source=medium&amp;utm_medium=referral">Adi Goldstein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Despite the plethora of blogs one can find today that talk about fancy machine learning and deep learning models, I could not find many resources that spoke about model calibration and its importance. What I found even more surprising was that model calibration can be critical for some use cases and yet it is not spoken about enough. Hence, I will write a 4 part series delving into calibrating models. Here is what you can expect to learn once you reach the end of the series.</p><h4>Learning Outcomes</h4><ul><li><strong>What is model calibration and why it is important</strong></li><li><strong>When to and When NOT to calibrate models</strong></li><li><strong>How to assess whether a model is calibrated (reliability curves)</strong></li><li><strong>Different techniques to calibrate a Machine Learning model</strong></li><li>Model calibration in low-data settings</li><li>Calibrating multi-class classifiers</li><li>Calibrating modern Deep Learning Networks in PyTorch</li><li>Calibrating regressors</li></ul><p>In today’s blog, we will be looking at the first four highlighted points.</p><h3>What is model calibration?</h3><p>Let’s consider a binary classification task and a model trained on this task. Without any calibration, the model’s outputs cannot be interpreted as true probabilities. For instance, for a cat/dog classifier, if the model outputs that the prediction value for an example being a dog is 0.4, this value cannot be interpreted as a probability. <strong><em>To interpret the output of such a model in terms of a probability, we need to calibrate the model.</em></strong></p><p>Surprisingly, most models out of the box are not calibrated and their prediction values often tend to be under or over confident. What this means is that, they predict values close to 0 and 1 in many cases where they should not be doing so.</p><h4>Interpreting the output of a non-calibrated and calibrated model</h4><p>To better understand why we need model calibration, let’s look into the previous example whose output value is 0.4 .<strong> Ideally, what we would want this value to represent is the fact that if we were to take 10 such pictures and the model classified them as dogs with probabilities around 0.4 , then in reality 4 of those 10 pictures would actually be dog pictures. </strong>This is exactly how we should interpret outputs from a <strong><em>calibrated</em></strong> model.</p><p><strong>However, if the model is not calibrated, then we should not expect that this score would mean that 4 out of the 10 pictures will actually be dog pictures.</strong></p><h3>When NOT to calibrate models</h3><p>The whole reason we calibrate models, is that we want the outputs to make sense when interpreted as standalone probabilities. However for some cases such as a model that ranks titles of news articles in terms of quality, we just need to know which title scored the highest if our policy is to select the best title. In this case calibrating the model does not make much sense.</p><h3>When to calibrate models and why it can be critical</h3><p>Let’s say we want to classify whether a fire alarm triggers correctly. (We will go through this in code today.) Such a task is critical in the sense that we want to throughly understand our model’s predictions and improve the model so that is sensitive to true fires. Let’s say we run a test for a two examples that classify the chances of a fire as 0.3 and 0.9. <strong>For an uncalibrated model, it does not mean that the second example is likely to result in an actual fire thrice as many times as the first one.</strong></p><p>Moreover, after deploying this model and receiving some feedback, we now contemplate about improve our smoke detectors and sensors. Running some simulations using our new model, we see that the previous examples score 0.35 and 0.7 now.</p><p>Say, improving our system costs 200 thousand US Dollars. We want to know whether we should invest this amount of money for a change in score of 0.05 and 0.2 for each example respectively. <strong>For an uncalibrated model, comparing these numbers would not make any sense and hence we won’t be able to correctly estimate whether an investment will lead to tangible gains. But if our models were calibrated, we could settle this dilemma through an expert guided probability based investigation.</strong></p><p><strong><em>Often model calibration is critical for models in production that are being improved through continual learning and feedback.</em></strong></p><h3>Assessing Model Calibration</h3><p>Now that we know, why we should calibrate our model (if needed) let’s find out how to identify if our model is calibrated.</p><p>Those who directly want to skip to the code can access it here.</p><h4>The Dataset</h4><p>Today, we will look at the telecom customer churn prediction dataset from <a href="https://www.kaggle.com/datasets/rjmanoj/telecom-customer-churn-prediction">Kaggle</a>. You can read more about the covariates and the types of smoke detectors, check out the description page of the dataset on Kaggle. <strong>We will try calibrating a LightGBM model on this data since XGBoost usually is uncalibrated out-of-the-box.</strong></p><p><strong>The dataset is officially from IBM and can be freely downloaded </strong><a href="https://community.ibm.com/accelerators/catalog/content/Telco-customer-churn"><strong>here</strong></a><strong>. It is licensed under the Apache License 2.0 as found </strong><a href="https://github.com/IBM/telco-customer-churn-on-icp4d/blob/master/LICENSE"><strong>here</strong></a><strong>.</strong></p><h4>Reliability Curves</h4><p>The reliability curve is a nice visual method to identify whether or not our model is calibrated. First we create bins from 0 to 1. Then we divide our data according to the predicted outputs and place them into these bins. For instance if we bin our data in intervals of 0.1, we will have 10 bins between 0 and 1. Say we have 5 data points in the first bin, i.e we have 5 points <strong>(0.05,0.05,0.02,0.01,0.02)</strong> whose model prediction range lies between 0 and 0.1. Now on the X axis we plot the average of these predictions i.e <strong>0.03 and on the Y axis, we plot the empirical probabilities, i.e the fraction of data points with ground truth equal to 1. Say out of our 5 points, 1 point has the ground truth value 1. In that case our y value will be 1/5 = 0.2. Hence the coordinates of our first point are [0.03,0.2]. </strong>We do this for all the bins and connect the points to form a line. We then compare this line to the line</p><p><strong>y = x </strong>and assess the calibration. <strong>When the dots are above this line the model is under-predicting the true probability and if they are below the line, model is over-predicting the true probability.</strong></p><p>We can construct this plot using Sklearn and it looks like the plot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*ptp4mjN8PneLqJhuP07FBg.png" /><figcaption>Sklearn’s calibration curve (Image by Author)</figcaption></figure><p>As you can see the model is over-confident till about 0.6 and then under-predicts around 0.8</p><p>However, the Sklearn plot has a few flaws and hence <strong>I prefer using the plots from Dr. Brian Lucena’s ML-insights </strong><a href="https://ml-insights.readthedocs.io/en/latest/#"><strong>package</strong></a>.</p><p>This package shows you confidence intervals around the data points and also shows you how many data points you have across each interval (in each bin) and hence you can create custom bin intervals accordingly. As we will also see, sometimes models are over-confident and predict values very close to 0 or 1, in which case the package has a handy logit-scaling feature to show what’s happening around probabilities very close to 0 or 1.</p><p>Here is the same plot as the one above created using Ml-insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdCMqexzz1lEnyzGg9f37A.png" /><figcaption>Ml-insight’s reliability curve (Image by Author)</figcaption></figure><p>As you can see, we also see the histogram distribution of the data points in each bin along with the confidence interval.</p><h4>Quantitatively Assessing Model Calibration</h4><p>According to what I have gathered while reading on some literature in this area, capturing model calibration error has no perfect method. Metrics such as Expected calibration Error are often used in literature but as I have found (and as you can see in my notebook and code), ECE wildly varies with the number of bins you select and hence isn’t always fool proof. I will discuss this metric in more detail in the more advanced calibration blogs in the future. <strong>You can read more about ECE in this blog </strong><a href="https://medium.com/@wolframalphav1.0/evaluate-the-performance-of-a-model-in-high-risk-applications-using-expected-calibration-error-and-dbc392c68318"><strong><em>here</em></strong></a><strong>. I would strongly suggest you go through it.</strong></p><p>A metric I use here, based on Dr. Lucena’s blogs is traditional log loss. The simple intuition here is that, log-loss (or cross entropy) penalises models that are too overconfident when making wrong predictions or making predictions that differ significantly from their true probabilities. You can read more about quantitative model calibration in this <a href="https://github.com/numeristical/resources/blob/master/CalibrationWorkshop/Calibration_Workshop_1.ipynb">n</a>otebook.</p><p><strong><em>To summarize, we would expect a calibrated model to have a lower log-loss than one that is not calibrated well.</em></strong></p><h3>Methods to Calibrate Models</h3><h4>Splitting the Data</h4><p>Before we do ANY calibration, it is important to understand that we cannot calibrate our model and then test the calibration on the same dataset. Hence to avoid data leakage, we first split the data into three sets- train, validation and test.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D16&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D16&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d990ab5312acd5eb6a46766fa94116dc/href">https://medium.com/media/d990ab5312acd5eb6a46766fa94116dc/href</a></iframe><h4>Uncalibrated Performance</h4><p>First, this is how our uncalibrated LightGBM model performs on our data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D23&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D23&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2cd9f966fc208d1257374ecefd56936/href">https://medium.com/media/d2cd9f966fc208d1257374ecefd56936/href</a></iframe><h4>Platt Scaling</h4><p>Platt Scaling assumes that there is a logistic relationship between the model predictions and the true probabilities.</p><p><strong>Spoiler — This is not true in many cases.</strong></p><p>We simply use a logistic regressor to fit on the model predictions for the validation set and the true probabilities of this validation set as the outputs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D27&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D27&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/70a350734ea50cf4d10842a98fdecd22/href">https://medium.com/media/70a350734ea50cf4d10842a98fdecd22/href</a></iframe><p>Here is how it performs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D29&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D29&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/651361a017fb12fa3ab9cd09f056d0a3/href">https://medium.com/media/651361a017fb12fa3ab9cd09f056d0a3/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D28&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D28&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbc76f86344859d99f7c399aa8723115/href">https://medium.com/media/cbc76f86344859d99f7c399aa8723115/href</a></iframe><p><strong>As we can see our log-loss has definitely reduced here. Since we have many data points with model predictions close to 0, we can see the benefit of using the Ml-insights package (and its logit scaling feature) here</strong>.</p><h4>Isotonic Regression</h4><p>This method combines Bayesian classifiers and Decision trees to calibrate models and works better than Platt scaling when we have enough data for it to fit. The detailed algorithm can be found <a href="https://cseweb.ucsd.edu/~elkan/calibrated.pdf">here</a>.</p><p>I used the ml-insights package to implement isotonic regression.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D32&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D32&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2ca942c1761f6d5b150cc0c8bdac988/href">https://medium.com/media/d2ca942c1761f6d5b150cc0c8bdac988/href</a></iframe><p>This seems to work better than Platt scaling for our data. <strong>Although it would be much wiser to come to such conclusions after averaging the results of these experiments over different data splits and random seeds or using cross-validation (as we will see in future blogs).</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D33&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D33&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2557f257fd0eac33a8e0e5c06afea14/href">https://medium.com/media/a2557f257fd0eac33a8e0e5c06afea14/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D34&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D34&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4139145e313a305ae50e5221022f9f4/href">https://medium.com/media/d4139145e313a305ae50e5221022f9f4/href</a></iframe><h4>Spline Calibration</h4><p>This algorithm was given by the author of the Ml-insights package (Brian Lucena) and can be found in this <a href="https://arxiv.org/pdf/1809.07751.pdf">paper</a>.</p><p>Essentially, the algorithm uses a smooth cubic polynomial (which is chosen to minimize a certain loss as detailed in the paper for those interested in the technical nitty-gritties) and is fit on the model predictions on the validation set and its true probabilities.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D37&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D37&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/af95fb67568d035a3838456a077e85a6/href">https://medium.com/media/af95fb67568d035a3838456a077e85a6/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D36&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D36&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca3dd4c1cdc74168d7208a502c25703a/href">https://medium.com/media/ca3dd4c1cdc74168d7208a502c25703a/href</a></iframe><p>Spline Calibration fares the best on our data (for this split at least).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D38&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D38&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4ae7ae819598c56bd3aeef4c4822519/href">https://medium.com/media/b4ae7ae819598c56bd3aeef4c4822519/href</a></iframe><p>Here is how all of them do in a single plot</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D40%26hideInput%3Dtrue&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D40%26hideInput%3Dtrue&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ed893f8c6bd298cd9f781530bf7830f/href">https://medium.com/media/6ed893f8c6bd298cd9f781530bf7830f/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D42%26hideInput%3Dtrue&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D42%26hideInput%3Dtrue&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5d3a8785b8eceda2f706b3a6564b9a6/href">https://medium.com/media/d5d3a8785b8eceda2f706b3a6564b9a6/href</a></iframe><h3>Expected Calibration Error and its Flaws</h3><p>A lot of contemporary literature mentions ECE as a metric to measure how well a model is calibrated.</p><p>Here is how ECE is formally calculated.</p><ol><li>Choose n the number of bins as we did earlier</li><li>For each bin calculate the average of the model predictions of the data points belonging to that bin and normalize it by the number of data points in that bin.</li><li>For each bin also calculate the fraction of true positives.</li><li>Now for each bin calculate the absolute difference between the values calculated in step 3 and step 2and multiply this absolute difference by the number of data points in that bin.</li><li>Add the results for all bins calculated in step 4 and normalize this added sum by the total number of samples in all the bins.</li></ol><p>The code to calculate ECE can be found in this <a href="https://medium.com/@wolframalphav1.0/evaluate-the-performance-of-a-model-in-high-risk-applications-using-expected-calibration-error-and-dbc392c68318">blog</a> and has been used in my experiments.</p><p>However, in my case, the distribution of the data points across the bins was not very uniform (since most data points belonged to the first bin) and thus it is imperative to select the bins for ECE accordingly. We can see how the number of bins is directly affecting ECE in the algorithm.</p><p>For instance for only 5 bins, the uncalibrated model seemed to have lesser calibration error than all the other methods.</p><p>However when we increase the number of bins, we can see that model calibration has actually helped in our case.</p><p>In the code snippets below, this effect can be verified. Please overlook the OE (Overconfidence Error Metric for now) as it is not used widely in literature.</p><p><strong>For 5 bins we have</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D47&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D47&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9addcfdb8257614cf40c6c4c5685e3c/href">https://medium.com/media/f9addcfdb8257614cf40c6c4c5685e3c/href</a></iframe><p><strong>For 50 bins we have</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D48&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D48&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2e922ed977f39c84e14181c332c5206/href">https://medium.com/media/a2e922ed977f39c84e14181c332c5206/href</a></iframe><p><strong>For 500 bins we have</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D49&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D49&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/26448e81392e322ea62d9a1d318264d7/href">https://medium.com/media/26448e81392e322ea62d9a1d318264d7/href</a></iframe><p><strong>For 5000 bins we have</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D50&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fmodel-calibration-churn%2Fv%2F1%26cellId%3D50&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F8885ae1a8b1f4db7a04c7981ec970b04%2Fpreview%2Fc80f517bc2234251a981b113c2deb6ae&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5d7a849f350027c57a2b99f2b1c7d78/href">https://medium.com/media/a5d7a849f350027c57a2b99f2b1c7d78/href</a></iframe><h3>Conclusion</h3><p>In today’s blog we saw what model calibration is, how to assess the calibration of a model and some metrics to do so, explored the ml-insights package along with some methods to calibrate a model and finally explored the fallacies of ECE.</p><p>Next time we will look into robust calibration for low-data settings, calibrating deep learning models and finally calibrating regressors.</p><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><p>If you liked this here are some more!</p><ul><li><a href="https://towardsdatascience.com/interpreting-an-lstm-through-lime-e294e6ed3a03">Interpreting an LSTM through LIME</a></li><li><a href="https://towardsdatascience.com/adding-custom-layers-on-top-of-a-hugging-face-model-f1ccdfc257bd">Adding Custom Layers on Top of a Hugging Face Model</a></li><li><a href="https://towardsdatascience.com/dealing-with-features-that-have-high-cardinality-1c9212d7ff1b">Dealing with features that have high cardinality</a></li></ul><h3>Acknowledgements</h3><p>I thank Dr. Brian Lucena for his help and advice on various topics related to this blog. I also found his YouTube playlist on model calibration extremely detailed and helpful and most of my experiments are based on his videos.</p><h3>References</h3><ol><li><a href="https://www.youtube.com/playlist?list=PLeVfk5xTWHYBw22D52etymvcpxey4QFIk">https://www.youtube.com/playlist?list=PLeVfk5xTWHYBw22D52etymvcpxey4QFIk</a></li><li><a href="https://cseweb.ucsd.edu/~elkan/calibrated.pdf">https://cseweb.ucsd.edu/~elkan/calibrated.pdf</a></li><li><a href="https://www.unofficialgoogledatascience.com/2021/04/why-model-calibration-matters-and-how.html">https://www.unofficialgoogledatascience.com/2021/04/why-model-calibration-matters-and-how.html</a></li><li><a href="https://towardsdatascience.com/classifier-calibration-7d0be1e05452">https://towardsdatascience.com/classifier-calibration-7d0be1e05452</a></li><li><a href="https://medium.com/@wolframalphav1.0/evaluate-the-performance-of-a-model-in-high-risk-applications-using-expected-calibration-error-and-dbc392c68318">https://medium.com/@wolframalphav1.0/evaluate-the-performance-of-a-model-in-high-risk-applications-using-expected-calibration-error-and-dbc392c68318</a></li><li><a href="https://arxiv.org/pdf/1809.07751.pdf">https://arxiv.org/pdf/1809.07751.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73466eb5e09a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-comprehensive-guide-on-model-calibration-part-1-of-4-73466eb5e09a">A Comprehensive Guide on Model Calibration: What, When, and How</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[Adding Custom Layers on Top of a Hugging Face Model]]></title>
            <link>https://medium.com/data-science/adding-custom-layers-on-top-of-a-hugging-face-model-f1ccdfc257bd?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1ccdfc257bd</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 08:56:14 GMT</pubDate>
            <atom:updated>2022-01-26T08:56:14.309Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to extract the hidden states from a Hugging Face model body, modify/add task-specific layers on top of it and train the whole custom setup end-to-end using PyTorch</h4><p>Before starting, this post assumes basic familiarity with Hugging Face (using a model out-of-the-box ). Also, a huge shoutout to the folks at <a href="https://huggingface.co/"><strong>Hugging Face</strong> </a>for setting up a beginner-friendly learning environment!</p><h3>What will you learn from this blog?</h3><ol><li>Use task-specific models from the Hugging Face Hub and make them adapt to your task at hand.</li><li>De-coupling a Model’s head from its body and using the body to leverage domain-specific knowledge.</li><li>Building a custom head and attaching it to the body of the HF model in PyTorch and training the system end-to-end.</li></ol><h3>The anatomy of a Hugging Face Model</h3><p>Here is what a typical HF model looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*7JDSKluZfSSI0O1yRWUIOQ.png" /><figcaption>Image By Author</figcaption></figure><h3>Why will I need to use the head and body separately?</h3><p>Some models on Hugging Face are trained on downstream tasks like question-answering or text classification and contain knowledge about the data they were trained on in their weights.</p><p><strong>Sometimes, especially when our task at hand contains very little data or is domain-specific (such as medical or sports specific tasks), we can make use of other models on the </strong><a href="https://huggingface.co/models"><strong><em>hub</em></strong></a><strong> trained on tasks <em>(not necessarily the same task as our task at hand but falling within the same domain, such as sports or medicine)</em> and make use of some of the pretrained knowledge these models to improve performance on our own task.</strong></p><ol><li>A very simple example would be if say we <strong>have a small dataset</strong> about classifying whether some financial statements are positive or negative in terms of sentiment. <strong>However, we go onto the Hub and find that a lot of models have been trained for QA related to finance.</strong> We can use <strong><em>certain layer</em>s</strong> from these models for improving our own tasks.</li><li>Another simple example is when a certain <strong>domain-specific model has learned to classify text into 5 categories from a huge dataset it was trained on</strong>. <strong>Say we have a similar classification task, a completely different dataset in the same domain and only want to classify the data into 2 categories instead of 5. </strong>We can again use a model’s body and add our own head in an attempt to <strong>augment domain-specific knowledge on our own task.</strong></li></ol><p>Diagrammatically, this is what we are trying to do</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*5h3h7WtxAZpmmjfem3eoUQ.png" /><figcaption>Image By Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*Zz_QpVlAPF0Jkgd02948Yg.png" /><figcaption>Image By Author</figcaption></figure><h3>Jumping into the code!</h3><p><strong>Our task is simple, sarcasm detection on </strong><a href="https://www.kaggle.com/rmisra/news-headlines-dataset-for-sarcasm-detection"><strong>this</strong></a><strong> dataset from Kaggle.</strong></p><p><strong>You can check out the full code </strong><a href="https://jovian.ai/rajbsangani/emotion-tuned-sarcasm"><strong>here</strong></a><strong>. I have not included the preprocessing and some training details below in the interest of time so make sure to check out the notebook for the entire code.</strong></p><p><em>I will use a model with 5 classification outputs trained on a huge corpus of tweets to classify 5 different emotions, extract the body and add custom layers in PyTorch for our task (2 labels, sarcastic and not sarcastic) and train the new model end-to-end.</em></p><p><strong>Note: You can use any model in this example (not necessarily a model trained for classification) since we will only use that model’s body and leave the head.</strong></p><p>This is what our workflow looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*vBXL8SiUl9lPLvZkUIoGUQ.png" /><figcaption>Image By Author</figcaption></figure><p>I will be skipping the data-preprocessing steps and jumping straight to the main class, but you can check out the entire code in the link at the beginning of this section.</p><h4>Tokenization and Dynamic Padding</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D3&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D3&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2F1b735f821b8d44b0ba16780e6dc9ad2b%2Fpreview%2Fa6a19a0c24114d68b82723be07374196&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/cda6ebcfdc7712354fa81fbf424ad560/href">https://medium.com/media/cda6ebcfdc7712354fa81fbf424ad560/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D4&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Frajbsangani%2Fprofile_images%2F9938bfda0ae6401db98f694931268598%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e72bc839ae7387f23e52a42d1f5ff76/href">https://medium.com/media/3e72bc839ae7387f23e52a42d1f5ff76/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D5&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D5&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Frajbsangani%2Fprofile_images%2F9938bfda0ae6401db98f694931268598%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/16f31e4ec9ae93ccbc8eb9015cccb82a/href">https://medium.com/media/16f31e4ec9ae93ccbc8eb9015cccb82a/href</a></iframe><h4>Extracting the Body and adding our own layers</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D6&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Frajbsangani%2Fprofile_images%2F9938bfda0ae6401db98f694931268598%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa2f95aaab837e0b2a40045be7692f78/href">https://medium.com/media/aa2f95aaab837e0b2a40045be7692f78/href</a></iframe><p><strong>As you can see we first subclass the nn Module from PyTorch, extract the model body using AutoModel (from transformers) and provide the checkpoint to the model whose body we want to use.</strong></p><p><em>Note that a </em><strong><em>TokenClassifierOutput (from the transformers library)</em></strong><em> is returned which makes sure that our output is in a similar format to that from a Hugging Face model on the hub.</em></p><h4>Training the new model end-to-end</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D11&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Frajbsangani%2Fprofile_images%2F9938bfda0ae6401db98f694931268598%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/417d8c9287125a9e3f56bd7046467ee8/href">https://medium.com/media/417d8c9287125a9e3f56bd7046467ee8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Femotion-tuned-sarcasm%2Fv%2F1%26cellId%3D12&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Frajbsangani%2Fprofile_images%2F9938bfda0ae6401db98f694931268598%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e0034a8a3eb3e7d8901844acfc5294d/href">https://medium.com/media/7e0034a8a3eb3e7d8901844acfc5294d/href</a></iframe><p>As you can see, we achieve a decent performance using this method. <strong>Keep in mind that the aim of this blog isn’t to analyze performance for this particular dataset but to learn how to use a pre-trained Body and add a Custom Head.</strong></p><h3>Conclusion</h3><p>We saw how one can add custom layers to a pre-trained model’s body using the Hugging Face Hub.</p><p>Some takeaways:</p><ol><li>This technique is particularly helpful in cases where we have small domain-specific datasets and want to leverage models trained on larger datasets in the same domain (task-agnostic) to augment performance on our small dataset.</li><li>We can choose models that have been trained on downstream tasks different from our own task and still use the knowledge from that model’s body.</li><li>This may not be necessary at all if your dataset is large enough and generic, in which case you can use AutoModelForSequenceClassification or whatever other task you have to solve using a BERT like checkpoint. In fact, if that is so, I would strongly recommend not building your own head.</li></ol><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><p>If you liked this here are some more!</p><ul><li><a href="https://towardsdatascience.com/interpreting-an-lstm-through-lime-e294e6ed3a03">Interpreting an LSTM through LIME</a></li><li><a href="https://towardsdatascience.com/locality-sensitive-hashing-in-nlp-1fb3d4a7ba9f">Locality Sensitive Hashing in NLP</a></li><li><a href="https://towardsdatascience.com/dealing-with-features-that-have-high-cardinality-1c9212d7ff1b">Dealing with features that have high cardinality</a></li><li><a href="https://towardsdatascience.com/powerful-text-augmentation-using-nlpaug-5851099b4e97">Powerful Text Augmentation using NLPAUG !</a></li><li><a href="https://towardsdatascience.com/regex-essential-for-nlp-ee0336ef988d">Regex essential for NLP</a></li></ul><h3>References</h3><ol><li><a href="https://huggingface.co/course/chapter3/1?fw=pt">The amazing Hugging Face examples section!</a></li><li>Citation for the dataset and dataset <a href="https://rishabhmisra.github.io/publications/">reference</a></li></ol><pre>@article{misra2019sarcasm,<br>  title={Sarcasm Detection using Hybrid Neural Network},<br>  author={Misra, Rishabh and Arora, Prahal},<br>  journal={arXiv preprint arXiv:1908.07414},<br>  year={2019}<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1ccdfc257bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/adding-custom-layers-on-top-of-a-hugging-face-model-f1ccdfc257bd">Adding Custom Layers on Top of a Hugging Face Model</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[Interpreting an LSTM through LIME]]></title>
            <link>https://medium.com/data-science/interpreting-an-lstm-through-lime-e294e6ed3a03?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/e294e6ed3a03</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 13:58:39 GMT</pubDate>
            <atom:updated>2021-11-11T13:58:39.939Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to interpret a Keras LSTM through LIME and dive into the internal working of the LIME library for text classifiers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4y85TxW9eyKIwmBf" /><figcaption>Photo by <a href="https://unsplash.com/@glencarrie?utm_source=medium&amp;utm_medium=referral">Glen Carrie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>An overview</h3><ul><li>I decided to write this blog since I couldn’t find many tutorials out there that teach how to use LIME with Keras models. <strong>Sure enough many articles focus on Sci-kit learn based models, but using LIME with Keras requires us to write an additional function as we will see.</strong></li><li>Secondly, I would like to explain how LIME adapts to text classification problems which I was only able to understand when I went through the library’s code for text explainers (<strong>spoiler- it wasn’t straightforward</strong>).</li></ul><p>Now coming to the content, here is what I will be covering</p><ol><li>Why do we need to interpret models</li><li>What is LIME</li><li>How LIME works for text</li><li>Constructing an LSTM for a classification problem</li><li>Interpreting the LSTM through LIME through fancy visual explanations</li></ol><h3>Why do we need to interpret our model?</h3><p>Sometimes, especially in critical domains such as healthcare and finance, we want to know the reasoning behind our model’s predictions. When the margin for error is too narrow we want to be sure that our model is thinking like a human and making logical decisions. Simply getting the right answer is not enough, we want to know how our model found that answer. Say our classifier is predicting sentiment, in that case, we would like to be certain that the predictions are based on words that indicate sentiment, <strong>words like “happy” and “horrible” and not irrelevant words like someone’s name which do not contribute to sentiment.</strong> <em>More importantly, interpreting our model can help reduce bias, for instance, we can see whether our model is biased towards someone’s race or even gender. </em>Algorithms that help us interpret models fall under the wide category of <strong>Explainable AI (XAI).</strong></p><h3>The intuition behind LIME</h3><p>Firstly we categorise models based on interpretability. Models such as <strong>linear regressors or (small) decision trees</strong> are easily interpretable to humans. However, models such as <strong>neural networks and LSTMs</strong> have thousands of weights and many layers making it difficult for humans to interpret them.</p><p>Here is what LIME does to solve this problem. The following diagram is from the original <a href="https://arxiv.org/pdf/1602.04938.pdf"><strong>LIME</strong></a> paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*9mKjkVrlNSk98mWr.png" /><figcaption>How LIME works, as mentioned in the original LIME paper [1]</figcaption></figure><p>Consider the above to be a binary classification problem (red class and blue class)</p><ol><li>The curved red and blue regions indicate the decision space of our original model <strong>(which we shall call the black-box model)</strong></li><li>Say we want to interpret our model’s decision regarding the enlarged instance <strong>(denoted by the red plus)</strong>. First, we create samples in and around this red instance.</li><li>Now we <strong>weigh them according to their proximity to the instance we want to interpret</strong> and then <strong>generate predictions for these instances using our black-box model</strong>.</li><li>Now that we have new locally synthesized data and labels we train an <strong>INTERPRETABLE</strong> (LIME uses the ridge regressor by default) model on this data. While training we give more importance to data points close to the instance we want to interpret</li><li>Boom! we can now observe the <strong>weights of the trained model </strong>to gain insights about features (and their values) that influenced the black-box model’s prediction.</li></ol><h3>How does LIME work for text data?</h3><ol><li>Given a sentence, we first construct a <a href="https://en.wikipedia.org/wiki/Bag-of-words_model"><strong>bag of words </strong></a>(BoW) representation for the sentence.</li><li>Now the library randomly chooses words from the original sentence and manipulates the sentence to generate 5000 sentences with new word combinations/orders.</li><li>These samples are weighted by how similar they are to the original sentence using the <a href="https://en.wikipedia.org/wiki/Cosine_similarity"><strong>cosine distance</strong></a>.</li><li>Now that we have new samples of vectorised sentences and we know their proximity, LIME follows the same process as mentioned in the above section.</li></ol><h3>Using LIME to interpret an LSTM</h3><h4>The dataset</h4><p>We will work on the Yelp Coffee reviews dataset from<a href="https://www.kaggle.com/sripaadsrinivasan/yelp-coffee-reviews"> Kaggle</a>. I have preprocessed and cleaned the data and adapted it to a binary classification task. You can <a href="https://jovian.ai/rajbsangani/lime-medium"><strong>view the entire code here.</strong></a></p><p>Here is what the dataset looks like after preprocessing and cleaning</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D7&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D7&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4132f7a6361a40cc953c7b33638282a4%2Fpreview%2Fd66d5c3a5e484f75bcd308bb070e6ec4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/45307e2910b4c258cd4ce515bda4f5ab/href">https://medium.com/media/45307e2910b4c258cd4ce515bda4f5ab/href</a></iframe><h4>The model</h4><p>I have used an LSTM model with a hidden state of 100 dimensions, preceded by an embedding layer of 32 dimensions. You can see the model summary here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D10&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4132f7a6361a40cc953c7b33638282a4%2Fpreview%2Fd66d5c3a5e484f75bcd308bb070e6ec4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b592c4a996158e0538342c785d004c8/href">https://medium.com/media/0b592c4a996158e0538342c785d004c8/href</a></iframe><h4>Training and Results</h4><p>After training the model for a mere 2 epochs we achieve very high accuracy on the training data. Moreover, we achieve similar accuracy on the testing data along with a very good F1-score which shows us that the high accuracy isn&#39;t just a result of the data imbalance.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D11&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4132f7a6361a40cc953c7b33638282a4%2Fpreview%2Fd66d5c3a5e484f75bcd308bb070e6ec4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5509b952d7904cbd63fe5e192919edf/href">https://medium.com/media/e5509b952d7904cbd63fe5e192919edf/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D12&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4132f7a6361a40cc953c7b33638282a4%2Fpreview%2Fd66d5c3a5e484f75bcd308bb070e6ec4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cc43badd95456c190b23c3e9f53aba2/href">https://medium.com/media/2cc43badd95456c190b23c3e9f53aba2/href</a></iframe><h3>Interpreting the model using LIME Text Explainer</h3><p>Firstly pip install lime</p><p>Now instantiate the text explainer using our class labels.</p><p><strong>And for the most important part, since our Keras model doesn’t implement a predict_proba function like the sci-kit learn models we need to manually create one</strong>. Here is how you do it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D14&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D14&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4132f7a6361a40cc953c7b33638282a4%2Fpreview%2Fd66d5c3a5e484f75bcd308bb070e6ec4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/aec6bced918d5949520795dc7cd0553a/href">https://medium.com/media/aec6bced918d5949520795dc7cd0553a/href</a></iframe><p>Simply use the preprocessing and tokenization steps and use the model’s prediction to return an array of dimensions (input size X num__target_classes [2 in our case] )</p><h3>Results</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D19%26hideOutput%3Dtrue&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Flime-medium%2Fv%2F1%26cellId%3D19%26hideOutput%3Dtrue&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4132f7a6361a40cc953c7b33638282a4%2Fpreview%2Fd66d5c3a5e484f75bcd308bb070e6ec4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cfe34976902953f97f6833855b437cd/href">https://medium.com/media/8cfe34976902953f97f6833855b437cd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQS5eeDNVMp9IIbAghFnHg.png" /><figcaption>An explanation for a given sentence (Image By Author)</figcaption></figure><p>Firstly we note that the <strong>actual rating is 2/5 which isn’t a great review.</strong> <strong>Our model correctly classifies the output with the probability of it carrying negative sentiment as 0.82</strong>. Now when we see the negative and positive words we can see that <strong>words like meh and pricing contribute to negative sentiment</strong> whereas words like <strong>nice, vegan and fancy contribute to positive sentiment. </strong>The weights you see here (for each highlighted word) are calculated using our local (interpretable) model.</p><h3>Conclusion</h3><p>We saw how to interpret Keras models using LIME through a custom predict_proba function. However, note that LIME isn’t without its flaws and as we can see <strong>little</strong> has been misclassified as positive and <strong>food </strong>has been classified as positive when it should not be highlighted at all. (At least in my opinion). LIME is still powerful enough to interpret simple problems such as this one and can even be used to generate global explanations <strong>(as opposed to interpreting each instance separately)</strong>.</p><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><p>I’ll leave that for another article. If you liked this here are some more!</p><ul><li><a href="https://towardsdatascience.com/locality-sensitive-hashing-in-nlp-1fb3d4a7ba9f">Locality Sensitive Hashing in NLP</a></li><li><a href="https://towardsdatascience.com/dealing-with-features-that-have-high-cardinality-1c9212d7ff1b">Dealing with features that have high cardinality</a></li><li><a href="https://towardsdatascience.com/regex-essential-for-nlp-ee0336ef988d">Regex essential for NLP</a></li><li><a href="https://towardsdatascience.com/powerful-text-augmentation-using-nlpaug-5851099b4e97">Powerful Text Augmentation using NLPAUG !</a></li></ul><h3>References</h3><p>[1] Ribeiro, M. T., Singh, S., &amp; Guestrin, C. (2016, August). “ Why should I trust you?” Explaining the predictions of any classifier. In Proceedings of the 22nd ACM SIGKDD international conference on knowledge discovery and data mining (pp. 1135–1144).</p><p>LIME code: <a href="https://github.com/marcotcr/lime">https://github.com/marcotcr/lime</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e294e6ed3a03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/interpreting-an-lstm-through-lime-e294e6ed3a03">Interpreting an LSTM through LIME</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[Locality Sensitive Hashing in NLP]]></title>
            <link>https://medium.com/data-science/locality-sensitive-hashing-in-nlp-1fb3d4a7ba9f?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb3d4a7ba9f</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 15:10:38 GMT</pubDate>
            <atom:updated>2021-10-01T15:10:38.188Z</atom:updated>
            <content:encoded><![CDATA[<h4>A hands-on tutorial on how to speed up document retrieval by reducing the search space through Locality Sensitive Hashing (LSH)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nb0DqKExKBkJpLSA" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The problem at hand</h3><p>During one of my recent <a href="https://github.com/rajlm10/Pharmacat">projects</a>, I needed to analyze whether the medical problems similar to complaints presented by a patient had been diagnosed and documented earlier and what ailments these complaints indicated. In order to compare the current patient’s symptoms and troubles with other records in the past, I needed to compare the current problem text with <strong>all</strong> other documents in the dataset and find the ones most similar to it. For n items, this would involve n comparisons with the current document. Moreover, I used <strong>DistilBERT</strong> to encode these sentences; hence the comparison (cosine similarity) is also proportional to the embedding dimension (768) of these documents. <em>The medical dataset I have used is available </em><a href="https://archive.ics.uci.edu/ml/datasets/Drug+Review+Dataset+%28Drugs.com%29"><strong><em>here</em></strong></a><em>. </em>This is what the data looks like.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D6&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb7cfa21ead400cdf312d2117fa82b3d/href">https://medium.com/media/fb7cfa21ead400cdf312d2117fa82b3d/href</a></iframe><h3>Can we improve traditional search?</h3><p>Instead of comparing the vector with all the documents, wouldn’t it be nice if we could reduce the search space somehow? <strong>This is exactly what locality sensitive hashing (LSH) helps us do. </strong>Here is how we can use LSH to reduce the search space.</p><h3>The intuition behind LSH using Hyperplanes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*arW6jjcqd-prsYFMwEs01A.png" /><figcaption>Using lines to split the search space (Image By Author)</figcaption></figure><p>In the diagram above, we have various data points denoted by ‘X’s. Say we wanted to find the <strong>point most similar to point A</strong>. First, we <strong><em>randomly</em></strong> draw two lines <strong>(the red and blue lines). </strong>Now we can see where a data point lies with respect to each line. A data point can either be on side 0 of a line, or it can lie on the other side (side 1). First, we find out where all data points lie with respect to the two lines. Note that I have only shown 4 points in the table below to minimize clutter. More importantly, since our setting is 2-dimensional, I have used a <strong><em>line</em>. In higher dimensions, these lines are analogous to hyperplanes. </strong><em>More formally, in an n-dimensional setting, the hyperplane consists of (n-1) dimensions.</em></p><p>Here is how our current setting looks in a table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*8dw6dpJqkvdFinB-8_gFqA.png" /><figcaption>Position of the points with respect to planes (Image By Author)</figcaption></figure><p>From the table, we can see that points A and B lie on the same side of both the planes. We need to quantify this table and assign each point a hash value. Here is how a has value is calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*99fBIgbBWforQgbOmZSm0Q.png" /><figcaption>Hash Value (Image By Author)</figcaption></figure><p>Here is what we get when we apply this formula to our setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*QEHXn9YpMmZpyQZPoFsRrQ.png" /><figcaption>Hash Values (Image By Author)</figcaption></figure><p>We can see that points A and B have the same hash value and hence would lie in the same entry (hash bucket) if we were to construct a hash table. <strong>In simple terms, hash tables are data structures that allow instant lookups</strong>. They are mostly implemented through the dictionaries in Python, where the keys are the hash values, and the dictionary values are our vectors (data points). Let us construct a hash table using the 4 points above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*CXH_fWQ7yddnZVbeuxpJGw.png" /><figcaption>Hash Table (Image By Author)</figcaption></figure><p>Now we can clearly see that points A and B are in the same entry in our hash table. This indicates that these points are similar. <strong>If we want to find points similar to point A, all we need to do is look at points that have the same hash value as A. </strong>This simple intuition works very well in practice, but there are a few technical details that we must talk about before moving on to the implementation.</p><h3>How shall I determine the number of planes?</h3><p>In the simple setting above, we randomly drew two lines, but when we have more data, what shall we do? There is a tradeoff between the number of planes and speed. The more planes we have, the more time it will take to execute LSH. Here is how to work out the number of planes to be used.</p><p><strong>When we have n documents ( or n vectors), we would ideally want that each hash entry (bucket) has no more than 16 vectors. In that case, we would need n/16 buckets. Now each plane divides the search space into two parts (same side and opposite side). Hence if we had p planes, we would want that 2^p is equal to n/16. Solving for p, we can find the number of planes. </strong>Note the can be changed depending on the problem and size of the search space, and one should ideally try out different values to see what gives us the best results.</p><h3>Mathematically determining which side of the plane a vector lies on</h3><p>Above I had indicated two sides manually. In higher dimensions, the <strong>dot product helps us determine which side a vector lies on with respect to the plane. </strong>Every plane has a normal vector, a vector perpendicular to all points lying in the plane. We must take a vector and calculate its dot product with the normal vector to see which side of the plane it lies on. A non-negative dot product indicates that it lies on the same side as the normal, and a negative dot product indicates that it lies on the opposite side of the normal.<strong> In general, a plane represented as Ax+By+Cz=D has the normal &lt;A, B, C&gt;.</strong></p><p>Here is a simple diagram to help you visualize this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*DhDZO3LEKuUhxOYTjwFa_w.png" /><figcaption>Determining where a vector lies with respect to a hyperplane (Image By Author)</figcaption></figure><p>In the diagram above, we can see that vector V1 lies on one side of the plane, whereas vector v2 lies on the other side of the plane.</p><h3>Improving accuracy by creating multiple hash tables</h3><p>Since we randomly generate the planes, it is possible that some similar vectors are assigned to different buckets. To minimize the effect of this stochasticity, we can create multiple hash tables with different planes. While searching for a vector, we can then look for vectors that have the same hash value like it in all these hash tables. This would relatively increase the search space but greatly improve accuracy. <strong>(<em>Note</em>: the search space still remains much smaller than the original search space). </strong>In the code, I have created 25 hash tables.</p><h3>Let’s dive in!</h3><p>Before we start, this is what our code is going to represent. Also, note that I have not shown the entire code since it is verbose. <strong>Feel free to check out the entire code </strong><a href="https://jovian.ai/rajbsangani/nlp-pharmacat"><strong><em>here</em></strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*9KITucwaZDrGmdY0qfOiYg.png" /><figcaption>A visual overview of the code (Image By Author)</figcaption></figure><h4>1. Encode the entire text dataset into vectors (768 dimensional) using <a href="https://medium.com/huggingface/distilbert-8cf3380435b5"><strong>DistilBERT</strong></a>.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D8&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D8&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/be5bb4983584fdcf1927d404dc94d210/href">https://medium.com/media/be5bb4983584fdcf1927d404dc94d210/href</a></iframe><h4>2. Determine the number of planes to use. Also, set the number of hash tables (Denoted by n_repeats)</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D11&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d6546170915dc88b7b6529b413457bd/href">https://medium.com/media/9d6546170915dc88b7b6529b413457bd/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D12&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f6ffdd3d31066b59577f8d9d853d3b7/href">https://medium.com/media/8f6ffdd3d31066b59577f8d9d853d3b7/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D13&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a156dea9ae79fb3dbb40e760fba50847/href">https://medium.com/media/a156dea9ae79fb3dbb40e760fba50847/href</a></iframe><h4>3. Now, randomly generate planes and create a function to find the hash of a vector.</h4><pre><em>#Generate 11 planes randomly. This gives us a 768 X 11 dimensional matrix</em><br>planes_l = [np.random.normal(size=(embedding_dims, n_planes)) for i in range(n_repeats)]<br>print(len(planes_l))<br>planes_l[0].shape</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D15&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D15&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b0ab68e5c7107800af9680fe332d9c/href">https://medium.com/media/61b0ab68e5c7107800af9680fe332d9c/href</a></iframe><h4>4. Now, create multiple hash tables for improved accuracy</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D16&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D16&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b5c660c993800a94d37bd1dcd410e0b/href">https://medium.com/media/6b5c660c993800a94d37bd1dcd410e0b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D17&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D17&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8974ae2e4146be13277401d95dcade2b/href">https://medium.com/media/8974ae2e4146be13277401d95dcade2b/href</a></iframe><h4>5. Create a function that takes as input our problem text and finds vectors similar to it using LSH</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D18&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D18&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe1c30d2da35377878c1f2008dffb15/href">https://medium.com/media/3fe1c30d2da35377878c1f2008dffb15/href</a></iframe><p><strong><em>Notice how we add potential candidates with the same hash value as our query vector with respect to all 25 hash tables</em></strong></p><h4>6. From this reduced set of vectors, find the three most similar vectors using cosine similarity</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D22&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D22&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b38d140ffe86c20171dd6907859942c5/href">https://medium.com/media/b38d140ffe86c20171dd6907859942c5/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D23&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D23&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/be90234072b89b45bb600a690b861778/href">https://medium.com/media/be90234072b89b45bb600a690b861778/href</a></iframe><h4>7. Compare results between using the entire search space and using the reduced search space after LSH</h4><p><em>Here is our query vector for which we want to find historical documents containing similar complaints and conditions.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D19&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D19&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad70f43d27065f7c9a225d8d60b12bed/href">https://medium.com/media/ad70f43d27065f7c9a225d8d60b12bed/href</a></iframe><p><strong>Here is the search using the entire space</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D24&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D24&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c078a2fc30b3ddba520b85bf986ad49f/href">https://medium.com/media/c078a2fc30b3ddba520b85bf986ad49f/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D27&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D27&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c501f1ec294f6a7fcfbebe5a162fc36/href">https://medium.com/media/0c501f1ec294f6a7fcfbebe5a162fc36/href</a></iframe><p><strong>Here is the search using the reduced space after LSH</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D25&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D25&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b22c397941a2509aac952147832735d1/href">https://medium.com/media/b22c397941a2509aac952147832735d1/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D28&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fnlp-pharmacat%2Fv%2F1%26cellId%3D28&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F420395cb9dcc48beab0f3954985f5e41%2Fpreview%2F095c08c1567940248c6be6f89341ea3c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0656ab16716dcfe5a6a44a17ae0d430/href">https://medium.com/media/a0656ab16716dcfe5a6a44a17ae0d430/href</a></iframe><p><strong>Wow, we got exactly the same results but in a drastically lesser time! We reduced wall time from 576ms to 53ms!</strong></p><h3>Conclusion</h3><p>Using LSH, we reduced the search space from 25971 documents to 2042 documents, reduced search time from 576ms to 53ms and still got the same results! <strong>Note that these results may not always be the same since we are approximating the reduced search space but are still supposed to be fairly similar to our query vector.</strong></p><p>If you liked this article, here are some more!</p><ul><li><a href="https://towardsdatascience.com/overfitting-is-not-the-only-problem-regularisation-can-help-with-6fcdbfdb9384">Overfitting is not the only problem Regularisation can help with</a></li><li><a href="https://towardsdatascience.com/dealing-with-features-that-have-high-cardinality-1c9212d7ff1b">Dealing with features that have high cardinality</a></li><li><a href="https://towardsdatascience.com/regex-essential-for-nlp-ee0336ef988d">Regex essential for NLP</a></li><li><a href="https://towardsdatascience.com/powerful-text-augmentation-using-nlpaug-5851099b4e97">Powerful Text Augmentation using NLPAUG !</a></li><li><a href="https://towardsdatascience.com/scatter-plots-on-maps-using-plotly-79f16aee17d0">Scatter Plots on Maps using Plotly</a></li></ul><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb3d4a7ba9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/locality-sensitive-hashing-in-nlp-1fb3d4a7ba9f">Locality Sensitive Hashing in NLP</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[Overfitting is not the only problem Regularisation can help with]]></title>
            <link>https://medium.com/data-science/overfitting-is-not-the-only-problem-regularisation-can-help-with-6fcdbfdb9384?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fcdbfdb9384</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 13:39:05 GMT</pubDate>
            <atom:updated>2021-09-08T13:39:05.109Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding mathematically how Ridge Regression helps in cases where the number of features exceeds data points</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w01J9vNW9Ge3oFWs" /><figcaption>Photo by <a href="https://unsplash.com/@franki?utm_source=medium&amp;utm_medium=referral">Franki Chamaki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The problem of more features than data</h3><p>When we talk about regularisation, we almost always talk about it in the context of overfitting, but a lesser-known fact is that it can help solve the aforementioned problem.</p><p>Since data forms the very core of machine learning, you would never expect to run into such a problem. Having said that, it is common especially in ML problems concerning biology that we have many features and very few data points. <strong>In the case of regression problems, having more features than data points makes Ordinary Least Squares Regression (OLS) perform very poorly</strong>.</p><p>Let us understand why through a ridiculously simple example.</p><p>This is the equation of a straight line</p><p><strong>hθ(x) = θ0 + θ1x1</strong></p><p>To find out the values of <strong>θ0 and θ1 </strong>given <strong>x1 and hθ(x) </strong>we need <strong>at least 2 data points.</strong> Say we are predicting the <strong>weight</strong> of people based on a <strong>single feature</strong> — their <strong>age</strong>. In that case, we need data for at least two people to fit a straight line. <strong>What if we had the age of only ONE person?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*RNaT1q2W6yhc5vjGE44CyQ.png" /><figcaption>Infinite solutions (Image By Author)</figcaption></figure><p>We can see above that multiple straight lines can fit through one point and although I have only shown three such lines, <strong>such a system has infinite solutions!</strong></p><h3>The normal equation for linear regression and non-invertibility</h3><p>Firstly, the cost function we minimize during linear regression is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/0*4RCaSOTEuKCgu1T_" /><figcaption>Linear Regression Cost Function</figcaption></figure><p>Here m stands for the number of data points and theta is (n+1) dimensional vector, (n dimensions for n features + 1 dimension for the bias (<strong>θ0</strong>).</p><p><strong>To minimize this cost function we set the partial derivatives with respect to each entry in the theta matrix to 0 and simultaneously solve for theta.</strong></p><h4><strong>Here is our final normal equation</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/0*B0S2i7PresN5LILG" /><figcaption>Normal Equation for Linear Regression</figcaption></figure><p><em>A detailed derivation for those familiar with calculus can be found </em><a href="https://see.stanford.edu/materials/aimlcs229/cs229-notes1.pdf"><strong><em>here</em></strong></a><em> on page 11.</em></p><p><strong>Now X is an (m X (n+1)) dimensional matrix consisting of m data points and n features. Note that the first column of X is filled with 1s to account for the bias. Hence X has a column for each of the n features plus a column of 1s making it (n+1) total columns.</strong></p><p>If we had two data points consisting of features (2,5) and (4,7) this is what our matrix would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/69/0*vwOZNuxfBeCs5y9p" /><figcaption>An example X matrix</figcaption></figure><p>Now in the normal equation, <strong>whenever we have m&lt;n </strong>that is whenever X has lesser rows than features the <strong>inverse of the product of X transpose and X DOES NOT EXIST.</strong></p><p><strong>Here is a mathematical proof for the same. Please feel free to skip the proof if you are not familiar with linear algebra.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60FU8Xkd00BdMCS8QiVjDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*338dKQf6ZNiskY12rpoiuQ.png" /><figcaption>Proof 1</figcaption></figure><h4>Takeaway</h4><p><strong><em>Ordinary linear regression will not give us a solution for a problem where the number of data points is lesser than the number of features due to the non-invertibility of the normal equation.</em></strong></p><h3>Regularisation to the rescue!</h3><p>Here is the equation of the regularised cost function, more specifically <a href="https://www.mygreatlearning.com/blog/what-is-ridge-regression/#:~:text=Ridge%20regression%20is%20a%20model,away%20from%20the%20actual%20values."><em>Ridge Regression.</em></a><em> </em><strong>Lambda</strong> is the regularisation parameter here which is often fine-tuned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/0*4lbVWolpUrqfk2SD" /><figcaption>Ridge Regression Cost Function</figcaption></figure><p>Using the same logic as in the previous section, we differentiate this function and set it equal to zero, solving for <strong>theta</strong> to arrive at the <strong>regularised normal equation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/0*qxnFg9scK1IbjwmV" /><figcaption>Regularised Normal Equation</figcaption></figure><p>Here is M is a matrix with the dimensions <strong>(n+1 X n+1) </strong>and has 1s on its diagonal and 0s everywhere else except for the entry in the top-left position which is 0. <strong>For example, a 3X3 M matrix looks like this:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*N_heZG-bAu5YrYqp" /><figcaption>3 Dimensional M matrix</figcaption></figure><p>Ta-Da! As long as lambda is strictly greater than 0 we can prove that the product in the regularised normal equation is invertible.</p><p><strong>Here is the proof for the mathematically curious! Please feel free to skip it if you are not familiar with linear algebra.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ucwmJ901hYCpP5iw-Ntcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VgBa2Xqzk8IaujmuZO9gQ.png" /><figcaption>Proof 2</figcaption></figure><h4>Takeaway</h4><p><strong><em>Regularised linear regression (Ridge or Lasso) will give us a solution using the normal equation for a problem where the number of data points is lesser than the number of features due to the additional regularisation constraint.</em></strong></p><h3>So what about gradient descent then?</h3><p>So far we have only spoken about the normal equation for linear regression, but what if you use gradient descent to optimize theta? Well although theoretically, this should give you a solution, <strong>it turns out that since we have multiple solutions due to more unknowns than features, the solution may not generalize well</strong>. Adding a regularisation term will help constrain the objective further and bias the solution to “small” values of theta(small changes in input don’t translate to large changes in output). This will usually help us converge to a more generalisable solution.</p><h3>How are such problems dealt with in practice?</h3><p>Usually when we face the problem of more features than data points when we are trying to solve a regression problem, here is what we do.</p><ol><li>Choose either Ridge (L2) Or Lasso Regression (L1)</li><li>Use K-Fold Cross-Validation and tune the regularisation parameter (lambda)</li><li>After tuning a lambda strictly greater than 0 should result in better performance than Ordinary Least Squares Regression</li><li>In some extreme cases, after tuning if lambda turns out to be zero, this would mean that the problem itself is not a good fit for the algorithm and that regularization won’t give a better solution than OLS</li></ol><p>I know I talked about extreme examples where we only had 1 or 2 data points but in practice, you will face problems that have ~500 data points and ~5000 features giving you the option to tune lambda.</p><h3>Conclusion</h3><p>We saw an interesting use case of Regularisation apart from the more famous one (solving overfitting). We also saw mathematical proofs which show how regularisation can solve our objective. <strong>I would want you to be cautious though. Just because regularisation finds a solution, it doesn&#39;t mean that this is the best one. In fact, regularisation will help perform better than OLS but other ML algorithms could solve your problem even better!</strong></p><p><strong>Moreover, there are other ways like dimensionality reduction to solve this problem of more features than data points</strong></p><p>If you liked this article here are some more!</p><ul><li><a href="https://towardsdatascience.com/dealing-with-features-that-have-high-cardinality-1c9212d7ff1b">Dealing with features that have high cardinality</a></li><li><a href="https://towardsdatascience.com/regex-essential-for-nlp-ee0336ef988d">Regex essential for NLP</a></li><li><a href="https://towardsdatascience.com/powerful-text-augmentation-using-nlpaug-5851099b4e97">Powerful Text Augmentation using NLPAUG !</a></li><li><a href="https://towardsdatascience.com/scatter-plots-on-maps-using-plotly-79f16aee17d0">Scatter Plots on Maps using Plotly</a></li><li><a href="https://towardsdatascience.com/effortless-exploratory-data-analysis-eda-201c99324857">Effortless Exploratory Data Analysis (EDA)</a></li></ul><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fcdbfdb9384" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/overfitting-is-not-the-only-problem-regularisation-can-help-with-6fcdbfdb9384">Overfitting is not the only problem Regularisation can help with</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[How do transformers fare on a grammar test?]]></title>
            <link>https://medium.com/geekculture/how-do-transformers-fare-on-a-grammar-test-d3b7b26e5004?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3b7b26e5004</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 15:19:16 GMT</pubDate>
            <atom:updated>2021-09-09T13:53:04.679Z</atom:updated>
            <content:encoded><![CDATA[<h4>Find out how well BERT and RoBERTa deal with questions from grammar quizzes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TsXUgfqRSRomYKTE" /><figcaption>Photo by <a href="https://unsplash.com/@benmullins?utm_source=medium&amp;utm_medium=referral">Ben Mullins</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><ol><li>A little bit about BERT and its training on the Cloze task.</li><li>RoBERTa and how it differs from BERT</li><li>Hugging Face and the fill mask pipeline</li><li>Comparing BERT and RoBERTa’s ability to <strong>predict prepositions, articles, question tags, opposites and popular proverbs </strong>using questions from grammar quizzes. ( In English)</li></ol><p><em>Feel free to skip to part 4 in case you are only here to see the results and already know about transformer models.</em></p><h3>BERT and the Cloze Task</h3><p>Bidirectional Encoder Representations from Transformers (BERT) is a state-of-the-art NLP model which was created by Google AI Language. Here is a link to the original <a href="https://arxiv.org/pdf/1810.04805.pdf"><strong>paper</strong></a><strong>. </strong>The model is trained on a huge corpus (more on that later) and this pre-trained model can then be used on several downstream tasks (mostly related to natural language understanding) like text classification, extractive question answering, and named-entity recognition. More formally, BERT uses the Encoder model described in the original <a href="https://arxiv.org/abs/1706.03762"><strong>transformers paper</strong></a> by Vaswani et al.</p><p>BERT’s vocabulary is represented by <strong>vectors of dimension 768</strong> which are learned during the training. BERT is trained on two specific tasks.</p><ol><li><strong>Masked Language Modelling (MLM)</strong></li><li><strong>Next Sentence Prediction (NSP)</strong></li></ol><h4>Masked Language Modelling (MLM)</h4><p>While training, each sentence is fed into the model all at once unlike previous seq2seq models (LSTMs and RNNs). However, <strong>15%</strong> of the tokens in the sentence are masked by a special token <strong>[MASK] </strong>and the model must predict the token that is being masked. Note that training is done on a huge scale in a semi-supervised manner. In this case, we do not need to manually annotate huge datasets which would be impossible given the size of the corpus BERT was trained on, rather various batches of masked sentences are fed to the model and the model learns to predict the masked tokens over time. This is formally called the <strong>Cloze task.</strong></p><p>This is what gives BERT the ability to interpret its context and this is exactly what we will be using when we test the models on questions.</p><p>Here is what MLM looks like. This picture is from an <a href="https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270"><strong>excellent blog</strong></a> on BERT by Rani Horev and I would strongly recommend reading it to better understand the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*FfY47UrSYEmKKxxBA-HkLg.png" /><figcaption>How an input mask is predicted (Image by Author)</figcaption></figure><p><strong>As you can see here, the word “your” is masked before the sentence is fed into the model and the model predicts a token corresponding to the mask.</strong></p><h4>Next Sentence Prediction (NSP)</h4><p>This is another training objective of BERT where it receives pairs of sentences and must predict whether the second sentence follows the first sentence. I will not dive deep into this since Roberta completely does away with this objective and performs better on a few tasks.</p><h3>RoBERTa vs BERT</h3><p>RoBERTa stands for Robustly Optimized BERT Pretraining Approach and follows a similar architecture to that of BERT. It employees a few major tweaks, which make it better suited for certain tasks compared to BERT.</p><ol><li><strong>Discarding the Next Sentence Prediction training objective</strong>. Unlike BERT, RoBERTa doesn’t use the NSP objective and according to the paper, only training on the MLM objective leads to better performance.</li><li><strong>Unlike BERT, RoBERTa uses dynamic masking</strong>. In BERT, the masking is performed once during the data preprocessing step, resulting in a single static mask. To change the token being masked, training data is duplicated and masked 10 times, each time with a different mask strategy over 40 epochs thus having 4 epochs with the same mask. In dynamic masking, different masks are generated each time before feeding a sequence into the model. The authors find that this works better for more training data and more epochs.</li><li><strong>Most importantly, RoBERTa is trained on a massive corpus</strong> (as if BERT’s training corpus wasn’t massive enough) and is trained for much longer than BERT was. To be more specific, BERT was trained on <strong>16GB of text data whereas RoBERTa was trained on 160GB of text data!</strong></li><li>RoBERTa also performs several other minor tweaks such as changing the hyperparameters of the Adam optimizer and using longer sequences for training. The <a href="https://arxiv.org/pdf/1907.11692.pdf"><strong>original paper</strong></a> goes into much more detail and is a nice read.</li></ol><h3>HuggingFace and the fill-mask pipeline</h3><p>Hugging Face is an amazing hub that hosts implementations of various transformer models. They provide abstracted versions of these models so users can leverage the power of transformers without any fuss.</p><p>The fill-mask pipeline is an abstract pipeline for the masked language modelling task. We only need to enter a sentence with the mask token in place(<strong>[MASK] for BERT and &lt;mask&gt; for RoBERTa</strong>) and it will give us possible words that can replace the masked token.</p><p><strong><em>Note: With Hugging Face, only one token can be masked per sequence.</em></strong></p><p>This is what an example looks like. Examine the output, it contains 5 possible suggestions. Each suggestion is a dictionary with features such as <strong>score(confidence of the prediction), sequence (the complete sequence with the mask filled in), token(token id), and finally the token (predicted word). </strong>We will go through the detailed code in the next section and you will see how simple it is!</p><h3>GRAMMAR TEST!</h3><p>For this test, I chose 3 questions from 5 categories — prepositions, articles, question tags, opposites, and proverbs. This totals up to a score of 15. These questions are from some popular online quizzes (free to use). Let’s see how BERT and RoBERTa fare.</p><h4>Setup</h4><p>Here is the code to set up and install the transformers library in Google Colab.</p><pre>!pip install transformers</pre><p>And the single import</p><pre>from transformers import pipeline</pre><p>Then, we create a pipeline for both BERT and RoBERTa by selecting the <strong>fill-mask task and mentioning the model name. </strong>Note that BERTs predictions are not case-sensitive whereas RoBERTa’s are.</p><pre>unmasker_BERT = pipeline(&#39;fill-mask&#39;, model=&#39;bert-base-uncased&#39;)</pre><pre>unmasker_ROBERTA=pipeline(&#39;fill-mask&#39;, model=&#39;roberta-base&#39;)</pre><p>Here are the questions in the test</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D2&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D2&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4355519b092c40bf903ef2aa357c48dc%2Fpreview%2F493a515352884482b24f489d53e3be96&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/55f3b99a8bc9d10d11ab3516fba290f8/href">https://medium.com/media/55f3b99a8bc9d10d11ab3516fba290f8/href</a></iframe><h4>Prepositions</h4><p>Prepositions indicate relationships between other words in a sentence. This was an easy task for both the models and both of them predicted all answers correctly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D4&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4355519b092c40bf903ef2aa357c48dc%2Fpreview%2F493a515352884482b24f489d53e3be96&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/14976c3b0d854dd63be6cdfff05b098d/href">https://medium.com/media/14976c3b0d854dd63be6cdfff05b098d/href</a></iframe><h4>Articles</h4><p>Articles consist of <strong>a, an,</strong> and <strong>the. </strong>Articles are usually used to determine whether a noun is specific or general.</p><p>Notice how both models predict “<strong>a”</strong> for the special case <strong><em>Carl lives alone in [MASK] one-bedroom apartment. </em></strong>Although one-bedroom starts with a vowel, we must<strong> use “a one-bedroom” and not “an one-bedroom” due to the sound</strong> <strong>of the word.</strong></p><p>BERT missed out on one article though whereas RoBERTa predicted all correctly. Notice how RoBERTa capitalises the predicted token in the second sentence since it&#39;s the first word in the sentence.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D6&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4355519b092c40bf903ef2aa357c48dc%2Fpreview%2F493a515352884482b24f489d53e3be96&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b91923377b0185c8fd27336ae866a002/href">https://medium.com/media/b91923377b0185c8fd27336ae866a002/href</a></iframe><h4><strong>Question Tags</strong></h4><p>These turn a statement into a question. They are often used for checking information that we think we know is true.</p><p>Here is where both the models start having some trouble. The models cannot handle negations well and only predict one answer correctly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D8&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D8&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4355519b092c40bf903ef2aa357c48dc%2Fpreview%2F493a515352884482b24f489d53e3be96&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a067ddbf3fc2d41f0c235ae484d14aab/href">https://medium.com/media/a067ddbf3fc2d41f0c235ae484d14aab/href</a></iframe><h4>Opposites</h4><p>This was a complete surprise for me since I did not expect the models to predict opposites from context. This only goes on to show how powerful these models are and the comprehensive training they have undergone. Here RoBERTa gets all correct but BERT misses out on one.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D10&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4355519b092c40bf903ef2aa357c48dc%2Fpreview%2F493a515352884482b24f489d53e3be96&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5afa46200ec9cb063bead376a37f43bc/href">https://medium.com/media/5afa46200ec9cb063bead376a37f43bc/href</a></iframe><h4>Proverbs</h4><p>Proverbs are popular sayings. Again RoBERTa surprised me by performing so well since predicting words of a proverb is such a tough task and this requires the model to have seen similar sentences during training. RoBERTa clearly outperforms BERT here and predicts all the proverbs correctly. <strong>I’m guessing the huge corpus RoBERTa trained on has something to do with this.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Ftransformers-grammar-test%2Fv%2F1%26cellId%3D12&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F4355519b092c40bf903ef2aa357c48dc%2Fpreview%2F493a515352884482b24f489d53e3be96&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3313ffd061b3b150231873bf1747bbd9/href">https://medium.com/media/3313ffd061b3b150231873bf1747bbd9/href</a></iframe><h4>Final Scores</h4><p>Here is how both fared in each section and their total scores. RoBERTa clearly performs better on this test outscoring BERT 13 to 9!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*oQrdAHgcVL0I5OEwyziztQ.png" /><figcaption>Final Scores (Image By Author)</figcaption></figure><h3>Conclusion</h3><p>We can see how powerful Transformers are through this test particularly seeing them perform so well on opposites and proverbs. It is remarkable how language models have gone from merely statistical predictors to deep complex models which can train on such huge corpora without the need for manual annotation. This test also shows how strong RoBERTa is at the Cloze task.</p><p>If you liked this article here are some more!</p><ul><li><a href="https://towardsdatascience.com/scatter-plots-on-maps-using-plotly-79f16aee17d0">Scatter Plots on Maps using Plotly</a></li><li><a href="https://towardsdatascience.com/regex-essential-for-nlp-ee0336ef988d">Regex essential for NLP</a></li><li><a href="https://towardsdatascience.com/powerful-text-augmentation-using-nlpaug-5851099b4e97">Powerful Text Augmentation using NLPAUG !</a></li><li><a href="https://towardsdatascience.com/effortless-exploratory-data-analysis-eda-201c99324857">Effortless Exploratory Data Analysis (EDA)</a></li><li><a href="https://towardsdatascience.com/representing-5-features-in-a-single-animated-plot-using-plotly-e4f6064c7f46">Representing 5 Features in a single animated plot using Plotly</a></li></ul><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3b7b26e5004" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-do-transformers-fare-on-a-grammar-test-d3b7b26e5004">How do transformers fare on a grammar test?</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with features that have high cardinality]]></title>
            <link>https://medium.com/data-science/dealing-with-features-that-have-high-cardinality-1c9212d7ff1b?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c9212d7ff1b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 14:23:43 GMT</pubDate>
            <atom:updated>2021-08-11T16:52:24.996Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/tips-and-tricks">Tips and Tricks</a></h4><h4>A simple utility I use to address categorical features with many unique values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UffX4jFW-uxTxeRz" /><figcaption>Photo by <a href="https://unsplash.com/@gpthree?utm_source=medium&amp;utm_medium=referral">George Pagan III</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is high cardinality?</h3><p>Almost all datasets now have categorical variables. Each categorical variable consists of unique values.<em> A categorical feature is said to possess high cardinality when there are too many of these unique values.</em> One-Hot Encoding becomes a big problem in such a case since we have a separate column for each unique value (indicating its presence or absence) in the categorical variable. This leads to two problems, one is obviously space consumption, but this is not as big a problem as the second problem, the <strong>curse of dimensionality. </strong>I will talk about the curse of dimensionality in more detail but first, let&#39;s look at the data before and after one-hot encoding.</p><h3>A peek at our categorical feature before and after one-hot encoding</h3><p>We will be looking at the Qualifications feature. Since this data was collected from a form filled by many people the column contains many different Qualifications. Here is what the column looks like and all the unique values it has.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D1&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D1&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F3d36d0eb90a64289bf454dae902f0f2a%2Fpreview%2F56e8e38aa04f460386bf8bba27a1c4c9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/beb16f5636ec04dc75132360e0fe6b2a/href">https://medium.com/media/beb16f5636ec04dc75132360e0fe6b2a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D2&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D2&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F3d36d0eb90a64289bf454dae902f0f2a%2Fpreview%2F56e8e38aa04f460386bf8bba27a1c4c9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/332c6a4d18ee947d50a4a9cd73b0648b/href">https://medium.com/media/332c6a4d18ee947d50a4a9cd73b0648b/href</a></iframe><p><strong>We can see that there are 15 unique values in the feature and that it consumes 316KB of space.</strong> Let’s one_hot encode this feature using pandas.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D3&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D3&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F3d36d0eb90a64289bf454dae902f0f2a%2Fpreview%2F56e8e38aa04f460386bf8bba27a1c4c9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c725c180169ae8af445ae14ea2d33226/href">https://medium.com/media/c725c180169ae8af445ae14ea2d33226/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D4&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F3d36d0eb90a64289bf454dae902f0f2a%2Fpreview%2F56e8e38aa04f460386bf8bba27a1c4c9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab5078f9359a0929008b8f4223ca550f/href">https://medium.com/media/ab5078f9359a0929008b8f4223ca550f/href</a></iframe><p>We now see how big our original feature has become and naturally the space required to store it has increased to <strong>592KB.</strong> This is just ONE feature, if during training we possess hundreds of categorical variables we will end up with many hundreds of features which is not conducive for model training in some cases. Simple models cannot handle so many variables. <strong>But now let’s look at another major problem, the curse of dimensionality.</strong></p><h3>The Curse of Dimensionality</h3><p>Here is a simple summarization:</p><blockquote>As the number of features grows, the amount of data we need to accurately be able to distinguish between these features (in order to give us a prediction) and generalize our model (learned function) grows <strong>EXPONENTIALLY</strong>.</blockquote><p><strong><em>Feel free to skip to the next section if you do not want to read the technicalities below.</em></strong></p><p>I would like to use <strong>Yoshua Bengio’s (Yes the legendary Yoshua Bengio !) quora answer</strong> to explain this in more detail. I strongly advise reading the whole answer <a href="https://www.quora.com/What-is-the-curse-of-dimensionality">here</a>. According to the answer, increasing the number of different values in a feature simply increases the total number of possible combinations that can be made using the input row (<strong>containing n such features</strong>). <strong>Say we have two features with two distinct values each, this gives us a total of 4 possible ways to combine the two features. Now if one of these had three distinct values we would have 3X2 =6 possible ways to combine them.</strong></p><p>In classical non-parametric learning algorithms (e.g. nearest-neighbor, Gaussian kernel SVM, Gaussian kernel Gaussian Process, etc.) the model needs to see at least one example for each of these combinations (or at least as many as necessary to cover all the variations of configurations of interest), in order to produce a correct answer, one that is different from the target value required for other nearby configurations.</p><p>There is a workaround to this, that is the model even in the absence of a lot of training data can discern between configurations (not in the training set) for future predictions provided there is some sort of structure (pattern) in these combinations. <strong>In most cases, high cardinality makes it difficult for the model to identify such patterns and hence the model doesn’t generalise well to examples outside the training set.</strong></p><h3>Reducing Cardinality by using a simple Aggregating function</h3><p>Below is a simple function I use to reduce the cardinality of a feature. The idea is very simple. Leave instances belonging to a value with high frequency as they are and replace the other instances with a new category which we will call <strong><em>other.</em></strong></p><ol><li>Choose a threshold</li><li>Sort unique values in the column by their frequency in descending order</li><li>Keep adding the frequency of these sorted (descending) unique values until a threshold is reached.</li><li>These are the unique categories we will keep and instances of all other categories shall be replaced by <strong>“other”.</strong></li></ol><p>Let’s run through a quick example before going through the code. Say our column colour has <strong>100</strong> values and our threshold is 90% (that is <strong>90</strong>). We have 5 different categories of colours:<strong> Red (50), Blue(40), Yellow (5), Green (3) and Orange (2).</strong> The numbers within the bracket indicate how many instances of that category are present in the column.</p><p>We see that Red (50)+Blue (40) reaches our threshold of 90. In that case, we retain only 2 categories (Red, Blue) and mark all other instances of other colours as “<strong>Other</strong>”.</p><p>Thus we have reduced cardinality from <strong>5 to 3 (Red, Blue, Other)</strong></p><p>Here is the utility function I wrote to facilitate this. It’s well commented and follows exactly what I described above so you won’t have a problem following along. We can set a <strong>custom threshold</strong> and the <strong>return_categories</strong> option optionally lets us see the list of all unique values after reducing cardinality.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D5&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D5&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F3d36d0eb90a64289bf454dae902f0f2a%2Fpreview%2F56e8e38aa04f460386bf8bba27a1c4c9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/290c569a9b9bd14973a299de3309538d/href">https://medium.com/media/290c569a9b9bd14973a299de3309538d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fhigh-cardinality%2Fv%2F1%26cellId%3D6&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2F3d36d0eb90a64289bf454dae902f0f2a%2Fpreview%2F56e8e38aa04f460386bf8bba27a1c4c9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/adee6841d9b13d1c092982366a4d607c/href">https://medium.com/media/adee6841d9b13d1c092982366a4d607c/href</a></iframe><p><strong>As you can see using this function we reduced the cardinality of the qualifications column from 15 to 6!</strong></p><h3><strong>Conclusion</strong></h3><p>We saw how to reduce cardinality by using a simple function and more importantly why that is necessary (curse of dimensionality). Keep in mind however that we were fortunate that the distribution of values in our column allowed us to use this method. If all the 15 categories had been equally distributed we would not have been able to use this and in that case would probably need to apply PCA in combination with the other features of the dataset but more on that some other time.</p><p>If you liked this article here are some more!</p><ul><li><a href="https://towardsdatascience.com/scatter-plots-on-maps-using-plotly-79f16aee17d0">Scatter Plots on Maps using Plotly</a></li><li><a href="https://towardsdatascience.com/regex-essential-for-nlp-ee0336ef988d">Regex essential for NLP</a></li><li><a href="https://towardsdatascience.com/powerful-text-augmentation-using-nlpaug-5851099b4e97">Powerful Text Augmentation using NLPAUG !</a></li><li><a href="https://towardsdatascience.com/effortless-exploratory-data-analysis-eda-201c99324857">Effortless Exploratory Data Analysis (EDA)</a></li></ul><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c9212d7ff1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dealing-with-features-that-have-high-cardinality-1c9212d7ff1b">Dealing with features that have high cardinality</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[Scatter Plots on Maps using Plotly]]></title>
            <link>https://medium.com/data-science/scatter-plots-on-maps-using-plotly-79f16aee17d0?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/79f16aee17d0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Wed, 28 Jul 2021 12:36:03 GMT</pubDate>
            <atom:updated>2021-07-28T12:36:03.825Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to create interactive scatter maps to represent multiple features in your data with very little code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JKjppsVIyEteX3h7" /><figcaption>Photo by <a href="https://unsplash.com/@geojango_maps?utm_source=medium&amp;utm_medium=referral">GeoJango Maps</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Plotly and Mapbox bring to the table</h3><p>Plotly is a powerful visualisation library that provides amazing capabilities like <strong>interactive, dynamic, easy to use, </strong>and <strong>highly detailed </strong>plots. <strong>Plotly Express</strong> is a built-in part of the Plotly library that provides high-level APIs which require very little code to plot a variety of figures. We will be using Plotly express in combination with <strong>Mapbox. </strong>Mapbox is a location data platform that provides various APIs for Maps, routing and navigation.</p><h3>Visualising Airbnbs around San Francisco</h3><p>In this article, we will be using the <a href="https://www.kaggle.com/jeploretizo/san-francisco-airbnb-listings"><em>San Francisco Airbnb listings dataset from Kaggle</em></a><em> </em>to analyse the relation between prices, types of accommodations and their areas visually. By simply looking at the map we shall see how the area affects the price.</p><p>This data has a lot of columns, but the ones concerning this article are <strong>latitude</strong>, <strong>longitude</strong>, <strong>price</strong> and <strong>room_type. </strong>The price is the price per night and the room_type indicates whether the Airbnb is a hotel, a private room, a shared room or an entire house.</p><p>Here is what the data looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*_HPm0aYYfMqwP3wg_KcQUA.png" /><figcaption>The columns we will use in the plot (Image By Author)</figcaption></figure><h3>Let’s dig in!</h3><ol><li>Firstly we will need a Mapbox access token. Don’t worry it&#39;s completely free up to a certain amount of calls and it <strong>doesn’t</strong> require any card details when signing up. You can get your token <a href="https://www.mapbox.com/">here</a> for no cost. <strong>After signing up the token will be under your account page.</strong></li><li>Convert the price to a <strong>float. </strong>The price column currently contains strings with the <strong>‘$’ symbol and commas. </strong>For example <strong>$1,200. </strong>Here is a super quick way of converting the entire column to float values. This will con</li></ol><pre>import locale</pre><pre>locale.setlocale(locale.LC_ALL, &#39;en_US.UTF8&#39;)</pre><pre>data[&#39;price&#39;]=data[&#39;price&#39;].apply(lambda x: locale.atof(x.strip(&quot;$&quot;)))</pre><p>3. Now comes the best part, the plot. If you are running this code in Colab which I recommend you don’ need to install Plotly. Else you can pip install it.</p><p>import plotly.express as px</p><p>After this, we just need to write the code shown below. Here we first pass in our Mapbox access token. Then we use the function px.scatter_mapbox with the following arguments.</p><ul><li>data: This refers to our data frame</li><li>lat=” latitude”: This points to the latitude column in our data frame.</li><li>lon=” longitude”: This points to the longitude column in our data frame.</li><li>color=”room_type”: This basically colours each data point based on its value in the room_type column. Since we have four different room types we will have four colours.</li><li>size=” price”: This is the interesting part, each Airbnb will be denoted by a bubble that is proportional in size to its price. <strong>Cheaper Airbnbs will be denoted by smaller bubbles whereas expensive ones will be portrayed by larger bubbles.</strong></li><li>The other arguments are just utilities to help make the plot easier to view.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Frajbsangani%2Fairbnb%2Fv%2F1%26cellId%3D15&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Frajbsangani%2Fairbnb%2Fv%2F1%26cellId%3D15&amp;image=https%3A%2F%2Fjovian.ai%2Fapi%2Fgist%2Fe23523a3560b4110a508ebd85f252f86%2Fpreview%2F32b598839b3c490fb43d28689c8ade6b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ea7e0fad01c1abefcfd03e9cd665203/href">https://medium.com/media/6ea7e0fad01c1abefcfd03e9cd665203/href</a></iframe><p>4. Feel free to play around with the options in the top right corner of the plot for utilities like zooming, selecting specific areas, or downloading the graph as an image. You can zoom in to a particular region to see how detailed the map is Also notice how the hotel’s information is displayed when we <strong>hover over a bubble! Clicking on any room type in the legend will remove all rooms of that type from the map!</strong></p><h3>Looking for Trends</h3><p>We see that some trends make sense. Before jumping to conclusions however note that the Airbnb price depends on various amenities and other features like the size, services, host popularity etc. However, we can still see some general trends.</p><ol><li>Houses near <strong>Pacific Heights and Russian Hill </strong>have prices higher than those in other parts of San Francisco.</li><li>On zooming out, we notice that the density of houses is not uniform. There are many more rooms on the right half of the map than on the left.</li><li>We see that most rooms are either full-fledged apartments or private rooms.</li><li>There is an unusually high priced apartment costing <strong>9999 dollars</strong> near <strong>Carl St. </strong>Wonder what that is !</li></ol><h3>Conclusion</h3><p>Thanks to Plotly Express and Mapbox, we can plot such powerful and information-rich graphs with almost no effort. <strong>This is just one kind of GeoPlot that Plotly offers. You can check out their other Map plots </strong><a href="https://plotly.com/python/maps/"><strong>here</strong></a><strong>.</strong></p><p>If you liked this article here are some more!</p><ul><li><a href="https://towardsdatascience.com/regex-essential-for-nlp-ee0336ef988d">Regex essential for NLP</a></li><li><a href="https://towardsdatascience.com/powerful-text-augmentation-using-nlpaug-5851099b4e97">Powerful Text Augmentation using NLPAUG !</a></li><li><a href="https://towardsdatascience.com/representing-5-features-in-a-single-animated-plot-using-plotly-e4f6064c7f46">Representing 5 Features in a single animated plot using Plotly</a></li><li><a href="https://towardsdatascience.com/effortless-exploratory-data-analysis-eda-201c99324857">Effortless Exploratory Data Analysis (EDA)</a></li></ul><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79f16aee17d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/scatter-plots-on-maps-using-plotly-79f16aee17d0">Scatter Plots on Maps using Plotly</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[Ideas for mini projects using WhatsApp chats]]></title>
            <link>https://medium.com/data-science/ideas-for-mini-projects-using-whatsapp-chats-f834783a6545?source=rss-7e3aebe20c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/f834783a6545</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Raj Sangani]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 15:04:57 GMT</pubDate>
            <atom:updated>2021-07-20T15:04:57.557Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything you can do using WhatsApp chats from analyzing texting habits to building generator models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a-bF2bfV0nCyGo3H" /><figcaption>Photo by <a href="https://unsplash.com/@jdiegoph?utm_source=medium&amp;utm_medium=referral">Diego PH</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>A personalised touch</h3><p>You’ll find tons of datasets from Kaggle for all sorts of analysis and model-prototyping. However, none of them are quite as fun as analysing your own data, making sense of your chatting habits, building models that can text like you or even predicting emojis you would use in a particular situation. The fact that you can relate so well with what you are analyzing is very exciting (at least for me!)</p><h3>Overview</h3><p>I will be listing some ideas that can be useful for making some mini-projects. I will leave <strong>resources or links to libraries and tools</strong> you can use for each idea. The ideas are listed in increasing order of difficulty (in terms of implementation). We will be starting with basic EDA, moving on to time-series analysis and end with Transformer models. Let’s get started!</p><p>To download any chat as a text file</p><ol><li>Open the chat on WhatsApp and click on the three dots at the top right.</li><li>Click on more</li><li>Click on Export chat</li><li>Choose the Without media option (all the ideas here require only text data)</li><li>The chat should be downloaded as a text file.</li></ol><h3>Note on Data cleaning</h3><p>The downloaded chat will not have separate features for the user, time, date, message body etc. All of these features are clubbed together in one column. You will have to create separate columns for these features. <a href="https://jovian.ai/PrajwalPrashanth/whatsapp-chat-data-analysis"><strong><em>Here</em></strong></a><strong><em> </em></strong>is a notebook which will help you with that. Also since we haven’t exported any media, all the media in the chats is represented by a placeholder called <strong>&lt;Media omitted&gt; </strong>You can drop these rows.</p><h3>Private Chats</h3><p>Here are some questions that you can get answers to from your chats</p><h4>1. Are messages sent in equal proportions in the chat?</h4><p>You can group the messages by username and check the count of the messages.</p><h4>2. What is the average length of each message you send?</h4><p>Again for every message sent by you you can split the text by a space delimiter and count the length of the list. Then you can average this count and compare it with the average length of messages sent by the other user.</p><h4>3. Finding the most used emojis and words</h4><p>The <a href="https://github.com/carpedm20/emoji/"><strong>emoji</strong></a> library is a brilliant way to handle emojis in python. For this, you just need to tokenize your text appropriately and use the <strong>Counter class from Collections to help find the most common emojis. </strong>Similarly, for words, you can use a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html">CountVectorizer</a> from Sklearn or just use the Counter class again.</p><h4>4. When are you most active?</h4><p>Again using the dates you can find dates for when you sent the most messages using <strong>Counter on the dates column since WhatsApp records the date separately for every message you send. </strong>With a little more effort you can extend this to finding time intervals where you are most active. You can pre-define time intervals during a day and find which intervals contain the most messages.</p><h4>5. Find how much Media you send</h4><p>A lot of people prefer sending voice notes over texting long messages. A lot of people communicate through memes or gifs. You can analyze what percentage of your messages are text.</p><h3>Group Chats</h3><ol><li><strong>Find out who is most Active</strong></li><li><strong>Find out how many times the group name or description has been changed</strong></li><li><strong>Find out if you reply only to certain people in the group.</strong></li></ol><h3>Finding patterns using Time-Series analysis</h3><p>This one is very interesting because it can reveal many repeating trends. For instance, before my exams, I always text a certain number of people asking for notes :P Also before my football group goes mad during the weekend games but is very inactive during other times. Here is how you can create a time-series dataset.</p><ul><li>Using Counter (from collections) create a dictionary for dates and counts.</li><li>The counts here signify the number of messages sent corresponding to each unique date.</li><li>Set the date as the data frame index and the counts as a separate feature column</li></ul><p>Now you can decompose the time series into <strong>trends, seasonality and residuals.</strong> <strong>This is a great </strong><a href="https://towardsdatascience.com/time-series-from-scratch-decomposing-time-series-data-7b7ad0c30fe7?source=user_profile---------1----------------------------"><strong>article</strong></a><strong> that will help you decompose time series. You can also check for Autocorrelations in the time series.</strong></p><h3>Predicting what emojis you would use for a certain sentence</h3><p>This one is particularly fun because every person uses a different set of emojis for expressing emotions. Instead of using datasets that probably use emojis differently, you can create your own dataset and train a model to predict what emojis to use for a sentence. This one is a little tough though! The preprocessing takes a bit of effort. Here is an overview of the steps you would have to follow.</p><ol><li>Define some label emojis. Say I want to represent Happiness by ❤️, Sadness by 😞 and jealousy by 😏. What I can do is create a list with these emojis.</li><li>Also, create a list for their demojized versions using emoji.demojize() on each emoji in the previous list.</li><li>Now for each sentence, for each emoji in your list, use the <strong>replace function and replace the emoji with its demojized version For example </strong><em>emoji.demojize(‘😞’) .</em></li><li>Now remove all other emojis from the text. <a href="https://towardsdatascience.com/text-preprocessing-for-data-scientist-3d2419c8199d"><strong>This</strong></a> is a helpful article that will help you remove emojis.</li><li>Now create a new column called labels and loop through the sentences. On finding any string from the demojized list (step 2) in the sentence add that string to the labels column.</li><li>Now replace the demojized strings from the sentences.</li><li>Drop all the rows where the label is empty. <strong>(indicates the absence of emojis we are trying to predict)</strong></li><li>We are left with a data frame that contains sentences along with their emojis.</li><li>Now use any classifier model as you normally would for an NLP classification problem!</li></ol><h3>Teaching a GPT-2 to text like you!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xdPVcxV33KkjVPV7" /><figcaption>Photo by <a href="https://unsplash.com/@rocknrollmonkey?utm_source=medium&amp;utm_medium=referral">Rock&#39;n Roll Monkey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Saving the best for the end.</strong></p><p><strong>With almost 40k messages for each conversation, you have enough data to fine-tune a generator model like a GPT-2. </strong><a href="https://huggingface.co/">HuggingFace</a> provides great abstractions to use State of the Art pre-trained models like the GPT-2 . Simply fine-tune it with your own sentences (after some preprocessing) and have it generate text with your style!</p><p><a href="https://towardsdatascience.com/how-to-fine-tune-gpt-2-for-text-generation-ae2ea53bc272"><strong><em>Here is a great reference to help you fine-tune a GPT-2 in no time at all!</em></strong></a></p><h3>Conclusion</h3><p>I hope this was helpful to everyone who wants to make some quick projects using personalised data. I hope that the hints and references were enough to help you implement these ideas. Please feel free to ask me for implementation details if you feel anything is missing.</p><p>If you liked this article here are some more!</p><ul><li><a href="https://towardsdatascience.com/regex-essential-for-nlp-ee0336ef988d">Regex essential for NLP</a></li><li><a href="https://towardsdatascience.com/representing-5-features-in-a-single-animated-plot-using-plotly-e4f6064c7f46">Representing 5 Features in a single animated plot using Plotly</a></li><li><a href="https://towardsdatascience.com/powerful-text-augmentation-using-nlpaug-5851099b4e97">Powerful Text Augmentation using NLPAUG !</a></li><li><a href="https://towardsdatascience.com/effortless-exploratory-data-analysis-eda-201c99324857">Effortless Exploratory Data Analysis (EDA)</a></li></ul><p>Check out my <a href="https://github.com/rajlm10"><strong>GitHub</strong></a> for some other projects. You can contact me <a href="https://rajsangani.me/"><strong><em>here</em></strong></a><strong><em>. </em></strong>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f834783a6545" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ideas-for-mini-projects-using-whatsapp-chats-f834783a6545">Ideas for mini projects using WhatsApp chats</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>