<?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 Taaniya Arora on Medium]]></title>
        <description><![CDATA[Stories by Taaniya Arora on Medium]]></description>
        <link>https://medium.com/@TaaniyaArora?source=rss-c16af717ac09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9TXcLPsSWpI_U9l-RWJ8pg.jpeg</url>
            <title>Stories by Taaniya Arora on Medium</title>
            <link>https://medium.com/@TaaniyaArora?source=rss-c16af717ac09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:25:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@TaaniyaArora/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[Visualizing GPT2 word embeddings on Tensorboard]]></title>
            <link>https://medium.com/@TaaniyaArora/visualizing-gpt2-word-embeddings-on-tensorboard-ea5c8fef9efa?source=rss-c16af717ac09------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea5c8fef9efa</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[gpt-2]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[tensorboard]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <dc:creator><![CDATA[Taaniya Arora]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 20:58:58 GMT</pubDate>
            <atom:updated>2023-04-04T05:58:44.837Z</atom:updated>
            <content:encoded><![CDATA[<p>Word embeddings are dense vector representations of words or tokens, and are a common way to vectorize text data before feeding it into machine learning algorithms for Natural Language Processing. There are different ways to obtain word embeddings and this article will focus on word embeddings learnt by a pre-trained GPT2 model. More details on the significance of word embeddings in Natural Language Processing and background on their use in NLP can be referred to in my previous article — <a href="https://towardsdatascience.com/from-linear-algebra-to-text-representation-for-natural-language-processing-239cd3ccb12f">Vector algebra for Natural Language Processing</a>.</p><p>GPT2 is a Transformer Decoder based language model with a vocabulary size of 50,257 tokens and 768 dimensions of word embeddings in its embedding matrix.</p><p>As every language model learns and uses its own word embeddings, it is often useful to explore and analyze the word embeddings of tokens present in its vocabulary. This is especially useful with an increase in applications of pre-trained models, for example, to analyze its pre-trained learnings before fine-tuning them for a specific use case.</p><h4>Visualization</h4><p>Let’s see how to visualize and analyze these word embeddings using Tensorboard -</p><ol><li>Load model</li></ol><pre>from transformers import GPT2TokenizerFast, GPT2LMHeadModel<br>import tensorflow as tf<br>from tensorboard.plugins import projector<br><br><br>model = GPT2LMHeadModel.from_pretrained(&#39;gpt2&#39;)</pre><p>2. Get its word embeddings</p><pre>word_embeddings = model.transformer.wte.weight # Word Token Embeddings<br><br>print(word_embeddings.shape)</pre><p>3. Save metadata for visualization</p><p>Tensorboard uses saved tensor checkpoints to load and visualize tensors and a CSV formatted file containing corresponding metadata to display labels during the interaction.</p><p>GPT2 maintains tensors of all tokens in its vocabulary as an embedding matrix in the order of its index associated with each token in the vocabulary.</p><p>A sample of tokens in its dictionary of vocabulary can be seen below. Each token in this dictionary is a key and its index in the embedding matrix is its value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*qa5SDX40avOZAz7J75pY1A.png" /><figcaption>Sample of tokens &amp; their indices in GPT-2 vocabulary (Image by Author)</figcaption></figure><p>Let’s add these tokens into a metadata file in the order of their index to align them with their labels with tensors from the embedding matrix.</p><pre># Create list of tokens in vocab sorted by their index in vocab<br><br>vocab_list = sorted(tokenizer.vocab.items(), key=lambda x:x[1])<br><br><br># save them as csv<br>with open(os.path.join(log_dir, &#39;metadata.tsv&#39;), &quot;w&quot;) as f:<br>    for word, idx in tqdm(vocab_list):<br>        f.write(&quot;{}\n&quot;.format(str(word.encode(encoding=&#39;iso-8859-1&#39;, errors=&#39;replace&#39;))))</pre><p>4. Save the embeddings obtained from the model initially</p><pre>embeddings = tf.Variable(model.transformer.wte.weight.detach().numpy())<br>checkpoint = tf.train.Checkpoint(embedding=embeddings)<br>checkpoint.save(os.path.join(log_dir, &quot;embedding.ckpt&quot;))</pre><p>5. Set up Tensorboard projector configuration</p><p>We will use Tensorboard’s projector to visualize the embeddings and create its configuration file (it is created with .pbtxt extension).</p><pre># Set up config<br>config = projector.ProjectorConfig()<br>embedding = config.embeddings.add()<br><br># The name of the tensor will be suffixed by `/.ATTRIBUTES/VARIABLE_VALUE`.<br>embedding.tensor_name = &quot;embedding/.ATTRIBUTES/VARIABLE_VALUE&quot;<br>embedding.metadata_path = &#39;metadata.tsv&#39;<br>projector.visualize_embeddings(log_dir, config)</pre><p>6. Run Tensorboard to visualize the embeddings from the command line</p><pre>tensorboard --logdir ./logs/vocab/</pre><p>The tensorboard projector uses PCA as the default dimensionality reduction technique to project high-dimensional vectors into 2D or 3D spaces.</p><p>Use UMAP for more intuitive and faster visualization that retains the proximity of vectors in higher-dimensional after projecting them into lower-dimensional space.</p><h4>Insights</h4><p>With 3D settings, we can see a few clusters of data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSdRLRbHe7rSmR1IC-V87w.png" /><figcaption>Image by author</figcaption></figure><p>One of the clusters has all the digits. We can click on one of the data points in the cluster and see their nearest neighbors in the drop-down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXnVuhBEldUvQK6Uv0vIfg.png" /><figcaption>Digits in a separate cluster</figcaption></figure><p>Another cluster has all years …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfuzCbF7dgWVobyv_uNqnA.png" /><figcaption>Years in a cluster</figcaption></figure><p>One has numbers and years spelled in words…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dENC8-S-QA1UlLVDTOQ84Q.png" /><figcaption>Numbers and years spelled in words in a separate cluster</figcaption></figure><p>We can also search a few keywords on the right, choose one of the suggestions matching our search keyword, and get its nearest neighbors.</p><p>Isolating 101 nearest points shows relevant points of our interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmioVu8CiT4k-w5JcMY30g.png" /><figcaption>Tokens with 101 nearest neighbors in isolation</figcaption></figure><p>After showing all points again, rotating this further reveals another cluster with symbols and Unicode characters in close proximity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAWAG8j-3LduJtYyTwMUDw.png" /><figcaption>Symbols and Unicode characters</figcaption></figure><p>The detailed steps can be referred from <a href="https://github.com/Taaniya/exploring-gpt2-language-model/blob/main/Visualizing_gpt2_token_embeddings.ipynb">this jupyter notebook in my git repository.</a></p><p>Hope you found this article useful. Let me know in the comments how visualization has also helped you in your projects.</p><h4>References</h4><ul><li><a href="https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf">GPT paper (2018)</a></li><li><a href="https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf">GPT-2 paper (2019)</a></li><li>Embedding matrix : By Andrew Ng— <a href="https://youtu.be/VkjSaOZSZVs">https://youtu.be/VkjSaOZSZVs</a></li><li>Embedding layers in Keras: By Jeff Heaton — <a href="https://youtu.be/OuNH5kT-aD0">https://youtu.be/OuNH5kT-aD0</a></li><li>UMAP — <a href="https://umap-learn.readthedocs.io/en/latest/">https://umap-learn.readthedocs.io/en/latest/</a></li><li><a href="https://www.tensorflow.org/tensorboard/tensorboard_projector_plugin">Tensorflow embedding projector</a></li><li><a href="https://towardsdatascience.com/how-to-visualize-text-embeddings-with-tensorboard-47e07e3a12fb">https://towardsdatascience.com/how-to-visualize-text-embeddings-with-tensorboard-47e07e3a12fb</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5c8fef9efa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Algebra for Natural Language Processing]]></title>
            <link>https://medium.com/data-science/from-linear-algebra-to-text-representation-for-natural-language-processing-239cd3ccb12f?source=rss-c16af717ac09------2</link>
            <guid isPermaLink="false">https://medium.com/p/239cd3ccb12f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[vector-space]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <dc:creator><![CDATA[Taaniya Arora]]></dc:creator>
            <pubDate>Sun, 01 Aug 2021 21:25:02 GMT</pubDate>
            <atom:updated>2023-04-02T15:08:46.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vector Algebra for Natural Language Processing</h3><h4>Representing word semantics in vector space</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PTgab97k0YdQhN-9" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The field of Natural Language Processing involves building techniques to process text in natural language by people like you and me, and extract insights from it for performing a variety of tasks from interpreting user queries on search engines and returning web pages, to solving customer queries as chatbot assistant. The importance of representing every word into a form that captures the meaning of the word and the overall context becomes crucial especially when major decisions are based upon the insights extracted from text on a large scale — like forecasting stock price change with social media.</p><p>In this article, we’ll begin with the basics of vector algebra to get an intuition of vectors and their significance for representing specific types of information, the different ways of representing text in vector space, and how the concept has evolved to the current state of the art models.</p><p>We’ll step through the following areas -</p><ul><li>Unit vectors in our coordinate system</li><li>Linear combination of vectors</li><li>Span in vector coordinate system</li><li>Collinearity &amp; multicollinearity</li><li>Linear dependence and independence of vectors</li><li>Basis vectors</li><li>Vector Space Model for NLP</li><li>Dense Vectors</li></ul><h3>Unit vectors in our coordinate system</h3><p><strong><em>i</em></strong>-&gt; Denotes a unit vector (vector of length 1 unit) pointing in the x-direction</p><p><strong><em>j</em></strong><em> </em>-&gt; Denotes a unit vector in the y-direction</p><p>Together, they are called the basis of our coordinate vector space.</p><p>We’ll come to the term <strong>basis</strong> more in the subsequent parts below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*3w4-fN7V_AyLWy2CEZdGXg.png" /><figcaption>Standard Unit vectors — Image by Author</figcaption></figure><ul><li>Suppose we have a vector 3<strong><em>i</em></strong>+ 5<strong><em>j</em></strong></li><li>This vector has x,y coordinates : 3 &amp; 5 respectively</li><li>These coordinates are the scalars that flip and scale the unit vectors by 3 &amp; 5 units in the x &amp; y directions respectively</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*Op84Eik1xpxyMd3hXnfInw.png" /><figcaption>A vector in 2D X-Y space — Image by Author</figcaption></figure><h3>Linear Combination of 2 vectors</h3><p>If <strong><em>u</em></strong> &amp; <strong><em>v</em></strong> are two vectors in a 2 dimensional space,then their linear combination resulting into a vector <strong><em>l</em></strong> is represented by -</p><p><strong><em>l</em></strong> = <em>x1.</em> <strong><em>u</em></strong> + <em>x2.</em> <strong><em>v</em></strong></p><ul><li>The numbers <em>x1</em>, <em>x2</em> are the components of a vector x</li><li>This is essentially a scaling and addition operation by x on the given vectors.</li></ul><p>The above expression of linear combination is equivalent to the following linear system -</p><p><strong>B<em>x</em></strong> = <strong><em>l</em></strong></p><p>Where <strong><em>B</em></strong> denotes a matrix whose columns are <strong><em>u</em></strong> and <strong><em>v</em></strong>.</p><p>Let’s understand this by an example below with vectors <strong><em>u</em></strong> &amp; <strong><em>v</em></strong> in a 2 dimensional space -</p><pre># Vectors u &amp; v<br># The vectors are 3D, we&#39;ll only use 2 dimensions<br>u_vec = np.array([1, -1, 0])<br>v_vec = np.array([0, 1, -1])</pre><pre># Vector x<br>x_vec = np.array([1.5, 2])</pre><pre># Plotting them<br># fetch coords from first 2 dimensions<br>data = np.vstack((u_vec, v_vec))[:,:2]<br>origin = np.array([[0, 0, 0], [0, 0, 0]])[:,:2]<br>plt.ylim(-2,3)<br>plt.xlim(-2,3)<br>QV = plt.quiver(origin[:,0],origin[:,1], data[:, 0], data[:, 1], color=[&#39;black&#39;, &#39;green&#39;], angles=&#39;xy&#39;, scale_units=&#39;xy&#39;, scale=1.)<br>plt.grid()<br>plt.xlabel(&quot;x-axis&quot;)<br>plt.ylabel(&quot;y-axis&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*J1heCAa-ajwoe14j06QSeg.png" /><figcaption>Linear Combination of vectors — Image by Author</figcaption></figure><p>We can also understand it from this explanation for a similar example with 3 dimensions given by a Professor in his notes here -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*eiQGUSraOnO9spxieLTqiQ.png" /><figcaption>Linear Algebra, Chapter 1- Introduction to Vectors, MIT</figcaption></figure><p>Taking the 3 vectors from the example in the image and plotting them in 3D space (The units of axes are different than the vectors in the plot)</p><pre>u_vec = np.array([1, -1, 0])<br>v_vec = np.array([0, 1, -1])<br>w_vec = np.array([0, 0, 1])</pre><pre>data = np.vstack((u_vec, v_vec, w_vec))<br>origin = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])<br>fig = plt.figure()<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)<br>ax.quiver(origin[:,0],origin[:,1], origin[:,2], data[:, 0], data[:, 1], data[:,2])</pre><pre>ax.set_xlim([-1, 2])<br>ax.set_ylim([-1, 2])<br>ax.set_zlim([-1, 2])<br>plt.grid()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*2FewINX4BVqDUA9cnY2Q-A.png" /><figcaption>Vectors in 3D space — Image by Author</figcaption></figure><h3>Span</h3><ul><li>A span is a set of all possible combinations of vectors that we can reach with a linear combination of a given pair of vectors</li><li>The span of most pairs of 2-D vectors is all vectors in the 2-D space. Except, when they line up in the same direction (i.e if they are collinear) , in which case, their span is a line.</li></ul><p>i.e span( <strong><em>a</em></strong>, <strong><em>b</em></strong>) = <strong>R² </strong>(all vectors in 2D space) , provided they are not collinear.</p><h3>Collinearity</h3><p>Collinearity is the case when we have p different predictor variables but some of them are linear combinations of others, so they don’t add any other information. 2 collinear vectors / variables will have correlation close to +/- 1 and can be detected by their correlation matrix.</p><p><strong>Multicollinearity</strong> exists when more than 2 vectors are collinear and any pair of vectors may not necessarily have high correlation.</p><p><strong>Linear Independence</strong></p><p>We say that <em>v1</em> , <em>v2</em>, . . . , <em>vn</em> are linearly independent, if none of them is</p><p>a linear combination of the others. This is equivalent to saying</p><p>that <em>x1.v1</em> + <em>x2.v2</em> + . . . + <em>xn.vn</em> = 0 implies <em>x1 = x2 = . . . = xn = 0</em></p><p>Since collinear vectors can be expressed as linear combinations of each other, they are <strong>linearly dependent.</strong></p><h3><strong>Basis</strong></h3><p>A basis is that set of linearly independent vectors that span that space.</p><p>We call these vectors as basis vectors</p><h3>Vector space Models in NLP</h3><p>A <strong>Vector space</strong> is a set V of vectors, where two operations — vector addition and scalar multiplication are defined. For E.g. If two vectors <strong><em>u</em></strong> &amp; <strong><em>v</em></strong> are in space <strong><em>V</em></strong>, then their sum, <strong><em>w = u + v</em></strong> will also lie in the vector space <strong><em>V</em></strong>.</p><p>A 2D vector space is a set of linearly independent basis vectors with 2 axes.</p><p>Each axis represents a dimension in the vector space.</p><p>Recalling the previous plot of vector <strong><em>a</em></strong> = (3,5) = 3 <strong><em>i</em></strong> + 5 <strong><em>j</em></strong> again. This vector is represented on a 2D space with 2 linearly independent basis vectors — X &amp; Y, who also represent the 2 axes as well as the 2 dimenions of the space.</p><p>3 &amp; 5 here are the x,y components of this vector for representation on the X-Y 2D space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*Op84Eik1xpxyMd3hXnfInw.png" /><figcaption>Vector in 2D X-Y plane — Image by Author</figcaption></figure><h3><strong>Vector space model in NLP</strong></h3><p>A vector space model is a representation of text in vector space.</p><p>Here, each word in a corpus is a linearly independent basis vector and each basis vector represents an axis in the vector space.</p><ul><li>This means, each word is orthogonal to other words/axes.</li><li>For a corpus of vocabulary <strong><em>|V|</em></strong>, <strong>R </strong>will contain <strong><em>|V|</em></strong> axes.</li><li>Combination of terms represent documents as points or vectors in this space</li></ul><p>For 3 words, we’ll have a 3D vector model represented like this -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*h-pcnvLfZYDC-hcW5ihvjg.png" /><figcaption>Vector Space Model for 3 words — Image by Author</figcaption></figure><p>The table above the graph represents the TF-IDF incident matrix.</p><p><strong><em>D1</em></strong> = (0.91, 0, 0.0011) represents a document vector in the 3 axes — good, house, car. Similarly, we have <strong><em>D2</em></strong> &amp; <strong><em>D3</em></strong> document vectors.</p><p>How does representation in vector space help us, though?</p><ul><li>One of the common application using this representation is information retrieval for search engines, question answering systems and much more.</li><li>By representing the text into vectors, we aim to use vector algebra to extract semantics from the text and use it for different applications like searching documents containing the similar sementics as those contained in a given search query.</li></ul><p>For eg. For a search token ‘buy’ , we would want to get all the documents containing different forms of this word — buying, bought and even synonyms of the word ‘buy’. Such documents can not be captured from other rudimentary methods representing documents as Binary <a href="https://en.wikipedia.org/wiki/Incidence_matrix">incident matrix</a>.</p><p>This is achieved through distance metrics like cosine similarity between vectors of document &amp; query, where the documents closer to the query are ranked the highest.</p><ul><li>The number of words / vocabulary size can be as huge as in millions eg. Google news corpus is 3 Million, which means as many independent axes/dimensions to represent the vectors. Hence, we want to use the operations in vector space to reduce the number of dimensions and bring words with similar to each other in the same axis.</li></ul><h3>Dense vectors</h3><ul><li>The above operations are possible on document vectors which are represented by extending the above vector representation of documents to documents represented as distributed or dense vectors. These representations capture the semantics of the text and also captures the linear combinations of word vectors</li><li>The previous vector space model with each word representing a separate dimension results in sparse vectors.</li><li>Dense vectors captures the context in the vector representation. The dense vector of words are such that words appearing in similar contexts will have similar representations.</li><li>These dense vectors are also called as word embeddings or distributed representations.</li><li>word2vec is one such framework to <strong>learn</strong> dense vectors of words from large corpus. It has 2 variants — skip-gram and CBOW(continuous bag of words)</li><li>Some of the other frameworks and techniques to obtain dense vectors are Global Vectors(GloVe), fastText, <a href="https://aclanthology.org/N18-1202.pdf">ELMo</a>(Embeddings from Language Model) and <a href="https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf">Transformers</a> architecture based Language Models to obtain contextualized word embeddings.</li></ul><h4>Conclusion</h4><p>This article introduced the concept of vector space based on vector algebra and highlighted the related concepts as part of their application in Natural Language Processing for representing text documents in semantics representation and extraction tasks.</p><p>The applications of word embeddings have been extended to more advanced and wide applications with much-improved performance than earlier.</p><p>You can also refer to the source code and run on colab by accessing my <a href="https://github.com/Taaniya/linear-algebra-for-ml">Git repository here</a>.</p><p>Hope you enjoyed reading it. :)</p><h4>References</h4><ul><li><a href="https://www.youtube.com/watch?v=eeMJg4uI7o0">Linear Independence, Basis &amp; Dimension, MIT</a></li><li><a href="https://math.mit.edu/~gs/linearalgebra/linearalgebra5_1-3.pdf">Matrices-Introduction to Vectors, MIT</a></li><li><a href="https://www.youtube.com/watch?v=6Nz88LHOIdo">Vector space models for NLP, NPTEL</a></li><li>An introduction to statistical learning, E-Book by Gareth James, Daniela Witten, Trevor Hastie and Robert Tibshirani</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=239cd3ccb12f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-linear-algebra-to-text-representation-for-natural-language-processing-239cd3ccb12f">Linear Algebra for Natural Language Processing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graph Laplacian and its application in Machine learning]]></title>
            <link>https://medium.com/data-science/graph-laplacian-and-its-application-in-machine-learning-7d9aab021d16?source=rss-c16af717ac09------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d9aab021d16</guid>
            <category><![CDATA[graph-laplacian]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-analytics]]></category>
            <category><![CDATA[spectral-clustering]]></category>
            <dc:creator><![CDATA[Taaniya Arora]]></dc:creator>
            <pubDate>Sun, 19 Jul 2020 01:00:45 GMT</pubDate>
            <atom:updated>2023-04-02T14:57:31.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>Apply Graph Laplacian in Spectral clustering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ibv3jbiFZ-Lv3oR8" /><figcaption>Photo by <a href="https://unsplash.com/@pietrozj?utm_source=medium&amp;utm_medium=referral">Pietro Jeng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article highlights graphs, properties of its representations and its application in Machine learning to perform Spectral clustering.</p><h3>Introduction</h3><p>A graph is a data structure with nodes connected to each other through directed or undirected edges. The edges can have weights to represent for eg. the distance between 2 cities for a graph representing an urban road network with cities as nodes.</p><h3><strong>Contents</strong></h3><ul><li>Loading data</li><li>Constructing a graph from features</li><li>Deriving its Laplacian representation</li><li>Explore properties of Graph Laplacian</li><li>Applications in machine learning — Spectral clustering</li></ul><p><strong>Loading data</strong></p><p>We will begin with a toy make_moons data set from python library scikit-learn.</p><pre>import numpy as np<br>from scipy import sparse</pre><pre>from sklearn.datasets import make_moons<br>from sklearn.neighbors import kneighbors_graph<br>from sklearn.cluster import KMeans<br>from sklearn.metrics import homogeneity_score, completeness_score,v_measure_score</pre><pre>import networkx as nx<br>import matplotlib.pyplot as plt</pre><pre>random_state = 213<br>np.random.seed(random_state)</pre><pre>data_size = 150</pre><pre>features,y = make_moons(n_samples=data_size, noise=0.07, random_state=213)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*oUFvap6mMXctTyF5HanRnA.png" /><figcaption>Data set with 2 clusters</figcaption></figure><p><strong>Construction of K-nearest neighbors graph</strong></p><p>K-nearest neighbors graph can be constructed in 2 modes — ‘distance’ or ‘connectivity’.</p><p>With ‘distance’ mode, the edges represent the distance between 2 nodes and with ‘connectivity’ , the graph has edge weight 1 or 0 to denote presence or absence of an edge between them. We will choose euclidean distance metric to compute the distance.</p><pre>n_neighbors = 10<br>knn_dist_graph = kneighbors_graph(X=features,<br>                                 n_neighbors=n_neighbors,<br>                                 mode=&#39;distance&#39;,<br>                                 metric=&#39;euclidean&#39;,<br>                                 n_jobs=6)</pre><p>It returns a sparse graph with edges representing the distance between the data points. The distance of the first data point with its nearest 10 neighbors is shown below. Note the sparsity of the graph and it will have continuous value representing distance at only those places/indices in the matrix which corresponds to its k nearest neighbors, the rest will be zero.</p><pre>knn_dist_graph.todense()[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*fcnGBp8LwLdJXos4-Kka_g.png" /></figure><p>This data is commonly used to find groups within the data points where similar data points lie in the same class or cluster.</p><p>Similarly in other such cases when you want to capture similarity within the data points rather than the distance, we can convert this graph to similarity based using a Gaussian kernel with its width (sigma = 1 ) and the distance d(x1, x2) is the euclidean distance in the non zero places in the sparse graph above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*6K9UIlCnRwsyLYH5AqHuqw.png" /></figure><p>Note that the locations with distance = 0 in the array above mean that the distance is beyond the largest distance of k nearest neighbors. This value can be interpreted as highest similarity when fed to Gaussian kernel. So, we will only apply this kernel to indices containing distances.</p><pre>sigma = 1<br>similarity_graph = sparse.csr_matrix(knn_dist_graph.shape)<br>nonzeroindices = knn_dist_graph.nonzero()</pre><pre>similarity_graph[nonzeroindices] = np.exp( -np.asarray(knn_dist_graph[nonzeroindices])**2 / 2.0 * sigma**2)</pre><pre>similarity_graph = 0.5 * (similarity_graph + similarity_graph.T)<br>similarity_graph.todense()[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*IA8klHglBuhIpJC9PU1gmQ.png" /></figure><p>This graph may be asymmetric since it is based on k-nearest neighbors. We need to make this graph symmetric for reasons we will know next in properties of Laplacian. We add the transpose of its graph to itself and divide all the values by 2.</p><p>Let’s see how the graph looks like when visualized</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*5hc_zbzikrI5Cy8Y8gFCNQ.png" /><figcaption>Visualization with networkx</figcaption></figure><p><strong>Deriving Graph Laplacian representation</strong></p><p><strong><em>L = D-W</em></strong></p><p>D: Degree matrix</p><p>W: Similarity graph (represented by weighted adjacency matrix)</p><p>We will create a degree matrix of the graph which is a diagonal matrix with node degrees <strong><em>d</em></strong> at the diagonals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*VDx83Dma_ONS8olhasTP6w.png" /></figure><pre>degree_matrix = similarity_graph.sum(axis=1)<br>diagonal_matrix =         <br>np.diag(np.asarray(degree_matrix).reshape(data_size,))</pre><pre>L =  diagonal_matrix - similarity_graph</pre><p><strong><em>Note:</em></strong> By subtracting the similarity matrix from the degree matrix, the effect of cycles in a graph gets nullified. Finally, the Laplacian contains the degree on diagonals and the negative edge weights in the rest of the matrix.</p><p><strong>Properties of Graph Laplacian</strong></p><ol><li><strong><em>Real symmetric</em></strong></li></ol><p>Because it is real and symmetric, its eigen values are real and its eigen vectors are orthogonal.</p><p>2. <strong><em>Positive semi-definite</em></strong></p><p>The Laplacian has at least one eigen value equal to 0. We can check this by its quadratic form. L being real symmetric and if <strong><em>x</em></strong> is a n x 1 column vector and then its quadratic form Q is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/1*mObExibBXRiQ9F2f_931Bg.png" /></figure><p>A quadratic form is positive semi-definite if -</p><ul><li><strong><em>Q≥0</em></strong> for all x and <strong><em>Q = 0</em></strong> for some <strong><em>x≠0</em></strong></li></ul><p>We will set x to be a column vector of 1&#39;s.</p><pre>x = np.ones(shape=(data_size,1))<br>Q = np.dot(np.dot(x.T, L.todense()), x)<br>Q.round(10)</pre><p>Any column vector x containing same values throughout, will result in quadratic form equal to 0.</p><p>3. <strong><em>The number of zero eigen values of Laplacian is equal to the number of connected components in the graph</em></strong></p><pre># Finding eigen values and eigen vectors<br>e, evecs = np.linalg.eig(L.todense())<br>e.shape, evecs.shape</pre><pre># No. of eigen values equal to 0<br>e_rounded_off = e.round(5)<br>e_rounded_off[e_rounded_off == 0].shape</pre><pre># No. of connected components<br>nx.number_connected_components(nx_graph)</pre><p><strong><em>4. Two similar data points with high edge weight will have similar values at their corresponding indices in the resulting eigen vectors</em></strong></p><p>One of these eigen vectors is Fiedler vector — Eigen vector corresponding to the smallest non-zero eigen value. In the image below, the data points are quite well separated by sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*IpnlPnbYASjqDPQkn90H8Q.png" /><figcaption>Eigen vector plot corresponding to smallest non-zero eigen value</figcaption></figure><h4>Application of Graph Laplacian</h4><p>By extension of all the above properties, and the fact that the eigen vector separates data points in groups, it is used for clustering. This method is called <strong>Spectral clustering</strong>.</p><p>This is performed by choosing a threshold to separate data points into 2 clusters from the 1st smallest eigen vector. For more than 2 clusters, we can use Kmeans algorithm to obtain K clusters directly from the first smallest K eigen vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*EUyeiX7HCACPIewuL9guew.png" /><figcaption>Eigen values plotted against data indices</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*kHW7wvRTSSN7SHbiGdCheg.png" /><figcaption>Eigen values (sorted) plotted against data indices</figcaption></figure><p><strong><em>Using Fiedler vector to partition data points</em></strong></p><p><a href="https://en.wikipedia.org/wiki/Graph_partition#:~:text=In%20mathematics%2C%20a%20graph%20partition,edges%20in%20the%20partitioned%20graph.">Graph partitioning</a> — In this, the vertices are partitioned into disjoints sets. The graph is partitioned such that the edges within the groups have high weights (points within clusters are similar) and the edges between groups have small weights (points in different clusters are dissimilar to each other).</p><p>The Fiedler vector is the eigen vector corresponding to smallest non-zero eigen value. Indices of values below 0 are assigned to cluster 1 and the indices of rest of them are assigned to cluster 2.</p><p>We are able to use this vector this way because this eigen vector is a scaled version of the indicator vector. An indicator vector is associated with every non-zero eigen value of a matrix. Each indicator vector is also orthogonal to each other and ideally contains binary values 0 or 1 to indicate cluster membership.</p><p>In this case, instead of indicator vector containing 0’s and 1’s, we have signed continuous values.</p><pre># Get smallest non-zero eigen value&#39;s index for obtaining partition to cluster<br>fiedler_index = sorted_indices[1]</pre><pre><br># The eigen vector for smallest non-zero eigen value i.e plotting the Fiedler vector<br></pre><pre>plt.figure(figsize=(8,6))<br>plt.scatter(np.arange(data_size), evecs[:,fiedler_index].tolist())<br>plt.title(&quot;Eigen (Fiedler) vector plot&quot;)<br>plt.show()</pre><pre>fiedler_vector = evecs[:,fiedler_index].copy()</pre><pre><br># Thresholding the values in this eigen vector at 0<br>fiedler_vector[fiedler_vector &lt; 0.0] = 0<br>fiedler_vector[fiedler_vector &gt; 0.0] = 1<br>new_labels = np.asarray(fiedler_vector)[:,0]</pre><pre># Plot cluster result<br>plt.scatter(features[:,0], features[:,1],         <br>                          c=new_labels.astype(float))<br>plt.title(&quot;Clusters plot&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*-9z0X63rFXWgbPSTOy2qtQ.png" /><figcaption>Clusters obtained from Spectral clustering</figcaption></figure><p><strong>Evaluation with entropy based external cluster evaluation measures</strong></p><p><a href="https://scikit-learn.org/stable/modules/clustering.html#homogeneity-completeness">Homogeneity &amp; completeness score and v-measure</a> evaluate the cluster results based on the ground truth and takes into account the distribution of class and cluster labels to measure coherence of clusters obtained. Highest score is 1.0 for each of the measure. We get 1.0 score each metric for the above procedure.</p><pre># Evaluation of clustering result of the above procedure<br>homogeneity_score(y, new_labels), completeness_score(y, new_labels), v_measure_score(y, new_labels)</pre><p><strong>Comparison with Kmeans</strong></p><pre>num_clusters = 2<br>kmean_labels = KMeans(n_clusters=num_clusters, random_state=random_state, n_jobs=6).fit_predict(features)</pre><pre>plt.scatter(features[:,0], features[:,1],                                                                           c=kmean_labels.astype(float))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*1sJKmyIEUafX5c-4slvY5w.png" /><figcaption>Clusters obtained from KMeans clustering</figcaption></figure><pre># Evaluation of clustering result of KMeans<br>homogeneity_score(y, kmean_labels), completeness_score(y, kmean_labels), v_measure_score(y, kmean_labels)</pre><pre># Scores<br># (0.1836464702880451, 0.1837407327840609, 0.18369358944333708)</pre><p>Kmeans, assuming presence of spherical clusters, isn’t able to distinguish the 2 clusters well.</p><p>Recalling about Laplacian representation and solving the eigen value system to obtain clusters, one question is —<strong> Why Eigen value system, though?</strong></p><p>This is because the eigen value system approximates a graph cut.</p><p>For eg. <strong><em>Cut(V1, V2</em>)</strong> to obtain 2 partitions V1 &amp; V2 is expressed as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*UhfA9SnpMCXPS7jlGIvl0g.png" /></figure><p>In the above approach, the eigen values approximate a <a href="https://people.eecs.berkeley.edu/~malik/papers/SM-ncut.pdf">Normalized graph cut</a> — <strong><em>NCut(V1, V2)</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*td6BkWWQWz_4mwKKi1xzyA.png" /></figure><h4><strong><em>How is it so?</em></strong></h4><p>The above equation of NCut can be re-expressed as <a href="https://en.wikipedia.org/wiki/Rayleigh_quotient#:~:text=The%20Rayleigh%20quotient%20is%20used,approximation%20from%20an%20eigenvector%20approximation.">Rayleigh’s quotient</a>, whose minimum is obtained by the smallest eigen value from a generalized eigen value problem. Let x be an N dimensional indicator vector where <strong><em>xi</em></strong>=1, if the graph node <strong><em>i</em></strong> is in V1 and 0 otherwise, then the minimization of Ncut is expressed as the following Rayleigh’s quotient,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*ejiaIy3NyiXu4kNeRKLsJw.png" /></figure><p>subject to one of the conditions,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/95/1*HGicvbsoBvLQ2vRBaqmC8Q.png" /></figure><p>where <strong><em>y</em></strong> is also subject to constraints as that of our indicator vector x.</p><p>This way the graph partitioning problem gets converted to clustering problem.</p><h3>Conclusion</h3><p>We began with features of data, constructing its Graph and Laplacian and using its spectral embeddings (eigen vectors), we found optimal partitions to obtain clusters. Spectral theory, the source of this concept of working with eigen values and eigen vectors of graph representation, is also used in other areas of machine learning such as image segmentation, spectral graph convolutional neural networks and many more in the industry as well as research community.</p><p>This article aimed to summarize the concepts and the applications in machine learning and linear algebra and I hope it also raises curiosity to explore and learn more about it.</p><p>Hope it is helpful.</p><p>Do share your feedback or if you come across the application of these concepts in other areas.</p><p>You can find the code on GitHub here.</p><p><a href="https://github.com/Taaniya/graph-analytics/blob/master/Graph_Laplacian_and_Spectral_Clustering.ipynb">Taaniya/graph-analytics</a></p><h4>References</h4><ul><li><a href="https://www.cs.cmu.edu/~aarti/Class/10701/readings/Luxburg06_TR.pdf">Ulrike von Luxburg , A Tutorial on Spectral Clustering, 2006.</a></li><li><a href="https://people.eecs.berkeley.edu/~malik/papers/SM-ncut.pdf">Jianbo Shi and Jitendra Malik,</a> Normalized Cuts and Image Segmentation,2000</li><li><a href="https://www.youtube.com/watch?v=cxTmmasBiC8">Prof. Gilbert Strang, Clustering in Graphs</a>, MIT OpenCourseWare.</li><li><a href="http://www2.econ.iastate.edu/classes/econ501/Hallam/documents/Quad_Forms_000.pdf">Quadratic forms and definite matrices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d9aab021d16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/graph-laplacian-and-its-application-in-machine-learning-7d9aab021d16">Graph Laplacian and its application in Machine learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>