<?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 Varun on Medium]]></title>
        <description><![CDATA[Stories by Varun on Medium]]></description>
        <link>https://medium.com/@varundse?source=rss-ba53c16ffd24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s87zyULp6TAiz5VQ5PFG-g.jpeg</url>
            <title>Stories by Varun on Medium</title>
            <link>https://medium.com/@varundse?source=rss-ba53c16ffd24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:00:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varundse/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[A/B Testing: Simple explanation of Maths behind]]></title>
            <link>https://medium.com/analytics-vidhya/a-b-testing-simple-explanation-of-maths-behind-a3b2f059e619?source=rss-ba53c16ffd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b2f059e619</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[p-value]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[z-score]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Tue, 19 Jan 2021 18:21:16 GMT</pubDate>
            <atom:updated>2021-01-21T15:53:59.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWeU2b11BT7Ld5SEgTJr5w.jpeg" /><figcaption>Image by author.</figcaption></figure><h3><strong>Introduction</strong></h3><p>Hypothesis testing or A/B testing is a crucial step before integrating a data science solution or any feature update into the product. This is basically a statistical way of measuring the impact of the feature we are trying to add/update in the product.</p><p>According to Wikipedia,</p><p><em>A/B testing is a way to compare two versions of a single variable, typically by testing a subject’s response to variant A against variant B, and determining which of the two variants is more effective. A/B testing includes an application of statistical hypothesis testing.</em></p><p>Since A/B testing is a testing it should have three basic components as they are in any kind of test, a metric/variable that needs to be tested, a way to perform the test and a way to evaluate the result/passing criteria.</p><p>For eg., if we are trying to add a feature that will improve the click through rate than we will compare two versions, A and B, of click through rate variable. Value of the variable in Version A is as per the current product and in Version B is as per the updated version of the product.</p><h3><strong>Variable to test</strong></h3><p>The test variable/metric should quantify the performance of the new feature such as click through rate for an updated website, successful payments for a recommendation page, etc.</p><p>We can measure the sample value of the variable from a sample set of users for both the versions. Version A is the sample set with the original product, this group is called the controlled group. Version B is the sample set with the updated product, this group is called the target group.</p><p>In terms of statistical hypothesis testing, null hypothesis is that there won’t be any impact of the new feature on the variable. Alternate hypothesis states that the new feature will have an impact on the variable in other words Version B value will deviate from Version A value because of the new feature. We need to state the two hypothesis specifically as per the actual scenario.</p><h3>Way to perform the test</h3><p>Can we just compare the values from the two versions and declare the result? Not really! Let’s say Version B gives better values. Still we cannot declare Version B the winner(reject the null hypothesis) because we don’t know if the improvement in the variable is just by chance(may be we got lucky) or there is actually an impact of the new product because we just took a sample from the population.</p><p>So how do we actually perform the test than? The answer is if we somehow know the actual population distribution of the variable that we are trying to measure then we can deduce the likelihood of the variable being at least as extreme as measured in Version B. This probability can help us decide whether the results are by chance or not. This likelihood is called the <strong>p-value</strong> of a statistical hypothesis test. Lower the p-value more are the chances of Version B value being an impact of the new feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gRRjzhzJZqwlcq0m05CP2w.jpeg" /><figcaption>Image by author</figcaption></figure><p>We want to calculate the probability of B&gt;A provided null hypothesis is true, P(B&gt;A | null hypothesis).</p><p>But the problem is we never know the population distribution of the variable so we cannot just calculate the likelihood. The <a href="https://en.wikipedia.org/wiki/Central_limit_theorem"><strong>Central Limit Theorem</strong></a> comes for our rescue at this point.</p><p>The Central Limit Theorem states that the sampling distribution of the sample mean approaches a normal distribution if the sample size gets larger. Which means if we take a large number of samples of same size from a population, the distribution of mean of theses samples (this is called sampling distribution of sample mean) will be a normal distribution if each sample size is large (a sample size of more than 30 is large enough) no matter what is the population distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWaBgL-ppQrDHCIwJN90nw.png" /><figcaption>Image by author</figcaption></figure><p>Check the below simulation, actual population is not normal but the sampling distribution of sample mean is. Verify the mean and standard deviation as per the equations above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZJUOev44nt6I5H7v8bzHA.png" /><figcaption>Image by author, generated from <a href="http://onlinestatbook.com/stat_sim/sampling_dist/index.html">http://onlinestatbook.com/stat_sim/sampling_dist/index.html</a></figcaption></figure><p>For eg, if we take 1000 samples each of 100 users from our users population and calculate mean of the variable for each 1000 samples (sample mean) then the distribution of these means (sampling distribution of the sample mean) will be a normal distribution. And mean of this normal distribution will be an approximation of the mean of the population.</p><p>As we don’t know the population distribution we also don’t know the standard deviation of the population. So we cannot directly calculate the standard deviation of the sampling distribution of sample mean(also called as standard error of the mean) but we can estimate it using the below formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyIfGLEdLfj1Sp4iQWO27g.png" /><figcaption>Image by author</figcaption></figure><h3>Way to evaluate the result/passing criteria</h3><p>As we now know the sampling distribution of the sample mean is a normal distribution we can also calculate the likelihood of the value we have measured in Version B. One way of doing this is to calculate the likelihood of the deviation between A and B, which is nothing but the likelihood from the distribution of A-B.</p><p>Sampling Distribution of sample mean for version A and version B is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*6SVIirB8UGoMVNB4PjAS9Q.png" /><figcaption>Image by author</figcaption></figure><p>As A and B are independent, A-B will also follow a normal distribution,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*WuHUPZNsUYduDSeKJfqNKQ.png" /><figcaption>Image by author</figcaption></figure><p>As per the null hypothesis and the estimation of standard error,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*wFFZz0vATlCdCOqEq5DF4A.png" /><figcaption>Image by author</figcaption></figure><p>A-B is a zero-centred normal distribution. We can calculate likelihood of the observed difference in version A and version B value by using z-score.</p><p>z-score tells how many standard deviations far from the mean(of the distribution) a data point is. Once we have the z-score we can use the z-table to figure out the p-value of that data point. We use t-table in the similar way if the size of the sample is less than 30.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F9mkvymwWsi4osca.png" /><figcaption>Image from Wikipedia(<a href="https://en.wikipedia.org/wiki/Standard_score">https://en.wikipedia.org/wiki/Standard_score</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*7Pje_3XabWCoHPUrZ0pm9A.png" /><figcaption>Image by author</figcaption></figure><p>Once we have the corresponding p-value from the z-table or t-table, we can set a threshold on it to accept or reject the null hypothesis. This threshold is called the significance level and is denoted by alpha. Alpha of 5% is widely used in the industry. It means if the p-value is less than 5% only then we will reject the null hypothesis. Alpha of 5% corresponds to a significance level 95%.</p><p>This means we only reject null hypothesis when,</p><p>P(B&gt;A |null hypothesis)&lt;alpha</p><p>Consider the following example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*q1tpt9GrNYyx378HFi7_Qw.png" /><figcaption>Image by author</figcaption></figure><p>As the sample size is less than 30, we will use t-table,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*JcfzCA6BxuXkWKBDxzP9Mw.png" /><figcaption>Image by author</figcaption></figure><p>If the alpha is 5%, we can not reject null hypothesis in this case.</p><p>P(B&gt;A|null hypothesis)&gt;5% for the observed case. That means the observed value in version B isn’t actually a rare event as per our alpha and this can be observed in the original population, which is the older version.</p><p><strong><em>References</em></strong></p><ul><li><a href="http://onlinestatbook.com/stat_sim/index.html">Simulations</a></li><li><a href="https://en.wikipedia.org/wiki/Central_limit_theorem"></a></li><li><a href="https://en.wikipedia.org/wiki/Standard_score">Standard score - Wikipedia</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.khanacademy.org%2Fembed_video%3Fv%3DJNm3M9cqWyc&amp;display_name=Khan+Academy&amp;url=https%3A%2F%2Fwww.khanacademy.org%2Fmath%2Fap-statistics%2Fsampling-distribution-ap%2Fsampling-distribution-mean%2Fv%2Fcentral-limit-theorem&amp;image=https%3A%2F%2Fimg.youtube.com%2Fvi%2FJNm3M9cqWyc%2F0.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=khanacademy" width="853" height="520" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fd7db27a48de5e4e569890d7231de11/href">https://medium.com/media/9fd7db27a48de5e4e569890d7231de11/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b2f059e619" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-b-testing-simple-explanation-of-maths-behind-a3b2f059e619">A/B Testing: Simple explanation of Maths behind</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cosine similarity: How does it measure the similarity, Maths behind and usage in Python]]></title>
            <link>https://medium.com/data-science/cosine-similarity-how-does-it-measure-the-similarity-maths-behind-and-usage-in-python-50ad30aad7db?source=rss-ba53c16ffd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ad30aad7db</guid>
            <category><![CDATA[cosine-similarity]]></category>
            <category><![CDATA[math-for-machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[similarity-metrics]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Sun, 27 Sep 2020 16:05:50 GMT</pubDate>
            <atom:updated>2020-09-27T18:56:43.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yYMofdAlVtlbfpwi" /><figcaption>Photo by <a href="https://unsplash.com/@artem_kniaz?utm_source=medium&amp;utm_medium=referral">Artem Kniaz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What is cosine similarity?</strong></p><p>Cosine similarity measures the similarity between two vectors by calculating the cosine of the angle between the two vectors.</p><p>Cosine similarity is one of the most widely used and powerful similarity measure in Data Science. It is used in multiple applications such as finding similar documents in NLP, information retrieval, finding similar sequence to a DNA in bioinformatics, detecting plagiarism and may more.</p><p>Cosine similarity is calculated as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*AqWG1VHnLf8P7_H4KDBwVQ.png" /><figcaption>Angle between two 2-D vectors A and B (Image by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfW66-WsYkFqWc4XYJbEJg.png" /><figcaption>calculation of cosine of the angle between A and B</figcaption></figure><p><strong>Why cosine of the angle between A and B gives us the similarity?</strong></p><p>If you look at the cosine function, it is 1 at theta = 0 and -1 at theta = 180, that means for two overlapping vectors cosine will be the highest and lowest for two exactly opposite vectors. You can consider 1-cosine as distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTPC_CFlHlQ1oyPsn9zRqQ.png" /><figcaption>cosine(Image by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17iIvBSo_BS9T3Ww7hUdkg.png" /><figcaption>values of cosine at different angles (Image by author)</figcaption></figure><p><strong>How to calculate it in Python?</strong></p><p>The numerator of the formula is the dot product of the two vectors and denominator is the product of L2 norm of both the vectors. Dot product of two vectors is the sum of element wise multiplication of the vectors and L2 norm is the square root of sum of squares of elements of a vector.</p><p>We can either use inbuilt functions in Numpy library to calculate dot product and L2 norm of the vectors and put it in the formula or directly use the cosine_similarity from sklearn.metrics.pairwise. Consider two vectors A and B in 2-D, following code calculates the cosine similarity,</p><pre>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre># consider two vectors A and B in 2-D<br>A=np.array([7,3])<br>B=np.array([3,7])</pre><pre>ax = plt.axes()</pre><pre>ax.arrow(0.0, 0.0, A[0], A[1], head_width=0.4, head_length=0.5)<br>plt.annotate(f&quot;A({A[0]},{A[1]})&quot;, xy=(A[0], A[1]),xytext=(A[0]+0.5, A[1]))</pre><pre>ax.arrow(0.0, 0.0, B[0], B[1], head_width=0.4, head_length=0.5)<br>plt.annotate(f&quot;B({B[0]},{B[1]})&quot;, xy=(B[0], B[1]),xytext=(B[0]+0.5, B[1]))</pre><pre>plt.xlim(0,10)<br>plt.ylim(0,10)</pre><pre>plt.show()<br>plt.close()</pre><pre># cosine similarity between A and B<br>cos_sim=np.dot(A,B)/(np.linalg.norm(A)*np.linalg.norm(B))<br>print (f&quot;Cosine Similarity between A and B:{cos_sim}&quot;)<br>print (f&quot;Cosine Distance between A and B:{1-cos_sim}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*BZMKAFB5YRbw38_yROaAJw.png" /><figcaption>Code output (Image by author)</figcaption></figure><pre># using sklearn to calculate cosine similarity<br>from sklearn.metrics.pairwise import cosine_similarity,cosine_distances</pre><pre>cos_sim=cosine_similarity(A.reshape(1,-1),B.reshape(1,-1))<br>print (f&quot;Cosine Similarity between A and B:{cos_sim}&quot;)<br>print (f&quot;Cosine Distance between A and B:{1-cos_sim}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*rgP7-TGp8Nz8yMTE4eRE5w.png" /><figcaption>Code output (Image by author)</figcaption></figure><pre># using scipy, it calculates 1-cosine<br>from scipy.spatial import distance</pre><pre>distance.cosine(A.reshape(1,-1),B.reshape(1,-1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*aEnzPEGh55orcD1JPBztXw.png" /><figcaption>Code output (Image by author)</figcaption></figure><p><strong>Proof of the formula</strong></p><p>Cosine similarity formula can be proved by using Law of cosines,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScrWLNQ7IzZrYZdt6-Yu5g.png" /><figcaption>Law of cosines (Image by author)</figcaption></figure><p>Consider two vectors A and B in 2-dimensions, such as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mv617aAq7NHIXFXFa2xH4A.png" /><figcaption>Two 2-D vectors (Image by author)</figcaption></figure><p>Using Law of cosines,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DauTnyl2DYjKb2G5bryyA.png" /><figcaption>Cosine similarity using Law of cosines (Image by author)</figcaption></figure><p>You can prove the same for 3-dimensions or any dimensions in general. It follows exactly same steps as above.</p><p><strong>Summary</strong></p><p>We saw how cosine similarity works, how to use it and why does it work. I hope this article helped in understanding the whole concept behind this powerful metric.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ad30aad7db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/cosine-similarity-how-does-it-measure-the-similarity-maths-behind-and-usage-in-python-50ad30aad7db">Cosine similarity: How does it measure the similarity, Maths behind and usage in Python</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[Calculating Document Similarities using BERT and other models]]></title>
            <link>https://medium.com/data-science/calculating-document-similarities-using-bert-and-other-models-b2c1a29c9630?source=rss-ba53c16ffd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2c1a29c9630</guid>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[text-mining]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 05:25:56 GMT</pubDate>
            <atom:updated>2020-12-03T15:16:43.927Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/getting-started">Getting Started</a></h4><h3>Calculating Document Similarities using BERT, word2vec, and other models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4yppLHBTu9uBBMOr" /><figcaption>Photo by <a href="https://unsplash.com/@viktortalashuk?utm_source=medium&amp;utm_medium=referral">Viktor Talashuk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p>Document similarities is one of the most crucial problems of NLP. Finding similarity across documents is used in several domains such as recommending similar books and articles, identifying plagiarised documents, legal documents, etc.</p><p>We can call two documents similar if they are semantically similar and define the same concept or if they are duplicates.</p><p>To make machines figure out the similarity between documents we need to define a way to measure the similarity mathematically and it should be comparable so that machine can tell us which documents are most similar or which are least. We also need to represent text from documents in a quantifiable form (or a mathematical object, which is usually a vector form), so that we can perform similarity calculations on top of it.</p><p>So, converting a document into a mathematical object and defining a similarity measure are primarily the two steps required to make machines perform this exercise. We will look into different ways of doing this.</p><p><strong>Similarity Function</strong></p><p>Some of the most common and effective ways of calculating similarities are,</p><p><em>Cosine Distance/Similarity</em> - It is the cosine of the angle between two vectors, which gives us the angular distance between the vectors. Formula to calculate cosine similarity between two vectors A and B is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*YInqm5R0ZgokYXjNjE3MlQ.png" /></figure><p>In a two-dimensional space it will look like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*mRjgETrg-mPt8jMBu1VtDg.png" /><figcaption>angle between two vectors A and B in 2-dimensional space (Image by author)</figcaption></figure><p>You can easily work out the math and prove this formula using the <a href="https://en.wikipedia.org/wiki/Law_of_cosines">law of cosines</a>.</p><p>Cosine is 1 at theta=0 and -1 at theta=180, that means for two overlapping vectors cosine will be the highest and lowest for two exactly opposite vectors. For this reason, it is called similarity. You can consider 1 - cosine as distance.</p><p><em>Euclidean Distance </em>- This is one of the forms of Minkowski distance when p=2. It is defined as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*55jbZL3qTdeEI5gL.png" /></figure><p>In two-dimensional space, Euclidean distance will look like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*aUFcVBD_dBAAayDFfAmo_A.png" /><figcaption>Euclidean distance between two vectors A and B in 2-dimensional space (Image by author)</figcaption></figure><p><em>Jaccard Distance - </em>Jaccard Index is used to calculate the similarity between two finite sets. Jaccard Distance can be considered as 1 - Jaccard Index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ZyyreB3IE90pHLWO.png" /></figure><p>We can use Cosine or Euclidean distance if we can represent documents in the vector space. Jaccard Distance can be used if we consider our documents just the sets or collections of words without any semantic meaning.</p><p>Cosine and Euclidean distance are the most widely used measures and we will use these two in our examples below.</p><p><strong>Embeddings</strong></p><p>Embeddings are the vector representations of text where word or sentences with similar meaning or context have similar representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*k-9s1B8LTONza48LTeVxUQ.png" /><figcaption>vector representation of words in 3-D (Image by author)</figcaption></figure><p>Following are some of the algorithms to calculate document embeddings with examples,</p><p><strong><em>Tf-idf - </em></strong>Tf-idf is a combination of term frequency and inverse document frequency. It assigns a weight to every word in the document, which is calculated using the frequency of that word in the document and frequency of the documents with that word in the entire corpus of documents. For more details on tf-idf please refer to this <a href="https://medium.com/analytics-vidhya/the-quantitative-value-of-text-tf-idf-and-more-e3c7883f1df3">story</a>.</p><p>Let’s define following as the corpus(collections) of documents for which we want to calculate similarities,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmhAh50gcb3ZAQJjuE5IzA.png" /><figcaption>Document corpus (Image by author)</figcaption></figure><p>We will perform basic text cleaning, removing special characters, removing stop words, and convert everything to lower case. Then we will convert documents to their tf-idf vectors and calculate pairwise similarities using cosine and euclidean distance.</p><p>Pairwise cosine similarity would just be the dot product of the tf-idf vectors becasue tf-idf vectors from sklearn are already normalised and L2 norm of these vectors is 1. So denominator of cosine similarity formula is 1 in this case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9df28328247d7e596b100cd5a9cf25a7/href">https://medium.com/media/9df28328247d7e596b100cd5a9cf25a7/href</a></iframe><pre>print (tfidf_vectors[0].toarray())</pre><pre>print (pairwise_similarities.shape)</pre><pre>print (pairwise_similarities[0][:])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_f4aA0b_uRv83Nakk2RuA.png" /></figure><pre># documents similar to the first document in the corpus<br>most_similar(0,pairwise_similarities,&#39;Cosine Similarity&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_hv4N8ixoY4HeRHl0A5WQ.png" /><figcaption>Documents similar to first document based on cosine similarity and euclidean distance (Image by author)</figcaption></figure><p><strong><em>Word2vec - </em></strong>As the name suggests word2vec embeds words into vector space. Word2vec takes a text corpus as input and produce word embeddings as output. There are two main learning algorithms in word2vec: continuous bag of words and continuous skip gram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/0*sW3mNscCRw_K20pR.png" /><figcaption>Continuous bag of words (CBOW) and skip-gram model (Image by <a href="https://arxiv.org/pdf/1301.3781.pdf">https://arxiv.org/pdf/1301.3781.pdf</a>)</figcaption></figure><p>We can train our own embeddings if have enough data and computation available or we can use pre-trained embeddings. We will use a pre-trained embedding provided by <a href="https://code.google.com/archive/p/word2vec/">Google</a>.</p><p>We will start with tokenising and padding each document to make them all of the same size.</p><pre># tokenize and pad every document to make them of the same size<br>from keras.preprocessing.text import Tokenizer<br>from keras.preprocessing.sequence import pad_sequences</pre><pre>tokenizer=Tokenizer()<br>tokenizer.fit_on_texts(documents_df.documents_cleaned)<br>tokenized_documents=tokenizer.texts_to_sequences(documents_df.documents_cleaned)<br>tokenized_paded_documents=pad_sequences(tokenized_documents,maxlen=64,padding=&#39;post&#39;)<br>vocab_size=len(tokenizer.word_index)+1</pre><pre>print (tokenized_paded_documents[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdH3O4iwWe6xrtt4zCx92w.png" /><figcaption>tokenised document (Image by author)</figcaption></figure><p>Let’s load the pre-trained embeddings. Each word is represented as a 300-dimensional vector.</p><pre># loading pre-trained embeddings, each word is represented as a 300 dimensional vector</pre><pre>import gensim</pre><pre>W2V_PATH=&quot;GoogleNews-vectors-negative300.bin.gz&quot;<br>model_w2v = gensim.models.KeyedVectors.load_word2vec_format(W2V_PATH, binary=True)</pre><p>Using this embedding we can convert every word of our document corpus into a 300-dimensional vector. As we have 6document and we have padded each document to be of maximum size 64, vector representation of the corpus would be of shape 6X64X300.</p><pre># creating embedding matrix, every row is a vector representation from the vocabulary indexed by the tokenizer index. <br>embedding_matrix=np.zeros((vocab_size,300))<br>for word,i in tokenizer.word_index.items():<br>    if word in model_w2v:<br>        embedding_matrix[i]=model_w2v[word]</pre><pre># creating document-word embeddings<br>document_word_embeddings=np.zeros((len(tokenized_paded_documents),64,300))</pre><pre>for i in range(len(tokenized_paded_documents)):<br>    for j in range(len(tokenized_paded_documents[0])):<br>        document_word_embeddings[i][j]=embedding_matrix[tokenized_paded_documents[i][j]]</pre><pre>document_word_embeddings.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*8ZdDU0jX6U2Gp4hGSVXI-w.png" /><figcaption>document-word embedding shape (Image by author)</figcaption></figure><p>Now we have to represent every document as a single vector. We can either average or sum over every word vector and convert every 64X300 representation into a 300-dimensional representation. But averaging or summing over all the words would lose the semantic and contextual meaning of the documents. Different lengths of the documents would also have an adverse effect on such operations.</p><p>One better way of doing this could be taking a weighted average of word vectors using the tf-idf weights. This can handle the variable length problem to a certain extent but cannot keep the semantic and contextual meaning of words. After doing that we can use the pairwise distances to calculate similar documents as we did in the tf-idf model.</p><pre># calculating average of word vectors of a document weighted by tf-idf</pre><pre>document_embeddings=np.zeros((len(tokenized_paded_documents),300))<br>words=tfidfvectoriser.get_feature_names()</pre><pre>for i in range(len(document_word_embeddings)):<br>    for j in range(len(words)):<br>        document_embeddings[i]+=embedding_matrix[tokenizer.word_index[words[j]]]*tfidf_vectors[i][j]</pre><pre>print (document_embeddings.shape)</pre><pre>pairwise_similarities=cosine_similarity(document_embeddings)<br>pairwise_differences=euclidean_distances(document_embeddings)</pre><pre>most_similar(0,pairwise_similarities,&#39;Cosine Similarity&#39;)<br>most_similar(0,pairwise_differences,&#39;Euclidean Distance&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ci8IjuBC_FktVgNG0BLbg.png" /><figcaption>Documents similar to first document based on cosine similarity and euclidean distance (Image by author)</figcaption></figure><p><strong><em>GloVe - </em></strong>Global Vectors for word Embedding (GloVe) is an unsupervised learning algorithm to produce vector representations of word. Training is performed on aggregated global word-word co-occurrence statistics from a corpus, and the resulting representations showcase interesting linear substructures of the word vector space.</p><p>We will use the pre-trained Glove embeddings from <a href="https://nlp.stanford.edu/projects/glove/">Stanford</a>. All the steps would remain same as word2vec embeddings it’s just that in this case we will use the Glove pre-trained model. We are using Glove embeddings of 100-dimensions because of the large size of the embeddings file. You can use higher dimensions also.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42b4698d38e263fa8411ea2ecf6fcb49/href">https://medium.com/media/42b4698d38e263fa8411ea2ecf6fcb49/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKSETNXYo49r5GwyI_gpDQ.png" /><figcaption>Documents similar to first document based on cosine similarity and euclidean distance (Image by author)</figcaption></figure><p><strong><em>Doc2Vec - </em></strong><a href="https://cs.stanford.edu/~quocle/paragraph_vector.pdf">Doc2vec</a> is an unsupervised learning algorithm to produce vector representations of sentence/paragraph/documents. This is an adaptation of word2vec. Doc2vec can represent an entire documents into a vector. So we don’t have to take average of word vectors to create document vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUL_B1Oyq5q5syH5O7vrrg.png" /><figcaption>Distributed Bag of Words version of Paragraph Vectors(PVDOBW) and Distributed Memory version of Paragraph Vectors(PVDM) (Image from <a href="https://arxiv.org/pdf/1405.4053.pdf">https://arxiv.org/pdf/1405.4053.pdf</a>)</figcaption></figure><p>We will use gensim to train a Doc2vec model on our corpus and create vector representations of documents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02cc06d014ad2cc97225aa6af46e0f80/href">https://medium.com/media/02cc06d014ad2cc97225aa6af46e0f80/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWBVgrY7O8-cqoZpyWCfWA.png" /><figcaption>Documents similar to first document based on cosine similarity and euclidean distance (Image by author)</figcaption></figure><p><strong><em>BERT- </em></strong><a href="https://arxiv.org/abs/1810.04805">Bidirectional Encoder Representation from Transformers (BERT)</a> is a state of the art technique for natural language processing pre-training developed by Google. BERT is trained on unlabelled text including Wikipedia and Book corpus. BERT uses transformer architecture, an attention model to learn embeddings for words.</p><p>BERT consists of two pre training steps Masked Language Modelling (MLM) and Next Sentence Prediction (NSP). In BERT training text is represented using three embeddings, Token Embeddings + Segment Embeddings + Position Embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6RzQeTqlsABXJsLZLV0UjA.png" /><figcaption>BERT training architecture (Image from <a href="https://arxiv.org/pdf/1810.04805.pdf">https://arxiv.org/pdf/1810.04805.pdf</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9HagJnUt6mAujVfY58nvA.png" /><figcaption>BERT input representation (Image from <a href="https://arxiv.org/pdf/1810.04805.pdf">https://arxiv.org/pdf/1810.04805.pdf</a>)</figcaption></figure><p>We will use a pre trained BERT model from <a href="https://huggingface.co/sentence-transformers/bert-base-nli-mean-tokens">Huggingface</a> to embed our corpus. We are loading the BERT base model, which has 12 layers (transformer blocks), 12 attention heads, 110 million parameters and hidden size of 768.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/796b507abb5717ca5fec02b0fa402ce5/href">https://medium.com/media/796b507abb5717ca5fec02b0fa402ce5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsGE4vz_rVJBkK1WEfGoxA.png" /><figcaption>Documents similar to first document based on cosine similarity and euclidean distance (Image by author)</figcaption></figure><p>So you have seen multiple ways of representing documents in vector forms and measuring similarities. You can customise them for your own problem and see what works best for you.</p><p>Complete code of this story is available here - <a href="https://github.com/varun21290/medium/blob/master/Document%20Similarities/Document_Similarities.ipynb">https://github.com/varun21290/medium/blob/master/Document%20Similarities/Document_Similarities.ipynb</a></p><p><em>References:</em></p><ul><li><a href="https://en.wikipedia.org/wiki/Law_of_cosines">Law of cosines - Wikipedia</a></li><li><a href="https://code.google.com/archive/p/word2vec/">Code</a></li><li><a href="https://arxiv.org/abs/1301.3781">Efficient Estimation of Word Representations in Vector Space</a></li><li><a href="https://nlp.stanford.edu/projects/glove/">GloVe: Global Vectors for Word Representation</a></li><li><a href="https://arxiv.org/abs/1405.4053">Distributed Representations of Sentences and Documents</a></li><li><a href="https://arxiv.org/abs/1810.04805">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a></li><li><a href="https://huggingface.co/sentence-transformers/bert-base-nli-mean-tokens">sentence-transformers/bert-base-nli-mean-tokens · Hugging Face</a></li><li><a href="https://medium.com/analytics-vidhya/the-quantitative-value-of-text-tf-idf-and-more-e3c7883f1df3">The quantitative value of text, tf-idf and more…</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c1a29c9630" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/calculating-document-similarities-using-bert-and-other-models-b2c1a29c9630">Calculating Document Similarities using BERT and other models</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[The quantitative value of text, tf-idf and more…]]></title>
            <link>https://medium.com/analytics-vidhya/the-quantitative-value-of-text-tf-idf-and-more-e3c7883f1df3?source=rss-ba53c16ffd24------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c7883f1df3</guid>
            <category><![CDATA[tf]]></category>
            <category><![CDATA[idf]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Varun]]></dc:creator>
            <pubDate>Sun, 16 Aug 2020 13:33:57 GMT</pubDate>
            <atom:updated>2020-08-19T14:43:14.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HyWLpuWLOavkS8Nq" /><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><p><strong>Introduction</strong></p><p>tf-idf, which stands for term frequency-inverse document frequency is used to calculate a quantitative digest of any document, which can be further used to find similar documents, classification of documents, etc.</p><p>This article will explain tf-idf, it’s variations and what is the impact of these variations on the model output.</p><p>tf-idf, which stands for term frequency-inverse document frequency is similar to Bag of Words (BoW) where documents are considered as a bag or collection of words/terms and converted to numerical forms by counting the occurrences of every term. The whole idea is to assign a weight to each term occurring in the document.</p><p>tf-idf takes it to one step further and also consider the relative importance of every term to the document in a collection (normally addressed as corpus) of documents.</p><p>Wikipedia summarises it well,</p><p><em>term frequency–inverse document frequency, is a numerical statistic that is intended to reflect how important a word is to a document in a collection or corpus.</em></p><p>Following is a sample collection of documents taken from Wikipedia which will be the corpus (of size 4) for this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5fh-8FkozYen_4zQcAAQg.png" /><figcaption>Document Corpus</figcaption></figure><p>We will have to perform some text cleansing and pre-processing such as removing special characters, removing stop words and lemmatizing words in the corpus before further steps. Text look like this after these steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhMEBIscwXLWjRf3lSm4PA.png" /><figcaption>Processed text</figcaption></figure><p><strong>Calculations</strong></p><p>tf, term frequency, is the simplest way of calculating weights. As the name suggests, weight of a term <em>t</em> in document <em>d</em> is the number of occurrences of <em>t</em> in <em>d</em>, which is exactly the Bag of Words model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37swCklo2ildgoFxSFfHvQ.png" /><figcaption>Term Frequencies</figcaption></figure><p>In tf there is no notion of importance. idf, inverse document frequency, is used to introduce the importance factor of any term. This is required because some of the terms would have little or no discriminating power such as the collection of documents about machine learning would have term machine in almost all the documents and does not hold much discriminating relevance.</p><p>Document frequency, which is the number of documents in the corpus that contains the term <em>t, </em>is used to scale the weight(factor of importance) of term <em>t</em>. idf of a term <em>t</em> in the document collection is defined as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*dxpKTQ46ZBLpdw8GpLI87A.png" /></figure><p>where,</p><p><em>N</em> is the number of documents in the collection, <em>dft </em>is the document frequency of term <em>t</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzp3TfyLF9BQDzgRFnHN7A.png" /><figcaption>idf values</figcaption></figure><p><strong>Different variations of tf and idf</strong></p><p>tf-idf,</p><p>tf-idf is the combination of tf and idf, which is the scaled version of weight. tf-idf of a term <em>t</em> present in a document <em>d</em> from a corpus of documents <em>D</em> is defined as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*OFLrkDOKdkIp_ZDQw-4Sqw.png" /></figure><p>tf-idf is highest for a <em>t</em> if it occurs many times within a small number of documents</p><p>tf-idf is lower for <em>t</em> when it occurs fewer times in a document, or occurs in many documents</p><p>tf-idf is lowest when <em>t</em> occurs in all the documents</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpHg6VClsp-lK1YqvYjDlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4BjyJgqMYk1egZ5zDFsqA.png" /></figure><p>We can see that the weight of <em>data</em> is more than <em>computer </em>even their term frequency is same for document 0. This is because of idf as <em>data</em> occurred in a smaller number of documents.</p><p><em>Machine</em> occurred in all the documents, hence it has the 0 weight. We can add 1 to idf to avoid getting 0 for such terms as per the use case.</p><p>Sub linear tf-scaling,</p><p>It is not always true that multiple occurrences of a term in a document mean more significance of that term in proportion to the number of occurrences. Sublinear tf-scaling is modification of term frequency, which calculates weight as following,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*w196eSpaeDKcHzCxY5gejA.png" /></figure><p>In this case tf-idf becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*o0S_4-4cmqHxifEHpH51HQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmT4ejZMBb6I2qFVYBQ8aQ.png" /><figcaption>wf-idf</figcaption></figure><p>As intended sub linear tf-scaling has scaled down the weight of term <em>algorithm</em> as it is occurring multiple times(maximum tf) in first document.</p><p>Maximum tf-normalization,</p><p>This is another modification of term frequency where tf of every term occurring in a document is normalized by the maximum tf in that document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*jbT8Olg0oAtet7qJPnoBTg.png" /></figure><p>where <em>a</em> is the smoothing term ranging between 0 to 1 and is generally set to 0.4.</p><p>Maximum tf-normalization handles the case when a long document has higher values of term frequencies just because of the length of the document and it will have same terms repeated again and again.</p><p>This approach falls short in the case when a document will have a term occurring unusually very high number of times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukoTA4aGwM_ZlOn1JzPZsg.png" /></figure><p>High frequency terms such as <em>algorithm</em> and <em>computer</em> are scaled down as it is normalized by the maximum frequency. Terms with zero frequency are also having some weight because of the smoothing term.</p><p>Normalization,</p><p>We can normalize documents vectors either by L2 or L1 norm. After L2 normalization, sum of elements of every document vector will be 1. In this case cosine similarity between any two document vectors is just the dot product of the vectors. In case of L1 normalization, sum of absolute values of elements of very document vector becomes 1.</p><p>Code used in the article can be found at this link — <a href="https://github.com/varun21290/medium/blob/master/tfidf/tfidf.ipynb">https://github.com/varun21290/medium/blob/master/tfidf/tfidf.ipynb</a></p><p>Scikit-Learn provides most of these calculations out of the box, check links in the references.</p><p><strong>References</strong></p><p><a href="https://nlp.stanford.edu/IR-book/">https://nlp.stanford.edu/IR-book/</a></p><p><a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">https://en.wikipedia.org/wiki/Tf%E2%80%93idf#</a></p><p><a href="https://en.wikipedia.org/wiki/Machine_learning">https://en.wikipedia.org/wiki/Machine_learning</a></p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#</a></p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html">https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#</a></p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html">https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html#</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c7883f1df3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/the-quantitative-value-of-text-tf-idf-and-more-e3c7883f1df3">The quantitative value of text, tf-idf and more…</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>