<?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 Ajit Rajput on Medium]]></title>
        <description><![CDATA[Stories by Ajit Rajput on Medium]]></description>
        <link>https://medium.com/@ajit.rajput?source=rss-85de2049e1ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LFcj7UzR9m4610k9</url>
            <title>Stories by Ajit Rajput on Medium</title>
            <link>https://medium.com/@ajit.rajput?source=rss-85de2049e1ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:07:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajit.rajput/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[Clustering City Nightlife using Machine Learning]]></title>
            <link>https://medium.com/@ajit.rajput/clustering-city-nightlife-using-machine-learning-d96e6b5a36f9?source=rss-85de2049e1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/d96e6b5a36f9</guid>
            <category><![CDATA[party]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[nightlife]]></category>
            <dc:creator><![CDATA[Ajit Rajput]]></dc:creator>
            <pubDate>Wed, 15 Sep 2021 13:01:00 GMT</pubDate>
            <atom:updated>2021-09-15T13:01:00.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQvLqQ-ofFQfTkcQgNfJvw.jpeg" /></figure><p>KMeans Clustering using Foursquare API</p><h3>Introduction</h3><p>Everyone knows how Covid-19 pandemic devastated the nightlife industry with social distancing, lockdowns, mask-wearing and early curfews. These nightlife spaces were shuttered because they had been deemed non-essential services and places of easy transmission for the coronavirus. Now that central and state governments in India have eased the restrictions people can finally enjoy a breather, commemorating a special occasion or just spending time with friends over food and drinks.</p><p>In a city like Pune, which boasts a happening nightlife scene, there’s always a party happening somewhere or the other. Widely known as the “IT hub of India”, “Automobile and Manufacturing hub of India” and “Oxford of the East”, Pune is known for its lifestyle, pleasant weather and just… everything good. With escalating number of pubs, bars, lounges and similar hangout joints, night life in Pune has become ever more exciting. There are many bars, clubs, pubs in Pune for couples, groups of friends, as well as night owls.</p><p>For any new visitor in Pune, it can be difficult to figure out where they should hang out for party and drinks. With this article we will aim to cluster the city into areas or suburbs having high concentration of bars and pubs</p><h3>Neighborhood Exploration</h3><p>For clustering we will require list of neighborhoods of Pune and their latitude and longitude.</p><h4>Get the Neighbors</h4><p>Wikipedia is great source of information. The list of neighborhoods of Pune was scraped using Python’s BeautifulSoup library from the given Wikipedia page.</p><pre>data = requests.get(&quot;<a href="https://en.wikipedia.org/wiki/Category:Neighbourhoods_in_Pune">https://en.wikipedia.org/wiki/Category:Neighbourhoods_in_Pune</a>&quot;).text</pre><pre>soup = BeautifulSoup(data, &#39;html.parser&#39;)</pre><pre>neighbors = []<br>for row in soup.find_all(&quot;div&quot;,  {&quot;class&quot;: &quot;mw-category&quot;})[0].findAll(&quot;li&quot;):<br>    neighbors.append(row.text)<br>    <br>#Create a new DataFrame from the list<br>df_neighbors = pd.DataFrame({&quot;neighbor&quot;: neighbors})</pre><pre>df_neighbors = df_neighbors.drop(labels=[26,32,39, 40], axis=0)<br>df_neighbors.reset_index(drop=True)</pre><h4>Fetch the Neighbor Co-ordinates</h4><p>Next, using <a href="https://pypi.org/project/geocoder/"><strong>geocoder</strong></a><strong> </strong>python library, we will fetch the latitude and longitude of each neighborhood.</p><pre>## Function to fetch the geo coordinates for the locations<br>def getNeighborCoords(neighbor):<br>    lat_lng_coords = None<br>    <br>    while(lat_lng_coords is None):<br>        geo = geocoder.arcgis(&#39;{}, Pune, India&#39;.format(neighbor))<br>        lat_lng_coords = geo.latlng<br>    <br>    return lat_lng_coords</pre><p>Using the above function we will fetch the co-ordinates for each of the neighborhood areas. The resultant output from the function is mapped as new columns i.e. ‘latitude’ and ‘longitude</p><pre>coords = [ getNeighborCoords(neighbor) for neighbor in df_neighbors[&quot;neighbor&quot;].tolist()]</pre><pre>## Map the latitude and longitude retuned from the function <br>df_neighbors[&#39;latitude&#39;], df_neighbors[&#39;longitude&#39;] = zip(*coords)</pre><p>Our final dataframe now has the neighbor and its corresponding latitude and longitude co-ordinates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*3hN-Hgs14wNQDNHyZex47w.png" /></figure><p>Let’s see how our neighbors look on a map. I have used the <em>geopy </em>and <em>folium </em>library to create a map of Pune with our neighbor coordinates superimposed on top.</p><pre>## center of pune<br>pune_center = [18.5204303, 73.8567437]</pre><pre>## plot the neighbors on the map using Folium library</pre><pre>map_pune = folium.Map(location=pune_center, zoom_start=11)</pre><pre>for neighbor, lat, lon in  zip(df_neighbors[&#39;neighbor&#39;],df_neighbors[&#39;latitude&#39;],df_neighbors[&#39;longitude&#39;]):<br>    label = &#39;{}&#39;.format(neighbor)<br>    label = folium.Popup(label, parse_html=True)<br>    folium.CircleMarker([lat, lon], radius=5, color=&#39;black&#39;, fill_color=&#39;blue&#39;, fill_opacity=0.25, popup=label, fill=True).add_to(map_pune)<br>    <br>map_pune</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGzPW8wpb42WM-JMhyUrgA.png" /></figure><h3>Venues Exploration</h3><p>Now that we have the neighborhoods of Pune, with its respective latitude and longitude information, let us fetch the surrounding venues within specified radius (km)</p><h4>Fetch the Venues</h4><p><a href="https://developer.foursquare.com/">Foursquare API</a>, a social location service allows users to discover about businesses and attractions. As we are trying to find bars venues, I added the category ID ‘<em>4bf58dd8d48988d116941735</em>’ as part of the API request URL. I have defined the limit of venues returned to be 100 within radius of 1 km.</p><pre>url = &#39;<a href="https://api.foursquare.com/v2/venues/explore?&amp;client_id={}&amp;client_secret={}&amp;categoryId=4bf58dd8d48988d116941735&amp;v={}&amp;ll={},{}&amp;radius={}&amp;limit={}&amp;offset={}&#39;.format(">https://api.foursquare.com/v2/venues/explore?&amp;client_id={}&amp;client_secret={}&amp;categoryId=4bf58dd8d48988d116941735&amp;v={}&amp;ll={},{}&amp;radius={}&amp;limit={}&amp;offset={}&#39;.format(</a><br>            CLIENT_ID, <br>            CLIENT_SECRET, <br>            VERSION, <br>            latitude, <br>            longitude, <br>            RADIUS, <br>            LIMIT, offset)</pre><p>With the Foursquare API call, we fetched around 168 venues</p><h4>Data Engineering</h4><p>With our extracted information of nearby bar venues, we can merge this into a new data frame containing our neighbor information. Also, from this new dataframe, we will drop neighbors that do not have any venues returned i.e. drop NA records.</p><pre>df_Venues = getNearbyVenues(df_neighbors[&#39;neighbor&#39;],df_neighbors[&#39;latitude&#39;],df_neighbors[&#39;longitude&#39;])</pre><pre>df_Venues.dropna(how=&#39;any&#39;, inplace=True)<br>df_Venues.reset_index(drop=True, inplace=True)<br>df_Venues.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*KfgoLPcKwNnUnhN7ngGBrw.png" /></figure><p>Next, within the defined radius of 1km, there are high chances of Foursquare API returning same venues for neighbors which are in close proximity. Let’s find and drop the duplicate venues. In this process we will keep the “first” occurrence of the duplicate records and delete the rest.</p><pre>df_Venues.drop_duplicates(subset=[&#39;name&#39;,&#39;categories&#39;,&#39;lat&#39;,&#39;lng&#39;], keep=&#39;first&#39;, inplace=True)</pre><p>This resulted into deleting duplicate venues and we are left with 113 venues now. So far, great ! Now lets explore the unique venues returned by the Foursquare API</p><pre>df_Venues[&#39;categories&#39;].unique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*E3Ca8Gmg1KCLMSOEC6irOw.png" /><figcaption>Unique list of venues</figcaption></figure><p>You see that the unique list includes all sorts of venues including <em>Juice Bars</em>, <em>Falafel Restaurants</em>, <em>Jazz Club</em>, <em>Cafe</em> etc. Though not sure if all of these venues serve alcohol, but for sake of simplicity and better clustering let’s just focus on few known venue categories.</p><pre>## filter out only Bars from the fetched venues</pre><pre>df_hotels = df_Venues[df_Venues[&#39;categories&#39;].isin([&#39;Bar&#39;, &#39;Hotel Bar&#39;,&#39;Pub&#39;, &#39;Cocktail Bar&#39;, Lounge&#39;,&#39;Sports Bar&#39;, &#39;Gastropub&#39;,&#39;Brewery&#39;,&#39;Distillery&#39;]) ]<br>df_hotels.reset_index(drop=True, inplace=True)</pre><pre>## rearrange and rename the columns<br>df_hotels.columns=[&#39;neighbor&#39;,&#39;latitude&#39;,&#39;longitude&#39;,&#39;venue&#39;,&#39;category&#39;,&#39;venue_lat&#39;,&#39;venue_lon&#39;]<br>df_hotels.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*KexWudWzOHzcxMLB6V1fBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xn3NeNOUbpQf6aEiKQFFNw.png" /></figure><h3>Clustering Neighbors and Venues</h3><p>With the neighbors and venues data in place with all data engineering tasks completed, lets now get onto clustering.</p><p>We will first apply one-hot encoding technique on the ‘category’ column; take mean frequency for each venue category and finally perform the K-Means clustering, an unsupervised learning algorithm used to create <em>K</em> clusters of data points based on feature similarity.</p><pre>## one-hot encode the category<br>df_hotels_OHE = pd.get_dummies(df_hotels[&#39;category&#39;], prefix=&#39;&#39;, prefix_sep=&#39;&#39;)<br>df_hotels_OHE[&#39;neighbor&#39;] = df_hotels[&#39;neighbor&#39;]</pre><pre>## rearrange the columns with &#39;neighbor&#39; as first column.</pre><pre>fixed_columns = [df_hotels_OHE.columns[-1]] + list(df_hotels_OHE.columns[:-1])<br>df_hotels_OHE = df_hotels_OHE[fixed_columns]</pre><pre>df_hotels_grouped = df_hotels_OHE.groupby(&#39;neighbor&#39;).mean().reset_index()</pre><pre>df_hotels_grouped.head()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*tiTuKCPjM0QzZlJ8yhdn8A.png" /></figure><p>Using this grouped data frame, we will drop the neighbor column and apply <em>K-means</em> clustering technique to arrive at optimal ‘k’ value. Looking at the elbow method and silhouette score, it appears that the optimal number of clusters to use is <em>K = 8</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*3iR3j5fXHZSAEFN89TeE1A.png" /></figure><p>Now, lets perform the actual K-Means Clustering using k=8 on the dataset and map cluster labels to the each neighbor.</p><pre>kclusters <strong>=</strong> 8 </pre><pre>x <strong>=</strong> df_hotels_grouped.drop([&#39;neighbor&#39;], 1)​</pre><pre><em># run k-means clustering</em></pre><pre>kmeans <strong>=</strong> KMeans(n_clusters<strong>=</strong>kclusters, random_state<strong>=</strong>0).fit(x)​</pre><pre>df_hotels_merged[&quot;cluster&quot;] <strong>=</strong> kmeans.labels_</pre><pre>df_clustered <strong>=</strong> pd.merge(df_hotels, df_hotels_merged[[&#39;neighbor&#39;,&#39;cluster&#39;]] ,on<strong>=</strong>[&quot;neighbor&quot;])</pre><p>To visualize how the clusters are formed, lets again plot map of neighbors and their cluster-labels with unique color-coding.</p><pre>occurences = folium.map.FeatureGroup()<br>map_clusters = folium.Map(location=pune_center, zoom_start=11)</pre><pre># Setting color scheme for the clusters<br>x = np.arange(kclusters)<br>ys = [i+x+(i*x)**2 for i in range(kclusters)]</pre><pre>colors_array = cm.rainbow(np.linspace(0, 1, len(ys)))<br>rainbow = [colors.rgb2hex(i) for i in colors_array]</pre><pre>for lat, lon, poi, cluster in zip(df_clustered[&#39;latitude&#39;], df_clustered[&#39;longitude&#39;],                                df_clustered[&#39;neighbor&#39;], df_clustered[&#39;cluster&#39;]):<br>    <br>    label = folium.Popup(str(poi) + &#39; - Cluster &#39; + str(cluster), parse_html=True)<br>    <br>    folium.CircleMarker([lat,lon],<br>                        radius=5,<br>                        popup=label,<br>                        color=rainbow[cluster-1],<br>                        fill=True,<br>                        fill_color=rainbow[cluster-1],<br>                        fill_opacity=1,<br>                        icon = folium.Icon(icon=&#39;beer&#39;, prefix=&#39;fa&#39;)).add_to(map_clusters)</pre><pre>map_clusters</pre><p>Below is the map displaying the clusters for different neighborhoods. The data points in different colors are the clustered areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*OYDE3adg8ym1442-I23Kbw.png" /></figure><p>To better understand how the neighborhood has been clustered, lets visualize it in a bar chart plot. As you see, there are 8 clusters and the plot shows clustered neighbors according to their count of venues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1CV5R9_9wRmlg_NkYd7tA.png" /></figure><p>To further explore and an additional insight into clustering, here is the heat-map of the clustered neighbors. If you see the area — Vimannagar is showing strong density whereas central Pune areas with medium density.</p><pre>df_neighbor_HM = df_clustered.groupby([&#39;neighbor&#39;,&#39;latitude&#39;,&#39;longitude&#39;])[&#39;category&#39;].count().reset_index()</pre><pre>pune_latlons = df_neighbor_HM[[&#39;latitude&#39;,&#39;longitude&#39;,&#39;category&#39;]]</pre><pre>pune_map = folium.Map(location=pune_center, zoom_start=10)<br>folium.TileLayer(&#39;cartodbpositron&#39;).add_to(pune_map) #cartodbpositron cartodbdark_matter<br>HeatMap(pune_latlons, blur=10).add_to(pune_map)</pre><pre>folium.Marker(pune_center).add_to(pune_map)</pre><pre>pune_map</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAlCEztJk4JQSahZ7Etviw.png" /></figure><p>Lets also plot heatmap for the different venues as well to see how these are placed on the geographical map.</p><pre>pune_latlons = df_clustered[[&#39;venue_lat&#39;,&#39;venue_lon&#39;]]</pre><pre>pune_map = folium.Map(location=pune_center, zoom_start=13)<br>folium.TileLayer(&#39;cartodbpositron&#39;).add_to(pune_map) #cartodbpositron cartodbdark_matter<br>HeatMap(pune_latlons, blur=20).add_to(pune_map)</pre><pre>folium.Circle(pune_center, radius=2000, fill=False, color=&#39;white&#39;).add_to(pune_map)<br>folium.Circle(pune_center, radius=4000, fill=False, color=&#39;white&#39;).add_to(pune_map)</pre><pre>pune_map</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEqDM6uk51qbLI7scrIBRQ.png" /></figure><h3>Conclusion</h3><p>To conclude, we used K-means clustering which created 8 different clusters for Pune neighbors which are populated with nightlife venues around them. A good number of night-life venues are densely populated (within 1km radius) around Vimannagar, KalyaniNagar. These neighborhoods are in close proximity to IT hubs and hence these venues are good revenue earning sources.</p><p>Additionally, if you see the central Pune, Camp areas also have good number of nightlife party venues. Surprisingly, the Pimpri-Chinchwad, Baner, Wakad areas which are close to Hinjewadi Park (major IT Hub) appear not to have many venues. This could be probably because of the neighborhood data/locations OR not many places/venues registered on Foursquare.</p><p>So, if you are visiting Pune for first time OR planning a party, you can use this map to get a good idea of where to binge.</p><p><strong>Happy Partying ! Drink Responsibly</strong> 🍻 🍸 🍷</p><p>I hope you found the article insightful. I would love to hear feedback to improvise it and come back with better content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d96e6b5a36f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Long story short... An NLP use-case on Text Summarization]]></title>
            <link>https://medium.com/codex/long-story-short-an-nlp-use-case-on-text-summarization-2752a7daa5f7?source=rss-85de2049e1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2752a7daa5f7</guid>
            <category><![CDATA[summarization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[Ajit Rajput]]></dc:creator>
            <pubDate>Wed, 28 Jul 2021 12:23:37 GMT</pubDate>
            <atom:updated>2021-07-31T11:49:09.963Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_UwWKYiMdGv9IR3h6FyBQ.jpeg" /></figure><h3>Long story short.. An NLP use-case on Text Summarization</h3><p>In this fast paced age, we all want to keep ourselves updated on the daily happenings across the globe, but there are very few people who get that luxury. As for reading newspapers and articles, skimming is the point i.e. run through the headlines first and then jump into it only if its interesting or worth reading. Especially when the content is available on click of a button, we all prefer glance at “summarized” news aggregated from popular newspapers, websites, blogs, and magazines; delivered in three to four sentences — rather than reading lengthy, and at times overrated and exaggerated writings in newspaper.</p><blockquote>Text summarization which comes under AI has been an important research area that identifies the relevant sentences from a piece of text. By Text Summarization, we can get short and precise information by preserving the contents of the text.</blockquote><p>Google News, Inshorts, Pulse are some of the news aggregator apps take advantage of text summarization algorithms. In this post, I will take you through various traditional and advanced methods to implement automatic Text Summarization</p><p>Text Summarization is broadly divided into two classes — Extractive Summarization and Abstractive Summarization.</p><ul><li><strong>Extractive summarization</strong> — This is traditional method which picks up sentences directly from the original document depending on their importance. Note that the summary obtained contains exact sentences from the original text.</li><li><strong>Abstractive summarization —</strong> Abstractive summarization is closer to what a human usually does — i.e. conceive the text, compare it with his/her memory and related information, and then re-create its core in a brief text. That is why the abstractive summarization is more challenging than the extractive method, as the model should break the source corpus apart to the very tokens and regenerate the target sentences. Achieving meaningful and grammatically correct sentences in the summaries is a big deal that demands highly precise and sophisticated models.</li></ul><p>In the next sections, let’s explore the extractive and abstractive methods which you can compare and familiarize with advantages and limitations of each method.</p><p>Consider this extract on Tesla’s quarterly results from an business news website</p><pre>text = &quot;&quot;&quot;<br>Tesla reported second-quarter earnings after the bell Monday, and it’s a beat on both the top and bottom lines. Shares rose about 2% after-hours. Here are the results.</pre><pre>Earnings: $1.45 vs 98 cents per share adjusted expected, according to Refinitiv. Revenue: $11.96 billion vs $11.30 billion expected, according to Refinitiv</pre><pre>Tesla reported $1.14 billion in (GAAP) net income for the quarter, the first time it has surpassed $1 billion. In the year-ago quarter, net income amounted to $104 million.</pre><pre>Overall automotive revenue came in at $10.21 billion, of which only $354 million, about 3.5%, came from sales of regulatory credits. That’s a lower number for credits than in any of the previous four quarters. Automotive gross margins were 28.4%, higher than in any of the last four quarters.</pre><pre>Tesla had already reported deliveries (its closest approximation to sales) of 201,250 electric vehicles, and production of 206,421 total vehicles, during the quarter ended June 30, 2021.</pre><pre>The company also reported $801 million in revenue from its energy business, including solar photovoltaics and energy storage systems for homes, businesses and utilities, an increase of more than 60% from last quarter. While Tesla does not disclose how many energy storage units it sells each quarter, in recent weeks CEO Elon Musk said, in court, that the company would only be able to produce 30,000 to 35,000 at best during the current quarter, blaming the lag on chip shortages. Tesla also reported $951 million in services and other revenues. The company now operates 598 stores and service centers, and a mobile service fleet including 1,091 vehicles, an increase of just 34% versus a year ago. That compares with an increase of 121% in vehicle deliveries year over year. A $23 million impairment related to the value of its bitcoin holdings was reported as an operating expense under “Restructuring and other.”<br>&quot;&quot;&quot;</pre><p>Let’s start with installing and importing the libraries required to run the summarization process using different methods.</p><pre>!pip install bert-extractive-summarizer<br>!pip install spacy<br>!pip install transformers<br>!pip install torch<br>!pip install sentencepiece</pre><p>Import the libraries</p><pre>import gensim</pre><pre>from gensim.summarization import summarize</pre><pre>import torch</pre><pre>from transformers import pipeline<br>from transformers import T5Tokenizer<br>from transformers import T5ForConditionalGeneration<br>from transformers import T5Config</pre><pre>from summarizer import Summarizer<br>from summarizer import TransformerSummarizer</pre><h4>Summarization using Gensim (Text Rank)</h4><p>gensim package is used for natural language processing and information retrievals tasks such as topic modeling, document indexing, word2vec, and similarity retrieval. Here we are using it for text summarization using TextRank algorithm.</p><p>TextRank is an extractive and unsupervised text summarization technique, based on the concept that words which occur more frequently are significant. Hence, the sentences containing highly frequent words are important . Based on this, the algorithm assigns scores to each sentence in the text. The top-ranked sentences then make it to the summary.</p><p>Let us use the gensim’ssummarize function using different summarizing parameters given below</p><ol><li>ratio: It can take values between 0 to 1. It represents the proportion of the summary compared to the original text.</li><li>word_count: It decides the no of words in the summary.</li></ol><p><strong>Summarize by Ratio :</strong></p><pre>summary_by_ratio = summarize(text, ratio=0.15) <br>print(&quot;Summary : \n&quot; + summary_by_ratio)</pre><pre><strong>Output &gt;&gt;&gt;</strong></pre><pre>Summary :  The company also reported $801 million in revenue from its energy business, including solar photovoltaics and energy storage systems for homes, businesses and utilities, an increase of more than 60% from last quarter. Tesla also reported $951 million in services and other revenues.</pre><p><strong>Summarize by Word Count</strong></p><pre>summary_by_count=summarize(text, word_count=60)<br>print(&quot;Summary : &quot; + summary_by_count)</pre><pre><strong>Output &gt;&gt;&gt;</strong></pre><pre>Summary : Overall automotive revenue came in at $10.21 billion, of which only $354 million, about 3.5%, came from sales of regulatory credits. The company also reported $801 million in revenue from its energy business, including solar photovoltaics and energy storage systems for homes, businesses and utilities, an increase of more than 60% from last quarter. Tesla also reported $951 million in services and other revenues.</pre><h3>Abstractive Summarization with pre-trained models</h3><p>Here we use transformers library in Python to perform abstractive text summarization on the input text. All the documentation for the transformers library can be found on this website: <a href="https://huggingface.co/transformers/">https://huggingface.co/transformers/</a></p><p>Let us now explore summarization techniques using below methods.</p><ul><li>Pipeline API</li><li>T5 Transformer</li><li>BERT</li><li>GPT2</li><li>XLNet</li></ul><h3>Summarization using Pipeline API</h3><p>The most straightforward way to use models in transformers is using the pipeline API. The pipelines are a great and easy way to use models for inference. These pipelines are objects that abstract most of the complex code from the library, offering a simple API dedicated to several tasks, including Named Entity Recognition, Masked Language Modeling, Sentiment Analysis, Feature Extraction and Question Answering</p><p>The models that this pipeline can use are models that have been fine-tuned on a summarization task, which is currently, ‘bart-large-cnn’, ‘t5-small’, ‘t5-base’, ‘t5-large’, ‘t5–3b’, ‘t5–11b’</p><p>Run the Summarization pipeline with default model</p><pre>summarization = pipeline(&quot;summarization&quot;)</pre><pre>## Call the transformer&#39;s summarization api by passing text</pre><pre>abstract_text = summarization(text)[0][&#39;summary_text&#39;]<br>print(&quot;Summary:&quot;, abstract_text)</pre><p>Note: The first time you execute this or any of the techniques listed, it make take a while to download the model architecture and the weights, as well as tokenizer configuration in some cases.</p><p>Here is the summary generated after executing the above pipeline code</p><pre><strong>Output &gt;&gt;&gt;</strong></pre><pre>Summary:  Tesla reported $1.14 billion in (GAAP) net income for the quarter, the first time it has surpassed $1 billion . The company also reported $801 million in revenue from its energy business, including solar photovoltaics and energy storage systems . Shares rose about 2% after-hours .</pre><p>The abstractive summary generated looks pretty decent, isn’t it !</p><p>Run the same pipeline by explicitly passing the t5-base model</p><pre>## setup the pipeline with t5-base model<br>t5summarizer = pipeline(&quot;summarization&quot;, model=&quot;t5-base&quot;, tokenizer=&quot;t5-base&quot;, framework=&quot;tf&quot;)</pre><pre>## Build the summary with min 5 and max 60 words<br>t5summarizer(text, min_length=5, max_length=60)</pre><pre><strong>Output &gt;&gt;&gt;</strong></pre><pre>Summary: Tesla reported $1.45 vs 98 cents per share adjusted expected, according to Refinitiv . overall automotive revenue came in at $10.21 billion, of which only $354 million, about 3.5%, came from sales of regulatory credits</pre><h3>Summarization with T5 Transformer</h3><p>T5 is an encoder-decoder model pre-trained on a multi-task mixture of unsupervised and supervised tasks and for which each task is converted into a text-to-text format. T5 works well on a variety of tasks out-of-the-box by prepending a different prefix to the input corresponding to each task</p><p>Instantiate the pretrained “t5-small” model through from_pretrained method.</p><pre>t5model = T5ForConditionalGeneration.from_pretrained(&#39;t5-small&#39;)</pre><pre>t5tokenizer = T5Tokenizer.from_pretrained(&#39;t5-small&#39;)</pre><pre>device = torch.device(&#39;cpu&#39;)</pre><p>Add the string summarize: at the beginning of your raw text and encode . T5 transformers performs different tasks by prepending the particular prefix to the input text.</p><pre>t5tokenized_text = t5tokenizer.encode(&quot;summarize:&quot;+ text,<br>                                truncation=True,<br>                                return_attention_mask=True,<br>                                add_special_tokens=True, <br>                                padding=&#39;max_length&#39;,     <br>                                return_tensors=&quot;pt&quot;).to(device)</pre><p>Next you will pass the input_ids from the tokenized text returned from the encode function along with other parameters. The technique used here is “Beam Search”. Beam search reduces the risk of missing hidden high probability word sequences by keeping the most likely num_beams of hypotheses at each time step and eventually choosing the hypothesis that has the overall highest probability</p><p>Read more about Greedy Search and Beam Search here : <a href="https://huggingface.co/blog/how-to-generate">https://huggingface.co/blog/how-to-generate</a></p><pre>t5summary_ids =  t5model.generate(input_ids=t5tokenized_text[&#39;input_ids&#39;],<br>                 attention_mask=t5tokenized_text[&#39;attention_mask&#39;],<br>                 num_beams=3,<br>                 min_length=20,<br>                 max_length=70,<br>                 repetition_penalty=2.0,<br>                 early_stopping=True)</pre><p>The parameters explanation are as below;</p><ul><li>max_length: The maximum number of tokens to generate.</li><li>min_length: This is the minimum number of tokens to generate.</li><li>length_penalty: Exponential penalty to the length, 1.0 means no penalty, increasing this parameter, will increase the length of the output text.</li><li>num_beams: Specifying this parameter, will lead the model to use beam search instead of greedy search, setting num_beams to 4, will allow the model to lookahead for 4 possible words (1 in the case of greedy search).</li><li>early_stopping: We set it to True, so that generation is finished when all beam hypotheses reached the end of string token (EOS).</li></ul><pre>output = t5tokenizer.decode(t5summary_ids[0],  <br>                             skip_special_tokens=True, <br>                             clean_up_tokenization_spaces=True)</pre><pre>print (&quot;Summary:&quot;, output)</pre><pre><strong>Output &gt;&gt;&gt;</strong></pre><pre>Summary: shares rose about 2% after-hours, according to Refinitiv. in the year-ago quarter, net income amounted to $104 million. overall revenue came in at $10.21 billion, of which only $354 million came from regulatory credits.</pre><h3>Summarization with BERT Model</h3><p><strong>BERT</strong> (Bidirectional transformer) is a transformer used to overcome the limitations of RNN and other neural networks as Long term dependencies. It is a pre-trained model that is naturally bidirectional. This pre-trained model can be tuned to easily perform the NLP tasks as specified, <strong>Summarization</strong> in our case.</p><pre>bert_model = Summarizer()</pre><pre>bert_summary = &#39;&#39;.join(bert_model(text, min_length=60))</pre><pre>print(&quot;Summary: &quot; + bert_summary)</pre><pre><strong>Output &gt;&gt;&gt;</strong></pre><pre>Summary: Tesla reported second-quarter earnings after the bell Monday, and it’s a beat on both the top and bottom lines. The company also reported $801 million in revenue from its energy business, including solar photovoltaics and energy storage systems for homes, businesses and utilities, an increase of more than 60% from last quarter. That compares with an increase of 121% in vehicle deliveries year over year.</pre><h3>Summarization with GPT2 Model</h3><p>Generative Pre-trained Transformer (GPT) models by OpenAI have taken natural language processing (NLP) community by storm by introducing very powerful language models. These models can perform various NLP tasks like <a href="https://en.wikipedia.org/wiki/Question_answering">question answering</a>, <a href="https://en.wikipedia.org/wiki/Textual_entailment#:~:text=Textual%20entailment%20(TE)%20in%20natural,hypothesis%20(h)%2C%20respectively.">textual entailment</a>, text summarization etc. without any supervised training.</p><p>GPT-2 is capable of next word prediction on a much larger and more sophisticated scale. For reference, the smallest available GPT-2 has 117 million parameters, whereas the largest one (invisible to the public) has over 1.5 billion parameters. The largest one available for public use is half the size of their main GPT-2 model.</p><p>Let’s load the model, and get the generated summary!</p><pre>GPT2_model = TransformerSummarizer(transformer_type=&quot;GPT2&quot;,<br>                         transformer_model_key=&quot;gpt2-medium&quot;)</pre><pre>gpt_summary = &#39;&#39;.join(GPT2_model(text, min_length=60))</pre><pre>print(gpt_summary)</pre><pre><strong>Output &gt;&gt;&gt;</strong></pre><pre>Summary: Tesla reported second-quarter earnings after the bell Monday, and it’s a beat on both the top and bottom lines. In the year-ago quarter, net income amounted to $104 million. The company also reported $801 million in revenue from its energy business, including solar photovoltaics and energy storage systems for homes, businesses and utilities, an increase of more than 60% from last quarter.</pre><p>Wow! much <strong>better than Bert</strong>! Look at such an <strong>insightful summary it has generated!</strong></p><p>Now, let’s jump into our final model, <strong>the XLNet!</strong></p><h3>Summarization with XLNet</h3><p>XLNet is a generalized autoregressive language model that learns unsupervised representations of text sequences. This model incorporates modelling techniques from Autoencoder(AE) models(BERT) into AR models while avoiding limitations of AE.</p><p>Let’s load the model and print out the summary/</p><pre>xlnet_model = TransformerSummarizer(transformer_type=&quot;XLNet&quot;,<br>                     transformer_model_key=&quot;xlnet-base-cased&quot;)</pre><pre>xlnet_summary = &#39;&#39;.join(xlnet_model(text, min_length=60))</pre><pre>print(&quot;Summary: &quot; + xlnet_summary)</pre><pre><strong>Output &gt;&gt;&gt;</strong></pre><pre>Summary: Tesla reported second-quarter earnings after the bell Monday, and it’s a beat on both the top and bottom lines. That’s a lower number for credits than in any of the previous four quarters. The company also reported $801 million in revenue from its energy business, including solar photovoltaics and energy storage systems for homes, businesses and utilities, an increase of more than 60% from last quarter.</pre><p>For all the transformer models, the generated results illustrate that it works really well, which is really impressive! 👌</p><h3>Conclusion</h3><p>Text summarization has become an important and timely tool for assisting and interpreting text information in today’s fast-growing information age. Its application can be seen where ever text document is involved irrespective of the field. Due to its applications and ease that it brings, text summarization is a popular topic in the field of Natural language processing.</p><p>I hope this article gives you heads-up on the different types and different approaches that are used for the text summarization. If yes, please do share clap.. 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2752a7daa5f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/long-story-short-an-nlp-use-case-on-text-summarization-2752a7daa5f7">Long story short... An NLP use-case on Text Summarization</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Search Engine using NLP]]></title>
            <link>https://medium.com/analytics-vidhya/semantic-search-engine-using-nlp-cec19e8cfa7e?source=rss-85de2049e1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/cec19e8cfa7e</guid>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Ajit Rajput]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 10:52:46 GMT</pubDate>
            <atom:updated>2023-08-24T08:02:24.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Semantic Search using NLP</h3><h4>An starter guide on building intelligent search engine using semantic understanding of search queries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*GLZ4j3lsWLT396543CR7bQ.jpeg" /></figure><h3>Introduction</h3><p>Search engines have been with us for several decades as an integral part of our digital life. We are casually searching over billions of web pages to retrieve and share information from various resources. While humans are very good at conversational context and background knowledge which helps them to deal with intrinsic ambiguity of words, it may not be true in case of search engines, especially when it comes to <em>out-of-the-vocabulary</em> searches</p><p>The answer to this problem is <strong><em>semantic </em></strong>search. Using the latest insights from NLP research, it is possible to train a Language Model on a large corpus of documents. Afterwards, the model is able represent documents based on their “<em>semantic” </em>content. In particular, this includes the possibility to search for documents with semantically similar content.</p><blockquote>Semantic search means understanding the intent behind the query and representing the “knowledge in a way suitable for meaningful retrieval,” according to <a href="https://towardsdatascience.com/semantic-search-73fa1177548f">Towards Data Science</a>.</blockquote><p>In this work, we will retrieve relevant movie titles using semantic search based on the concept of Natural Language processing (NLP)</p><p>For those who want to jump directly to the code, here’s the link to my Kaggle Notebook.</p><p><a href="https://www.kaggle.com/ajitrajput/semantic-search-engine-using-nlp">Semantic Search Engine using NLP</a></p><h4>Keyword Search Vs Semantic Search</h4><p>At first, search engines were lexical: the search engine looked for literal matches of the query words, without understanding of the query’s meaning and only returning links that contained the exact query.By using regular keyword search, a document either contains the given word or not, and there is no middle ground</p><p>On the other hand, “Semantic Search” can simplify query building, because it is supported by automated natural language processing programs i.e. using Latent Semantic Indexing — a concept that search engines use to discover how a keyword and content work together to mean the same thing.</p><blockquote>According to Wikipedia,</blockquote><blockquote>LSA (Latent Semantic Analysis) also known as LSI (Latent Semantic Index) LSA is a technique in natural language processing of analyzing relationships between a set of documents and the terms they contain by producing a set of concepts related to the documents and terms. LSI is based on the principle that words that are used in the same contexts tend to have similar meanings. A key feature of LSI is its ability to extract the conceptual content of a body of text by establishing associations between those terms that occur in similar contexts.</blockquote><p>LSI adds an important step to the document indexing process. LSI examines a collection of documents to see which documents contain some of those same words. LSI considers documents that have many words in common to be semantically close, and ones with less words in common to be less close.</p><p>In brief, LSI does not require an exact match to return useful results. Where a plain keyword search will fail if there is no exact match, LSI will often return relevant documents that don’t contain the keyword at all.</p><h4>Load the data</h4><p>We will now load the movies data csv into dataframe and quickly peek into the columns and data provided</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c4fff258fffac41c04d685518079a65/href">https://medium.com/media/3c4fff258fffac41c04d685518079a65/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*v4wJtq2onoJF_KIWD8-Bsw.png" /></figure><h4>Data Cleaning and Pre-processing</h4><p>Data pre-processing is one of the most significant step in text analytics. The purpose is to remove any unwanted words or characters which are written for human readability, but won’t contribute to topic modelling in anyway.</p><p>The following function applies regular expression for matching patterns of unwanted text and removing/replacing them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b7d9394596d2653cf4b73807744f17d/href">https://medium.com/media/6b7d9394596d2653cf4b73807744f17d/href</a></iframe><p>Now let us apply the data-cleaning and pre-processing function to our movies “wiki_plot” column and store the cleaned, tokenized data into new column</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e429beabb5efa041e55d9adfdd31aff/href">https://medium.com/media/8e429beabb5efa041e55d9adfdd31aff/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*QWYJi3uCRa8pTLngkppXmw.png" /></figure><h4>Building Word Dictionary</h4><p>In the next step we will build the vocabulary of the corpus in which all the unique words are given IDs and their frequency counts are also stored. You may note that we are using gensim library for building the dictionary. In gensim, the words are referred as “tokens” and the index of each word in the dictionary is called ID</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ea169c5763034343c27271d43834c8b/href">https://medium.com/media/4ea169c5763034343c27271d43834c8b/href</a></iframe><p>You can see that there are 2 additional steps performed after creating the dictionary.</p><ol><li>All the tokens in the dictionary which either have occurred in less than 4 articles or have occurred in more than 20% of the articles are removed from the dictionary, as these words will not be contributing to the various themes or topics.</li><li>Removing content neutral words from the dictionary and additional stop-words.</li></ol><h4>Feature Extraction (Bag of Words)</h4><p>A bag of words model, or BoW for short is a way of extracting features from text for use in modelling, such as with machine learning algorithms. It is a representation of tet that describes teh occurence of words within a document. It involves two things</p><ol><li>A vocabulary of known words</li><li>A measure of the presence of known words</li></ol><p>The doc2bow method of dictionary, iterates through all the words in the text, if the word already exists in the corpus, it increments the frequency count, other wise it inserts the word into the corpus and sets it frequency count to 1</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45422833b84cfa307f5e01fcd9681dee/href">https://medium.com/media/45422833b84cfa307f5e01fcd9681dee/href</a></iframe><h4>Build Tf-Idf and LSI Model</h4><p>Tf-Idf means, Term frequency-Inverse Document Frequency. it is a commonly used NLP model that helps you determine the most important words in each document in the corpus. Once the Tf-Idf is build, pass it to LSI model and specify the num of features to build</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/254ad2aeedc0641edcb3032aa5406078/href">https://medium.com/media/254ad2aeedc0641edcb3032aa5406078/href</a></iframe><h4>Time for Semantic Search</h4><p>Now comes the fun part. With the index of movies initialized and loaded, we can use it to find similar movies based</p><p>We will input a search query and model will return relevant movie titles with “Relevance %” which is the similarity score. The higher the similarity score, the more similar the query to the document at the given index</p><p>Below is the helper function to search the index, sort and return the results</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98766cf80fa618c36fdf86dc12bfb97e/href">https://medium.com/media/98766cf80fa618c36fdf86dc12bfb97e/href</a></iframe><pre><em># search for movie tiles that are related to below search parameters</em><br>search_similar_movies(&#39;crime and drugs &#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*vLQgGBgA3IQjNnJkGQwDkg.png" /></figure><p>The model returns movie titles with “Relevance %”. Definitely, the top list movies are related to crimes and drugs.</p><pre><em># search for movie tiles that are related to below search parameters</em><br>search_similar_movies(&#39;violence protest march&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*w5jimU9XqjveqzLm-1VbeA.png" /></figure><p>Here the top most movie title “Gandhi” is surely related to non-violence protests</p><h4>Closing Notes</h4><p>In general usage, computing semantic relationships between textual data enables to recommend articles or products related to given query, to follow trends, to explore a specific subject in more details.</p><p>In this article we saw the basic version of how semantic search can be implemented. There are many ways to further enhance it using newer deep learning models.</p><p>This was just an attempt to showcase my learning journey into field of NLP and Machine Learning. Your valuable feedback, comments and suggestions are welcome!</p><p>Hope you all like it and vote for it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cec19e8cfa7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/semantic-search-engine-using-nlp-cec19e8cfa7e">Semantic Search Engine using NLP</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Food Recipes using Machine Intelligence]]></title>
            <link>https://medium.com/@ajit.rajput/exploring-food-recipes-using-machine-intelligence-87cb1a983cfd?source=rss-85de2049e1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/87cb1a983cfd</guid>
            <category><![CDATA[machinelerning]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[food]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Ajit Rajput]]></dc:creator>
            <pubDate>Mon, 08 Jun 2020 10:52:06 GMT</pubDate>
            <atom:updated>2020-06-08T10:52:06.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*mGLBkdzKR60AfK6w0RBSTQ.jpeg" /></figure><p>Using Word2Vec model for recipe analysis</p><h3>Introduction</h3><p>Food is an inseparable part of our lives. It has been observed that ingredients and recipes are often considered when an individual chooses to eat. Influenced by ingredients and style of cooking, a cuisine can have several hundred or thousands of recipes for different dishes. A recipe on Website shows the ingredients that are needed for a dish and the procedure of the cooking. But the problem is, the user cannot identify what are the dishes can be cooked by using the ingredients available by the user. To overcome these problems, Machine Learning approach is used which enables to suggest the recipes based on the available ingredients by the user.</p><p>So, before we dig further into how machine learning can be used in food industry, lets first understand more about Natural Language Processing (NLP).</p><h3>What is NLP</h3><p>Natural language refers to the language used by humans to communicate with each other. This communication can be verbal or textual. For instance, face-to-face conversations, tweets, blogs, emails, websites, SMS messages, all contain natural language. However, for computers to easily comprehend and process this natural language requires applying rules and algorithms such that the unstructured data is converted into a form that computers can understand.</p><blockquote><strong>Syntactic analysis</strong> and <strong>Semantic analysis</strong> are the main techniques used to complete Natural Language Processing tasks. “Syntax” refers to the arrangement of words in a sentence such that they make grammatical sense, whereas “Semantics” refers to the meaning that is conveyed by a text</blockquote><p>With these rules and word embedding algorithms we convert the natural language words in a numeric format that is understandable by the computers.</p><h3>Word Embedding</h3><p><strong><em>Word embedding</em></strong> is a type of word representation that allows words with similar meaning to be understood by machine learning algorithms. It is also called as distributed semantic model or semantic vector space or vector space model; which means categorizing or grouping vectors of similar words together<strong> in vector space</strong>. The idea behind it is fairly straightforward: <strong>you shall know a word by the company it keeps. </strong>Thus words having similar neighbors, i.e., the usage context is about the same, are highly possible <strong><em>having same meaning or at least highly related</em></strong>.</p><h3>Word2Vec - An Word Embedding Approach</h3><p>The Word2Vec is an word embedding approach, developed by <a href="https://research.fb.com/people/mikolov-tomas/">Tomas Mikolov</a>, is considered the state of the art. Word2Vec approach uses deep learning and neural networks-based techniques to convert words into corresponding vectors in such a way that the semantically similar vectors are close to each other in N-dimensional space, where N refers to the dimensions of the vector.</p><p>Wait ! Why on earth do we need word embedding in analyzing food recipes and ingredients? Well, we need some way to convert text and categorical data into numeric machine readable variables if we want to compare one recipe with another. With this tutorial, we will learn how the Word2Vec can be used to;</p><ul><li><strong>Suggest similar concepts</strong> — Here, word embedding helps us to suggest similar ingredients to the word being subjected to the prediction model.</li><li><strong>Create a group of related words</strong>: It is used for semantic grouping which will group things of similar characteristic together and dissimilar far away.</li><li><strong>Find unrelated concepts</strong></li><li><strong>Compute similarity between two words and more</strong></li></ul><p>P.S. The point of this post is intended as a reference and starting point for those interested in exploring the field further.</p><h3>Food Recipes Dataset</h3><p>The secret to getting Word2Vec really working for you is to have lots of text data in the relevant domain. For this tutorial, we will be using dataset that has around roughly 5000 recipes of different cuisines and varying ingredients.</p><h4>Data Cleaning and Pre-Processing</h4><p>Let us first load the recipes into pandas dataframe and remove empty rows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c810749cd097caf7cf4b9420458d5c7/href">https://medium.com/media/4c810749cd097caf7cf4b9420458d5c7/href</a></iframe><p>The resultant is around approximately 5400 recipes with respective columns i.e. <em>recipe name, rating, course-type, cuisine and list of ingredients</em> required for each recipe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmM4vDmDNRDYPmsCMLFgqA.png" /></figure><p>The raw data is as always prone to noise where there are lots of typos, stop word unwanted spacings, punctuations, numbers etc are removed. Additional pre-processing that is covered includes,</p><ol><li>Ingredients are represented in plural forms (e.g. <em>tomatoes</em> instead of <em>tomato</em>; <em>potatoes </em>vs <em>potato</em>) which needs to be converted into singular form to reduce the word dimensions.</li><li>Most ingredients are prefixed with adjectives e.g. <em>dried tomatoes,</em> s<em>queezed lemons</em>, <em>fresh coriander</em> etc. These words (<em>dried, squeezed, fresh</em> etc) are no useful in generating meaningful word embeddings. Hence these are stripped using regular expression functions.</li></ol><p>Here’s the script that cleans &amp; pre-processes the ingredients data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/627e5ee99031d083517d049ca58a486c/href">https://medium.com/media/627e5ee99031d083517d049ca58a486c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*LJfzPbiPDQZ4vP1gIwVXUQ.png" /></figure><p>As you see from the results, a total of 55K ingredients are used across 5400+ recipes, out of which 2600+ ingredients appear to be unique after pre-processing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f926898545b9314b8e5e10f4f20b6ec/href">https://medium.com/media/1f926898545b9314b8e5e10f4f20b6ec/href</a></iframe><p>Now, lets explore the most common and least common ingredients.</p><pre>#find the most common ingredients used across all recipes<br>print (&quot;---- Most Common Ingredients ----&quot;)<br>print (counts_ingr.most_common(10))</pre><pre>print (&quot;\n&quot;)</pre><pre>#find the most common ingredients used across all recipes<br>print (&quot;---- Least Common Ingredients ----&quot;)<br>print (counts_ingr.most_common()[-10:])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8JfYO0ArJp6IQkJ7-QCVw.png" /><figcaption>Most and Least Common ingredients</figcaption></figure><p>Let’s visualize this with word-cloud visualization technique.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8b970edab0e383300ac1fc1cc0e9d36/href">https://medium.com/media/c8b970edab0e383300ac1fc1cc0e9d36/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*qMNbGLmzlPMdXB8CeiBgKw.png" /><figcaption>Word Cloud Visualization</figcaption></figure><h3>Training Word2Vec</h3><p>With Gensim, it is extremely straightforward to create Word2Vec model. The ingredients list is passed to the Word2Vec class of the gensim.models package. Word2Vec uses all these tokens to internally create a vocabulary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca5f82f18e1eefbe1a7fd1fc47deaa9a/href">https://medium.com/media/ca5f82f18e1eefbe1a7fd1fc47deaa9a/href</a></iframe><p>The step above, builds the vocabulary using the ingredients list, and starts training the Word2Vec model. Behind the scenes, we are training a neural network with a single hidden layer to predict the current word based on the context. The goal is to learn the weights of the hidden layer. These weights are essentially the word vectors that we’re trying to learn. The resulting learned vector is known as the <strong>embeddings</strong>.</p><h4>Results</h4><p>Let’s get into the fun stuff now! This first example shows a simple look up of words (e.g. ingredients like <em>paneer, egg, mango, bread, rice</em>) appear to be similar or at the least related with other ingredients</p><pre># check the similar ingredients returned by the model for search_terms</pre><pre>similar_words = {search_term: [item[0] for item in model.wv.most_similar([search_term], topn=5)]<br>                  for search_term in [&#39;paneer&#39;,&#39;egg&#39;,&#39;mango&#39;,&#39;bread&#39;, &#39;rice&#39;]}<br>similar_words</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*srBb1mdCIrvohT3I-GH9oQ.png" /><figcaption>sdf</figcaption></figure><p>Wow, that looks pretty good. Let’s look at more ingredients</p><p><em>Similar or related ingredients for ingredient “chocolate”</em></p><pre>model.wv.most_similar(&#39;chocolate&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*fosXh9o5_0taRwQKpXvpsA.png" /></figure><p>Great, the similarity brings out all the words that are closely related with “chocolate” e.g. dark chocolate, vanilla beans etc</p><p><em>Similar or related ingredients for ingredient “mayonnaise”</em></p><pre>model.wv.most_similar(&#39;mayonnaise&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*ZnAifL91tvjOZWubxXjKNA.png" /></figure><p><em>Similar or related ingredients for ingredient “chicken”</em></p><pre>model.wv.most_similar(‘chicken’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*UGLk3PMHQ6YkF0NArUcHQg.png" /></figure><p>Overall, the results actually make sense. All of the related words end to be used in similar contexts. Now lets use Word2Vec to compute similarity between two ingredients in the vocabulary by invoking the similarity(...) function and passing in the relevant words.</p><pre>model.wv.similarity(‘paneer’, ‘chicken’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*5Fvl6SLxYkiF6_R1iKEzTA.png" /></figure><p>Under the hood, the model computes the cosine similarity between the two specified words using word vectors (embeddings) of each. The resultant score makes sense as, “paneer” is primarily used in vegetarian diet, whereas “chicken” into non-vegetarian diet</p><p>Another fun stuff is to identify food analogies, similar to word analogies. For the analogy “bread is to cheese”, the goal is to predict a reasonable analogy for “chicken is to ….”</p><pre>x = ‘chicken’<br>b= ‘cheese’<br>a = ‘bread’<br>predicted = model.wv.most_similar([x, b], [a])[0][0]<br>print(“ {} is to {} as {} is to {} “.format(a, b, x, predicted))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*MdMHYizgB7CSNq6LUY6-cQ.png" /></figure><h3>Evaluating Word2Vec</h3><p>We’ve created embeddings of 300 dimensions with word2vec. Luckily, when we want to visualize our high dimensional word embeddings, we can employ a dimensionality reduction technique. Below, we can see some of the vector embeddings for common ingredients projected onto two dimensions by t-SNE. The positions of the ingredients below represent probability distributions rather than actual positions in space. t-SNE plots can be difficult to interpret as the hyper parameter, perplexity, can drastically change the size and distance between clusters. However, we aren’t trying to interpret clusters, but rather hoping to evaluate whether or not our model learned something useful about our recipes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/806fc8d4a5e2c2b6d5b239e48ec4df24/href">https://medium.com/media/806fc8d4a5e2c2b6d5b239e48ec4df24/href</a></iframe><p>You can see, the vegetarian food “paneer” ingredients are nearby which includes the masalas, garlic and ginger pastes. And it definitely makes sense. Similarly all ingredients w.r.t. “eggs”, “mango” are closely appearing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGaovgOVRjetRxLwg_jKGQ.png" /></figure><h3>What’s Next?</h3><p>The above tutorial explores just the ingredients part for the recipes. There are many other use-cases or exploration ideas that can be further implemented. Here are some of questions that I will try to build and get it answered in my next tutorial.</p><ol><li>Cuisine classification/prediction based on ingredients provided</li><li>Given a recipe, finding similar recipes from the corpus</li><li>Recipe Recommendation based on ingredients supplied.</li><li>Using set of given ingredients, what recipes can be prepared.</li></ol><h3>Conclusion</h3><p>Capturing the meaning and relations between words is hugely important when identifying information in text. The embeddings provide a foundation for more complex tasks and models in Natural Language Processing and Machine Learning.</p><p>So go have fun — try and find some interesting data sets of text stuff you can feed in and what you can work out about the relationships — and feel free to comment here with anything interesting you find.</p><p>Happy Cooking !</p><p>You can find my Kaggle notebook/kernel here :</p><p><a href="https://www.kaggle.com/ajitrajput/exploring-food-recipes-using-word2vec/notebook">Exploring Food Recipes using Word2Vec</a></p><p><strong>Documentation and Learning References:</strong></p><ul><li><a href="https://jaan.io/food2vec-augmented-cooking-machine-intelligence/">food2vec - Augmented cooking with machine intelligence - Jaan Altosaar</a></li><li><a href="https://www.guru99.com/word-embedding-word2vec.html">Word Embedding Tutorial: word2vec using Gensim [EXAMPLE]</a></li><li><a href="https://kavita-ganesan.com/gensim-word2vec-tutorial-starter-code/#.XttvKjozZPY">Gensim Word2Vec Tutorial - Full Working Example | Kavita Ganesan</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87cb1a983cfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing for IT Support Incident]]></title>
            <link>https://medium.com/analytics-vidhya/natural-language-processing-for-it-support-incident-51cb35af0735?source=rss-85de2049e1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/51cb35af0735</guid>
            <category><![CDATA[tfidf-vectorizer]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[incident-management]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Ajit Rajput]]></dc:creator>
            <pubDate>Sun, 17 May 2020 14:35:30 GMT</pubDate>
            <atom:updated>2020-05-20T14:32:09.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bju1447SMWNgUbpglNi5yQ.jpeg" /></figure><h3>Natural Language Processing for IT Support Incidents</h3><p>Learn how to leverage NLP to extract hotspots from unstructured incidents</p><h3>Introduction</h3><p>Enterprises face an ever increasing volume and velocity of IT service tickets each month. Largely, the investigation, diagnosis and root cause analysis is manual process. When IT managers wish to get a pulse of their IT system or applications to understand the problem areas and see where the resources are spending their time, they use standard reporting technique, which can usually only get them information on ticket count, ownership, categories, severity etc. However, relying on KPI driven reports will only tell how you are doing, not what to do and where to focus the efforts.</p><h4>Problem Statement</h4><p>Service ticket templates typically have a finite list of choices, categories to classify the incident ticket. When the finite list of category doesn’t describe a user’s issue, or the user cannot find a choice with which they are happy, they will typically choose the default bucket of “General” or “Other”. In such cases, the details of their exact issue or concern is going to be in the unstructured incident summary and/or description that they provide. And in this free-form, unstructured text there are hidden “<strong>hotspots</strong>” which needs to be brought to forefront to understand the real problem areas and perform accurate root-cause analysis</p><p>Let us look at some random incidents logged under “General” category and see if we can extract the “hotspots”</p><pre>+--------------------------------------------------------+<br>|                    Incident Summary                    |<br>+--------------------------------------------------------+<br>| Firefox crashes when working with Gmail                |<br>| Password reminder not working                          |<br>| Missing back buttons not returning, links not working  |<br>| Client search functionality is not working              |<br>| when navigating to certain links Firefox stops working |<br>+--------------------------------------------------------+</pre><p>It is pretty easy for humans to understand these incident summary as we know the semantics of the words and sentences. We can even identify the hotspots at broader level. Now imagine performing this activity with thousands of such incidents logged on monthly basis, with limited resources. It is not possible to find relevancy across the entire set and identify factors causing high number of incidents.</p><p>Hence, in order to make sense out of the unstructured data, we have to transform and organize it in such a way that it produces “information”, for which to further become “knowledge” and progress towards “insight” requires leveraging Natural Language Processing (NLP) technique to extract actionable insights from the text data.</p><h4>Tune to NLP based Incident Analytics</h4><p>Given that most description in the text is human generated, leveraging NLP can help us go deeper into information, understand and identifying relevant insight from the content, highlighting connections between information within one or more texts that would otherwise go undiscovered using traditional tools</p><h3>The Process</h3><h4>Data Acquisition</h4><p>To perform natural language processing, we need some data containing natural language to work with. Often you can collect your own data for projects by scraping the web or downloading existing files, like in this case I have used bugs/defects data for Firefox browser that is publicly available at https://<a href="https://bugzilla.mozilla.org/">bugzilla.mozilla.org</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tg0yrf2LBFgl3LIeGtFHEw.png" /><figcaption>Read the input source data-set</figcaption></figure><p>The result below shows the incidents logged under “General” category. There are around 900 records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*mUB1Yfhn3Y7lwaFomR9nhQ.png" /></figure><p>Now that data has been acquired, its time for data pre-processing. The data must be arranged in proper form to work with machine learning models that will be used for data analysis.</p><h4>Data Pre-Processing</h4><p>The first pre-processing step which we will do is transform our records into lower case. This avoids having multiple copies of the same words. For example, while calculating the word count, ‘Sound’ and ‘sound’ will be taken as different words.</p><p>The subsequent steps shows the data-cleansing activity, which removes the unwanted or un-necessary information, such as http(s) urls, punctuations, single digits or words containing digits. Here the text data is structured to ensure data can be read the same way across the system and to improve the data integrity (also known as “text normalization)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uz8BMsdbU0NBm-InecDxnQ.png" /><figcaption>Text normalization process</figcaption></figure><p><strong>Stop-words removal</strong> : These are the most common words like “the”, “a”, “on”, “is”, “all” etc. These words do not carry important meaning and are usually removed from the sentences in order to obtain better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLXl3A9bw7gBsbRNQDWJUA.png" /><figcaption>Stop-words removal process using nltk stopwords library</figcaption></figure><p><strong>Rare words removal</strong>: Sometimes, you would need to remove the words that are very unique in nature like names, brands, product names, and some of the noise characters, such as html leftouts. This is considered as “rare word removal”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYF-gm_PKZggqmXeCyqkSw.png" /><figcaption>Rare words removal</figcaption></figure><p><strong>Lemmatization</strong>: In natural language processing, you want your program to recognize that the words “ask” and “asked” are just different tenses of the same verb. This is the idea of reducing different forms of a word to a core root. Lemmatizing means to extract the ‘lemma’ from a given word after its morphological analysis.</p><p><strong>For example:</strong> If we lemmatize <em>‘studies’</em> and <em>‘studying’</em>, we will end up with <em>‘study’</em> as its lemma. We got to this conclusion after the morphological analysis of both words. These were mapped in a <em>dictionary </em>which helped in arriving at the lemma<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HA5b3HVoxdDhYEYwOr88Lw.png" /><figcaption>Lemmatize process</figcaption></figure><p>Up until this point, we performed the text cleaning i.e. data pre-processing in order to make it compatible with machine learning models. Now, we finally move on to extracting features using NLP techniques, using the TF-IDF technique</p><h4>Feature Extraction using TF-IDF</h4><p>As we know, machines are good with numbers, but not that much with textual data. One of the most widely used techniques to process textual data is TF-IDF</p><p>TF-IDF stands for <strong><em>term frequency-inverse document frequency</em></strong>, is a technique that is used when we need a machine to identify topics of a huge set of documents. There are many literature, articles and references about <a href="http://www.tfidf.com/">TF-IDF</a> on internet, so we will not go into depth. Just to give a quick example;</p><blockquote>Consider a document containing 100 words wherein the word <em>cat</em> appears 3 times. The term frequency (i.e., tf) for <em>cat</em> is then (3 / 100) = 0.03. Now, assume we have 10 million documents and the word <em>cat</em> appears in one thousand of these. Then, the inverse document frequency (i.e., idf) is calculated as log(10,000,000 / 1,000) = 4. Thus, the <strong><em>Tf-idf weight</em></strong> is the product of these quantities: 0.03 * 4 = 0.12</blockquote><p>In the below step sklearn’s TfidfVectorizer is used to process our documents. Here, bi-grams are used to extract the features (i.e. ngram_range=(2,2))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PEwv2FoV3rZzdIbyaHrMUQ.png" /><figcaption>sklearn — TfidfVectorizer for Bi-gram Feature extraction</figcaption></figure><blockquote><strong>Note</strong>: N-grams are the combination of multiple words used together. Ngrams with N=1 are called unigrams. Similarly, bigrams (N=2), trigrams (N=3) and so on can also be used. They are basically a set of co-occuring words within a given window.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*oIv4SQHWWsWsVjNgwkoF1A.png" /><figcaption>Bi-Gram Term Frequency</figcaption></figure><p>The result shows frequency of bi-gram terms (aka “hot-spots” appearing in the documents.</p><p>For ex: the bi-gram term “<em>firefox stop</em>” has the highest Tfidf weight, which can be interpreted as — from the total 900+ “General” category incidents majority of the users have mentioned “firefox browser getting stopped”. Let us look at another example, the next top bi-gram term is “<em>right click</em>” — which could be interpreted as incidents getting reported around mouse right-click operations.</p><p>Let us look at this in form of graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8mBj4G-ytdmp2dBYeKA5w.png" /><figcaption>Plotting of Term Vs Frequency graph</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*Fw9DkTcKBfK0GNIvyQx6Pg.png" /></figure><p>Thus we saw how powerful TF-IDF is as a tool to process textual data out of a corpus. To learn more about sklearn TF-IDF, you can use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">this link</a>.</p><h3>Wrap-up</h3><p>Service agents are overwhelmed with tickets, and hiring extra manpower is not going to solve the problem. Furthermore, customers expect faster interactions meaning service agents would need to spend even more time attending to individual customer issues. As ticket volumes continue to increase, AI-led NLP solutions are the answer. NLP algorithms can go through this free-form text, cluster issues and identify the hotspots. This is particularly useful if the categories have not been kept up-to-date by the service desk team.</p><p><strong>Happy coding!</strong></p><p>Thanks for reading this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51cb35af0735" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/natural-language-processing-for-it-support-incident-51cb35af0735">Natural Language Processing for IT Support Incident</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>