<?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 Mahendramids on Medium]]></title>
        <description><![CDATA[Stories by Mahendramids on Medium]]></description>
        <link>https://medium.com/@mahendramids?source=rss-593e365cafe5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nb4P_WAHdpE1ao9YZEXC9w.jpeg</url>
            <title>Stories by Mahendramids on Medium</title>
            <link>https://medium.com/@mahendramids?source=rss-593e365cafe5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:08:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahendramids/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[Automatic Text Summarization]]></title>
            <link>https://medium.com/@mahendramids/automatic-text-summarization-caf6e98e31a6?source=rss-593e365cafe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/caf6e98e31a6</guid>
            <category><![CDATA[textrank]]></category>
            <category><![CDATA[extractive-summarization]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[pagerank]]></category>
            <category><![CDATA[text-summarization]]></category>
            <dc:creator><![CDATA[Mahendramids]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 13:27:51 GMT</pubDate>
            <atom:updated>2020-09-25T16:08:45.231Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Author</strong>: Saurabh Singh and Dr. Mahendra Nayak</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*dXec92FDLivvx83bHNqM9Q.png" /></figure><p>Text Summarization is the process of creating a short and coherent version of a long document by distilling the most important information.</p><p>In the business world, there are multiple use cases which need text summarization — we worked on a problem where users would upload knowledge sharing document on knowledge exchange portal without providing a brief description of the document. Missing description lead to lack of searchability of the document and hence we were asked auto generate a brief description of the document.</p><p>Below we have described one of the unsupervised approaches we tried. We also tried supervised approach to generate the summarized description, but that would be for another article. The implementation code is available on <a href="https://github.com/sxsing9/Text-Summarization/upload">GitHub</a>.</p><p>Essentially there are two approaches to text summarization:</p><ul><li>Extractive Methods — Extractive text summarization involves the selection of phrases and sentences from the source document to make up the new summary. Techniques involve ranking the relevance of sentences and phrases in order to choose only those most relevant to the meaning of the source.</li><li>Abstractive Methods — text summarization involves generating entirely new phrases and sentences to capture the meaning of the source document. This is a more challenging approach.</li></ul><p>We used the Extractive method using TextRank as it is very quick and easy to do and it met our purpose of creating a brief description using the most relevant sentences in the document.</p><p>TextRank summarization algorithm internally uses the popular PageRank algorithm, which is used by Google for ranking web sites and pages and measure their importance. The core algorithm in PageRank is a graph based scoring algorithm, where pages are scored or ranked based on their importance — the importance being determined by how many pages link to the page as well as importance of pages linking to the page. In case of TextRank, sentences, phrases are considered same as pages i.e. the vertex of the graph while the similarity between sentences, phrases are considered as weights / strength of the edges connecting the vertices. Using this, scores are calculated that identify the sentences that are most similar / representative of the document. In case you are interested in detailed explanation, refer to this <a href="https://www.analyticsvidhya.com/blog/2018/11/introduction-text-summarization-textrank-python/">AnalyticsVidhya </a>article that has a very easy to understand detailed explanation.</p><p>Following is the key steps of the approach / algorithm:</p><ul><li>Tokenize and extract sentences from the document to be summarized</li><li>Decide on the number of sentences K that we want in the summary</li><li>Build sentence term features matrix using methods like Bag of words, Tf-idf, word2vec, BERT etc. we used word2vec.</li><li>Compute sentence similarity matrix (using methods likes cosine similarity, WMD etc.) between each sentence combination present in the document. If there are N sentences, it will lead to creation of a NxN matrix with similarity scores.</li><li>Feed this matrix to PageRank algorith. Each sentence is the vertex, and similarity score is the edge.</li><li>Get score for each sentence</li><li>Rank the sentences based on score and return the top k.</li></ul><p>Having summarized the steps, let’s see the implementation</p><pre>import pandas as pd<br>import numpy as np<br>import re, os, string, time<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import nltk<br>from nltk.tokenize import sent_tokenizefrom bs4 import BeautifulSoup<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;words&#39;)<br>nltk.download(&#39;stopwords&#39;)<br>nltk.download(&#39;averaged_perceptron_tagger&#39;)<br>nltk.download(&#39;punkt&#39;)<br>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize<br>from nltk.corpus import wordnet<br>import timeit<br>stop_words = stopwords.words(&#39;english&#39;)<br>remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)<br>lemmer = nltk.stem.WordNetLemmatizer()news = pd.read_excel(r&#39;C:\Saurabh\Publication\tennis_articles.xlsx&#39;)<br>news</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*InFtLXHSmfUDkUmS" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4l8Q_eS29vecJkzK.png" /></figure><p>we are interested in article_text for summarization. Let’s clean the text.</p><pre>#define fucntions for deep cleaning - data normalization<br>def beauty(raw_text):<br>    res_text = BeautifulSoup(raw_text, &quot;html.parser&quot;).get_text() <br>    return res_textdef tokenize(text):<br>    result=sent_tokenize(text)<br>    result=[s for s in result if len(s)&gt;5]<br>    return result if len(result) else np.NaNdef get_wordnet_pos(word):<br>    &quot;&quot;&quot;Map POS tag to first character lemmatize() accepts&quot;&quot;&quot;<br>    tag = nltk.pos_tag([word])[0][1][0].upper()<br>    tag_dict = {&quot;J&quot;: wordnet.ADJ,<br>                &quot;N&quot;: wordnet.NOUN,<br>                &quot;V&quot;: wordnet.VERB,<br>                &quot;R&quot;: wordnet.ADV}<br>    return tag_dict.get(tag, wordnet.NOUN)def LemTokens(tokens):<br>    tokens = [token for token in tokens if token not in stop_words] <br>    return [lemmer.lemmatize(token, get_wordnet_pos(token)) for token in tokens]def LemNormalize(text):<br>     return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))def normalize(sent_list):<br>    return [&quot; &quot;.join(LemNormalize(s)) for s in sent_list]news[&#39;sentences&#39;] = news[&#39;article_text&#39;].apply(beauty)<br>news[&#39;sentences&#39;] = news[&#39;sentences&#39;].apply(tokenize)<br>news[&#39;lem_sentences&#39;]= news[&#39;sentences&#39;].apply(normalize)news[&#39;lem_sentences&#39;]0    [Maria Sharapova has basically no friends as t...<br>1    [BASEL, Switzerland (AP) — Roger Federer advan...<br>2    [Roger Federer has revealed that organisers of...<br>3    [Kei Nishikori will try to end his long losing...<br>4    [Federer, 37, first broke through on tour over...<br>5    [Nadal has not played tennis since he was forc...<br>6    [Tennis giveth, and tennis taketh away., The e...<br>7    [I PLAYED golf last week with Todd Reid., He p...<br>Name: sentences, dtype: object</pre><p>We have the cleaned, stop words excluded, lemmatized sentences. Now let’s convert the sentences into vector. We will use the spaCy word2vec pre-trained model.</p><pre>def getVector(sentences):<br>    sentences_v = []<br>    for s in sentences:<br>        doc = nlp(s)<br>        sentences_v.append(doc.vector)<br>    return sentences_vnews[&#39;sentences_vector&#39;]= news[&#39;lem_sentences&#39;].apply(getVector)<br>len(news[&#39;sentences_vector&#39;][1])12</pre><p>Now we will create the similarity matrix between the sentences by calculating distance between the vectors using cosine similarity</p><pre>from sklearn.metrics.pairwise import cosine_similarity<br>def getMatrix(sentences_vector):<br>    similarity_matrix = np.zeros([len(sentences_vector), len(sentences_vector)])<br>    for i in range(len(sentences_vector)):<br>        for j in range(len(sentences_vector)):<br>            similarity_matrix[i,j] = cosine_similarity(sentences_vector[i].reshape(1,300), sentences_vector[j].reshape(1,300))[0,0]<br>            #similarity_matrix[i,j] = sentences_vector[i].similarity(sentences_vector[j])return similarity_matrixnews[&#39;similarity_matrix&#39;]= news[&#39;sentences_vector&#39;].apply(getMatrix)news[&#39;similarity_matrix&#39;][1].shape(19, 19)</pre><p>Time to feed the similarity matrix to the pageRank algorithm and score the sentences</p><pre>import networkx as n<br>graph = n.from_numpy_array(news[&#39;similarity_matrix&#39;][1])<br>n.draw_networkx(graph,arrows=True,with_labels=True)def getPageRank(similarity_matrix):<br>    graph = n.from_numpy_array(similarity_matrix)<br>    page_rank = n.pagerank(graph)<br>    return page_ranknews[&#39;page_rank&#39;]= news[&#39;similarity_matrix&#39;].apply(getPageRank)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*pTiEM7zjTtGL6S7r.png" /></figure><p>We draw the graph, nodes are sentences and edge between them is the similarity. We have the rank score, let’s get the top 5 sentences</p><pre>def getSummary(row):<br>    dict = {}<br>    #print(row)<br>    for i,s in enumerate(row[&#39;sentences&#39;]):<br>        dict[s] = row[&#39;page_rank&#39;].get(i) <br>    df = pd.DataFrame.from_dict(dict, orient=&#39;index&#39;, columns=[&#39;page_rank&#39;]).reset_index().sort_values([&#39;page_rank&#39;], ascending=False)<br>    return list(df[&#39;index&#39;].head(5))news[&#39;summary&#39;] = news.apply(lambda x: getSummary(x), axis=1)news[&#39;summary&#39;][2]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*EiJwVFqBUZ8a-PP7" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y9FdXS9k54P161i9.png" /></figure><p>This is a decent, I would not say perfect, summary of the article_text without much effort. Depending on the use case, this summarization might be sufficient to meet the need. You could also apply few more optimization to make this summary more meaningful — one simple next step we could do, specially in this use case of news article is apply name entity recognition and of the Top N, prioritize the sentence with person name as the first sentence to display. Can you think of some more?</p><p>That’s all on Text summarization, if you liked it do clap.</p><h3>About Authors</h3><p><strong>Mr. Saurabh Singh </strong>and <strong>Dr. Mahendra Nayak </strong>are<strong> </strong>principal data scientists at Accenture Applied Intelligence, Bangalore. They primarily work on Large unstructured Data, predictive modeling, machine learning, and building enterprise-scale intelligent systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caf6e98e31a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>