<?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 Aravind CR on Medium]]></title>
        <description><![CDATA[Stories by Aravind CR on Medium]]></description>
        <link>https://medium.com/@AravindR07?source=rss-fff69debc77c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*mnZFhPssctnKeymj0VlFZQ.jpeg</url>
            <title>Stories by Aravind CR on Medium</title>
            <link>https://medium.com/@AravindR07?source=rss-fff69debc77c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:29:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AravindR07/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[Word Embeddings in NLP | Word2Vec | GloVe | fastText]]></title>
            <link>https://medium.com/analytics-vidhya/word-embeddings-in-nlp-word2vec-glove-fasttext-24d4d4286a73?source=rss-fff69debc77c------2</link>
            <guid isPermaLink="false">https://medium.com/p/24d4d4286a73</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aravind CR]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 05:52:40 GMT</pubDate>
            <atom:updated>2020-09-10T13:36:06.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*LdviucnshWgIIcQvhTTF-g.png" /></figure><p><strong>Word embeddings are word vector representations where words with similar meaning have similar representation. </strong>Word vectors are one of the most efficient ways to represent words.</p><p>In previous blogs(<a href="https://medium.com/analytics-vidhya/natural-language-processing-using-spacy-in-python-part-1-ac1bc4ad2b9c">part1</a>, <a href="https://medium.com/@AravindR07/nlp-using-spacy-and-topic-modeling-using-gensim-python-42c4574830d">part2</a>) we have discussed about vectors and how they are used to represent textual data in mathematical form and basis for all ML algorithms rely on these representations. So, let’s take one step ahead and use ML techniques to generate vector representation of words that better <strong>encapsulates </strong>meaning of a word.</p><p>One of the most important application of ML in text analysis. As the name suggests it creates a vector representation of words based on the corpus we are using.</p><h3>Word vectors with Word2Vec</h3><p>Using Deep Learning to NLP tasks has proven to be performing very well. The core concept is to feed the human readable sentences into <strong>neural networks </strong>so that the models can <strong>extract </strong>some sort of <strong>information </strong>from them.</p><p>It’s important to understand how to <strong>pre-process textual data for the neural neural networks</strong>. Neural networks can take numbers as an input but not raw text. Hence we need to convert these words into numerical format.</p><h3>Word Vectors</h3><p>Word vectors are much better ways to represent words than <strong><em>one hot encoded vectors </em></strong>(As the size of vocabulary increases, leads to extensive memory usage while representing text vectors). The index which is assigned to each word does not hold any semantic meaning. In one hot encoded vectors, the vectors for “dog” and “cat” are just as close to each other as “dog” and “computer”, hence neural network has to try really hard to understand each word since they are being treated as completely isolated entities. The usage of word vectors aim to resolve both these issues.</p><blockquote><em>“Word vectors consume much less space than one hot encoded vectors and they also maintain semantic representation of word”.</em></blockquote><p>One important aspect before diving directly to word vectors is, similar words occur more frequently together than dissimilar words.</p><p>Just because word occurs within the vicinity of another word it doesnt always mean they have similar meaning , but when we consider frequency of words which are found close together we find that words of similar meaning are found together.</p><h3>Word2Vec</h3><p>In word2vec there are 2 architectures <strong>CBOW</strong>(Continuous Bag of Words) and <strong>Skip Gram</strong>.</p><p><em>First thing to do is to collect word co-occurrence data. We need set of data telling us which words are occurring close to certain word. We will use something called as </em><strong><em>context window</em></strong><em> for doing this.</em></p><p>Consider, “Deep Learning is very hard and fun”. We need to set something known as <strong><em>window size</em></strong>. Let’s say 2 in this case. What we do is iterate over all the words in the given data, which in this case is just one sentence, and <strong>then consider a window of word which surrounds it</strong>. Here since our window size is 2 we will consider 2 words behind the word and 2 words after the word, hence each word will get 4 words associated with it. We will do this for each and every word in the data and collect the word pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*i4l0ve-UbhaNmmfX.png" /><figcaption>Context word example</figcaption></figure><p>As we are <strong><em>passing the context window</em></strong> through the text data, we find all <strong>pairs of target and context</strong> words to form a dataset in the format of target word and context word. For the sentence above, it will look like this:</p><p><strong>1st Window pairs:</strong> (Deep, Learning), (Deep, is)</p><p><strong>2nd Window pairs: </strong>(Learning, Deep), (Learning, is), (Learning, very)</p><p><strong>3rd Window pairs:</strong> (is, Deep), (is, Learning), (is, very), (is, hard)</p><p>And so on. At the end our <strong>target word vs context word data set</strong> is going to look like this:</p><blockquote><em>(Deep, Learning), (Deep, is), (Learning, Deep), (Learning, is), (Learning, very), (is, Deep), (is, Learning), (is, very), (is, hard), (very, learning), (very, is), (very, hard), (very, and), (hard, is), (hard, very), (hard, and), (hard, fun), (and, very), (and, hard), (and, fun), (fun, hard), (fun, and)</em></blockquote><p>This can be considered as our <strong><em>“training data”</em></strong> for word2vec.</p><blockquote>In skipgram model, we try to predict each context word given a target word.</blockquote><p>We use neural network for this prediction task. <strong>The input to the neural network is the one hot encoded version of the context word</strong>. Hence the size of the input and output layer is <strong>V</strong>(vocabulary count). This neural network has only one layer in the middle, the <strong>size of the hidden layer determines the size of the word vectors we wish to have at the end.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*vm1_SO4Z6mp4tE4d.png" /><figcaption>Skip Gram architecture in Word2Vec</figcaption></figure><p>Since this neural network has a total of 3 layers, there will be only 2 weight matrices for the network, <strong>W1 </strong>and <strong>W2</strong>. <strong>W1 </strong>will have dimensions of 10000*300 and <strong>W2 </strong>will have dimensions of 300*10000. These two weight matrices will play an important role in calculating word vectors.</p><p>For the entire dataset which we have collected from the original textual data, we will pass each pair into the neural network and train it.<strong> Neural network here is trying to guess which context words can appear given a target word.</strong> After training the neural network, if we input any target word into the neural network, it will give a vector output which represents the words which have a high probability of appearing near the given word.</p><p><strong>For CBOW the only difference is that we try to predict the target word given the context words</strong>, essentially we just invert the skip gram model to get the CBOW model. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*eLn2x-fdSsE4-Qno.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/1309.4168v1.pdf">Exploiting Similarities among Languages for Machine Translation</a> paper.</figcaption></figure><p>Here when we give a vector representation of a <strong>group of context words</strong>, we will get the <strong>most appropriate target word which will be within the vicinity of those words</strong>.</p><p>For example, if we give the sentence: Deep _____ is very hard, where [“Deep”, “is”, “very”, “hard”] represents the context words, the neural network should hopefully give “Learning” as the <strong>output target word</strong>. This is the core task the neural network tries to train for in the case of CBOW.</p><p><strong>Word vectors help represent semantics of the words — </strong>What does this mean?</p><p>It we means we could use vector reasoning for words one of the most famous example is from <a href="https://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf"><strong>Mikolov’s paper</strong></a>, where we see that if we use the word vectors and perform (here, we use <strong>V(word)</strong> to represent the vector representation of the word) V(King) -V(Man) + V(Woman), and the resulting vector is closest to V(Queen). It is easy to see why this is remarkable — our intuitive understanding of these words is reflected in the learned vector representations of the words.</p><p>This gives us the ability to add more of a punch in our text analysis pipelines-having an intuitive semantic representation of vectors will come in handy more than once.</p><p><strong>Word2Vec </strong>takes as its input a large corpus of text and produces a vector space, typically of several hundred dimensions, with each unique words in the corpus being assigned a corresponding vector in the space. Word vectors are positioned to vector space such that words that share common contexts in the corpus are located in close proximity to one other in the space</p><h3>Implementation</h3><p><strong>Word2Vec </strong>model uses<strong> hierarchical softmax for training</strong> and will have 200 features this means that it has hierarchical output and uses the softmax function in its final layer.</p><pre>Extract the data set in your colab or ipython notebook<br>!wget <a href="http://mattmahoney.net/dc/text8.zip">http://mattmahoney.net/dc/text8.zip</a></pre><pre># Unzip the data from the path you extracted the data to<br>!unzip /content/text8.zip</pre><ul><li>There is the huge list of parameters for the <strong><em>word2vec.Word2Vec</em></strong> class. They can be found in the documentation page <a href="https://radimrehurek.com/gensim/models/word2vec.html">here</a>.</li></ul><pre>from gensim.models import word2vec<br>sentences = word2vec.Text8Corpus(&#39;/content/text8&#39;)<br>model = word2vec.Word2Vec(sentences, size=200, hs=1) <br># hs: If hirearchical softmax used for model training</pre><ul><li>Print the model:</li></ul><pre>print(model)<br>Output: Word2Vec(vocab=71290, size=200, alpha=0.025)</pre><ul><li>Lets try with an example:</li></ul><pre>model.wv.most_similar(positive=[&#39;woman&#39;, &#39;king&#39;], negative=[&#39;man&#39;], topn=1)[0]</pre><pre>o/p: (&#39;queen&#39;, 0.5473929643630981)</pre><p>Since, this is a probabilistic process there may be sight change in the results obtained. For example, words like “throne” or “empire” might show up.</p><ul><li>We can also use the <strong>most_similar_cosmul</strong> method -</li></ul><pre>model.wv.most_similar_cosmul(positive=[&#39;woman&#39;, &#39;king&#39;], negative=[&#39;man&#39;])</pre><ul><li>If we wish to look up the vector representation of a word, all we need to do is this:</li></ul><pre>model.wv[&#39;computer&#39;]</pre><ul><li>If you want to save your model to disk and reuse it again, we can do this using the save and load functionalities.</li></ul><pre>model.save(&#39;text8_model&#39;)<br>model = word2vec.Word2Vec.load(&#39;text8_model&#39;)</pre><ul><li>Using word vectors we can identify which word in a list is the farthest away from the other words. Gensim implements this functionality with <strong>dosent_match </strong>method.</li></ul><pre>model.wv.doesnt_match(&quot;breakfast cereal dinner lunch&quot;.split())</pre><pre>Output: “cereal” <br># One word which dosent match the other in the list is picked out.</pre><ul><li>We can also use the model to understand how similar or different words are in a corpus:</li></ul><pre>model.wv.distance(‘man’, ‘woman’) <br><strong>0.35839658414569464 # the result is self explanatory</strong></pre><ul><li><strong>CBOW </strong>is faster and has <strong>better representation</strong> for more <strong>frequent words.</strong></li><li><strong>Skipgram </strong>works well with small amount of data and is found to represent rare words well.</li></ul><h3>Glove</h3><p>Glove is based on <strong>matrix factorization technique on word context matrix</strong>. It first <strong>constructs</strong> a <strong>large matrix</strong> of (words x context) co-occurrence information ie. for each word, you count how frequently we see those word in some context in a large corpus.</p><p>In order to understand how GloVe works, we need to understand 2 main methods which GloVe was built on -</p><ol><li><strong>Global matrix factorization</strong></li></ol><p>In NLP, global matrix factorization is the process of using matrix factorization form linear algebra to reduce large term frequency matrices. These matrices usually represent the occurrences or the absence of words in the document.</p><p>2. <strong>Local context window.</strong></p><p>Local context window methods are <strong>CBOW </strong>and <strong>Skip-Gram</strong>, the one which were explained above.</p><p><strong><em>Glove is a word vector representation method where training is performed on aggregated global word-word co-occurrence statistics from the corpus</em></strong>. This means that like word2vec it uses context to understand and create the word representations. The research paper describing the method is called <em>GloVe: </em><a href="https://nlp.stanford.edu/pubs/glove.pdf"><em>Global Vectors for Word Representation</em></a> and is well worth a read as it describes some of the drawbacks of LSA and Word2Vec before describing their own method.</p><p>The author of the paper mention that instead of learning the <strong>raw occurance probabilities,</strong> it was more useful to learn <strong>ratios of these co-occurence probabilities</strong>. The embeddings are optimized , so that <strong>the dot product of 2 vectors equals the log of number of times the 2 words will occur near each other.</strong></p><p>For example, if 2 words “cat” and “dog” occur in the context of each other , say 20 times in 10-word window in the document corpus, then —</p><p><strong>Vector(cat).Vector(dog) = log(10)</strong></p><p>This forces the model to encode the frequency distibution of words that occur near them in a more global context.</p><h3>fastText</h3><p>FastText is a vector representation technique developed by facebook AI research. As its name suggests its <strong>fast and efficient method</strong> to perform same task and because of the nature of its training method, it ends up learning <strong>morphological </strong>details as well.</p><p>FastText is unique because it can <strong>derive word vectors for unknown words or out of vocabulary words</strong> — this is because by taking morphological characteristics of words into account, it can <em>create</em> the word vector for an unknown word. Since <strong>morphology refers to the structure or syntax of the words</strong>, FastText tends to perform better for such task, <strong>word2vec </strong>perform better for <strong>semantic task</strong>.</p><p><strong>FastText works well with rare words</strong>. So even if a word wasn’t seen during training, it can be broken down into n-grams to get its embeddings.</p><p><em>Word2vec and GloVe both fail to provide any vector representation for words that are not in the model dictionary</em>. This is a huge advantage of this method.</p><p>The implementation by Facebook can be found in their <a href="https://github.com/facebookresearch/fastText">GitHub </a>repository.</p><h3>Applications</h3><ul><li>Analysing survey responses .</li><li>Analysing verbatim comments.</li><li>Music/Video recommendation system.</li></ul><h3>Summary</h3><p>In this post one of the <strong>major innovation in text analysis</strong>, word embeddings or word vectors were explored. This helps not only to represent our <strong>docs </strong>and <strong>words </strong>but also a new way of looking at our words. Some topics of the blog are referred form deeplearning demisifying page and from book <a href="https://www.packtpub.com/product/natural-language-processing-and-computational-linguistics/9781788838535">NLP and CL</a> from Bhargav Srinivasa-Desikan. The success of word2vec lead to explosion in various word embedding methods each with its own advantages and disadvantages.</p><p>If you like this article do give it claps. Thank you for reading.</p><p><strong>Keep learning</strong>………..</p><h3>— — — — — — — — — — Thank You — — — — — — — — —</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24d4d4286a73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/word-embeddings-in-nlp-word2vec-glove-fasttext-24d4d4286a73">Word Embeddings in NLP | Word2Vec | GloVe | fastText</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[Topic Modeling using Gensim-LDA in Python]]></title>
            <link>https://medium.com/analytics-vidhya/topic-modeling-using-gensim-lda-in-python-48eaa2344920?source=rss-fff69debc77c------2</link>
            <guid isPermaLink="false">https://medium.com/p/48eaa2344920</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Aravind CR]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 14:20:58 GMT</pubDate>
            <atom:updated>2020-07-31T09:50:27.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Iol-C47mo4deMFnE" /></figure><p>This blog post is part-2 of NLP using spaCy and it mainly focus on topic modeling.</p><p>Do check <a href="https://medium.com/analytics-vidhya/natural-language-processing-using-spacy-in-python-part-1-ac1bc4ad2b9c">part-1</a> of the blog, which includes various preprocessing and feature extraction techniques using spaCy.</p><h3>What is topic modeling ?</h3><p><strong>Topic modeling</strong> is technique to extract the hidden topics from large volumes of text. Topic model is a probabilistic model which contain information about the text.</p><p>Ex: If it is a news paper corpus it may have topics like economics, sports, politics, weather.</p><p>Topic models are useful for purpose of document clustering, organizing large blocks of textual data, information retrieval from unstructured text and feature selection. <strong><em>Finding good topics depends on the quality of text processing , the choice of the topic modeling algorithm, the number of topics specified in the algorithm.</em></strong></p><p>There are several existing algorithms you can use to perform the topic modeling. The most common ones are Latent Semantic Analysis or Indexing(LSA/LSI), Hierarchical Dirichlet process (HDP), <strong><em>Latent Dirichlet Allocation(LDA) </em></strong>the one we will be discussing in this post.</p><p>LDA’s approach to topic modeling is, it considers each document as a collection of topics and each topic as collection of keywords. Once you provide the algorithm with number of topics all it does is to rearrange the topic distribution within documents and key word distribution within the topics to obtain good composition of topic-keyword distribution.</p><p>Topics are nothing but collection of prominent keywords or words with highest probability in topic , which helps to identify what the topics are about.</p><h3>Install dependencies</h3><blockquote><em>pip3 install spacy</em></blockquote><blockquote><em>python3 -m spacy download en #Language model</em></blockquote><blockquote><em>pip3 install gensim # For topic modeling</em></blockquote><blockquote><em>pip3 install pyLDAvis # For visualizing topic models</em></blockquote><ul><li>For this implementation we will be using stopwords from NLTK.</li></ul><pre>import nltk<br>nltk.download(&#39;stopwords&#39;)</pre><h3>Imlementation</h3><ul><li><strong>Import libraries</strong></li></ul><pre>import re<br>import numpy as np<br>import pandas as  pd<br>from pprint import pprint# Gensim<br>import gensim<br>import gensim.corpora as corpora<br>from gensim.utils import simple_preprocess<br>from gensim.models import CoherenceModel# spaCy for preprocessing<br>import spacy# Plotting tools<br>import pyLDAvis<br>import pyLDAvis.gensim<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><h3>Prepare stopwords</h3><ul><li>You can extend the list of stopwords depending on the dataset you are using or if you see any stopwords even after preprocessing. You can also visualize your cleaned corpus using <a href="https://amueller.github.io/word_cloud/">wordcloud</a> and check if any words are adding noise or there are any stopwords still left out in the cleaned corpus.</li></ul><pre># NLTK Stop words<br>from nltk.corpus import stopwords<br>stop_words = stopwords.words(&#39;english&#39;)<br>stop_words.extend([&#39;from&#39;, &#39;subject&#39;, &#39;re&#39;, &#39;edu&#39;, &#39;use&#39;])</pre><h3>Load Dataset</h3><p>We will be 20-Newsgroups dataset. It contains about 11K news group post from 20 different topics. Dataset is available at <a href="https://raw.githubusercontent.com/selva86/datasets/master/newsgroups.json">newsgroup.json</a>.</p><pre># LoadDataset<br>df=pd.read_json(&#39;https://raw.githubusercontent.com/selva86/datasets/ master/newsgroups.json&#39;)<br>print(df.target_names.unique())<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*NdLWV5sHEGzfKR9t.png" /></figure><h3>Remove emails and newline characters</h3><ul><li>As you can see there are lot of emails and newline characters present in the dataset. Remove them using regular expression. Use<strong><em> </em>sub()</strong> of <strong>re</strong> module. IN <strong>re.sub()<em> </em></strong>specify a regular expression pattern in the first argument, a new string in the second argument, and a string to be processed in the third argument.</li></ul><pre><em># Convert to list</em> <br>data = df.content.values.tolist()  <br><em># Remove Emails</em> <br>data = [re.sub(&#39;\S*@\S*\s?&#39;, &#39;&#39;, sent) <strong>for</strong> sent <strong>in</strong> data]  <br><em># Remove new line characters</em> <br>data = [re.sub(&#39;\s+&#39;, &#39; &#39;, sent) <strong>for</strong> sent <strong>in</strong> data]  <br><em># Remove distracting single quotes</em> <br>data = [re.sub(&quot;<strong>\&#39;</strong>&quot;, &quot;&quot;, sent) <strong>for</strong> sent <strong>in</strong> data]  <br>pprint(data[:1])</pre><ul><li>The text still looks messy , carry on further preprocessing.</li></ul><h3>Tokenize words and cleanup the text</h3><p>Use gensims simple_preprocess(), set deacc=True to remove punctuations.</p><pre>def sent_to_words(sentences):<br>  for sentence in sentences:<br>    yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))            #deacc=True removes punctuations<br>data_words = list(sent_to_words(data))<br>print(data_words[:1])</pre><h3>Creating Bigram and Trigram models</h3><p>Bigrams are 2 words frequently occuring together in docuent. Trigrams are 3 words frequently occuring. Many other techniques are explained in <a href="https://medium.com/analytics-vidhya/natural-language-processing-using-spacy-in-python-part-1-ac1bc4ad2b9c"><strong>part-1</strong></a> of the blog which are important in NLP pipline, it would be worth your while going through that blog. The 2 arguments for <strong>Phrases<em> </em></strong>are<strong><em> </em>min_count<em> </em></strong>and <strong>threshold</strong>. The higher the values of these parameters , the harder its for a word to be combined to bigram.</p><pre># Build the bigram and trigram models<br>bigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) <strong># higher threshold fewer phrases.</strong><br>trigram = gensim.models.Phrases(bigram[data_words], threshold=100)<br># Faster way to get a sentence clubbed as a trigram/bigram<br>bigram_mod = gensim.models.phrases.Phraser(bigram)<br>trigram_mod = gensim.models.phrases.Phraser(trigram)<br># See trigram example<br>print(trigram_mod[bigram_mod[data_words[0]]])</pre><h3>Remove Stopwords, make bigrams and lemmatize</h3><ul><li>Using lemmatization instead of stemming is a practice which especially pays off in topic modeling because lemmatized words tend to be more human-readable than stemming.</li></ul><pre><em># Define function for stopwords, bigrams, trigrams and lemmatization</em><br><strong>def</strong> remove_stopwords(texts):<br>    <strong>return</strong> [[word <strong>for</strong> word <strong>in</strong> simple_preprocess(str(doc)) <strong>if</strong> word <strong>not</strong> <strong>in</strong> stop_words] <strong>for</strong> doc <strong>in</strong> texts]<br><br><strong>def</strong> make_bigrams(texts):<br>    <strong>return</strong> [bigram_mod[doc] <strong>for</strong> doc <strong>in</strong> texts]<br><br><strong>def</strong> make_trigrams(texts):<br>    <strong>return</strong> [trigram_mod[bigram_mod[doc]] <strong>for</strong> doc <strong>in</strong> texts]<br><br><strong>def</strong> lemmatization(texts, allowed_postags=[&#39;NOUN&#39;, &#39;ADJ&#39;, &#39;VERB&#39;, &#39;ADV&#39;]):<br>    <em>&quot;&quot;&quot;https://spacy.io/api/annotation&quot;&quot;&quot;</em><br>    texts_out = []<br>    <strong>for</strong> sent <strong>in</strong> texts:<br>        doc = nlp(&quot; &quot;.join(sent)) <br>        texts_out.append([token.lemma_ <strong>for</strong> token <strong>in</strong> doc <strong>if</strong> token.pos_ <strong>in</strong> allowed_postags])<br>    <strong>return</strong> texts_out</pre><h3>Call the functions in order</h3><pre><em># Remove Stop Words</em><br>data_words_nostops = remove_stopwords(data_words)<br><br><em># Form Bigrams</em><br>data_words_bigrams = make_bigrams(data_words_nostops)<br><br><em># Initialize spacy &#39;en&#39; model, keeping only tagger component (for efficiency)</em><br><em># python3 -m spacy download en</em><br>nlp = spacy.load(&#39;en&#39;, disable=[&#39;parser&#39;, &#39;ner&#39;])<br><br><em># Do lemmatization keeping only noun, adj, vb, adv</em><br>data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=[&#39;NOUN&#39;, &#39;ADJ&#39;, &#39;VERB&#39;, &#39;ADV&#39;])<br><br>print(data_lemmatized[:1])</pre><h3>Create Dictionary and Corpus needed for Topic Modeling</h3><ul><li>Make sure to check if dictionary[id2word] or corpus is clean otherwise you may not get good quality topics.</li></ul><pre><em># Create Dictionary</em> <br>id2word = corpora.Dictionary(data_lemmatized)  <br><em># Create Corpus</em> <br>texts = data_lemmatized  <br><em># Term Document Frequency</em> <br>corpus = [id2word.doc2bow(text) <strong>for</strong> text <strong>in</strong> texts]  <br><em># View</em> <br>print(corpus[:1])</pre><blockquote><em>[[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 5), (6, 1), (7, 1), (8, 2), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), (20, 2), (21, 1), (22, 1), (23, 1), (24, 1), (25, 1), (26, 1), (27, 1), (28, 1), (29, 1), (30, 1), (31, 1), (32, 1), (33, 1), (34, 1), (35, 1), (36, 1), (37, 1), (38, 1), (39, 1), (40, 1)]]</em></blockquote><ul><li>Gensim creates unique id for each word in the document. Its mapping of <strong>word_id</strong> and <strong>word_frequency</strong>. Example: (8,2) above indicates, word_id 8 occurs twice in the document and so on.</li><li>This is used as input to LDA model.</li></ul><p>If you want to see what word corresponds to a given<strong> id,</strong> then pass the id as a key to dictionary. Example: id2word[4].</p><ul><li>Readable format of corpus can be obtained by executing below code block.</li></ul><pre>[[(id2word[id], freq) for id, freq in cp] for cp in corpus[:1]]</pre><h3>Building topic model</h3><p><strong>&gt; Parameters of LDA</strong></p><ul><li><strong><em>Alpha</em></strong> and <strong><em>Beta</em></strong> are Hyperparameters — alpha represents document-topic density and Beta represents topic-word density, chunksize is the number of documents to be used in each training chunk, update_every determines how often the model parameters should be updated and passes is the total number of training passes.</li><li>A measure for best number of topics really depends on kind of corpus you are using, the size of corpus, number of topics you expect to see.</li></ul><pre>lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,<br>                                           id2word=id2word,<br>                                           num_topics=20, <br>                                           random_state=100,<br>                                           update_every=1,<br>                                           chunksize=100,<br>                                           passes=10,<br>                                           alpha=&#39;auto&#39;,<br>                                           per_word_topics=<strong>True</strong>)</pre><p>View topics in LDA model</p><ul><li>Each topic is combination of keywords and each keyword contributes a certain weightage to the topic.</li><li>You can see keywords for each topic and weightage of each keyword using <strong>lda_model.print_topics()</strong>.</li></ul><pre># Print the keyword of topics<br>pprint(lda_model.print_topics())<br>doc_lda = lda_model[corpus]</pre><p>Output: First 5 topics -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*FFx2MHkOo3w_1dT7.png" /><figcaption>Fig. First 5 topics</figcaption></figure><ul><li>You can see the top keywords and weights associated with keywords contributing to topic.</li><li>Topics are words with highest probability in topic and the numbers are the probabilities of words appearing in topic distribution.</li><li>But looking at keywords can you guess what the topic is?</li><li>You may summarize topic-4 as space(In the above figure). Each one may have different topic at particular number , topic 4 might not be in the same place where it is now, it may be in topic 10 or any number.</li></ul><h3>Evaluate topic models</h3><h4>Compute model Perplexity and <a href="https://rare-technologies.com/what-is-topic-coherence/">Coherence score</a></h4><ul><li>Coherence score and perplexity provide a convinent way to measure how good a given topic model is.</li></ul><pre><em># Compute Perplexity</em><br>print(&#39;<strong>\n</strong>Perplexity: &#39;, lda_model.log_perplexity(corpus))  <br><em># a measure of how good the model is. lower the better.</em><br><br><em># Compute Coherence Score</em><br>coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence=&#39;c_v&#39;)<br>coherence_lda = coherence_model_lda.get_coherence()<br>print(&#39;<strong>\n</strong>Coherence Score: &#39;, coherence_lda)</pre><p>Output:</p><ul><li>Lower the perplexity better the model.</li><li>Higher the topic coherence, the topic is more human interpretable.</li></ul><pre>Perplexity:  -8.348722848762439  <br>Coherence Score:  0.4392813747423439</pre><h3>Visualize the topic model</h3><pre><strong># Visualize the topics</strong><br>pyLDAvis.enable_notebook()<br>vis = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)<br>vis</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/0*IfkDAs9lFfGQvvZ6.png" /><figcaption>Fig. Visualizing topic model</figcaption></figure><p>Each bubble on the left-hand side represents topic. The larger the bubble, the more prevalent or dominant the topic is. Good topic model will be fairly big topics scattered in different quadrants rather than being clustered on one quadrant.</p><ul><li>The model with too many topics will have many overlaps, small sized bubbles clustered in one region of chart.</li><li>If you move the cursor the different bubbles you can see different keywords associated with topics.</li></ul><p><strong>How to find optimum number of topics ?</strong></p><ul><li>One approach to find optimum number of topics is build many LDA models with different values of number of topics and pick the one that gives highest coherence value.</li><li>If you see the same keywords being repeated in multiple topics, it’s probably a sign that the ‘k’ is too large.</li><li>Sometimes topic keyword may not be enough to make sense of what topic is about. So for better understanding of topics, you can find the documents a given topic has contributed the most to and infer the topic by reading the documents.</li><li>Finally, one needs to understand the volume and distribution of topics in order to judge how widely it was discussed.</li></ul><h3>Hope this blog was informative</h3><p><strong><em>Keep Learning………..</em></strong></p><h3>— — — — — — — Thank you — — — — — — —</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48eaa2344920" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/topic-modeling-using-gensim-lda-in-python-48eaa2344920">Topic Modeling using Gensim-LDA in Python</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[Similarity Queries and Text Summarization in NLP]]></title>
            <link>https://medium.com/swlh/similarity-queries-and-text-summarization-in-nlp-50ef4cf04f7b?source=rss-fff69debc77c------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ef4cf04f7b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Aravind CR]]></dc:creator>
            <pubDate>Sun, 14 Jun 2020 17:19:47 GMT</pubDate>
            <atom:updated>2020-06-21T04:39:16.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*32eJdPIYPulCkW7A-A1onw.jpeg" /></figure><p>Before diving directly into similarity queries it is important to know what a similarity metric is.</p><h3><strong>Similarity Metric</strong></h3><p>Similarity metrics are mathematical constructs which is particularly useful in NLP — especially information retrieval. <strong>We can understand a metric as a function that defines the distance between each pair of elements of a set or vectors.</strong> We can see how this can be useful — we can compare between how similar 2 documents would be based on the distance. If a lower value is returned by a distance function then it is known that 2 documents are similar and vice-versa.</p><p>We can technically compare any 2 elements in the set — this also means that we compare 2 sets of topics created by topic model (If you don’t know what a topic model is please do checkout my previous blog <a href="http://Topic Modeling using Gensim-LDA-Python">Topic modeling-LDA</a>)</p><p>Most of them would be aware of one distance metric — <strong>Eucledian metric</strong> . It a distance metric we come across in high school mathematics, and we would have likely seen it being used to calculate the distance between two points in a 2-dimensional space (XY).</p><p>Gensim, scikit-learn and most other ML packages recognize the importance of distance metric and have them implemented in their package.</p><h3><strong>Similarity queries</strong></h3><p>Its demostrated in the below implementation that we have the capability to compare between two documents, now its possible for us to set up an algorithm to extract out the most similar documents for an input query.</p><blockquote>Index each of the documents, then search for the lowest distance value returned between the corpus and the query, and return the documents with the lowest distance values — these would be most similar. Gensim has in-built structures to do this document similarity task.</blockquote><p>The tutorial on the <a href="https://radimrehurek.com/topic_modeling_tutorial/3%20-%20Indexing%20and%20Retrieval.html">Gensim </a>website performs a similar experiment, but on the Wikipedia corpus — it is a useful demonstration on how to conduct similarity queries on much larger corpuses and is worth checking if you are dealing with a very large corpus.</p><p>In the examples, we used LDA models for both distance calculation and to generate the index for the similarities. We can, however, use any vector representation of documents to generate this — it’s up to us to decide which one would be most effective for our use case.</p><p>Below attached notebook contains samples for both similarity metrics and queries and has detailed explanation for each and every step, run the cells in the notebook before moving to next topic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72e566d7df43aead168b55ac48bd2a66/href">https://medium.com/media/72e566d7df43aead168b55ac48bd2a66/href</a></iframe><h3><strong>Text Summarization</strong></h3><blockquote>Summarization is a process of distiling most important information form source or sources to produce an abridged version for a particular users and tasks.</blockquote><p>Text Summarization is a task of condensing piece of text into shortened form while preserving the meaning of the content and overall meaning. Text summarization is important because of the amount of textual data generated is increasing on another level day by day and it becomes difficult to read textual information and often people get bored to read large blocks of text. This is when text summarization came to rescue to make work easier for the readers.</p><p>The idea of text summarization is to find the subset of data which contains information of the entire set, but sometimes it results in loss of information.</p><p><strong>Main idea —</strong></p><ul><li>Text processing</li><li>Word frequency distribution — how many times each words appear in document.</li><li>Score each sentence depending on the words it contain and the frequency table.</li><li>Build summary by joining every sentence above a certain score limit.</li></ul><p><strong>2 approaches for text summarization are —</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*ab5nXaRDNbqJ1myK3Ui38Q.jpeg" /></figure><ul><li>Extractive summarization (selecting a subset of sentences / extracts objects from the entire collection).</li><li>Abstractive Summarization (paraphrases/Sentences generated might not be present in the original text).</li></ul><h3><strong>Summarizing text</strong></h3><p>In text analysis, it is useful to summarize large bodies of text — either to have brief overlook of the text before deeply analyzing it or identifying keywords from the text.</p><p><strong>We will not be working on building our own text summarization pipeline , but rather focus on using the built in summarization API wich gensim offers.</strong></p><p>Its also important to know that gensim dosen’t create it own sentences, but rather extracts key sentences from the text which we run the algoirthm on (Extractive summarization). The summarization is based on the text rank algorithm(A graph based ranking model for text processing).</p><blockquote>Graph-based ranking algorithms are essentially a way of deciding the importance of a vertex within a graph, based on global information recursively drawn from the entire graph. The basic idea implemented by a graph-based ranking model is that of “voting” or “recommendation”. When one vertex links to another one, it is basically casting a vote for that other vertex. The higher the number of votes that are cast for a vertex, the higher the importance of the vertex. Moreover, the importance of the vertex casting the vote determines how important the vote itself is, and this information is also taken into account by the ranking model. Hence, the score associated with a vertex is determined based on the votes that are cast for it, and the score of the vertices casting these votes(you can find this explanation in <a href="https://web.eecs.umich.edu/~mihalcea/papers/mihalcea.emnlp04.pdf">research paper</a>).</blockquote><h3><strong>Implementation</strong></h3><p>Run the cells in the notebook for clear understanding .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f5999ae7e61f1fea882166634820446/href">https://medium.com/media/4f5999ae7e61f1fea882166634820446/href</a></iframe><p>Above code sample contains extractive summarization of text. There are deep learning approaches and pretained models(which have achieved state-of-art-results) available for abstractive summarization of text, check out their implementation to dig-deep into the concept.</p><h4>A State-of-the-Art Model for Abstractive Text Summarization by Google AI.</h4><p>One of the recent research for abstractive text summarization where the model predicts the masked sentence for summarization.</p><blockquote>Paper: <a href="https://lnkd.in/gtaNRF7">https://lnkd.in/gtaNRF7</a></blockquote><blockquote>GitHub: <a href="https://lnkd.in/gKJJ2c9">https://lnkd.in/gKJJ2c9</a></blockquote><blockquote>Read more here: <a href="https://lnkd.in/g--hiY6">https://lnkd.in/g--hiY6</a></blockquote><ul><li>Experiments demonstrate it achieves state-of-the-art performance on 12 downstream datasets measured by <a href="https://en.wikipedia.org/wiki/ROUGE_(metric)#:~:text=The%20following%20five%20evaluation%20metrics,the%20system%20and%20reference%20summaries.">ROUGE</a> scores.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZXjZz6paDGETyNVzM1kgBA.gif" /><figcaption>A self-supervised example for PEGASUS during pre-training. The model is trained to output all the masked sentences.</figcaption></figure><h4><strong>Conclusion:</strong></h4><p>Throught the blog we saw how basic mathematical and information retrieval methods can be used to help identify how similar or dissimilar 2 documents are and how text summarization can come in handy for various tasks(Financial research, Question answering and bots, Medical cases, Books and literature, Email overload, Science and R&amp;D,Patent research, Helping disabled people, Programming languages,Automated content creation). Checkout the <a href="https://blog.frase.io/20-applications-of-automatic-summarization-in-the-enterprise/">applications of automatic summarization in enterprise</a>.</p><p>— — — — — — — — — — — Thank you — — — — — — — — — — —</p><p><strong>Sometimes later becomes never. So do it now.</strong></p><p><strong>Keep Learning……………………</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ef4cf04f7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/similarity-queries-and-text-summarization-in-nlp-50ef4cf04f7b">Similarity Queries and Text Summarization in NLP</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing using spaCy in Python(part-1)]]></title>
            <link>https://medium.com/analytics-vidhya/natural-language-processing-using-spacy-in-python-part-1-ac1bc4ad2b9c?source=rss-fff69debc77c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac1bc4ad2b9c</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Aravind CR]]></dc:creator>
            <pubDate>Tue, 31 Mar 2020 11:16:46 GMT</pubDate>
            <atom:updated>2020-06-15T14:20:57.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jDP1YC1BU3o7UnICGp5tQ.png" /></figure><p>This blog post gives you a brief idea about python library spaCy used for NLP in python.</p><p>This post includes various preprocessing and feature extraction techniques using open source NLP library spaCy written in python and cython used for advanced natural language processing.</p><p>Before feeding your data to machine learning algorithms we need to process the data so that it is understandable by machine learning algorithms.</p><p>Before diving directly into NLP , its important to know…..</p><h3><strong>What is Text Analysis?</strong></h3><p>Text analysis is the technique of gathering useful information from the text. The purpose of text analysis is to create<strong><em> structured data</em></strong> out of free text content.Text analysis is close to other terms like Text Mining, Text Analytics and Information Extraction<strong><em>(IE)</em></strong>.</p><p><strong>Garbage in, Garbage out(GIGO)</strong></p><p>GIGO is one of the important aspect when dealing with machine learning and even more when dealing with textual data. Garbage in, Garbage out means that, <strong><em>if we have poorly formatted data it is likely we will have poor results</em></strong><em>.</em></p><p>More data usually leads to better prediction, but it is not always true with text analysis, where more data can result in nonsense results. Examples might be <em>stop words</em>, these words are often removed from text before applying text analysis on them. In a similar way we remove words with high frequency in the body of text and words which may appear only once or twice-its highly likely that these words will not be useful for text analysis.</p><p>NLP techniques can also help us construct tools that can assist personal businesses or enterprizes, for example: chatbots are becoming increasingly common in major websites. This is largely due to subfield of <strong>machine learning</strong>, called <strong>Deep</strong> <strong>learning</strong>, where we use algorithms and structures that are inspired by the structure of human brain. These algorithms and structures are referred to as <strong>neural</strong> <strong>networks</strong>.</p><p>SpaCy is also one of the fastest NLP framework in python.</p><p>Install spaCy using the command:</p><blockquote>pip3 install spacy</blockquote><h3><strong>SpaCy’s Language models</strong></h3><p>One of the spaCy’s most interesting features is its language models. A language model is a statistical model that lets us perform NLP tasks such as POS-tagging and NER-tagging.</p><p>Download these models using:</p><blockquote>spacy download en # English model</blockquote><blockquote>spacy download de # German model</blockquote><blockquote>spacy download xx # multi-language model</blockquote><p>Download specific model for your spaCy installation:</p><blockquote>python3 -m spacy download en_core_web_sm</blockquote><p>Run the following command in your Python shell:</p><pre>import spacy<br>nlp = spacy.load(‘en_core_web_sm’)</pre><pre>doc = nlp(&#39;This is nlp with spaCy&#39;)</pre><p>We will be using spaCy’s language model to help us with preprocessing. Before getting into preprocessing steps , lets understand what happens when you run this:</p><pre>doc = nlp(&#39;This is nlp with spaCy&#39;)</pre><p>When you call NLP on text , spaCy first tokenizes the text to produce a <strong>Doc </strong>object. Doc is then is processed in several different steps, which we also refer to as pipeline.</p><figure><img alt="Fig. Default pipeline" src="https://cdn-images-1.medium.com/max/613/1*gP6Hm4OIjWwMz2rVHTaWJQ.png" /><figcaption>Fig. Default pipeline</figcaption></figure><p>Tokenizing is task of splitting sentence into meaningful segments called <strong>tokens</strong>. These segments could be words, punctuations, numbers or other special characters that are building blocks of sentence.</p><p>SpaCy’s default pipeline also preforms rule based matching. This annotates the text with more information and adds value during preprocessing.</p><p><strong>Preprocessing:</strong></p><p>With spaCy, stop words are easy to identify, each token has IS_STOP attribute, which lets us know if word is stopword or not.</p><p>We can add our on stopwords to list of stop words.</p><pre>stop_words = [&#39;say&#39;, &#39;said&#39;, &#39;it&#39;, &#39;an&#39;, &#39;none&#39;, &#39;all&#39;, &#39;saying&#39;]<br>for stopwords in stop_words:<br>  lexeme = nlp.vocab[stopwords]<br>  lexeme.is_stop = True</pre><p>Stop words can also be added using :</p><pre>from spacy.lang.en.stop_words import STOP_WORDS<br>print(STOP_WORDS) # SpaCy&#39;s default stop words<br>STOP_WORDS.add(&quot;your_additional_stopwords_here&quot;)</pre><p>If you have noticed <em>say, said, saying</em> provide the same information - gramatical difference aside, it wont affect the results.</p><p>Stemming and lemmatization are popular techniques. <strong>Stemming</strong> involves removing suffix in general. But often it may result in meaningless words. For example removing suffix from <strong>laziness </strong>will result in <strong>lazi</strong>, it dosen’t rely on parts of speech. Where as <strong>lemmatization</strong> on the other hand helps convert word into <strong>root word</strong>.</p><p>In spacy, the lemmatized form of word is accessed with the .<strong><em>lemma_</em></strong> attribute.</p><p>Lets check the sentence “<em>Real-time training during global emergencies is critical for effective preparedness and response.</em>”:</p><pre>doc = nlp(‘Real-time training during global emergencies is critical for effective preparedness and response. ‘)</pre><pre>sentence = []</pre><pre>for w in doc:</pre><pre>  # if it’s not a stop word or punctuation mark, add it to our     article!</pre><pre>  if w.text != ’n’ and not w.is_stop and not w.is_punct and not   w.like_num:</pre><pre>    # we add the lemmatized version of the word</pre><pre>    sentence.append(w.lemma_)</pre><pre>print(sentence)</pre><p>By using the .<strong>is_stop , is_punct ,</strong> and <strong>w.like_num </strong>attributes, we could remove the parts of the sentence we did not need.</p><p>Output would be:</p><pre>[&#39;real&#39;, &#39;time&#39;, &#39;training&#39;, &#39;global&#39;, &#39;emergency&#39;, &#39;critical&#39;, &#39;effective&#39;, &#39;preparedness&#39;, &#39;response&#39;]</pre><p>We can further remove or not remove words based in use-case.</p><h4><strong>Vectorizing text and transformations and n-grams</strong></h4><p>We can think of <strong><em>vectors</em></strong> as a way of projecting words onto mathematical space while preserving the information provided by these words. In machine learning this feature is called <strong><em>feature vector</em></strong> as each value corresponds to some feature, which are used to make predictions.</p><p>Some concepts for these vector representation are…</p><p><strong>Bag-of-words(BOW)</strong></p><p>It is one of the straight forward form of representing a sentence as a vector. For example:</p><pre>P1: “The dog sat near the door.”<br>P2: ”The bird likes grains.”</pre><p>Follow the same pre-processing steps mentioned above, the above sentences become:</p><pre>P1: “dog sat near door.”</pre><pre>P2: “birds like grains.”</pre><p>Vocabulary vector would be unique words from the sentences.</p><pre>vocab = [‘dog’, ‘sat’, ‘near’, ‘door’, ‘birds&#39;, &#39;like&#39;, &#39;grains&#39;]</pre><p>We can think of mapping each word in vocabulary to a number.</p><p><strong>BOW</strong> model use word frequencies to construct vectors. Now our sentence looks like..</p><pre>P1: [1, 1, 1, 1, 0, 0, 0]<br>P2: [0, 0, 0, 0, 1, 1, 1]</pre><p>There is 1 occurrence of word <em>dog</em> and 0 occurrence of word<em> birds, like and grains </em>in first sentence and so on.</p><h3>TF-IDF</h3><p><strong><em>Term frequency</em> and <em>inverse document frequency</em></strong><em> </em>is largely used in search engines to find relevant document based on the query. Imagine you have a search engine and someone looks for <em>Ronoldo</em>. The results will be displayed in the order of relevance. The most relevant sports articles will be ranked higher because TF-IDF gives the word <em>Ronoldo</em> a higher score.</p><pre>TF(t) = (number of times term t appears in a document) / (total    number of terms in the document)</pre><pre>IDF(t) = log_e (total number of documents / number of documents with term t in it)</pre><p>TF_IDF is simply the product of these 2 factors TF and IDF.</p><p>TF_IDF makes the rare words more prominent and ignore common words like is, or, an, that which may appear lot of time but may be less prominent.</p><p><strong>N-grams</strong></p><p>N-grams is the adjacent sequence of n-items in the text.</p><p>Bi-gram is one of the most popular n-gram. Removing stop words is necessary before running bigram model on your corpus or else there could be meaningless <strong>bi-gram</strong> formed.</p><p>For example: Machine Learning, Artificial Intelligence, New Delhi, Data Analytics, Big Data could be possible pairs of words created by bi-grams.</p><p>If you want to know more about n-grams refer the link(<a href="https://en.wikipedia.org/wiki/N-gram">ngrams</a>).</p><h3><strong>POS-Tagging</strong></h3><p>Parts-of-speech tagging is the process of tagging words in textual input with their appropriate parts of speech.</p><p><strong>POS-tagging with spacy</strong></p><p>This is one of the core feature loaded into the pipeline.</p><pre>import spacy<br>nlp = spacy.load(&#39;en_core_web_sm&#39;)</pre><pre>sent1 = nlp(&#39;Washing your hands with soap and water or using alcohol-based hand rub kills viruses that may be on your hands.&#39;)</pre><pre>sent2 = nlp(&#39;Antibiotics do not help, as they do not work against viruses.&#39;)</pre><pre>sent3 = nlp(u&#39;Marie took out her rather suspicious and fishy cat to gofish for fish.&#39;)</pre><pre>for token in sent2:<br>  print(token.text, token.pos_, token.tag_)</pre><p>output:</p><pre>Antibiotics NOUN NNS<br>do AUX VBP <br>not PART RB <br>help VERB VB <br>, PUNCT , <br>as SCONJ IN <br>they PRON PRP <br>do AUX VBP <br>not PART RB <br>work VERB VB <br>against ADP IN <br>viruses NOUN NNS <br>. PUNCT .</pre><p>As you can see, the words are tagged with appropriate parts of speech.</p><p>One important note, some words can be both noun or verb depending on context. Please do try out with the sentences where a word acts as noun in one and verb with other sentence and check if they are tagged with appropriate parts of speech. For example. ‘Marie took out her rather suspicious and fishy cat to go fish for fish.’</p><p>If you want to train your own pos-tagger, do check the link below….</p><p><a href="https://spacy.io/usage/training"><strong>Training spaCy’s Statistical Models</strong></a><strong>.</strong></p><h3><strong>NER-tagging</strong></h3><p>NER is Named Entity Recognition. A named entity is a real-world object with a proper name-for example India , Sunil Chetri, Google, Here India is a country and is identified as <strong>GPE</strong>(Geopolitical Entity), Sunil Chetri is <strong>PER</strong>(person), Google is an <strong>ORG</strong>(Organization).</p><p>This process involves finding named entities(people, place, organizations etc) from chunk of text and classify them into predefined set of categories.</p><p>SpaCy itself offers certain predefined set of entities. NER-tagging is not the end result , it end up being helpful for further tasks.</p><p>New Delhi is capital of India . NER-tagger would recognise New Delhi as palce (<strong>GPE</strong>), as well as India. Named entities can differ based on the context.</p><pre>import spacy<br>nlp = spacy.load(&#39;en_core_web_sm&#39;)<br>sentence = &#39;Uber eats India was acquired by Zomato for $350 million&#39;</pre><pre>doc = nlp(sentence)</pre><pre>for token in doc:<br>  print(token.text, token.ent_type_)</pre><p>Output:</p><pre>Uber<br>eats<br>India GPE<br>was<br>acquired<br>by<br>Zomato ORG<br>for<br>$ MONEY<br>350 MONEY<br>million MONEY</pre><p>For those words that were not identified as named entities , an empty string is returned. For example in the above output<em> eats, acquired</em> dosent refer to particular entity.</p><p>We can use displaCy to visualise our text,</p><pre>displacy.render(doc, style = &quot;ent&quot;,jupyter = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r7P6RA-VnBg80wPQ93_kmg.png" /><figcaption>Fig. Visualising parts-of-speech tags</figcaption></figure><h3><strong>Dependency parsing</strong></h3><p><em>Parsing </em>can be understood as a way to analyze a sentence or break up the sentence to understand the structure of the sentence. Parsing in NLP is determining the syntactic structure of text by analyzing its constituent words based on an underlying grammar.</p><p>As the title suggests <strong><em>dependency parsing </em></strong>refers to understanding the structure of a sentence via dependencies between words in a sentence. When a sentence is dependency parsed it would give us information about relationships between words in a sentence.</p><p>Parsers break up a sentence into a subject and an object which is noun phrase and a verb phrase. Dependency parser considers the verb as a head of sentence and all dependencies are built around it.</p><p>Example: The dog is faster than the cat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*AIzzeU9hhHL7QUcWwaAQ4Q.png" /><figcaption>Fig. Visualizing dependency parsing</figcaption></figure><p>The dog is noun phrase which is marked as <em>nsubj</em>, which refers to subject of sentence.<em> Acomp</em> means adjectival complement, which means that it is a phrase that modifies an adjective or adds to the meaning to an adjective. The word <em>than</em> is preposition , pobj here stands for object of prepositon, which is <em>the cat</em>.</p><pre>from spacy import displacy<br>nlp = spacy.load(‘en_core_web_sm’)<br>doc = nlp(u”displaCy uses JavaScript, SVG and CSS.”)<br>spacy.displacy.serve(doc, style=’dep’)</pre><p>The above code will run a web server. You can see the visualization by running <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000</a> in your browser.</p><p><strong>Conclusion:</strong></p><p>This blog gives brief idea about basic preprocessing techniques and feature extraction techniques such as BOW, TF_IDF, n-grams, POS-tagging, NER-tagging and dependency parsing in NLP pipeline . Next parts of the blog will contain topic modelling , text summarization ,Clustering and various word embedding techniques.</p><h3>References:</h3><p>-&gt; <a href="https://spacy.io/usage/processing-pipelines/">Spacy documentation</a>:</p><p>-&gt; Some part of the blog is written with reference of a book called <a href="https://www.packtpub.com/in/application-development/beginning-natural-language-processing">Natural language processing and computational linguistics</a> by Barghav Srinivasa Desikan.</p><p>— — — — — — — — — — —<em> </em><strong><em>Thank you</em></strong> — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac1bc4ad2b9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/natural-language-processing-using-spacy-in-python-part-1-ac1bc4ad2b9c">Natural Language Processing using spaCy in Python(part-1)</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>