<?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 Arnab on Medium]]></title>
        <description><![CDATA[Stories by Arnab on Medium]]></description>
        <link>https://medium.com/@arnabpushilal?source=rss-4823b06886ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v_eHeKqf5-N3FKyxrszdYA.jpeg</url>
            <title>Stories by Arnab on Medium</title>
            <link>https://medium.com/@arnabpushilal?source=rss-4823b06886ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:20:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arnabpushilal/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 review of basic recommender systems]]></title>
            <link>https://medium.com/analytics-vidhya/a-review-of-basic-recommender-systems-549837f56a83?source=rss-4823b06886ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/549837f56a83</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[matrix-factorization]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Arnab]]></dc:creator>
            <pubDate>Wed, 25 May 2022 17:24:52 GMT</pubDate>
            <atom:updated>2022-05-25T17:25:51.143Z</atom:updated>
            <content:encoded><![CDATA[<h3>A review of recommender systems — challenges, models &amp; evaluation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zNHVuU4kz9Y8ucKI" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=medium&amp;utm_medium=referral">charlesdeluvio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Challenge</h3><p>The main challenge for any recommender system application is: given the content in your database/application, suggest something to the user that they would like. For instance, the content could be music for spotify, movies for netflix or resturants for UberEats. We could look at it like a building a <strong><em>filter </em></strong><em>t</em>hat would take in all content that you have and providing the ones to user that they would probabily like the most.</p><h4>How do we go about this?</h4><p>For instance, let’s take this example of a user for an appliance website. For every user from all the appliances on the website, we have to assign a “score” to each user and show them the top K items depending on the magnitude of the scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4y2_HSKztIVOgZRxCd07Q.png" /></figure><p>Well, what do we know/ don’t know about the problem?</p><ol><li><strong>Content space: </strong>We know about our content catalog — for instance from the picture above we might have metadata about the description of the image. What is the price of the item? Is it a chair or a table? Who is the seller etc?</li><li><strong>User:</strong> What other items have this user interacted with prior to the current (browsing) session. Do they like more pricey stuff/ or maybe do they have an affinity for cheap furniture</li><li><strong>Context: </strong>What are looking for in the current session? Have they looked up “chairs”? Then it’s likely they want to be recommended good chairs for now.</li><li><strong>Scale: </strong>How large is the content database that we have to filter from? This restricts our ability to use some models.</li></ol><h3><strong>Two main approaches</strong></h3><p>The two main approaches used for the problem have been</p><ol><li><strong>Collaborative filtering: </strong>Following our example, based on the appliance that you liked/bought we will find other users that seem to enjoy the “same thing”. Then we would recommend to you appliances that they have bought and you may like them too.</li><li><strong>Content-based filtering: </strong>If you consistently bought only furniture from the website, chances are you like furniture.</li></ol><p>Note that with collaborative filtering there is the issue of the “cold-start” problem. For newer items or users, it becomes difficult to predict the interactions.</p><h3>Some useful models:</h3><p>If you want to build a baseline for your new recsys model this might be the place to start! For this let’s imagine our new problem is to recommend recipes to users based on the ratings that they give particular recipes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*wIR08c9UyIHHBJ1LB3awMA.png" /></figure><p>Let’s assume the matrix above to be <strong>S</strong>. The rows indicate each user and the columns indicate each recipe. The grey values show us the rating that a particular user has given to a recipe. We can notice that this matrix will be sparse since usually, the number of interactions is far lesser than the number of recipes/users. The crossed-out values are considered “missing” and we test our model by predicting these ratings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*-DfiYeD7LPasZEZdG57Lnw.png" /><figcaption>Source: <a href="https://dl.acm.org/doi/10.1145/2043932.2043979">https://dl.acm.org/doi/10.1145/2043932.2043979</a></figcaption></figure><ol><li><strong>Matrix factorization:</strong> In the most restrictive case of this factorization we need to find a feature vector for each user and recipe. The matrix <strong>U</strong> comprises the user feature vectors, &amp; <strong>R </strong>consists of the recipe feature vectors. The dimensionality of each feature vector, in this case, is considered to be “<strong>n(f)</strong>”. Then each predicted rating for a given user <strong>u </strong>with feature vector<strong> u </strong>and recipe <strong>r </strong>with feature vector<strong> p </strong>is given by<strong> S(u,r) = u.p</strong>. To compute these feature vectors we, therefore, have the objective:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*r2FLoVu0D9rr8Z-Z4ewaeA.png" /></figure><p>The first term is the minimization of the reconstruction error of the matrix S and the second term accounts for the regularization term. The problem can be solved by alternating gradient descent. Other versions of the matrix factorization exist. For instance, we might want to incorporate a bias-term in the objective which would account for the fact that some users usually rate higher than normal, or some items are just better liked by everyone. This is called Matrix Factorization with Biases.</p><p>2. <strong>Neural Collaborative Filtering</strong>: The disadvantage of matrix factorization is it’s supposed simplicity. As we saw before, the user-item interactions are modeled as the inner product of the feature vectors. Perhaps more complex interactions could be modelled?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*nnkElPz-irBqwoxFBsiucA.png" /><figcaption>The disadvantage of matrix factorization : <a href="https://arxiv.org/pdf/1708.05031.pdf">Source</a></figcaption></figure><p>We see in the figure above that modeling the feature vectors in the low-dimensional latent space may not always be the best choice for the ranking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*_dDmmYZrR5pG5LkYwfsNhQ.png" /></figure><p>The goal of the neural collaborative filtering method is the same as the matrix factorization case. Given a user and an item predict a rating score. However, instead of modeling rating as an inner product of the user &amp; the item vector, we pass them through a Multi-layer perceptron or a fully connected neural network. Suppose a user has interacted with 10 items, then we can take those and sample 10 negative examples from the rest of the data and train the model. Then we can easily learn the rating’s through a regression-based loss, depending on the kind of training data we have.</p><p>We note that we can append the input vectors with other features like content information that could help with the “cold-start” problem.</p><p>3: <strong>Multi-stage recommender models: </strong>Now we can tackle the challenge of scale. Let’s take the example of Youtube. There are approximately 800 million videos and 2 billion user’s on youtube. With such a scale, the above-discussed methods become intractable. To cope we must do this in two stages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KG2HPXn9gZRH1nRwnz6u6w.png" /><figcaption>Two-stage recommender model: <a href="https://dl.acm.org/doi/pdf/10.1145/2959100.2959190">Source</a></figcaption></figure><p>As we can see from the figure, we do not use our ranking model on the entire video corpus, but we have a candidate generation process to narrow out the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*dQdwAU_70AXpGg_VDKiyug.png" /></figure><p>The way that the authors did this was by posing recommendations as a classification problem. Based on the context ( previous video watches, the idea that the user would want something similar ) what is the probability that a user watches a particular video? We can see from the figure above that the input feature vector comprises the mean of the embeddings of previous video watches and searches along with other features. Then again passing them through multiple fully connected layers, we jointly learn the embeddings of the videos and the parameters of the model. Finally, with the learned embeddings we can perform an approximate nearest neighbor search to narrow down millions of videos into hundreds of candidates.</p><p><strong>Two tower model: </strong>Another common approach for candidate generation is to have two separate network structure’s for the user and the content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/0*Drbckjj5_0vKWVJN" /><figcaption>Two tower model used at pintrest: <a href="https://medium.com/pinterest-engineering/pinterest-home-feed-unified-lightweight-scoring-a-two-tower-approach-b3143ac70b55">Source</a></figcaption></figure><p>The goal would be to learn the embeddings of the user’s and the items only the architecture for the user and item will be separate. Then both the embeddings are passed dotted to generate a score. For training, we can use negative sampling the same as in the previous cases.</p><p>Post candidate generation we can use a separate ranking model to narrow down from the hundreds to the tens.</p><h3><strong>Evaluation</strong></h3><p>Suppose we have 3 relevant items for a particular user. Some metrics of evaluation are as follows:</p><ol><li><strong>Mean Average Precision@K:</strong> Ideally, we want the relevant items to be placed first in the list of recommendations. So in this case, the best possible scenario is the recommendation is [1,1,1] (we recommended all the relevant items in the first 3 ranks ). However, if it is [1,0,1] we don’t want to metric to say that’s absolute garbage. So we calculate precision as follows:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*US6Ngt8fgrgNyCrjhJPojg.png" /><figcaption>Precision@K</figcaption></figure><p>Intuitively we can understand this as follows. For the first rank, we can’t do better because we have suggested the relevant item, so precision@1 is 1/1, for the second rank we couldn’t suggest it so precision@2is 1/2, and so on. Then we compute the average precision@3 which just takes the mean of precision@1,precision@2 &amp; precision@3. Finally to compute the mean average precision@3 we take the average of all the individual average precision@3 for all users.</p><p>Like MAP there are other rank-based metrics like NDCG@K which take into account not only the binary relevance but that some items are more relevant are others.</p><p>2. <strong>Predictive Accuracy Based Metrics</strong>: For instance, in the matrix factorization problem we were getting a rating score between each user &amp; item. Here we could simply choose RMSE or MAE as the metric</p><p>3. <strong>Business-based metrics: </strong>This usually comes way down the line, when you put your model into production. Common ones include Click-through Rate(CTR) — Are the users clicking on your recommendations? Adoption &amp; Conversion — After clicking has the user used your recommendation?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=549837f56a83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-review-of-basic-recommender-systems-549837f56a83">A review of basic recommender systems</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[Tokenizers — Your first step into NLP]]></title>
            <link>https://medium.com/analytics-vidhya/tokenizers-your-first-step-into-nlp-837c2ddae60a?source=rss-4823b06886ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/837c2ddae60a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Arnab]]></dc:creator>
            <pubDate>Sat, 02 Oct 2021 20:02:39 GMT</pubDate>
            <atom:updated>2021-10-11T07:01:16.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tokenizers — Your first step into NLP</h3><p>One of the starting points of an NLP pipeline explained</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wp5yaXfQfPd2Bml-" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction: Machines v/s Humans — How do we read?</h3><p>For us, language is trivial. We’ve heard it since the day we’ve been born. We understand:</p><ol><li>Phonetics: The sound of the speech helps us perceive what it means.</li><li>Syntax: The combination of words and phrases that make up a sentence.</li><li>Semantics: The meaning of each of the words, phrases &amp; sentences</li></ol><p>Now, once you show a computer a sentence, it has no idea about the structure and the meaning of the sentence. Somehow, we have to encode the meaning at a word, phrase, and sentence level.</p><p>Can we encode rules? Can we say, “Nouns must agree with their verbs, which means that a singular noun requires a singular verb, and a plural noun requires a plural verb” and so and so forth? Well, that would take a long list of rules and make our jobs harder. With the advent of ML &amp; Deep learning it turns out, models can figure out these rules and meanings on their own.</p><h4><strong>Word Based Tokenization</strong></h4><p>The first step would be to break down the text into “chunks” and encoding them numerically. This numerical representation would then each have a vector representation ( <strong><em>Word Embeddings</em></strong>, <a href="https://medium.com/analytics-vidhya/word-embeddings-aaef8c6bd04a">you can check out an entire article I wrote about that</a>) which the model would learn.</p><p><strong>Whitespace Tokenization:</strong></p><p>At its simplest form, we split the entire text on <strong>whitespaces</strong>. This would separate it into words.</p><p>Let’s take an example from the harry potter novels for our vocabulary. All the words our model would know would come from this piece of text.</p><p>Here’s an abbreviation.</p><pre>/ \n\n\n\n\nTHE BOY WHO LIVED \n\nMr. and Mrs. Dursley, of number four, Privet Drive, \nwere proud to say that they were perfectly normal, \nthank you very much. They were the last people you’d \nexpect to be involved in anything strange or \nmysterious, because they just didn’t hold with such \nnonsense. \n\nMr. Dursley was the director of a firm called \nGrunnings, which made drills. He was a big, beefy \nman with hardly any neck, although he did have a \nvery large mustache...</pre><p>At this point, for simplicity, we would want to get rid of the punctuations and \nto clean the text by word.</p><pre><strong>Regex to match any non alphanumeric character or whitespace, ie punctuation and replacing with empty &#39;&#39;</strong></pre><pre>punc = re.sub(&#39;[^\w\s]&#39;, &#39;&#39;, string)</pre><pre><strong>Removing newlines \n and applying lowercase.</strong></pre><pre>newlines=re.sub(&#39;[\n+]&#39;,&#39;&#39;,punc).lower()    </pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be00b76cf1ddde9e99fb48bebe54dc94/href">https://medium.com/media/be00b76cf1ddde9e99fb48bebe54dc94/href</a></iframe><p>The code above converts the paragraph to something like this.</p><pre>c=Corpus(path) <br>c.tokenize()</pre><pre><strong>2D vector where each element is a sentence. [0,1,2,3] corresponds to &quot;the boy who lived&quot;</strong></pre><pre>--------------------------------------------------------------------</pre><pre>[[], [], [], [], [], [0, 1, 2, 3], [], [4, 5, 6, 7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18, 13, 19, 20], [21, 22, 23, 24, 18, 13, 0, 25, 26, 27], [28, 15, 29, 30, 31, 32, 33, 34], [35, ...</pre><p>Each number will correspond to some <strong>d-dimensional vector</strong> which the model will learn as it’s representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*lyy8ED9SDqCS3Du9gkjYWA.png" /><figcaption>example with the embedding dimension as 3</figcaption></figure><p>But here’s the problem</p><pre>df[df.word.str.startswith(&#39;brave&#39;)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*MuVunFiWuq1O6fioBLc6Kw.png" /><figcaption>Base word brave</figcaption></figure><p>For words like brave,bravery,bravely,braverthe model assumes separate embeddings which are probably a waste of space. Also, if every single unique word is used for our vocabulary, it might get excessively large.</p><p>There are also the complications of punctuations which I avoided. Ideally, you would like to keep some punctuation that adds meaning to a sentence. Characters like ? could be stripped and tokenized individually.</p><p>Libraries like nltk which have built-in tokenizers handle punctuations as follows.</p><p><strong>Rule-based tokenization:</strong></p><pre>from nltk.tokenize import word_tokenize<br>word_tokenize(&quot;Do you like this? I don&#39;t&quot;)</pre><pre>--------------------------------------------------------------</pre><pre>[&#39;Do&#39;, &#39;you&#39;, &#39;like&#39;, &#39;this&#39;, &#39;?&#39;, &#39;I&#39;, &#39;do&#39;, &quot;n&#39;t&quot;]</pre><p>Notice how ‘?’ is a separate token. And “don’t” is split into “do” &amp; “n’t”. This is due to the fact that “don’t” comes from “do not”. Such splitting is often referred to as <strong>rule-based tokenization.</strong></p><p><strong>Punctuation-based tokenization</strong></p><p>If you separate by punctuation dont will be split to donand tthe punctuation &#39; will be a separate token.</p><p>All these word-based tokenizers are faced with the fundamental issue of massive vocabulary size. And if you incorporate rules to shorten your vocabulary, like only taking frequent words — you are faced with the issue of the unktoken for <strong>unknown words </strong>at the time of testing/generation.</p><blockquote>But there’s a simple solution right? Characters! Atleast for the english language, there are way fewer characters than words.</blockquote><h4><strong>Character-Based Tokenization:</strong></h4><p>I’ve covered a little bit of this <a href="https://medium.com/analytics-vidhya/character-awareness-for-language-models-using-cnns-6b1c1a331042">in this article</a>. But the idea is just to have mapped to every character (or special character &amp; punctuation) and learn an embedding for each character.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*JrHEqjeIbFMIiRUW.png" /><figcaption>Image Credits: <a href="https://blog.floydhub.com/tokenization-nlp/">https://blog.floydhub.com/tokenization-nlp/</a></figcaption></figure><p>As shown in the example above, the model would learn a representation for each character I s n t.. separately. This would solve both of our initial problems.</p><ol><li><strong>Vocab size</strong>: There are only a few characters we need to consider. We can mix all of them to form any word.</li><li><strong>Out of vocabulary words</strong>: In the purely word-based tokenization, there&#39;s a chance that at testing time, we will encounter words that we haven’t seen before. For instance, if we have a rare word like Gobbledygookin our test set, instead of assigning the unktoken to it, it would combine all the individual characters and form a representation for it.</li></ol><p>But obviously, there are problems. In the case of words, each representation had a meaning. What does the vector representation of a single character really mean?</p><p>Also, our sequences get unnecessarily long. For a single sentence of 7 words, our word-based tokenizer would produce 7 tokens. For the same sequence, a character-based tokenizer would produce ~35–40 tokens depending on how big the words were. (This would’ve been a bigger issue with sequential models, where our inputs need to be processed one after the other. But now we’ve got Transformers, where inputs are processed parallelly.)</p><p>So, we move on to the sweet spot subword-based tokenizationwhere we (kind of) take a combination of both of our character-based and word-level tokens.</p><h4><strong>Sub-word Based Tokenization:</strong></h4><p>The main idea here is that rarer words would be broken down into sub-words, which the others remain as it is. For example, a common word in the corpus such as Harrywould be left alone as it is. And rarer words like gryffindorwould be broken up into subwords such as gr,y,ffin,dor</p><p>Do you notice something the suffixes y,r,ly,est,erwhen added to other words may mean something to? For example, Tallest/Strongest has a common suffix est which makes it superlative. So perhaps learning representations for estwould help us.</p><p><strong>Byte Pair Encoding:</strong></p><p><strong>Byte pair encoding</strong> is a form of data compression in which the most common <strong>pair of consecutive bytes</strong> of data is replaced with a byte that does not occur within that data.</p><p>For instance, if we had bytes like bbdcdcae</p><ol><li>Look at the pair dc repeated twice</li><li>We replace cd with X, so we have bbXXae</li><li>Next, we have a pair bbwhich we can replace with say Y, YXXae</li><li>Now no more pair exists, and we can stop.</li></ol><p>For tokenization using BPE, we apply an extremely similar algorithm.</p><ol><li>Start with the character vocabulary.</li></ol><pre>All tokens: dict_keys([&#39;/&#39;, &#39;&lt;/w&gt;&#39;, &#39;T&#39;, &#39;H&#39;, &#39;E&#39;, &#39;B&#39;, &#39;O&#39;, &#39;Y&#39;, &#39;W&#39;, &#39;L&#39;, &#39;I&#39;, &#39;V&#39;, &#39;D&#39;, &#39;M&#39;, &#39;r&#39;, &#39;.&#39;, &#39;a&#39;, &#39;n&#39;, &#39;d&#39;, &#39;s&#39;, &#39;u&#39;, &#39;l&#39;, &#39;e&#39;, &#39;y&#39;, &#39;,&#39;, &#39;o&#39;, &#39;f&#39;, &#39;m&#39;, &#39;b&#39;, &#39;P&#39;, &#39;i&#39;, &#39;v&#39;, &#39;t&#39;, &#39;w&#39;, &#39;p&#39;, &#39;h&#39;, &#39;c&#39;, &#39;k&#39;, &#39;’&#39;, &#39;x&#39;, &#39;g&#39;, &#39;j&#39;, &#39;G&#39;, &#39;|&#39;, &#39;2&#39;, &#39;S&#39;, &#39;-&#39;, &#39;J&#39;, &#39;K&#39;, &#39;R&#39;, &#39;;&#39;, &#39;N&#39;, &#39;A&#39;, &#39;“&#39;, &#39;”&#39;, &#39;—&#39;, &#39;F&#39;, &#39;z&#39;, &#39;?&#39;, &#39;3&#39;, &#39;!&#39;, &#39;q&#39;, &#39;4&#39;, &#39;C&#39;, &#39;5&#39;, &#39;6&#39;, &#39;(&#39;, &#39;)&#39;, &#39;:&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;1&#39;, &#39;0&#39;, &#39;U&#39;, &#39;&quot;&#39;, &#39;\\&#39;, &#39;‘&#39;, &#39;•&#39;, &#39;Z&#39;, &#39;Q&#39;, &#39;■&#39;, &quot;&#39;&quot;])</pre><pre>No. of tokens : 83</pre><p>Calculate how the frequency of each token.</p><pre>....</pre><pre>&#39;c&#39;: 6372,            <br>&#39;d&#39;: 16279,              <br>&#39;e&#39;: 41351,              <br>&#39;f&#39;: 6429,</pre><pre>....</pre><p>2. Split all the words according to the base vocabulary( which are all characters at the moment), mark the end of each with a token (So that suffixes and prefixes could be separated, for instance, with Real&lt;/w&gt; &amp; algebra&lt;/w&gt; if al&lt;/w&gt; was the token, it must’ve come from Real&lt;/w&gt;).</p><pre>T H E &lt;/w&gt; : 17 <br>B O Y &lt;/w&gt; : 1<br>W H O &lt;/w&gt; : 1 <br>L I V E D &lt;/w&gt; : 1<br>M r . &lt;/w&gt; : 79 <br>a n d &lt;/w&gt; : 2139 <br>M r s . &lt;/w&gt; : 44 <br>D u r s l e y , &lt;/w&gt; : 6 <br>o f &lt;/w&gt; : 1233 <br>n u m b e r &lt;/w&gt; : 14<br>...</pre><p>3. Calculate pairwise-frequencyfor the current words according to the current vocab.</p><pre>(&#39;/&#39;, &#39;&lt;/w&gt;&#39;) : 4 <br>(&#39;T&#39;, &#39;H&#39;) : 28 <br>(&#39;H&#39;, &#39;E&#39;) : 21 <br>(&#39;E&#39;, &#39;&lt;/w&gt;&#39;) : 33 <br>(&#39;B&#39;, &#39;O&#39;) : 4 <br>(&#39;O&#39;, &#39;Y&#39;) : 1 <br>(&#39;Y&#39;, &#39;&lt;/w&gt;&#39;) : 8 <br>(&#39;W&#39;, &#39;H&#39;) : 6 <br>(&#39;H&#39;, &#39;O&#39;) : 7 <br>(&#39;O&#39;, &#39;&lt;/w&gt;&#39;) : 6 <br>(&#39;L&#39;, &#39;I&#39;) : 3 <br>(&#39;I&#39;, &#39;V&#39;) : 2 <br>(&#39;V&#39;, &#39;E&#39;) : 6 <br>(&#39;E&#39;, &#39;D&#39;) : 9 <br>(&#39;D&#39;, &#39;&lt;/w&gt;&#39;)<br>...</pre><p>Each of the two letters was repeated with the frequency mentioned on its right.</p><p>4. Calculate the pair with the maximum frequency and merge. Add this to the current vocab.</p><pre>(&#39;e&#39;, &#39;&lt;/w&gt;&#39;): 13356 # these will be merged in this case</pre><pre>All tokens: dict_keys([&#39;/&#39;, &#39;&lt;/w&gt;&#39;, &#39;T&#39;, &#39;H&#39;, &#39;E&#39;, &#39;B&#39;, &#39;O&#39;, &#39;Y&#39;, &#39;W&#39;, &#39;L&#39;, &#39;I&#39;, &#39;V&#39;, &#39;D&#39;, &#39;M&#39;, &#39;r&#39;, &#39;.&#39;, &#39;a&#39;, &#39;n&#39;, &#39;d&#39;, &#39;s&#39;, &#39;u&#39;, &#39;l&#39;, &#39;e&#39;, &#39;y&#39;, &#39;,&#39;, &#39;o&#39;, &#39;f&#39;, &#39;m&#39;, &#39;b&#39;, &#39;P&#39;, &#39;i&#39;, &#39;v&#39;, &#39;t&#39;, &#39;w&#39;, <strong>&#39;e&lt;/w&gt;&#39;</strong>, &#39;p&#39;, &#39;h&#39;, &#39;c&#39;, ...</pre><pre>No of tokens: 84</pre><pre><strong>Current list of words</strong></pre><pre>&#39;T h e y &lt;/w&gt;&#39;: 155,  <br>&#39;t h <strong>e&lt;/w&gt;</strong>&#39;: 3654,  <br>&#39;l a s t &lt;/w&gt;&#39;: 61,</pre><p>Now we could combine e&lt;/w&gt; with other characters to form the next pairs. We also need to recalculate the token frequencies</p><pre>...</pre><pre>&#39;c&#39;: 6372,         <br>&#39;d&#39;: 16279,    <br>&#39;e&#39;: 27995,         <br>&#39;e&lt;/w&gt;&#39;: 13356,     <br></pre><pre>...  </pre><p>Notice how the frequency of ehas changed.</p><p>5. Repeat. Choose the number of merges as a hyper-parameter to your suiting. This way after a lot of merges, the common words would appear unchanged along with sub-words which would could then be combined to help form unknown words.</p><p>Once you have the list of tokens, for an unknown word we can combine the subwords found in this process to form representations.</p><p><strong>WordPiece:</strong></p><p>Once you’ve learned about BPE, there are only a few tweaks needed to learn WordPiece. This is the tokenization method used in BERT, one of the most successful NLP papers in recent times.</p><p>The main difference comes with the idea of merging tokens. In BPE, we just take the most frequent pair &amp; merge it.</p><p>In contrast,wordpiece merges, only when it increases the likelihood of the training data. For example, if “er” is more likely to appear than e &amp; r, they are merged. You can read more about this <a href="https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf">here</a>.</p><pre>from transformers import BertTokenizer<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>tokenizer.tokenize(&quot;Slytherin is the best house ever!&quot;)</pre><pre>Output:<br>[&#39;sly&#39;, &#39;##ther&#39;, &#39;##in&#39;, &#39;is&#39;, &#39;the&#39;, &#39;best&#39;, &#39;house&#39;, &#39;ever&#39;, &#39;!&#39;]</pre><p>The ## indicates that the word didn’t start with ther. “Syltherin” was the unknown word in BERTs vocabulary. But it had tokens corresponding to ##ther , ##in &amp; sly. Thus, it broke the word down with the tokens it knew.</p><p><strong>Resources:</strong></p><ol><li><a href="https://huggingface.co/transformers/tokenizer_summary.html">https://huggingface.co/transformers/tokenizer_summary.html</a></li><li><a href="https://blog.floydhub.com/tokenization-nlp/">https://blog.floydhub.com/tokenization-nlp/</a></li><li><a href="https://leimao.github.io/blog/Byte-Pair-Encoding/">https://leimao.github.io/blog/Byte-Pair-Encoding/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=837c2ddae60a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/tokenizers-your-first-step-into-nlp-837c2ddae60a">Tokenizers — Your first step into NLP</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[Understanding the building blocks of transformers]]></title>
            <link>https://medium.com/analytics-vidhya/understanding-the-building-blocks-of-transformers-c28484788d5a?source=rss-4823b06886ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/c28484788d5a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Arnab]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 17:30:32 GMT</pubDate>
            <atom:updated>2024-02-11T09:13:27.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Transformers have become ubiquitous as a choice of architecture for NLP problems. This article will go through some of the basic background needed to start understanding how transformers work from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*jFSeBSZ2WOTl-cUM2PfAow.png" /><figcaption>The transformer architecture proposed in <a href="https://arxiv.org/pdf/1706.03762.pdf">“Attention is all you need”</a></figcaption></figure><h3><strong>Previous architectures:</strong></h3><p>To understand why someone would come with such an idea, we can revisit some of the architectures used prior to transformers.</p><h4><strong>Encoder-Decoder RNN</strong></h4><p>In 2014, the paper titled “<a href="https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/?utm_source=Backlink&amp;utm_medium=SEO">Sequence</a> to Sequence Learning with Neural Networks” introduced the “encoder-decoder” structure that has a RNN to encode a sequence to obtain a <strong>fixed vector length representation</strong> (in English for example). Similarly, a decoder RNN would take in the fixed vector representation and convert it into french, word by word. This was useful because both the sequences could be of <strong>variable length</strong>, as it often is during language translations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*nKosSEf9_6Ramb5x.png" /><figcaption>An example of an encoder-decoder structure for NMT</figcaption></figure><p>In the example above, we can see how “RNN’s really rock” is converted into french. <strong>The last “hidden state” acts as the fixed encoding for the entire context of the sentence</strong>. The decoder then takes this context, a start token, and predicts over a distribution of words for timestep_0. Then the same word (“Les”in the figure above) is carried over as an input for the next timestep.</p><p>Already, we can try and figure out a few tweaks that could try and improve on this.</p><p>Why should we represent the entire input sentence <strong>as one fixed representation? </strong>Surely, if there’s a really long sentence, <strong>a fixed vector won’t do justice to the entire context</strong>. Here’s where RNNs with attention came in with the paper <a href="https://arxiv.org/pdf/1409.0473.pdf">“Neural Machine Translation By Jointly Learning to Align &amp; Translate”</a>.</p><h4><strong>Encoder-Decoder RNNs with Attention:</strong></h4><p>Instead of using a fixed context representation, here <strong>we calculate a context vector at every timestep</strong> by searching through the input sentence. So effectively, given a hidden state of the decoder, the model decides which part of the input sequence is important for it to translate (or generate) the current word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*ZAcpXcpZc-igGEYh2nDMqA.png" /><figcaption>Encoder-decoder with attention</figcaption></figure><p>Let’s try and figure out what’s going on in the figure above. Our input sequence is given by words (X1, X2 …XT)where each word is fed in through a bi-directional <a href="https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/?utm_source=Backlink&amp;utm_medium=SEO">RNN</a> where h1,h2.. are the hidden states. Without attention, we were taking the vector <strong>h_T</strong> as our context vector. But in this case, we take a linear combination of all our hidden states via some weights alpha, and the previous state of the decoder <strong>S_t-1</strong> to predict <strong>S_T</strong> and subsequently our translated word <strong>Y_t </strong>for the current time step.</p><p>Steps for attention model for a single prediction are as follows:</p><ol><li><strong>Encoder &amp; decoder</strong>: The encoder stays the same. Given input at time step t, the new hidden state is computed as a function of the input and the previous hidden state. The decoder used to have a fixed context vector c, <strong>but now at every timestep i of the decoder, we used a different vector</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/0*PclImV37UoHncNYZ.png" /><figcaption>Decoder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/0*8yaLH0_a7E8Z72XG.png" /><figcaption>Encoder</figcaption></figure><p>2. <strong>Similarity Scores:</strong> How do we know how relevant the various hidden states are to predict the current word in the decoder? We compute an <strong>alignment score</strong> between all the hidden states and the previous decoder state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/0*c5MV4delMQ2Xl2Lk.png" /></figure><p>Here <strong>e</strong> is a similarity score between each of the previous decoder hidden states and the encoder hidden states. F_att can be an MLP or even a dot product which would help in determining a score. The idea is that <em>t</em><strong><em>he higher the score the more that hidden state ( and hence the input ) would contribute to the current translated word</em></strong>.</p><p>3. <strong>Attention weights — Convert to Probabilities: </strong>We simply run all the similarity scores through a softmax to convert all of the scores into a probability distribution. These are our weights alpha as per the figure above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/0*lpGFWpuShxa7qEXQ.png" /></figure><p>4. <strong>Compute context vector: </strong>Once we obtain these probabilities associated with each hidden state of the encoder, we compute the context vector as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*NPvkELODDNEz20M2.png" /></figure><p>5. <strong>Predict the translated world</strong> using the <strong>context vector C_i</strong>, the previously predicted word<strong> Y_(i-1)</strong>, and the previous decoder hidden state <strong>s_(i-1)</strong></p><pre>Example: English to French</pre><pre>Source Sentence: &quot;I am eating pizza&quot;</pre><pre>Translated sentence: &quot;je mange des pizzas&quot;</pre><pre>The intuition would be that while predicting the word &quot;eating&quot; the similarity score of &quot;mange&quot; would be higher.</pre><p>The most astonishing part about this is, that <strong>this is not a supervised process</strong>. We are not explicitly telling the model to attend to a particular part in the sequence. Since the entire function was differentiable, during back-prop the model <strong>automatically converges to the best part of the sequence to attend to</strong>.</p><h4><strong>Disadvantages of using RNNs:</strong></h4><p>Somehow we want to get away from the sequential computations. With RNNs, each hidden state is dependant on the previous ones. With modern GPUs, we would like to process the entire input sequence in one go, with one giant matrix multiplication. Additionally, we must make sure that we can process sequences of longer length as well.</p><h4><strong>Generalization #1 — Single query Vector</strong></h4><ol><li>We have i<strong>nput vectors X</strong> (Shape: Nx, Dq) which can be thought of as the hidden states of the encoders in the previous example.</li><li>We introduce the <strong>query vector q </strong>(Shape: Dq) which can be thought of as analogous to the previous decoder state that we were using to compute the similarity scores. Effectively, this can be seen as our query to search for the most similar input.</li><li>As our similarity function, we use a <strong>scaled dot product </strong>where we multiply the query vector with the input scaled by the square of the dimension of the query vector<strong>. </strong>The score for the ith input in X is given as follows:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/0*kP3kIOtYhBUcLIFo.png" /></figure><pre>Side note: Why do we use the square root?</pre><pre>A higher dot product would cause a higher softmax for that input, and a very low probability for all others. This causes very low gradients during back-propagation. Hence a scaling factor, the square root of the query vector dimension is used to prevent this.</pre><h4><strong>Generalization #2 Multiple Query vectors &amp; the attention Layer</strong></h4><ol><li>Instead of having a single query vector q, we can Nq of them, and compute the same similarity scores with matrix multiplication. So now we have <strong>Q</strong> (Shape: Nq, Dq)</li><li><strong>Input Vectors X</strong> (Shape: Nx, Dq)</li></ol><p><strong>Computations:</strong></p><ol><li><strong>Similarities:</strong> We compute the similarities with one matrix multiplication</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/0*-wD1GZPvR-wgi4Pg.png" /></figure><p>Each element of this matrix is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/0*LHeaSsonjAGTDDpS.png" /></figure><p>which is essentially the dot product between the <strong>ith query vecto</strong>r and the j<strong>th input</strong></p><p>2. <strong>Attention Weights: </strong>Just as we were doing in the previous examples, we run our matrix E through a softmax to get a probability distribution over all of our inputs for each query vector.</p><p><strong>A= Softmax(E, dim=1)</strong></p><p>For 3 query vectors &amp; 3 input vectors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*wcDpB24g_DsRIwKH.png" /><figcaption>Similarity Matrix</figcaption></figure><p>Post normalization each column of this matrix will sum to 1</p><p>3. <strong>Output Vectors: </strong>We define an output vector as the linear combination of the attention weights, analogous to how we were finding the context vector in the previous example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/0*b_Mn_Sl8kQ1g-0o5.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/0*eanVDaxEH3LD_Mzl.png" /></figure><p>Each element of the output is given by the linear combination of the columns of the attention matrix with the input.</p><p>Now we’re at a point where we almost have <strong><em>a self-sufficient layer </em></strong>with Inputs (X1, X2…) and outputs (Y1, Y2...).</p><h4><strong>Generalization #3 Key and Value Matrix</strong></h4><p>In the previous generalization, we were using our input vectors twice, once to calculate our similarities and then again to calculate our output.</p><p>To separate these two tasks, we create <strong>two learnable matrices</strong>:</p><p><strong>Key Matrix &amp; Value Matrix:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/0*hvWxS0M0ET6UuiwY.png" /><figcaption>Key-matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/0*PaaX1kHKNYPb27xI.png" /><figcaption>Value matrix</figcaption></figure><p>The idea is to transform our inputs into two spaces, one when we would want to compute our similarities with our queries. And the other when we retrieve values that are related to our query.</p><p><strong>All Computations involved:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/0*V6NrlRgTWII1RrBP.png" /><figcaption>Key vectors</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*fazC4VFjAfVy73U5.png" /><figcaption>Value Vectors</figcaption></figure><p>Notice how we’ve input twice to calculate both key &amp; value vectors. Now we have to calculate our similarities with our keys and the output with our values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*d7oAPyCq8lpbPa2E.png" /><figcaption>Similarity Matrix between queries and keys</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*HdMpHrzme7nLa0hn.png" /><figcaption>Attention weights</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/0*kGyZXLcx69NGUguF.png" /><figcaption>Outputs as a linear combination of values</figcaption></figure><p>This is it, that’s our “<strong>attention layer</strong>”, we can use this to compare our query with our inputs!</p><h4><strong>Generalization #4 Self-attention</strong></h4><p>We’re slowly getting into one of the building blocks of these transformers. In the previous generalization, we had separate query vectors. But what if you had to figure out in a sequence, what each word is referring to. Or in other words, given a word, we would like to figure out the attention weights throughout the rest of the sequence. For example, if you have a sentence like “I arrived at the bank after crossing the river”. <strong>Does the bank denote a riverbank or an actual bank? </strong>To represent “bank”, we need context from the entire sentence. The self-attention mechanism does exactly this, in parallel, unlike RNNs. This is the main workhorse of the transformer. Instead of recurrence, or convolutions, we use self-attention for input-output dependencies.</p><p>The transformer architecture uses self-attention in 3 distinct ways. Let’s look at the example that was given in the demonstration for the paper. The input sentence is “The animal didn’t cross the street because it was too tired”:</p><ol><li>Input-Input: All the words in the input attend to each other.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4Y3kupnOz5jh79whtI5xFA.png" /></figure><p>2. Input-Output: Like our RNN encoder-decoder architecture with attention, during translation, we want to know the word which words in the input sequence corresponds to the translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*25ZJCBuYKDpfqS7BWyhPxg.png" /></figure><p>3) Output-Output: Instead of the connections, I wanted to show the weights in the corresponding diagram. Do you notice anything different?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*qo0HHSA_83O1Ww2dfnhe8A.png" /></figure><p>In the translated output, it’s as if the network is not looking ahead in the translated sequence. This is logical since during translation you don&#39;t want your network to already attend over words that it hasn’t translated yet. In the example above, we see active weights words that came before “die”. This is a nifty trick used where you push the similarity matrix to a large negative number, so post softmax those probabilities go to 0. It’s referred to as <strong>masked self-attention.</strong></p><p><strong>Computations for self-attention:</strong></p><ol><li>Inputs vector X ( Shape: Nx,Dx)</li><li>Key Matrix: W_k ( Shape: Dx,Dq)</li><li>Value Matrix: W_v ( Shape: Dx,Dv)</li><li>Query Matrix: W_q ( Shape: Dx, Dq): The only new learnable matrix, which converts our inputs to queries</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*la9O2mfNpKaTr6qx.png" /><figcaption>Query Vectors</figcaption></figure><p>That’s the only difference, we find the keys, values, similarities &amp; output in a similar way to generalization #3.</p><p><strong>Self-attention is permutation equivariant:</strong></p><p>This means that any permutations in the input will result in the exact same output but permuted in a similar way. This means if you changed the order of the sentence, the model wouldn’t really know. This is why the authors embed <strong>an extra positional encoding with the input</strong>.</p><h4>Generalization #5 Multi-Headed Self-attention</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*zbV4VMYEofZ26Akzr25mMA.png" /><figcaption>Multi-Headed self-attention as described in the paper</figcaption></figure><p>Instead of having one single self-attention block, we repeat this computation 8 times. Different sets of Key, Value &amp; Query matrices are used to transform our input. We also lower the dimensions of each of these heads to keep it computationally similar to that of a single attention head. For instance, if we had used 512 as our model dimensions earlier, and if we had to split into 8 heads. We would use 64 as the dimension for each of our Key, Value &amp; Query Matrix. Finally, when we concatenate all these 8 heads we would get an output dimensionality of (*Nx,64x8). But our input is that of (*Nx,512), which should be the same size as our output. Therefore would need another matrix <strong>W_o </strong>of shape (64x8, 512) to transform the output from our attention heads to (*Nx,512).</p><pre><strong>Example:</strong></pre><pre>We have a sentence which needs to be translated:</pre><pre>&quot;The boy plays on the field&quot; </pre><pre>We assume an embedding dimension of 512 for each word.</pre><pre>Therefore our input X is of size (5,512)</pre><pre>Now, let&#39;s assume 8 attention heads and an query dim of 64.</pre><pre>Therefore each of our matrices (key,query&amp;value) would be of size (512,64).</pre><pre>Post applying the self-attention mechnaism each of these 8 heads would give us an output of (5,64).</pre><pre>Now if we concatenate 8 of these matrices we would get one giant matrix of size (5,64*8) which would finally be transformed by the W_0 matrix to the same size as our input vector (5,512)</pre><h4><strong>Other layers</strong></h4><p>Post this self-attention layer, there is layer normalization followed by a fully connected network. Additionally, there are residual connections between inputs and outputs between all of these layers. The same block of attention-normalization-feed-forward networks is repeated. They are used for both the encoder and the decoder. I intend to dig deeper into them in another article with a practical coded example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c28484788d5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/understanding-the-building-blocks-of-transformers-c28484788d5a">Understanding the building blocks of transformers</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[Kernels]]></title>
            <link>https://medium.com/analytics-vidhya/kernels-e8fc0a51fc0a?source=rss-4823b06886ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8fc0a51fc0a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kernel-trick]]></category>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Arnab]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 10:40:20 GMT</pubDate>
            <atom:updated>2021-07-26T06:21:14.278Z</atom:updated>
            <content:encoded><![CDATA[<p>What might seem like an outdated idea, is an important step into understanding machine learning and the math that governs it.</p><h3><strong>Feature Maps:</strong></h3><p>Let y denote two classes (denoted by red and blue blobs) and our data have two attributes X¹ &amp; X².</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*7baL6PMVhho6CSKvR63Z5w.jpeg" /><figcaption>Linearly separable</figcaption></figure><p>Now, we may have a case where our data is linearly separable and we can clearly draw a line separating both classes.</p><p>But, we might also encounter situations where that is just not possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*riql5YuPiOfKfLctbZL8VQ.jpeg" /><figcaption>Not possible to separate linearly</figcaption></figure><p>In this case there is no line that can be drawn that can separate these two classes.</p><p>In such a case we map our input to a new ‘feature space’ so that we can use a higher dimensional hyperplane to separate our classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*CLFF1hF8Ahk7ho3C.png" /></figure><p>We define a function that takes our input points from R² -&gt; R</p><p>After applying this transformation our data looks something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c0dc2eefcdeb0eb859eec2c23448a30/href">https://medium.com/media/0c0dc2eefcdeb0eb859eec2c23448a30/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Jna93evW3UIb6K-7LCrVfQ.jpeg" /></figure><p>Now, <strong>we can draw a plane separating the data</strong>. Intiutively, we can see how this works. The only difference is in the 3rd dimension. The outer circle has a larger values of X¹ and X² leading to a lower value across the z-axis.</p><h3><strong>Kernels:</strong></h3><p>Usually, wherever we require a product of two input variables, and we have transformed the input space into a feature map, we need to compute <strong>the dot product of the feature map</strong>. These are usually pretty <strong>computationally expensive</strong> to compute or to store, this is where the “kernel trick” comes in.</p><p>For instance in SVM,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*meWHjsV86GWKCJGPDTie1w.png" /><figcaption>Optimization problem for SVM [<a href="http://web.mit.edu/6.034/wwwbob/svm-notes-long-08.pdf">Reference</a>]</figcaption></figure><p>Once we have transformed Xi and Xj into Phi(Xi) &amp; Phi(Xj), we need the efficient way of computing the dot product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*maggmTwXb8-OK_so.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*QL7Bt76x55vVUHzY31v8AA.png" /><figcaption>Optimization problem for SVM [<a href="http://web.mit.edu/6.034/wwwbob/svm-notes-long-08.pdf">Reference</a>]</figcaption></figure><p>Let’s take an example of a very common kernel:</p><h3><strong>Polynomial Kernel:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*5bJ27ejE_BG8_rRs.png" /><figcaption>2nd order polynomial kernel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/0*lvLGzusk1n1-nrVt.png" /></figure><p>So all this kernel is doing is taking a dot product between between two vectors of dimension d &amp; squaring it. This would take <strong>O(d) time</strong>.</p><p>More concretely, let’s take an example where <strong>d=2.</strong></p><p>What would be K(X,Z) ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGNhzhjc4B-gNEcN.png" /></figure><p>Expanding,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d2n6NMow7C-csjQk.png" /></figure><p>Now if we have a feature map like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*bav2511591sanO-q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*NYv972ocm28KHxOW.png" /></figure><p>From this we can clearly see that the dot product of the above two is the same as the output of the kernel function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*jda1KbMvuydumQY9.png" /><figcaption>Dot product of our feature maps equals our kernel</figcaption></figure><p>If we were to calculate Phi(X) &amp; Phi(Z) without the kernel we would have to spend O(d²) for the transformation &amp; the subsequent dot product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*ezCVixCbep_-ItXVT522vw.png" /><figcaption>Transforming our original circles data with our polynomial kernel (an approximation in 3D)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03e60be6eb8d6248f95b0fe19e1df7b8/href">https://medium.com/media/03e60be6eb8d6248f95b0fe19e1df7b8/href</a></iframe><p>Without the “kernel trick” the output time for a 1000 dimensional matrix with 10 training examples comes out to be ~5.5s</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6826a250c613bba524b6d4a227f02f4a/href">https://medium.com/media/6826a250c613bba524b6d4a227f02f4a/href</a></iframe><p>With the kernel trick time time comes around to be ~0.05s for the same size of matrix.</p><p><strong><em>Main takeaway: Whenever we have a dot product of individual input attribute vectors we can use kernels to make our computation more efficient.</em></strong></p><h3><strong>Gram Matrix:</strong></h3><p>Practically, if we have N training samples we form a <strong>Gram matrix (Matrix with the computed kernel value for a pair of samples)</strong> as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*z04fwbn9V5Y93_SQ.png" /><figcaption>N training samples</figcaption></figure><p>The ith row and the jth column of the matrix would be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/0*qQEGPLo7tuLS35VA.png" /></figure><p><strong>Conditions for valid Kernels:</strong></p><p>For a kernel to be valid, the constructed matrix must be symmetric ( this should be fairly obvious, since K[j,i] = K[i,j] because the dot product would remain the same ). Additionally, they must be positive semi-definite (eigen values are non negative). We can show this using the “energy-test” where for any vector x,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*ocC7jthLyHwB6xr0.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8fc0a51fc0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/kernels-e8fc0a51fc0a">Kernels</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[Character awareness for language models using CNNs]]></title>
            <link>https://medium.com/analytics-vidhya/character-awareness-for-language-models-using-cnns-6b1c1a331042?source=rss-4823b06886ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b1c1a331042</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Arnab]]></dc:creator>
            <pubDate>Thu, 17 Jun 2021 21:23:18 GMT</pubDate>
            <atom:updated>2021-06-23T16:36:05.420Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will go through a use-case of using CNNs for NLP with practical details of implementation on PyTorch &amp; Python. It is based on the paper “<a href="https://arxiv.org/pdf/1508.06615.pdf">Character-Aware Neural Language Models”</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r-YscSrImdpqYdmF" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Background:</strong></h3><p><strong>Language models:</strong> The language model assigns a probability to a sentence or a phrase. Given some words, we can predict the next word which would assign the highest probability to the phrase. We often see these being used for text completion for messaging services</p><p>The children play in the ________</p><p>A good language would be able to predict the next word as ‘park’ or something else which makes sense.</p><p>More formally,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*Sob6Q1NCFVa5JotZB2cjeQ.png" /></figure><p>We can model the probability of a given sequence of ‘m’ words, by taking in each word and computing the probability conditioned on the words that have appeared before.</p><p>In the pre-Transformer era, most of the papers used <strong>RNNs</strong> for such a task, and such is the case for the model used in the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*kKILs8Fnw0X8rKXWIjcNzg.png" /><figcaption>Typical RNN architecture for the language modeling task</figcaption></figure><p>Given a word, an embedding for the word is looked up in a pre-defined vocabulary and linearly transformed using weight matrix <strong>W_e</strong>. The recurrent part comes from the hidden states <strong>‘h’, </strong>where again we use the same weight matrix <strong>W_h </strong>at every timestep<strong>.</strong> Then it is squashed through a nonlinearity, usually a <strong>tanh</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*IDe024Cqr0RKccIZ.png" /></figure><p>Finally, when it comes to predicting the next word we use a softmax to output a distribution over the vocabulary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*sua1-a56k3PYk4Px.png" /></figure><p>The shapes of each of the matrices are as follows:</p><ol><li><strong>h_t</strong>: (D_h, ) → Shape of the hidden state</li><li><strong>W_h</strong>: (D_h x D_h) → Shape of the weight matrix for hidden states</li><li><strong>x_t</strong>: ( E, ) → Shape of the embedding of each word</li><li><strong>W_e:</strong> ( D_h x E ) → Shape of the weight matrix for embeddings</li></ol><p>To recap, during training we take in each input word by word and look up their word-level representation, feed them through an RNN to generate a prediction. We then, train our network against the true probability distribution of the label in our vocabulary.</p><p>Although these word-level embeddings work great in practice; when we encounter unknown words or rare words our predictions might be not as accurate.</p><p>Usually, for any unknown word which is not present in our vocabulary, we use an ‘unk’ token which in itself has some embedding representation.</p><p>In the above-mentioned paper, a character-level representation of each word is used which we obtain through 1d convolutions over character-level embeddings.</p><p><strong>Character Representation of words:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*8bWo9HLeQzxI_rRV2D8Mdg.png" /></figure><p>We represent each character as a 1D vector and concatenate them to represent each word. I also want to add some practical implementation details. So let’s through it step by step. Initially, we want a representation of each character as indices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7e503ad54f509d88ee0a7142ba56a1e/href">https://medium.com/media/b7e503ad54f509d88ee0a7142ba56a1e/href</a></iframe><p>We use the open &amp; close brackets ( { , } ) to denote the start and end of a word in a sentence. We also have to define a function that takes in a list of sentences and outputs the character indices ( the ones we mapped earlier )</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*zcQGaHCOGXzC1VKV2vlfnQ.png" /></figure><p>Each word is converted into indexes using the dictionary we defined earlier. Additionally they start with 1 ( { ) and end with 2 ( } ). But the lengths of the sentences &amp; words would be different. <strong>Thus, we must pad each word to get an equal length</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b865aca9e402605b61cebec3b5b392ff/href">https://medium.com/media/b865aca9e402605b61cebec3b5b392ff/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*EizaedP4uOKpthr30Ncqgg.png" /></figure><p>For each of these indices, we look up a specific character embedding and concatenate them together, to get them ready to pass them through the convolutional layer.</p><p>So if the size of the largest word is <strong>‘m’</strong> &amp; the character embedding dimension is <strong>‘d’</strong>, the size of the matrix passed on o the CNN layer would be<strong> (m x d)</strong>. We can call this X_emb.</p><p><strong>Conv layer:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*EnI94A3D662hQ4oFW-qQKw.png" /></figure><p>Now that we’ve got our concatenated character embedding, we pass it through 1D convolutions &amp; max pooling to obtain an embedding for a word of a <strong>fixed dimension</strong>.</p><p>In the original paper, the authors used multiple filters with<strong> separate filter widths</strong> where each filter would capture a different representation. According to the authors, “ <em>A filter is essentially picking out a character n-gram, where the size of the n-gram corresponds to the filter width</em>”. For instance, if we have the word “Anarchy”, a filter width of size three might focus on “ana”, “nar” or “arc” to see if they make sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*HJIb6Y7JjjaEeIAAvhFatQ.png" /></figure><p>From the (<strong>m x d) X_emb </strong>matrix, we have to follow the following steps:</p><ol><li>Reshape to (<strong>d x m)</strong>: This is just because PyTorch performs the convolutions across the last dimension of the matrix. So we want to move convolved along the columns ( ie each character ).</li><li>We choose the number of “filters”, this would ultimately be the size of the word’s embedding dimension that we want. So we can call this number “<strong>E”,</strong> as mentioned above in the RNN example. Another hyperparameter is the width <strong>“k”</strong>.</li><li>With the reshaped matrix of X_emb, we compute the element-wise product &amp; sum with each of our filters with the -width “k”.</li><li>For each word, we compute <strong>(m−k+1) long vector for each filter. A</strong>s we have E filters, we end up with our final matrix with the shape <strong>E x (m-k+1).</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*N9_WMArt1jJ3XY8E.png" /></figure><p>The equation above just denotes how we compute the i-th element of our m-k+1 long vector. We take the Frobenius inner product ( which is just like the dot product for matrices, element-wise multiplication + sum ) of the window of size k with our filter H of size <strong>( d x k ).</strong></p><p>5. Post this we add a non-linearity like tanh or a Relu. In the paper they used tanh.</p><p>6. Finally, we use max-pooling over the 2nd dimension, to arrive at a single vector of size E.</p><p>To recap, for each word we go from a matrix of <strong>(m x d) → E x (m-k+1) → E</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abc1510c58f9aeb89a9d9907d06d77dc/href">https://medium.com/media/abc1510c58f9aeb89a9d9907d06d77dc/href</a></iframe><p>So, finally for each word we have a word embedding derived from characters. Now in the paper, they passed this on to a “Highway Network”. The paper for this technique can be found <a href="https://arxiv.org/abs/1505.00387">here</a>.</p><p><strong>Highway Network:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*2FPsFeEpkt04foOBWaixsg.png" /></figure><p>Instead of passing the word_embedding derived from the conv layer directly to the RNN, we use a “gate” to regulate how much of the input is fed into the RNN. This seems to have helped with improved gradient flow, and optimization in general.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*0Ie-EYEivMY5JRw8xblA3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*s61p0WEGniYNknZaZRRfFA.png" /></figure><p>The gate which is controlled by a sigmoid has the connotation of “how much” information needs to be passed. The projection is calculated with a non-linearity &amp; multiplied with the gate. The rest is directly passed on with a factor of (1-x_gate).</p><p>The weights W_proj &amp; W_gate are of shape <strong>( E x E ) ie word_embedding x word embedding.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/277d821da605c754cb78ef08ade65277/href">https://medium.com/media/277d821da605c754cb78ef08ade65277/href</a></iframe><p><strong>Final Layer and predictions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*Tm_f3SM0Jl7t_KmIeSKfhg.png" /></figure><p>The output from the highway layer is passed on the RNN (LSTM in this case). And it is trained with the true label of the next word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*DqjzrAudK9b5eqxfQ23I9A.png" /></figure><p>According to the paper, this model was able to achieve better accuracy than a word-level model with few parameters. Here PPL refers to ‘perplexity’, a metric to evaluate language models. ( The lower the better )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b1c1a331042" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/character-awareness-for-language-models-using-cnns-6b1c1a331042">Character awareness for language models using CNNs</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[Word Embeddings]]></title>
            <link>https://medium.com/analytics-vidhya/word-embeddings-aaef8c6bd04a?source=rss-4823b06886ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaef8c6bd04a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Arnab]]></dc:creator>
            <pubDate>Fri, 28 May 2021 19:03:07 GMT</pubDate>
            <atom:updated>2021-05-31T17:51:29.946Z</atom:updated>
            <content:encoded><![CDATA[<p>This article aims to provide intuition for word embeddings using information from some of the most famous papers in the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Idm5uM-ru6voa1v" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Why do we need word vectors?</strong></h3><p>The other choice that we have is to represent each word in a document as a one-hot encoded vector. Let’s try to think about some problems with this.</p><ol><li><strong>Vocabulary Size</strong>: Each word would be represented by a shape as long as your vocabulary. This could be in the order of the millions.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/270a0c63092396eb212b3d7b85a26764/href">https://medium.com/media/270a0c63092396eb212b3d7b85a26764/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*LnpoIVO9i1Z9zYqe7eE71g.png" /><figcaption>Example output for one_hot_encode(“ The town was near the city “ )</figcaption></figure><p>2.<strong> Semantics</strong>: Now apart from an issue with scale, we lose the ‘similarity between words that should be close together. In other words with this representation, all words are orthogonal to each other. In a high dimensional space, they are all pointing in different directions.</p><p>Ideally, in the example given above ‘town’ and ‘city’ should have somewhat similar vector representations. But in this case, their cosine similarity is 0 (they are at an angle of 90 degrees from each other).</p><p>Thus, ideally what we would like is to represent each word by a vector of a size far lower than the size of the vocabulary. Additionally, we would also like these vectors to provide some ‘meaning’ by themselves to the word. Interestingly, in practice, adding or subtracting two or more of these words produces intriguing results. For instance, vector(Germany) + vector(Captial) might lead to vector(Berlin).</p><h3><strong>How do we build these word vectors?</strong></h3><p>Although there are several methods out there, one of the key concepts to understand amongst all of them is <strong><em>context</em></strong> &amp; <strong><em>center words</em></strong>.</p><p>The intuition ( known as<strong> distributional semantics </strong>) is that words that are close to a particular word in a document convey meaning for that word. For example, if we have a sentence like <strong>‘ The teacher scolds the student fairly often’</strong>. For a <strong>center word student </strong>and a window size of 5 ( taking both sides of the word), we would have the words <strong>‘teacher’, ‘scolds’, ‘the’, ‘fairly’, ‘often’</strong> in its <strong>context. </strong>Now, if we have a big enough corpus, the idea is that we would come up with representations for the word by looking at all the words in the context of each word.</p><p>Now there are two ways to go about this, we can either just <strong>count how often a word occurs in the context </strong>and figure out a representation for each word, or we can train a neural network to figure out which vectors are best suited by <strong>predicting the context vectors given our center word</strong>. In this article, I will cover the latter.</p><h3><strong>Word2vec:</strong></h3><p>Originally, the idea was proposed by Tomas Mikolov in 2013 in this <a href="https://arxiv.org/pdf/1301.3781.pdf">paper</a> titled ‘<a href="https://medium.com/r?url=https%3A%2F%2Farxiv.org%2Fpdf%2F1301.3781.pdf">Efficient Estimation of Word Representations in Vector Space</a>’ which was further improved by him in ‘<a href="https://papers.nips.cc/paper/2013/file/9aa42b31882ec039965f3c4923ce901b-Paper.pdf">Distributed Representations of Words and Phrases and their Compositionality</a>’. Two methods were introduced in the first paper.</p><ol><li>Continuos bag of words: The center word is predicted given the context words.</li><li>Skip-Gram: The context words are predicted given a center word.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*9WQ7elCLY4D9dnf_njTw8g.png" /><figcaption>The models as described in the paper.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*33qMCZ68OcQK0pPcxpAEyA.png" /><figcaption><strong>Skip-gram</strong> Illustration</figcaption></figure><p>As denoted by the illustration, with the skip-gram model, we need to find P ( context | center ). But our original goal was to find out word-vectors right? Here comes our build-up to the objective function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*V3zEw-VcUaAKXP7h34y-uw.png" /><figcaption>Likelihood function</figcaption></figure><p>The parameter theta in this case refers to our word vectors. We must <strong>maximize the likelihood of our model predicting the context words given the center word.</strong> The inner product is for a particular center word and the likelihood function is overall words as center words ( T total words ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*zCycvQR-IqRqbu1RyRCKRw.png" /><figcaption>’</figcaption></figure><p>For both the skip-gram &amp; the CBOW models we require two vectors to represent each of the words. One for when the word is in the context and the other when it is in the center. We call these vectors <strong>U &amp; V</strong>. To represent it as a distribution we take<strong> the dot product of both of these vectors</strong>, use exponential to make the dot product positive, and normalize it with all the vectors in the vocabulary. <strong>Our goal should be to find the vectors U &amp; V which maximizes the probability of the correct words being in the context given a center word. </strong>Defining the probability, <strong>Vcenter</strong> is given by multiplying our <strong>V matrix ( N x V)</strong> where N is the embedding dimension and ‘V’ is the size of the vocab, with the one-hot encoded input vector. That itself is multiplied by ALL of the context vectors in the <strong>U Matrix of size (V X N)</strong>. Ultimately we get ‘scores’ for each of the words in the vocabulary, and these scores are in turn passed into the softmax function. In a way, this is like multi-class classification, where we predict which ‘word’ is in the context given the center word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*V-bTcOxScCRQkECyEQ1fTA.png" /><figcaption>Final objective</figcaption></figure><p>To make it easier for us to take derivates we stick a log in front of the probabilities. Additionally, we add a minus sign so that we have to ‘minimize’ the function instead of taking the max. We also add the (1/T) to make things invariant of scale, and not depend on the size of the corpus.</p><p>To train this model, we need to update the vectors using gradient descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*Xxf7qhZddjG9NfGkYkrCZw.png" /><figcaption>Weight updates using gradient descent</figcaption></figure><p>Let’s take a concrete example and go through each step that we have to take to go through the forward pass of the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c7d4563f1ba4f5c01b056028620d044/href">https://medium.com/media/0c7d4563f1ba4f5c01b056028620d044/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80ad625f4241220aed6df04fcd5629bb/href">https://medium.com/media/80ad625f4241220aed6df04fcd5629bb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f9902ca5b1ce249623cabdb4990651b/href">https://medium.com/media/2f9902ca5b1ce249623cabdb4990651b/href</a></iframe><p>Initially, the text is one hot-encoded &amp; one of the words is passed to the network. In this case, <strong>‘Ease’</strong> is passed as a center word ( sorted by vocabulary, 2nd word ) and from the sentence, we can see that the context words for ease ( with a window of <strong>size 2</strong> ) are<strong> ‘with’ &amp; ‘town’</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*0o2-XbZCZmdd2_zy_5oCDw.png" /></figure><p>We randomly initialize the context and the center word matrix V &amp; U.</p><p>Again, <strong>each column of V</strong> contains the embedding for each word when it is in <strong>the center</strong>, and <strong>each row</strong> contains the embedding for each word when it is in <strong>the context</strong>. For example, this is the initialization for matrix U.</p><pre>#### U matrix as a dict with vocab as the key</pre><pre>{&#39;dangerous&#39;: array([ 1.2398147 , -0.87909626,  0.38028566]),  &#39;ease&#39;:       array([0.08540021, 0.18544306, 0.07096524]), <br>&#39;man&#39;:        array([ 0.14981179, -1.40251029,  1.02452393]),  <br>&#39;passed&#39;:     array([0.10055589, 1.09979612, 1.63213385]),  <br>&#39;the&#39;:        array([-0.22917658,  1.32505777, -0.74246023]), <br>&#39;through&#39;:    array([0.21855831, 1.05448857, 0.71948246]),  <br>&#39;town&#39;:       array([-0.17041045, -1.60960955, -0.56273196]),  <br>&#39;with&#39;:       array([-1.52561797,  0.00701094, -0.46619808])}</pre><p>After we pass one word to the network for the forward pass we receive softmax probabilities predicting each context word.</p><pre>##Predicted probability distribution</pre><pre>{&#39;dangerous&#39;: 0.0006688799877958782,  <br>&#39;ease&#39;:       0.024971817920074583,  <br>&#39;man&#39;:        0.004299169023935694,  <br>&#39;passed&#39;:     <strong>0.9438920599330834</strong>, <br> &#39;the&#39;:       0.004081941089464888,  <br>&#39;through&#39;:    0.0027767995527184113,  <br>&#39;town&#39;:       0.009752776322407003,  <br>&#39;with&#39;:       0.009556556170520179}</pre><p>With our gibberish normal initialization, the network predicts<strong> ‘passed</strong>’ as the word with the highest probability in context with center ‘ease’ with a probability of 0.94. But the true distribution, for the center word ease, has probability 1 for with and town and 0 everywhere else.</p><pre>###True Distribution</pre><pre>{&#39;dangerous&#39;: 0,<br> &#39;ease&#39;: 0,<br> &#39;man&#39;: 0,<br> &#39;passed&#39;: 0,<br> &#39;the&#39;: 0,<br> &#39;through&#39;: 0,<br> <strong>&#39;town&#39;: 1,<br> &#39;with&#39;: 1</strong>}</pre><p>So we compare and train our word vectors U &amp; V until our output finally looks something like the true distribution. I will ignore details of the backward pass since I believe with automatic differentiation available in the frameworks we have currently, it really isn’t that significant. But if you’re interested you can check out how it works <a href="https://aegis4048.github.io/demystifying_neural_network_in_skip_gram_language_modeling">here</a>.</p><p>There’s another problem with this method for word2vec, each time we have to go through the entire vocab, which as discussed before isn’t computationally great. If you think about the complexity it’s in the order of O( V + V ) where V is the size of your vocabulary.</p><p>We solve that problem with something known as<em> </em><strong><em>negative sampling </em></strong>which was introduced in the 2nd <a href="https://papers.nips.cc/paper/2013/file/9aa42b31882ec039965f3c4923ce901b-Paper.pdf">paper mentioned above</a><strong><em>. </em></strong>Instead of using the softmax function, we use a sigmoid function and turn it into a binominal classification problem (2 classes, positive &amp; negative ).</p><p>We sample from words that aren’t in the context and use them as the negative classes. In our running example for the center word ‘ease’, we sample some other words like ‘the’ and use it as the negative classes. We sample K of these classes. So instead of updating over the entire vocabulary, we get a complexity of ~ O (K).</p><h3><strong>Results</strong></h3><p>If you want to train them on your own corpus, it’s fairly straightforward on deep learning frameworks. The original word2vec paper had its model trained on news data from google. Later, down the years&#39; people have trained their models on Wikipedia datasets and shown better results. This is probably because a single document in Wikipedia has more words related to a certain topic, whereas in the news we might have more of a variety of words. Nevertheless, I will use the original word vectors in this section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2f16cb6548eae76442f75935b3866f0/href">https://medium.com/media/d2f16cb6548eae76442f75935b3866f0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d56d23708736ed1d4979cffaac8a778/href">https://medium.com/media/9d56d23708736ed1d4979cffaac8a778/href</a></iframe><p>We look at trained word vectors for labels like king, queen, cat, dog &amp; animal. Then we take the 2nd rank approximate for the vectors using SVD. (You can learn more about SVD from my previous article <a href="https://medium.com/analytics-vidhya/why-you-should-consider-studying-linear-algebra-as-a-data-scientist-part-1-svd-9d0ba3189a3e">here</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*FrRH9Tg0GaXH_wFU9Q-CtA.png" /></figure><p>We can see even with the 2nd rank approximate words like Animal, dog, and cat are clustered together, whereas king’ and ‘queen is closer together. Even though projection of the vectors (Originally in 300 dimensions) into 2 dimensions makes us lose a lot of information, we can visualize somewhat of how some vectors are similar.</p><p>We can use the full vectors to work out some word analogies and similarities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e1951642dac4856559ec854f229bbdf/href">https://medium.com/media/7e1951642dac4856559ec854f229bbdf/href</a></iframe><p>Some of the similarities worked out were as follows:</p><pre>#Analogy<br>similarity(w[&#39;king&#39;]-w[&#39;man&#39;]+ w[&#39;woman&#39;],w[&#39;queen&#39;]) ---&gt; 0.73 </pre><pre>#Dissimilar words<br>similarity(w[&#39;king&#39;], w[&#39;car&#39;])  ---&gt; 0.03</pre><pre>#Similar words<br>similarity(w[&#39;man&#39;], w[&#39;woman&#39;]) ---&gt; 0.76</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaef8c6bd04a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/word-embeddings-aaef8c6bd04a">Word Embeddings</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[Why you should consider studying Linear Algebra as a data scientist : SVD]]></title>
            <link>https://medium.com/analytics-vidhya/why-you-should-consider-studying-linear-algebra-as-a-data-scientist-part-1-svd-9d0ba3189a3e?source=rss-4823b06886ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d0ba3189a3e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Arnab]]></dc:creator>
            <pubDate>Wed, 12 May 2021 22:45:07 GMT</pubDate>
            <atom:updated>2021-08-26T13:43:21.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dARg_WJjjlOBenKT" /><figcaption>Photo by <a href="https://unsplash.com/@comparefibre?utm_source=medium&amp;utm_medium=referral">Compare Fibre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This article is to give a flavor for the reader to explore the topic more in-depth, on their own using the resources mentioned at the end.</em></p><p>Whether you’re doing least-squares approximation or reading a new paper in deep learning a fundamental understanding of linear algebra is critical to internalize key concepts.</p><h3><strong>The gist of Linear Algebra</strong></h3><p>Firstly, a few definitions that we should all know</p><p><strong>Column space: </strong>You could imagine each column of the matrix as a vector in space. Now, the space spanned by taking linear combinations of all the independent vectors in the matrix makes up the column space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*_2A17jGpQLUrAAnr3L_sjA.png" /><figcaption>Red vectors are the linear combinations of the black vectors</figcaption></figure><pre>import matplotlib.pyplot as plt<br>from mpl_toolkits.mplot3d import Axes3D</pre><pre>fig = plt.figure(figsize=(10,10))<br>ax = fig.gca(projection=&#39;3d&#39;)<br>ax.set_xlim3d(-1, 1)<br>ax.set_xlabel(&#39;x-axis&#39;)<br>ax.set_ylabel(&#39;y-axis&#39;)<br>ax.set_zlabel(&#39;z-axis&#39;)<br>ax.set_ylim3d(-1, 1)<br>ax.set_zlim3d(-1, 1)<br>A=np.array([[1,0],[0,1],[0,0]]) # Initial Column vectors<br>C=np.copy(A)<br>ax.quiver(0, 0, 0,*C[:,0],normalize=True,color=&#39;k&#39;)<br>ax.quiver(0, 0, 0,*C[:,1],normalize=True,color=&#39;k&#39;)<br>for i in range(50): # Taking 50 random linear combinations  </pre><pre> x1=np.random.uniform(-100,100,1)<br> x2=np.random.uniform(-100,100,1)<br> ax.quiver(0, 0, 0,*(C[:,0]*x1 + [:,1]*x2),normalize=True,color=&#39;r&#39;)</pre><pre>plt.show()</pre><p>Each Column of the matrix shown in the example ( [1,0,0] &amp; [0,1,0] ) is represented by the black vectors. The red vectors are linear combinations of both of these columns. Doesn’t it look like all the red vectors lie on the same plane? Because they do! All such vectors constitute the column space of the matrix. In this case, the column space is a plane (since there are two independent columns). But, if the number of independent columns is higher, the space can exist in higher dimensions.</p><p><strong>Rank:</strong> The number of independent columns (or rows) in a matrix. The column entries in your matrix cannot be linear combinations of each other. Essentially, you should not be able to use other columns to form that particular column in the matrix.</p><figure><img alt="A tiny example of a 3x3 matrix where the rank is 2, since one of the columns is dependant of the other two." src="https://cdn-images-1.medium.com/max/1024/1*X1Uzu1tjwbApkSEN9IeISA.jpeg" /><figcaption>A tiny 3x3 matrix where the rank is 2 since the 3rd column is dependant on the other two.</figcaption></figure><pre><strong>from</strong> <strong>numpy.linalg</strong> <strong>import</strong> matrix_rank<br>matrix_rank(np.eye(3)) </pre><pre>An identinty matrix with rank 3, since all the columns are independent of each other.</pre><p>At a very high level, we can view the rank of a matrix as the ‘information content’. For instance, if have an image of 1000x1000 pixel values, why would I want to store all of them, if I can have sufficient information with half the amount of values.</p><p>To get such a low-rank approximate, we can use several methods such as SVD, or NMF. The following pictures show us how a low-rank approximation may not be that bad all the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*_F4yLnsOzAJWw4CElkWtcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*VlkgE7liW2NPDqp5WS2uQA.png" /></figure><p>Not much of a difference, is it?</p><p><strong>Linear Transformations</strong></p><p>Any matrix can be thought of as a linear transformation <em>(with respect to a fixed basis</em> ). Whenever we multiply a vector with a matrix, we can think of a scaling, shearing, or rotating effect applied to the vector.</p><p>Let’s look at a simple example:</p><p>We form a 2 x (N*N) matrix and represent it using a scatterplot. Then we apply a transformation to the matrix and see the results.</p><pre>def build_array(startx,endx,starty,endy,N):</pre><pre>&#39;&#39;&#39; Build an array of 2 x (N*N) &#39;&#39;&#39;</pre><pre>xvals = np.array(np.linspace(startx, endx, N))<br>yvals = np.array(np.linspace(starty, endy, N))<br>arr=np.vstack(np.meshgrid(xvals,yvals)).reshape(2,N*N)</pre><pre>return arr</pre><pre>def visualize_array(arr):</pre><pre>&#39;&#39;&#39; scatterplot to visualize array &#39;&#39;&#39;</pre><pre>plt.figure(figsize=(7, 7))<br>plt.xlim([0,30 ])<br>plt.ylim([0,20])<br>plt.scatter(arr[0],arr[1])</pre><pre>arr_1=build_array(0,10,0,10,11) # array<br>visualize_array(arr_1)<br>transformation=np.array([[1,1],[0,1]]) # transformation<br>final_array=np.dot(transformation,arr_1)# Applied the trasnformation<br>visualize_array(final_array)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*gqSi57Vke-0T5GE03FvPTg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*qBiNauG0RpYR60F13w-N0Q.jpeg" /><figcaption>Original space on the right, transformed on the left</figcaption></figure><p>We can see that the x-axis has remained at it’s place, owing to <strong><em>[1,0]</em></strong> in the first column of the matrix ( similar to identity ), we can see a shear has occurred due to <strong><em>[1,1]</em></strong> in the second column. I urge you to try the code by yourself, apply various transformations, and see the matrix&#39;s resultant shape.</p><p><strong>Eigenvalues and EigenVectors:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kL-uYaGsSiaNY1OOWlElw.png" /></figure><p>This is the equation that we were taught in high school. But what was not clear (at least to me at that time), was the visual intuition behind them. Continuing our line of thought of a matrix as a linear transformation, eigenvectors are the vectors that are <em>not affected </em>when we apply a transformation A to them, and the eigenvalue is simply a scaling factor (The direction remains unchanged). Let’s quickly take a look at an example.</p><pre>def transform(A,B):</pre><pre>&#39;&#39;&#39; plot the transformation of a 2x1 vector, given a 2x2 matrix &#39;&#39;&#39;</pre><pre>fig = plt.figure(figsize=(7,7))<br>param=np.amax(A)*np.amax(B)<br>plt.xlim([-1,param])<br>plt.ylim([-1,param])<br>plt.quiver(0, 0, B[0],B[1],color=&#39;k&#39;,scale=1,units=&#39;xy&#39;,label=&#39;original_vector&#39;)<br>C= A[:,0]*B[0]  + A[:,1]*B[1]  # Expressing as a linear combination <br>plt.quiver(0, 0, C[0],C[1],color=&#39;B&#39;,scale=1,units=&#39;xy&#39;,label=&#39;post<br>transformation_vector&#39;)<br>plt.legend()</pre><pre>A=np.array([[2,4],[0,2]]) #Transformation<br>B=[[1],[0]] #Eigenvector<br>transform(A,B)</pre><pre>B=[[2],[1]] # Other vector<br>transform(A,B)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*Ocrl_Uv6qvSsnYwsUiPGsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*0zAYOZ-8NepapozTFbtahA.png" /><figcaption>Eigenvectors not being effected by the transformation A</figcaption></figure><p>We can see that the eigenvector was only ‘stretched’ by the transformation. The scaling factor is nothing but the eigenvalue.</p><p>An interesting property arises to these eigenvectors when we have <strong><em>symmetric matrices (Transpose(A) = A)</em></strong>. The eigenvectors in these cases appear to be <strong>orthogonal</strong><em> </em>or in other words perpendicular. We use the same function above to illustrate an example.</p><pre>A=np.array([[2,1],[1,2]]) # Symmetric Matrix<br>B=[[1],[1]] #Eigenvector<br>transform(A,B)<br>A=np.array([[2,1],[1,2]]) # Symmetric Matrix<br>B=[[-1],[1]] #Eigenvector<br>transform(A,B)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*VJcbgzv5qs6bITu9Oin-dQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*cW9LF3_1wXqm2BgW4RMO3A.png" /><figcaption>The eigenvectors are orthogonal ( at 90 degrees with each other )</figcaption></figure><p>Now, why would we care about the eigenvectors being orthogonal, Imagine if you could break up a matrix into factors of its eigenvectors and eigenvalues, and the matrix is symmetric you would end up with columns which are orthogonal to each other. This would indicate that each column of that particular matrix is completely different from one another<strong>. <em>This is how you would go about ‘categorizing’ your entries from an original matrix in the context of unsupervised learning.</em></strong></p><p>But there’s a problem, all matrices are not symmetric, and they are definitely not square (Eigenvectors don’t exist for non-square matrice). Can you imagine a dataset with the same number of rows and columns? In the real world, this would hardly ever happen. So what do we do?</p><p>We make it symmetric forcefully, multiplying the transpose of a matrix with itself results in the kind of symmetry that we want. Here’s where the entire idea of singular values and SVD kick in.</p><h3><strong>SVD:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*datP69fmstsHSvwVof5g5g.png" /><figcaption>Eigendecomposition</figcaption></figure><p>For symmetric matrices, the ‘eigendecomposition’ would be as above, but for others, we use this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9VKfgPHcd0mp5Wy-A5RQ-w.png" /><figcaption>SVD for a general n x d matrix</figcaption></figure><p>The vector U &amp; Transpose(V) have orthogonal columns. In the middle, we have our ‘singular values’ ( the substitute for eigenvalues ), but the important factor is that they are ordered (by convention). Taking the first ’n’ singular values we would get the best nth rank approximate of A. This is important since most of our information will be reconstructed from the first few ‘singular values’. If the rank of the matrix is r, we can imagine<strong> <em>the matrix V to be in the column space of A, and U to be in the row space of A. I didn’t explain row-space? It’s just the column space of Transpose(A). </em></strong>What’s the rest of the vectors (n-r) other the ‘r’ that are in the column space? Well, that goes into the nullspace (That’s for another day)</p><p>Let’s take a look at a small example of how we can use this for topic modeling. We will use the fetch_20newsgroups dataset from sci-kit-learn. This gives us around 13000 documents of various categories that our model has no idea about. To construct our initial matrix we use Tf-Idf so our matrix is in the form of <strong><em>document x words. W</em></strong></p><p>So again, the rows would be the documents and the columns would have words and the entries would have the tf-idf score for that particular word.</p><pre><strong>#### BUILDING UP DATAFRAME</strong></pre><pre>from sklearn.datasets import fetch_20newsgroups<br>dataset = fetch_20newsgroups(shuffle=True, random_state=1, remove=(&#39;headers&#39;, &#39;footers&#39;, &#39;quotes&#39;))<br>documents = dataset.data<br>vectorizer = TfidfVectorizer(stop_words=&#39;english&#39;,max_features= 1000,max_df = 0.5,smooth_idf=True) #picking 1000 words</pre><pre>df = pd.DataFrame({&#39;document&#39;:documents})<br>df[&#39;docs&#39;] = df[&#39;document&#39;].str.replace(&quot;[^a-zA-Z#]&quot;, &quot; &quot;) #cleaning<br>vectors = vectorizer.fit_transform(df[&#39;docs&#39;]).todense() </pre><pre>tf_dict={}<br>for i,k in enumerate(vectors):<br> a=np.squeeze(np.array(k))<br> tf_dict[f&#39;Doc{i}&#39;]= a</pre><pre>documents=pd.DataFrame.from_dict(tf_dict)<br>documents.index=words<br>documents.T #Final DataFrame</pre><p>After this, we would get a sparse matrix that would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0pO_nu9sVYL-gzDDdifVw.jpeg" /><figcaption>Dataframe for SVD decomposition</figcaption></figure><pre><strong>### SVD AND VIEWING TOPICS</strong></pre><pre>from scipy.linalg import svd</pre><pre>U, s, VT = svd(vectors)</pre><pre>def display_topics(model, feature_names, no_top_words):<br> topic_dict = {}</pre><pre>for topic_idx, topic in enumerate(model):</pre><pre> topic_dict[&quot;Topic %d words&quot; % (topic_idx)]=      [&#39;{}&#39;.format(feature_names[i])</pre><pre>for i in topic.argsort()[:-no_top_words - 1:-1]]</pre><pre> topic_dict[&quot;Topic %d weights&quot; % (topic_idx)]= [&#39;{:.1f}&#39;.format(topic[i])</pre><pre> for i in topic.argsort()[:-no_top_words - 1:-1]]</pre><pre>return pd.DataFrame(topic_dict)</pre><p>VT will contain our <strong><em>right singular vectors</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*YFxdfFGHe-EX6ad-HkxsqQ.png" /></figure><p>The<strong> <em>eigenvectors of Transpose(A) x A </em></strong><em>( which turns out to be symmetric ) </em>gives us our orthogonal right singular vectors. Recall the shape of our document, 13000 x 1000. Can you guess what the shape of VT will be?</p><p>If examine VT and order them by top words according to weight, we get the most important words to a topic.</p><pre>#Examining the top 10 words<br>display_topics(VT[1:3],words,10) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*jLwoOtxgLfGDd_0grLT3XA.png" /></figure><p>We can see that the first topic looks to be about computers and the second one seems to be about sports.</p><p>Let’s check if the topics are orthogonal like we expect it to be.</p><pre>np.dot(VT[2:3],VT[:1].T) Multiplying two columns</pre><pre>Output: array([[-1.73472348e-17]])</pre><p>It is difficult to articulate what is going on under the hood in one blog post. If you’re new to linear algebra, most of this probably sounded alien jibber-jabber to you. Hence I’ll recommend a learning path for linear algebra which help you deep-dive into the topic.</p><h3><strong>Resources</strong></h3><p>There are three main resources for going about this, I would suggest an order like this:</p><ol><li><a href="https://www.youtube.com/watch?v=e50Bj7jn9IQ">3Blue1Brown Linear Algebra Series</a>: A visual intuition into the concepts I mentioned here, and a great starting point.</li><li><a href="https://www.youtube.com/watch?v=Cx5Z-OslNWE&amp;list=PLUl4u3cNGP63oMNUHXqIUcrkS2PivhN3k">Gilbert Strang Lectures on Linear Algebra</a>: This course was meant for understanding linear algebra for data scientists. You can also get the book that goes along with the lectures. The concepts discussed here are theoretical and they will surely help out in the long run.</li><li><a href="https://www.youtube.com/watch?v=8iGzBMboA0I&amp;list=PLtmWHNX-gukIc92m1K0P6bIOnZb-mg0hY">Fast-AI Computational Linear Algebra:</a> Unlike the Gilbert Strang videos, this focuses on practical applications of the concepts. Once you learn all the theoretical concepts from the Gilbert Strang videos, these lectures will be very easy to follow.</li></ol><p>You can find all the codes mentioned in the post <a href="https://github.com/ArnabPushilal/LinAlg/tree/main">here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d0ba3189a3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/why-you-should-consider-studying-linear-algebra-as-a-data-scientist-part-1-svd-9d0ba3189a3e">Why you should consider studying Linear Algebra as a data scientist : SVD</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>