<?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 Kailash Lohar on Medium]]></title>
        <description><![CDATA[Stories by Kailash Lohar on Medium]]></description>
        <link>https://medium.com/@kailashloharvnit?source=rss-a078b278508d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VREbROhMTnR4DJjx</url>
            <title>Stories by Kailash Lohar on Medium</title>
            <link>https://medium.com/@kailashloharvnit?source=rss-a078b278508d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:03:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kailashloharvnit/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[From Text to Intelligence: NLP Journey with Python]]></title>
            <link>https://medium.com/@kailashloharvnit/from-text-to-intelligence-nlp-journey-with-python-b5fdce368fa9?source=rss-a078b278508d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5fdce368fa9</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Kailash Lohar]]></dc:creator>
            <pubDate>Sat, 31 May 2025 18:58:30 GMT</pubDate>
            <atom:updated>2025-06-01T05:53:26.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2X3r2ZSKaB0VQEft-QpqFw.png" /></figure><p>Have you ever asked Siri for the weather, chatter with a customer support bot, or used Google Translate to decode a foreign phrase? If so, you’re already benefitting from an amazing field called Natural Language Processing (NLP) — the magical bridge between human language and computer understanding.</p><p>When I first heard the term “NLP”, it sounded like jargon from a sci-fi movie. However, as I delved into it, I realized that NLP is behind some of the most innovative tech developments, enabling computers to understand and even generate human language truly.</p><p>In this blog, I’ll share my journey learning NLP — breaking down its core concepts, sharing practical code snippets, and exploring how you, too, can harness these tools to teach machines to read, write, and understand like never before!</p><h3>What is NLP?</h3><p>Natural Language Processing, or NLP, is a subfield of artificial intelligence that focuses on enabling computers to understand, interpret, and generate human language. It combines techniques from linguistics, computer science, and machine learning to bridge the gap between human communication and machine understanding.</p><h3>Why NLP?</h3><p>Human language is incredibly complex. It’s full of nuances, context, slang, and ambiguity. NLP helps machines make sense of this complexity so they can:</p><ul><li>Understand what people are saying or writing.</li><li>Respond in a meaningful way.</li><li>Extract insights from large volumes of text data.</li></ul><h3>Real-World Applications of NLP</h3><p>Here are just a few ways NLP is used in the real world:</p><ul><li>Chatbots and Virtual Assistants (like Siri, Alexa, and ChatGPT)</li><li>Spam Detection in Emails</li><li>Sentiment Analysis for product reviews or social media</li><li>Machine Translation (e.g., Google Translate)</li><li>Text Summarization and Keyword Extraction</li><li>Speech Recognition and Voice Commands</li></ul><h3>How NLP Works?</h3><p>At its core, NLP involves several key steps:</p><ol><li>Text Preprocessing — Cleaning and preparing text for analysis.</li><li>Feature Extraction — Converting text into numerical representations.</li><li>Modeling — Using machine learning or deep learning models to analyze or generate text.</li><li>Postprocessing — Refining the output for better interpretation or usability.</li></ol><p>Let’s start our journey with the simplest steps-and level up as we go!</p><p><strong>Tokenization: </strong><em>Breaking language down word by word.</em></p><p>Tokenization is like turning a paragraph into building blocks (words or sentences).</p><pre>import nltk<br>from nltk.tokenize import word_tokenize<br><br>text = &quot;Natural Language Processing (NLP) is at the heart of modern AI applications. \<br>        It&#39;s how chatbots talk, emails get sorted, and social media is analyzed!&quot;<br><br>tokens = word_tokenize(text)<br>print(tokens)<br>--------------------------------------------------------------------------------------------------------------------------------<br>[&#39;Natural&#39;, &#39;Language&#39;, &#39;Processing&#39;, &#39;(&#39;, &#39;NLP&#39;, &#39;)&#39;, &#39;is&#39;, &#39;at&#39;, <br> &#39;the&#39;, &#39;heart&#39;, &#39;of&#39;, &#39;modern&#39;, &#39;AI&#39;, &#39;applications&#39;, &#39;.&#39;, &#39;It&#39;, <br> &quot;&#39;s&quot;, &#39;how&#39;, &#39;chatbots&#39;, &#39;talk&#39;, &#39;,&#39;, &#39;emails&#39;, &#39;get&#39;, &#39;sorted&#39;, <br> &#39;,&#39;, &#39;and&#39;, &#39;social&#39;, &#39;media&#39;, &#39;is&#39;, &#39;analyzed&#39;, &#39;!&#39;]</pre><p><strong>Removing Stopwords: </strong><em>Cleaning up the clutter.</em></p><p>Common words (like “the”, “is”, “at”) don’t carry much meaning. We call them “stopwords.”</p><pre>from nltk.corpus import stopwords  <br>nltk.download(&#39;stopwords&#39;)  <br>  <br>stop_words = set(stopwords.words(&#39;english&#39;))  <br>filtered_tokens = [w for w in tokens if w.lower() not in stop_words]  <br>print(filtered_tokens)<br>--------------------------------------------------------------------------------------------------------------------------------<br>[&#39;Natural&#39;, &#39;Language&#39;, &#39;Processing&#39;, &#39;(&#39;, &#39;NLP&#39;, &#39;)&#39;, &#39;heart&#39;, &#39;modern&#39;, <br> &#39;AI&#39;, &#39;applications&#39;, &#39;.&#39;, &quot;&#39;s&quot;, &#39;chatbots&#39;, &#39;talk&#39;, &#39;,&#39;, &#39;emails&#39;, &#39;get&#39;, <br> &#39;sorted&#39;, &#39;,&#39;, &#39;social&#39;, &#39;media&#39;, &#39;analyzed&#39;, &#39;!&#39;]</pre><p><strong>Stemming and Lemmatization: </strong><em>Reducing words to their root form.</em></p><p>Stemming chops off word endings.<br>Lemmatization is smarter; it brings words to their dictionary base.</p><pre># Stemming Example:<br>from nltk.stem import PorterStemmer  <br>ps = PorterStemmer()  <br>  <br>stemmed = [ps.stem(w) for w in filtered_tokens]  <br>print(stemmed)<br>--------------------------------------------------------------------------------------------------------------------------------<br>[&#39;natur&#39;, &#39;languag&#39;, &#39;process&#39;, &#39;(&#39;, &#39;nlp&#39;, &#39;)&#39;, &#39;heart&#39;, &#39;modern&#39;, <br> &#39;ai&#39;, &#39;applic&#39;, &#39;.&#39;, &quot;&#39;s&quot;, &#39;chatbot&#39;, &#39;talk&#39;, &#39;,&#39;, &#39;email&#39;, &#39;get&#39;, <br> &#39;sort&#39;, &#39;,&#39;, &#39;social&#39;, &#39;media&#39;, &#39;analyz&#39;, &#39;!&#39;]</pre><pre># Lemmatization Example:<br>from nltk.stem import WordNetLemmatizer  <br>nltk.download(&#39;wordnet&#39;)  <br>lemmatizer = WordNetLemmatizer()  <br>  <br>lemmatized = [lemmatizer.lemmatize(w) for w in filtered_tokens]  <br>print(lemmatized)<br>--------------------------------------------------------------------------------------------------------------------------------<br>[&#39;Natural&#39;, &#39;Language&#39;, &#39;Processing&#39;, &#39;(&#39;, &#39;NLP&#39;, &#39;)&#39;, &#39;heart&#39;, &#39;modern&#39;,<br> &#39;AI&#39;, &#39;application&#39;, &#39;.&#39;, &quot;&#39;s&quot;, &#39;chatbots&#39;, &#39;talk&#39;, &#39;,&#39;, &#39;email&#39;, &#39;get&#39;,<br> &#39;sorted&#39;, &#39;,&#39;, &#39;social&#39;, &#39;medium&#39;, &#39;analyzed&#39;, &#39;!&#39;]</pre><p><strong>Part-of-Speech (POS) Tagging: </strong><em>Understanding grammar-the computer way.</em></p><p>What’s a noun? What’s a verb? POS tagging helps the machine “read” grammar.</p><pre>pos_tags = nltk.pos_tag(filtered_tokens)  <br>print(pos_tags)<br>--------------------------------------------------------------------------------------------------------------------------------<br>[(&#39;Natural&#39;, &#39;JJ&#39;), (&#39;Language&#39;, &#39;NNP&#39;), (&#39;Processing&#39;, &#39;NNP&#39;), <br> (&#39;(&#39;, &#39;(&#39;), (&#39;NLP&#39;, &#39;NNP&#39;), (&#39;)&#39;, &#39;)&#39;), (&#39;heart&#39;, &#39;NN&#39;), (&#39;modern&#39;, &#39;JJ&#39;), <br> (&#39;AI&#39;, &#39;NNP&#39;), (&#39;applications&#39;, &#39;NNS&#39;), (&#39;.&#39;, &#39;.&#39;), (&quot;&#39;s&quot;, &#39;POS&#39;), <br> (&#39;chatbots&#39;, &#39;JJ&#39;), (&#39;talk&#39;, &#39;NN&#39;), (&#39;,&#39;, &#39;,&#39;), (&#39;emails&#39;, &#39;VBZ&#39;), <br> (&#39;get&#39;, &#39;NN&#39;), (&#39;sorted&#39;, &#39;VBN&#39;), (&#39;,&#39;, &#39;,&#39;), (&#39;social&#39;, &#39;JJ&#39;), <br> (&#39;media&#39;, &#39;NNS&#39;), (&#39;analyzed&#39;, &#39;VBD&#39;), (&#39;!&#39;, &#39;.&#39;)]</pre><p><strong>Named Entity Recognition (NER):</strong> <em>Finding names, places, organizations in text.</em></p><p>For this, let’s use spaCy for its speed and accuracy.</p><pre>import spacy  <br>  <br>nlp = spacy.load(&#39;en_core_web_sm&#39;)  <br><br>text = &quot;Natural Language Processing (NLP) is at the heart of modern AI applications. \<br>        It&#39;s how chatbots talk, emails get sorted, and social media is analyzed!&quot;<br><br>doc = nlp(text)  <br>  <br>for ent in doc.ents:  <br>    print(ent.text, ent.label_)<br>--------------------------------------------------------------------------------------------------------------------------------<br>Natural Language Processing ORG<br>NLP ORG<br>AI GPE</pre><p><strong>Vectorization (Bag of Words): </strong><em>Turning text into numbers — so machines can work their magic.</em></p><p>Computers don’t understand words — they understand numbers! Vectorization represents text as numerical data, with the simplest approach being Bag of Words (counting each word’s occurrence).</p><pre>from sklearn.feature_extraction.text import CountVectorizer <br><br>corpus = [&quot;NLP creates amazing applications.&quot;,<br>          &quot;Chatbots use language processing.&quot;, <br>          &quot;Processing language is fun with NLP.&quot;] <br><br>vectorizer = CountVectorizer() <br>X = vectorizer.fit_transform(corpus) <br>print(vectorizer.get_feature_names_out()) <br>print(X.toarray()) <br>--------------------------------------------------------------------------------------------------------------------------------<br>[&#39;amazing&#39; &#39;applications&#39; &#39;chatbots&#39; &#39;creates&#39; &#39;fun&#39; &#39;is&#39; &#39;language&#39; &#39;nlp&#39;<br> &#39;processing&#39; &#39;use&#39; &#39;with&#39;]<br>[[1 1 0 1 0 0 0 1 0 0 0]<br> [0 0 1 0 0 0 1 0 1 1 0]<br> [0 0 0 0 1 1 1 1 1 0 1]]</pre><p><strong>N-grams: </strong><em>Building on Bag of Words — phrases instead of just words!</em></p><p>Sometimes meaning comes from combinations of words (“natural language” has a specific sense). These are called n-grams.</p><pre>bigram_vectorizer = CountVectorizer(ngram_range=(2,2)) <br><br>X2 = bigram_vectorizer.fit_transform(corpus) <br><br>print(bigram_vectorizer.get_feature_names_out()) <br>print(X2.toarray()) <br>--------------------------------------------------------------------------------------------------------------------------------<br>[&#39;amazing applications&#39; &#39;chatbots use&#39; &#39;creates amazing&#39; &#39;fun with&#39;<br> &#39;is fun&#39; &#39;language is&#39; &#39;language processing&#39; &#39;nlp creates&#39;<br> &#39;processing language&#39; &#39;use language&#39; &#39;with nlp&#39;]<br>[[1 0 1 0 0 0 0 1 0 0 0]<br> [0 1 0 0 0 0 1 0 0 1 0]<br> [0 0 0 1 1 1 0 0 1 0 1]]</pre><p><strong>Word Embeddings (Going Beyond Counts): </strong><em>Capturing context and meaning.</em></p><p>While bag-of-words only counts, embeddings represent words in vectors that capture similarity and context (so “king” and “queen” are closer than “king” and “car”).</p><pre>import spacy  <br><br>nlp = spacy.load(&#39;en_core_web_md&#39;)<br>word1 = nlp(&quot;king&quot;)<br>word2 = nlp(&quot;queen&quot;) <br>print(word1.similarity(word2))<br>--------------------------------------------------------------------------------------------------------------------------------<br>0.38253095746040344<br># A similarity score close to 1 means the words are similar in meaning.</pre><p><strong>Sentiment Analysis: </strong><em>Can the computer tell positive from negative?</em></p><p>Let’s see how TextBlob makes this fun:</p><pre>from textblob import TextBlob <br><br>sentence = &quot;NLP makes me excited and happy!&quot; <br>blob = TextBlob(sentence) <br>print(blob.sentiment) <br>--------------------------------------------------------------------------------------------------------------------------------<br>Sentiment(polarity=0.6875, subjectivity=0.875)</pre><p><strong>Topic Modeling: </strong><em>Finding hidden themes in large sets of documents.</em></p><p>Let’s peek at topics using Gensim’s LDA:</p><pre>from gensim import corpora, models <br><br>texts = [[&quot;nlp&quot;, &quot;language&quot;, &quot;processing&quot;, &quot;application&quot;], <br>         [&quot;chatbot&quot;, &quot;use&quot;, &quot;nlp&quot;], <br>         [&quot;processing&quot;, &quot;language&quot;, &quot;fun&quot;] ] <br><br>dictionary = corpora.Dictionary(texts) <br>corpus = [dictionary.doc2bow(text) for text in texts] <br>lda = models.LdaModel(corpus, num_topics=2, id2word=dictionary) <br>topics = lda.print_topics() <br><br>for topic in topics: <br>    print(topic) <br>--------------------------------------------------------------------------------------------------------------------------------<br>(0, &#39;0.217*&quot;processing&quot; + 0.209*&quot;language&quot; + 0.138*&quot;nlp&quot; + 0.136*&quot;fun&quot; + 0.132*&quot;application&quot; + 0.088*&quot;chatbot&quot; + 0.080*&quot;use&quot;&#39;)<br>(1, &#39;0.214*&quot;nlp&quot; + 0.154*&quot;use&quot; + 0.147*&quot;chatbot&quot; + 0.145*&quot;language&quot; + 0.138*&quot;processing&quot; + 0.103*&quot;application&quot; + 0.100*&quot;fun&quot;&#39;)</pre><p><strong>Detecting Language: </strong><em>Letting the Computer Guess What You Typed!</em></p><p>The langdetect library works out of the box for 55 languages, no training or setup required. Let’s see it in action:</p><pre>from langdetect import detect<br>from langcodes import Language  <br><br>texts = [&quot;Natural Language Processing is amazing!&quot;, <br>         &quot;La inteligencia artificial está cambiando el mundo.&quot;, <br>         &quot;自然语言处理是人工智能的重要领域。&quot;] <br><br>for text in texts: <br>    lang_code = detect(text) <br>    lang = Language.get(lang_code).language_name()<br>    print(f&quot;Text: {text} -- Detected Language: {lang}\n&quot;) <br>--------------------------------------------------------------------------------------------------------------------------------<br>Text: Natural Language Processing is amazing! -- Detected Language: English<br><br>Text: La inteligencia artificial está cambiando el mundo. -- Detected Language: Spanish<br><br>Text: 自然语言处理是人工智能的重要领域。 -- Detected Language: Chinese</pre><p><strong>Word2Vec: </strong><em>Word2Vec is a clever algorithm invented by Google in 2013. It learns to represent each word as a vector (a list of numbers) so that words used in similar contexts are close together in this “vector space.” It makes it possible for machines to understand similarity and relationships between words<br>Essential for most modern NLP tasks: search, recommendation, summarization, and more</em></p><p>For example, after training, the vectors for “king” and “queen” will be similar, and you’ll find fun math like:</p><p>vector(“king”) — vector(“man”) + vector(“woman”) ≈ vector(“queen”)</p><h4>How Does Word2Vec Work?</h4><blockquote>There are two main training ideas:</blockquote><blockquote>CBOW (Continuous Bag of Words): Predict a word based on its context.<br>Skip-Gram: Predict the context based on a single word.</blockquote><blockquote>Both methods rely on the idea that “you shall know a word by the company it keeps!”</blockquote><pre>from pprint import pprint<br>from gensim.models import Word2Vec<br><br>sentences = [[&#39;i&#39;, &#39;love&#39;, &#39;nlp&#39;],<br>             [&#39;nlp&#39;, &#39;stands&#39;, &#39;for&#39;, &#39;natural&#39;, &#39;language&#39;, &#39;processing&#39;],<br>             [&#39;word2vec&#39;, &#39;creates&#39;, &#39;word&#39;, &#39;embeddings&#39;],<br>             [&#39;embeddings&#39;, &#39;capture&#39;, &#39;meaning&#39;, &#39;of&#39;, &#39;words&#39;]]<br><br>model = Word2Vec(sentences, vector_size=100, window=3, min_count=1, workers=2, seed=42)<br><br>word_vec = model.wv[&#39;nlp&#39;]<br><br>print(&quot;Vector for &#39;nlp&#39; (first 5 dimensions)&quot;)<br>print(f&quot;{word_vec[:5]}\n&quot;)<br><br>print(&quot;Words most similar to &#39;nlp&#39;&quot;)<br>similar_words = model.wv.most_similar(&#39;nlp&#39;)<br>for word, score in similar_words:<br>    print(f&quot;  - {word:&lt;12} → similarity score: {score:.4f}&quot;)<br>--------------------------------------------------------------------------------------------------------------------------------<br>Vector for &#39;nlp&#39; (first 5 dimensions)<br>[ 0.00665473 -0.00600184  0.00609798 -0.00985275  0.00593685]<br><br>Words most similar to &#39;nlp&#39;<br>  - language     → similarity score: 0.1706<br>  - word2vec     → similarity score: 0.1525<br>  - embeddings   → similarity score: 0.0911<br>  - for          → similarity score: 0.0710<br>  - word         → similarity score: 0.0260<br>  - meaning      → similarity score: 0.0053<br>  - words        → similarity score: -0.0030<br>  - i            → similarity score: -0.0155<br>  - creates      → similarity score: -0.0348<br>  - love         → similarity score: -0.0635</pre><p><strong>TF-IDF: </strong><em>TF-IDF stands for Term Frequency–Inverse Document Frequency. It’s a simple but powerful statistic that tells us how important a word is in a specific document, relative to a collection of documents (the “corpus”).</em></p><p>TF (Term Frequency): How often does the word appear in the document?<br>IDF (Inverse Document Frequency): How rare is the word across all documents?</p><h4>How Does TF-IDF Work?</h4><blockquote>TF = (Number of times a word appears in a document) / (Total words in the document)<br>IDF = log(Total number of documents / Number of documents containing the word)</blockquote><blockquote>The TF-IDF score = TF × IDF.</blockquote><blockquote>So words like “the” get a low score (appear everywhere), while special words like “astronaut” get a higher score if they appear in your article but not all the others.</blockquote><pre>import pandas as pd<br>from sklearn.feature_extraction.text import TfidfVectorizer<br><br>docs = [&quot;the moon revolves around the earth&quot;,<br>        &quot;the earth revolves around the sun&quot;,<br>        &quot;an astronaut launched to the moon&quot;]<br><br>vectorizer = TfidfVectorizer()<br>tfidf_matrix = vectorizer.fit_transform(docs)<br>feature_names = vectorizer.get_feature_names_out()<br><br>print(&quot;Vocabulary:&quot;)<br>print(list(feature_names), &quot;\n&quot;)<br><br>print(&quot;TF-IDF Matrix:&quot;)<br>print(pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names).round(2))<br>--------------------------------------------------------------------------------------------------------------------------------<br>Vocabulary:<br>[&#39;an&#39;, &#39;around&#39;, &#39;astronaut&#39;, &#39;earth&#39;, &#39;launched&#39;, &#39;moon&#39;, &#39;revolves&#39;, &#39;sun&#39;, &#39;the&#39;, &#39;to&#39;] <br><br>TF-IDF Matrix:<br>     an  around  astronaut  earth  launched  moon  revolves   sun   the    to<br>0  0.00    0.39       0.00   0.39      0.00  0.39      0.39  0.00  0.61  0.00<br>1  0.00    0.37       0.00   0.37      0.00  0.00      0.37  0.49  0.58  0.00<br>2  0.45    0.00       0.45   0.00      0.45  0.34      0.00  0.00  0.27  0.45</pre><p><strong>Advanced NLP — Transformers and Transfer Learning: </strong><em>The latest leap: teaching computers to understand deep context, nuance, and even generate text!</em></p><p>Thanks to the rise of models like BERT and GPT, NLP has made monumental strides. Leveraging pretrained models, you can tackle tasks such as:</p><ul><li>Question answering</li><li>Text summarization</li><li>Translation</li><li>Chatbot creation</li></ul><p>Now I’ll walk through how to evaluate the overall sentiment of a multi-turn conversation using various popular models, including VADER, DistilBERT, RoBERTa, Facebook’s BART, and OpenAI’s GPT.</p><p><strong>VADER (Valence Aware Dictionary for sEntiment Reasoning): </strong><em>VADER is a lexicon and rule-based sentiment analysis tool especially attuned to social media text. It’s lightweight, requires no training, and is great for quick insights on short texts like tweets or chats.</em></p><pre>import nltk<br>from nltk.sentiment import SentimentIntensityAnalyzer<br><br>nltk.download(&#39;vader_lexicon&#39;)<br><br>SIA = SentimentIntensityAnalyzer()<br><br>conversation = [&quot;Customer: Hi, my internet has been down since yesterday.&quot;,<br>                &quot;Agent: I apologize for the inconvenience. Let me check your connection.&quot;,<br>                &quot;Customer: I have already restarted my router twice.&quot;,<br>                &quot;Agent: Thank you for the information. I see there&#39;s an outage in your area.&quot;,<br>                &quot;Customer: Oh, okay. Hope it gets fixed soon.&quot;,<br>                &quot;Agent: We&#39;re working on it and it should be resolved within 2 hours. Sorry again for the trouble.&quot;]<br><br>full_conversation = &quot; &quot;.join(conversation)<br>overall_score = SIA.polarity_scores(full_conversation)<br>print(f&quot;Overall Conversation Sentiment:\n{overall_score}&quot;)<br>--------------------------------------------------------------------------------------------------------------------------------<br>Overall Conversation Sentiment:<br>{&#39;neg&#39;: 0.089, &#39;neu&#39;: 0.768, &#39;pos&#39;: 0.143, &#39;compound&#39;: 0.4404}</pre><p><strong>DistilBERT (Hugging Face Transformers): </strong><em>DistilBERT is a smaller and faster version of BERT, pre-trained on a large corpus of English language data. It offers robust sentiment classification with transformer-level accuracy while being efficient for inference, making it a popular general-purpose choice.</em></p><pre>from transformers import pipeline<br><br>distilbert_pipe = pipeline(&quot;sentiment-analysis&quot;)<br><br>conversation = [&quot;Customer: Hi, my internet has been down since yesterday.&quot;,<br>                &quot;Agent: I apologize for the inconvenience. Let me check your connection.&quot;,<br>                &quot;Customer: I have already restarted my router twice.&quot;,<br>                &quot;Agent: Thank you for the information. I see there&#39;s an outage in your area.&quot;,<br>                &quot;Customer: Oh, okay. Hope it gets fixed soon.&quot;,<br>                &quot;Agent: We&#39;re working on it and it should be resolved within 2 hours. Sorry again for the trouble.&quot;]<br><br>full_conversation = &quot; &quot;.join(conversation)<br>result = distilbert_pipe(full_conversation)[0]<br><br>label = result[&#39;label&#39;]<br>score = result[&#39;score&#39;]<br><br>polarity = score if label == &quot;POSITIVE&quot; else -score<br><br>print(f&quot;Overall Conversation Sentiment: {label} ({score:.2f})&quot;)<br>print(f&quot;Approximate polarity score: {polarity:.2f}&quot;)<br>--------------------------------------------------------------------------------------------------------------------------------<br>Overall Conversation Sentiment: NEGATIVE (1.00)<br>Approximate polarity score: -1.00</pre><p><strong>Twitter-roBERTa-base (Cardiff NLP): </strong><em>This model, fine-tuned on millions of tweets, excels at analyzing sentiment in social media and conversational contexts. It understands internet slang, hashtags, and the nuances of informal language, providing precise classifications for real-world conversations.</em></p><pre>import torch<br>from scipy.special import softmax<br>from transformers import AutoTokenizer, AutoModelForSequenceClassification<br><br>model_name = &quot;cardiffnlp/twitter-roberta-base-sentiment-latest&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>model = AutoModelForSequenceClassification.from_pretrained(model_name)<br>labels = [&#39;Negative&#39;, &#39;Neutral&#39;, &#39;Positive&#39;]<br><br>conversation = [&quot;Customer: Hi, my internet has been down since yesterday.&quot;,<br>                &quot;Agent: I apologize for the inconvenience. Let me check your connection.&quot;,<br>                &quot;Customer: I have already restarted my router twice.&quot;,<br>                &quot;Agent: Thank you for the information. I see there&#39;s an outage in your area.&quot;,<br>                &quot;Customer: Oh, okay. Hope it gets fixed soon.&quot;,<br>                &quot;Agent: We&#39;re working on it and it should be resolved within 2 hours. Sorry again for the trouble.&quot;]<br><br>full_conversation = &quot; &quot;.join(conversation)<br>encoded_input = tokenizer(full_conversation, return_tensors=&#39;pt&#39;)<br>with torch.no_grad():<br>    output = model(**encoded_input)<br>scores = softmax(output.logits.numpy()[0])<br>sentiment = {l: float(s) for l, s in zip(labels, scores)}<br><br>formatted = &quot;, &quot;.join([f&quot;{label}: {score:.4f}&quot; for label, score in sentiment.items()])<br>print(f&quot;Overall Conversation Sentiment: {formatted}&quot;)<br>--------------------------------------------------------------------------------------------------------------------------------<br>Overall Conversation Sentiment: Negative: 0.5233, Neutral: 0.4428, Positive: 0.0339</pre><p><strong>Facebook BART Large MNLI (Zero-Shot Classification): </strong><em>BART Large MNLI enables zero-shot text classification, letting you feed in any custom set of labels (like “positive,” “negative,” “neutral”). It’s flexible and can adapt to specialized labeling needs, even when not directly trained for sentiment analysis.</em></p><pre>from transformers import pipeline<br><br>zero_shot_pipe = pipeline(&quot;zero-shot-classification&quot;, model=&quot;facebook/bart-large-mnli&quot;)<br><br>conversation = [&quot;Customer: Hi, my internet has been down since yesterday.&quot;,<br>                &quot;Agent: I apologize for the inconvenience. Let me check your connection.&quot;,<br>                &quot;Customer: I have already restarted my router twice.&quot;,<br>                &quot;Agent: Thank you for the information. I see there&#39;s an outage in your area.&quot;,<br>                &quot;Customer: Oh, okay. Hope it gets fixed soon.&quot;,<br>                &quot;Agent: We&#39;re working on it and it should be resolved within 2 hours. Sorry again for the trouble.&quot;]<br><br>labels = [&quot;positive&quot;, &quot;negative&quot;, &quot;neutral&quot;]<br>full_conversation = &quot; &quot;.join(conversation)<br>res = zero_shot_pipe(full_conversation, candidate_labels=labels)<br><br>top_label = res[&#39;labels&#39;][0]<br>top_score = res[&#39;scores&#39;][0]<br><br>polarity_map = {&quot;positive&quot;: 1.0, &quot;neutral&quot;: 0.0, &quot;negative&quot;: -1.0}<br>polarity = polarity_map.get(top_label.lower(), 0.0) * top_score<br>print(f&quot;Overall Conversation Sentiment: {top_label} ({polarity:.2f})&quot;)<br>--------------------------------------------------------------------------------------------------------------------------------<br>Overall Conversation Sentiment: negative (-0.76)</pre><p><strong>OpenAI GPT (Prompt-based Sentiment): </strong><em>OpenAI’s GPT models can perform sentiment analysis via intelligent prompting. You simply ask them to classify text as positive, negative, or neutral, and they’ll use their broad language understanding to respond, especially effective in nuanced or complex scenarios.</em></p><pre>import os<br>from openai import OpenAI<br>from dotenv import load_dotenv  # Load .env variables OPENAI_API_KEY=sk-proj-ln3O07g...EU0A<br><br>load_dotenv()<br><br>api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>if not api_key:<br>    raise ValueError(&quot;API key not found. Make sure .env is loaded and contains OPENAI_API_KEY.&quot;)<br><br>client = OpenAI(api_key=api_key)<br><br>conversation = [&quot;Customer: Hi, my internet has been down since yesterday.&quot;,<br>                &quot;Agent: I apologize for the inconvenience. Let me check your connection.&quot;,<br>                &quot;Customer: I have already restarted my router twice.&quot;,<br>                &quot;Agent: Thank you for the information. I see there&#39;s an outage in your area.&quot;,<br>                &quot;Customer: Oh, okay. Hope it gets fixed soon.&quot;,<br>                &quot;Agent: We&#39;re working on it and it should be resolved within 2 hours. Sorry again for the trouble.&quot;]<br><br>full_conversation = &quot; &quot;.join(conversation)<br><br>prompt = f&quot;Classify the sentiment of the following conversation as positive, negative, or neutral:\n&#39;&#39;&#39;{full_conversation}&#39;&#39;&#39;\nSentiment:&quot;<br><br>response = client.chat.completions.create(model=&quot;gpt-4o-mini&quot;,<br>                                          messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>                                          temperature=0)<br><br>sentiment = response.choices[0].message.content.strip()<br>print(f&quot;Overall Conversation Sentiment: {sentiment}&quot;)<br>--------------------------------------------------------------------------------------------------------------------------------<br>Overall Conversation Sentiment: The sentiment of the conversation can be classified as neutral. <br>While there are elements of inconvenience and apology, the overall tone is focused on <br>problem-solving and providing information, without strong positive or negative emotions.</pre><p>Sentiment analysis has come a long way — from rule-based systems like VADER to state-of-the-art transformer models like GPT-4o. Each model offers unique strengths, and choosing the right one depends on your specific use case. By aggregating sentiment over full conversations, you can move beyond isolated sentence-level judgments to a more human-like, contextual understanding.</p><p>As I continue to explore advanced topics like transformers, large language models, and real-world NLP applications, I plan to keep learning, building, and sharing.<br>Thanks for reading — and happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5fdce368fa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Unveiled: The Process and Its Impact]]></title>
            <link>https://medium.com/@kailashloharvnit/what-is-rag-how-it-works-29b39e2ac57d?source=rss-a078b278508d------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b39e2ac57d</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Kailash Lohar]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 16:36:49 GMT</pubDate>
            <atom:updated>2025-04-27T16:44:36.874Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re using an AI assistant to ask about the latest treatments for a specific medical condition, say diabetes. Traditional LLMs might provide general information based on their training data, which could be outdated or incomplete. This is where RAG comes into play.</p><p>Scenario: You ask, “What are the latest treatments for diabetes?”</p><p>Traditional LLM Response: The model might generate a response based on its pre-existing knowledge, which might not include the most recent advancements or research findings.</p><p>RAG-Enhanced Response:</p><ol><li>Retrieval: The RAG model first searches through external medical databases, such as PubMed, to find the latest research papers and articles on diabetes treatments.</li><li>Generation: Using the retrieved information, the model generates a response that incorporates the most current and authoritative data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*IyStr5zyi46A8gQdpqge4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ZCM8HQU6NPqdlVy-e7jWg.png" /></figure><p><strong>Retriever</strong> — Retrieval is the real time process of finding the most relevant pieces of information from a pre-built index based on user’s question. (Its like asking: <em>From all the knowledge I have which 3–5 chunks are most helpful to answer this query?</em>)</p><p>Tasks of Retriever:</p><ol><li>Query Processing: The retriever converts the input query into vector embeddings, which are numerical representations of the text.</li><li>Similarity Search: It matches these query embeddings with document embeddings from the knowledge base using similarity scores to identify the most relevant documents.</li><li>Information Retrieval: The retriever selects and retrieves the top relevant documents or text chunks that can provide the necessary context for generating a precise and accurate response</li></ol><p><strong>Augmentation</strong> — Augmentation refers to the step where the retrieved documents (chunks of relevant context) are combined with the user’s query to form a new , enriched prompt for the LLM.</p><p><strong>Generation</strong> — Generation is the final step where a Large Language Model (LLM) uses the user’s query and the retrieved &amp; augmented context to generate a response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-wrO_LOQ-T0IlqyEw3YPA.png" /></figure><h4>The Benefits of RAG</h4><ul><li>Enhanced Accuracy: By grounding responses in real-time data, RAG significantly reduces the chances of misinformation.</li><li>Increased Trust: Users can verify the sources of information, fostering greater trust in the AI’s outputs.</li><li>Cost Efficiency: RAG minimizes the need for frequent retraining of models, saving both computational and financial resources.</li></ul><p>In conclusion, Retrieval-Augmented Generation (RAG) is revolutionizing the way LLMs operate, making them more reliable, accurate, and trustworthy. It’s like having a supercharged assistant who not only knows a lot but also knows where to find the best answers, ensuring that you always get the most relevant and precise information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b39e2ac57d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From chaos to clarity, Decoding: ‘Attention Is All You Need’]]></title>
            <link>https://medium.com/@kailashloharvnit/from-chaos-to-clarity-decoding-attention-is-all-you-need-142b14fd5e77?source=rss-a078b278508d------2</link>
            <guid isPermaLink="false">https://medium.com/p/142b14fd5e77</guid>
            <dc:creator><![CDATA[Kailash Lohar]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 18:01:05 GMT</pubDate>
            <atom:updated>2025-04-10T18:01:05.449Z</atom:updated>
            <content:encoded><![CDATA[<h3>From chaos to clarity: Decoding ‘Attention Is All You Need’</h3><p>Imagine you’re at a busy airport, trying to find your friend in the crowd. Instead of scanning every face, you focus on specific features you remember about them — their height, hair color, and the bright red jacket they’re wearing. This focused approach helps you spot your friend quickly. Similarly, the groundbreaking AI model, “Attention Is All You Need,” uses a mechanism called “attention” to focus on the most relevant parts of the data, making it incredibly efficient and powerful. In this blog, we’ll break down this complex concept into simple steps, using easy-to-understand examples to show how attention works and why it’s so important in the world of AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVZh-YwV35nWFvnMvpvA7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*4dbXpxH6uYneSv1dhaHupg.png" /></figure><p><strong>1. Input Embedding</strong>: Each word in the sentence is converted into a continuous vector using an embedding matrix E of size <em>V</em>×<em>d</em>model, where <em>V</em> is the vocabulary size and <em>d</em>model​ is the embedding dimension.​ Currently V = 4 and <em>d</em>model = 2</p><p><strong>Importance</strong>: These embeddings capture semantic information about the words, allowing the model to understand their meanings and relationships</p><p><strong>2. Positional Encoding: </strong>Positional encodings are added to the input embeddings to provide information about the position of each word in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*YZxC3n6gPZiPCYjuBXV3RQ.png" /></figure><p><strong>Importance</strong>: Since the Transformer architecture does not inherently capture the order of sequence, positional encodings provide information about the position of each word in the sequence. This helps the model understand the order and structure of the sentence.</p><p><strong>3. Multi-Head Self-Attention Mechanism: </strong>The multi-head self-attention mechanism allows the model to focus on different parts of the input sequence simultaneously.</p><ul><li>The Query, Key, and Value matrices are computed using learned weight matrices.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*unfc6OeeiUZmZlB9TvPiPw.png" /></figure><ul><li>The attention scores are computed using the scaled dot-product attention formula.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*O_f_jP-C9KkesQw036GX6g.png" /></figure><ul><li>The process is repeated for multiple heads, and the results are concatenated and transformed to produce the final output.</li></ul><p><strong>4. Feed-Forward Network:</strong> The feed-forward network is applied independently to each position in the sequence. It consists of two linear transformations with a ReLU activation in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*zcofjxRzcJ7nmdVcyM1HFg.png" /></figure><p><strong>Importance</strong>: Introduces non-linearity into the model, allowing it to learn more complex patterns and relationships.</p><p><strong>5. Residual Connection and Layer Normalization: </strong>Residual connections add the input of a sub-layer to its output, and layer normalization normalizes the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*mWogw2WOYkkI8TUZFtqbeg.png" /></figure><p><strong>Importance</strong>: Residual connections helps in stabilizing the training process by improving the flow of gradients through the network. This prevents issues like vanishing or exploding gradients while Layer Normalization normalizes the output of each sublayer ensuring that the outputs have a consistent scale while helps in maintaining the stability of the model during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*ueVfXUdnQ1_2bcrVbCYz6Q.png" /></figure><p><strong>1. Input Embedding:</strong> Each word in the target sequence is converted into a continuous vector using an embedding layer.</p><p><strong>2. Positional Encoding:</strong> Positional encoding are added to the input embeddings to provide information about the position of each word in the sequence.</p><p><strong>3. Masked Multi-Head Self-Attention: </strong>The masked multi-head self-attention mechanism ensures that the decoder can only attend to previous tokens in the target sequence, not future tokens. This is crucial for autoregressive generation, where the model generates one token at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*zw1nakO7IEm0H0S_BMUzTw.png" /></figure><p><strong>4. Multi-Head Attention (Encoder-Decoder Attention): </strong>The multi-head attention mechanism allows the decoder to attend to the encoder’s output. This helps the decoder incorporate information from the source sequence.</p><p>The Query (<em>Q</em>) matrix is computed from the decoder’s previous layer output, while the Key (<em>K</em>) and Value (V<em>V</em>) matrices are derived from the encoder’s output.</p><p><strong>5. Feed-Forward Network:</strong> It consists of two linear transformations with a ReLU activation in between.</p><p><strong>6. Residual Connections and Layer Normalization:</strong> Each sub-layer is followed by residual connections and layer normalization to stabilize training and improve gradient flow.</p><p><strong>7. Linear Transformation and Softmax: </strong>Single linear layer projects the decoder output into logits for each word in the target vocabulary. Finally softmax function converts these logits into probabilities, ensuring a valid probability distribution.</p><p>This final step is crucial for generating the translated output, as it determines the probabilities of each word in the target vocabulary based on the decoder’s output.</p><p>In this case, the transformer architecture is explained using <strong>4 tokens of English</strong> and <strong>5 tokens of Hindi language</strong> with an<strong> embedding size of 2</strong>. However, to benchmark the architecture, the authors used an English-German dataset with a vocabulary size of <strong>37,000 tokens</strong> and an <strong>embedding size of 512</strong>. The batch size contains 25,000 source tokens and 25,000 target tokens. Assuming each sentence pair has an average sequence length of 25 tokens, the number of sentence pairs is 1,000. Therefore, the input matrix is of shape (1,000, 25, 512) and the weight matrix is (512, 37,000). Finally, the shape of the final matrix for a single batch is (1,000, 25, 37,000).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=142b14fd5e77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>