<?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 Sivasai Yadav Mudugandla on Medium]]></title>
        <description><![CDATA[Stories by Sivasai Yadav Mudugandla on Medium]]></description>
        <link>https://medium.com/@sivasai-yadav?source=rss-c615257004ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L-yqltIq7QIxZqJyyyan4A.png</url>
            <title>Stories by Sivasai Yadav Mudugandla on Medium</title>
            <link>https://medium.com/@sivasai-yadav?source=rss-c615257004ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:55:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sivasai-yadav/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[How LLMs Actually Process Your Messages: A Clear Guide to Context Windows, Token Limits, and…]]></title>
            <link>https://pub.towardsai.net/how-llms-actually-process-your-messages-a-clear-guide-to-context-windows-token-limits-and-0f9ff996ba8b?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f9ff996ba8b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 09:26:47 GMT</pubDate>
            <atom:updated>2026-03-23T03:21:52.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>How LLMs Actually Process Your Messages: A Clear Guide to Context Windows, Token Limits, and Conversation Flow</h3><h4>A beginner‑friendly explanation of how LLMs handle conversation history and why they sometimes “forget”.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55IOtMdyeMMIgxzTkP6rjw.png" /><figcaption>Generated by NotebookLM</figcaption></figure><p>· <a href="#ea92">1. Introduction</a><br>· <a href="#74d5">2. How LLMs Process Your Input</a><br> ∘ <a href="#df64">1. System instructions</a><br> ∘ <a href="#7d7b">2. Conversation history</a><br> ∘ <a href="#d369">3. Your latest message</a><br>· <a href="#d761">3. What Is a Context Window?</a><br>· <a href="#6f20">A simple way to visualise it</a><br>· <a href="#6fa3">4. Step‑by‑Step Walkthrough: How a Model Reads a Conversation</a><br> ∘ <a href="#7c27">Step 1: You send a new message</a><br> ∘ <a href="#370e">Step 2: The system gathers all relevant context</a><br> ∘ <a href="#43e2">Step 3: It builds one long prompt</a><br> ∘ <a href="#6bdb">Step 4: The model processes the prompt</a><br> ∘ <a href="#a591">Step 5: The model generates a response</a><br> ∘ <a href="#5de4">Flow Diagram (simple and intuitive)</a><br>· <a href="#e2b0">5. Token Counts Explained (With Realistic Numbers)</a><br> ∘ <a href="#ddc7">A simple example with token counts</a><br> ∘ <a href="#6288">Why token math matters</a><br> ∘ <a href="#5092">A larger example</a><br>· <a href="#dc0d">6. What Happens When the Conversation Gets Too Long</a><br> ∘ <a href="#addf">1. Truncate older messages</a><br> ∘ <a href="#9e9a">2. Summarise older messages</a><br> ∘ <a href="#0990">A practical example</a><br>· <a href="#9e94">7. Input Token Limits vs Output Token Limits</a><br> ∘ <a href="#da45">1. Input token limit</a><br> ∘ <a href="#f199">2. Output token limit</a><br> ∘ <a href="#37e3">Why this matters</a><br> ∘ <a href="#2f25">The key takeaway</a><br>· <a href="#fabe">8. Full End‑to‑End Example (Using Our Conversation)</a><br> ∘ <a href="#901b">Step 1: Early conversation (small token usage)</a><br> ∘ <a href="#1d6a">Step 2: Conversation grows (token usage increases)</a><br> ∘ <a href="#0508">Step 3: Conversation exceeds the limit</a><br> ∘ <a href="#4802">Step 4: Model generates a response</a><br> ∘ <a href="#eb10">Step 5: Next turn repeats the cycle</a><br> ∘ <a href="#f18a">Why this example matters</a><br>· <a href="#f522">9. Practical Tips for Users and Developers</a><br> ∘ <a href="#db2d">1. Keep prompts focused and clean</a><br> ∘ <a href="#e1ab">2. Summarise long conversations manually when needed</a><br> ∘ <a href="#936b">3. Don’t assume the model remembers anything</a><br> ∘ <a href="#e080">4. Be aware of output token limits</a><br> ∘ <a href="#2e53">5. When building apps, control the prompt explicitly</a><br> ∘ <a href="#292f">6. Reset the conversation when needed</a><br> ∘ <a href="#e3a8">7. Use shorter variable names, shorter examples, and concise instructions</a><br> ∘ <a href="#7536">8. Remember that context windows are not memory</a></p><h3>1. Introduction</h3><p>As part of my <em>Applied Gen AI</em> course at Johns Hopkins University, I’ve been diving deeper into how Large Language Models actually work behind the scenes. I’ve used LLMs for a while, but I realized I didn’t fully understand what happens when I type a message and the model responds. Does it remember everything I said earlier? Does it store the whole conversation somewhere? Or is something else going on?</p><p>Once I started exploring this topic properly, things finally clicked. LLMs don’t “remember” conversations the way humans do. Instead, they rely on something called a <strong>context window</strong>, and every response is generated from scratch using whatever text fits inside that window.</p><p>In this article, I’m documenting what I learned — in simple, practical terms — along with examples and diagrams that helped me understand the process clearly. If you’ve ever wondered how LLMs handle long chats, why they sometimes forget things, or what “token limits” actually mean, this breakdown should help.</p><h3>2. How LLMs Process Your Input</h3><p>One of the first things I learned is that LLMs are <strong>stateless</strong>. They don’t store your previous messages internally. Instead, every time you send a new message, the system rebuilds the entire context and sends it to the model as one long prompt.</p><p>That prompt usually contains three parts:</p><h4>1. System instructions</h4><p>Instructions or guidelines given to the model at the start (e.g., “You are a helpful assistant”). They’re usually hidden from the user.</p><h4>2. Conversation history</h4><p>All previous messages that still fit inside the model’s context window.</p><h4>3. Your latest message</h4><p>The new input you just typed.</p><p>The model receives all of this text at once and generates a response based only on what’s inside that prompt. If something isn’t included, the model has no way of knowing it happened.</p><p><strong>A simple example</strong></p><p><strong>User:</strong> Who is the CEO of OpenAI? <strong>Assistant:</strong> Sam Altman. <strong>User:</strong> Where did he study?</p><p>Behind the scenes, the system sends something like this to the model:</p><pre>[System]: You are a helpful assistant.<br><br>[User]: Who is the CEO of OpenAI?<br>[Assistant]: Sam Altman.<br><br>[User]: Where did he study?</pre><p>Because the earlier messages are included, the model can correctly interpret “he” as Sam Altman.</p><p>If the system only sent:</p><pre>[User]: Where did he study?</pre><p>The model would have no idea who “he” refers to.</p><p>This was the moment things started making sense for me — the model doesn’t remember anything unless it’s explicitly included in the prompt. The “memory” is just text.</p><h3>3. What Is a Context Window?</h3><p>One of the concepts that finally made things “click” for me was the <strong>context window</strong>.</p><p>A context window is simply the <strong>maximum amount of text (in tokens) that an LLM can read at once</strong>. Think of it like the model’s short-term memory: it can only hold so much information at once. That includes:</p><ul><li>the system prompt</li><li>the entire conversation history</li><li>your latest message</li><li>and even the model’s own output (because output also consumes tokens)</li></ul><p>Different models have different window sizes. Some smaller models support around 4k–8k tokens, while more advanced ones go up to 128k or even 200k tokens. But regardless of size, the rule is the same:</p><blockquote>The model can only “see” what fits inside its context window. Anything beyond that is invisible to it.</blockquote><p>This is why LLMs sometimes “forget” things you said earlier in a long conversation. It’s not because the model is confused — it’s because the older messages literally aren’t included in the prompt anymore.</p><h3>A simple way to visualise it</h3><p>Think of the context window as a <strong>sliding glass window</strong> over your conversation. As the conversation grows:</p><ul><li>new messages enter from the right</li><li>old messages fall out on the left</li></ul><p>The model only sees whatever is inside the window at that moment.</p><p>This sliding behaviour is what allows you to keep chatting with an LLM, even though the model itself never stores long‑term memory.</p><h3>4. Step‑by‑Step Walkthrough: How a Model Reads a Conversation</h3><p>Let’s walk through using a simple example.</p><h4>Step 1: You send a new message</h4><p>Say you ask:</p><blockquote><em>“Where did he study?”</em></blockquote><h4>Step 2: The system gathers all relevant context</h4><p>The system collects:</p><ul><li>the system instructions</li><li>the previous messages</li><li>your new message</li></ul><p>But only the parts that fit inside the context window.</p><h4>Step 3: It builds one long prompt</h4><p>It might look like this:</p><pre>[System]: You are a helpful assistant.<br><br>[User]: Who is the CEO of OpenAI?<br>[Assistant]: Sam Altman.<br><br>[User]: Where did he study?</pre><p>This entire block is what the model receives. There is no hidden memory — this text <em>is</em> the memory.</p><h4>Step 4: The model processes the prompt</h4><p>The model reads the entire prompt token by token. Because “Sam Altman” appears earlier in the prompt, the model can correctly interpret “he.”</p><p>If that earlier message had been trimmed out due to context window limits, the model would no longer know who “he” refers to.</p><h4>Step 5: The model generates a response</h4><p>LLMs generate text one token at a time, predicting the next token based on everything in the prompt. This continues until:</p><ul><li>the model reaches the output token limit</li><li>or it decides the answer is complete</li></ul><h4>Flow Diagram (simple and intuitive)</h4><pre>Your new message<br>        │<br>        ▼<br>System collects:<br>- system prompt<br>- recent history<br>- your message<br>        │<br>        ▼<br>Builds full prompt (must fit in context window)<br>        │<br>        ▼<br>LLM reads entire prompt<br>        │<br>        ▼<br>LLM generates response token by token</pre><h3>5. Token Counts Explained (With Realistic Numbers)</h3><p>One thing that really helped me understand context windows was learning how <strong>tokens</strong> work. Before, I used to think of text in terms of characters or words. But LLMs don’t operate that way — they work with tokens, which are small chunks of text. A token might be a whole word (“cat”), part of a word (“inter‑”), or even punctuation.</p><p>Once I started thinking in tokens, the behaviour of LLMs became much easier to reason about.</p><h4>A simple example with token counts</h4><p>Let’s take a short conversation and assign approximate token counts:</p><pre>Message Approx                           Tokens<br>--------------                           ------<br>System prompt                             50<br>User: “Who is the CEO of OpenAI?”         10<br>Assistant: “Sam Altman.”                  5<br>User: “Where did he study?”               6</pre><p>Total = <strong>71 tokens</strong></p><p>This is tiny compared to most context windows, so the model can easily process everything.</p><h4>Why token math matters</h4><p>Every time you send a message, the system builds a prompt like:</p><pre>SYSTEM + HISTORY + YOUR MESSAGE</pre><p>All of that must fit inside the model’s context window. If the total exceeds the limit, the system has to trim older messages.</p><h4>A larger example</h4><p>Imagine a model with an 8,000‑token context window.</p><p>You’ve had a long conversation:</p><ul><li>20 messages</li><li>each ~300 tokens</li><li>total history = 6,000 tokens</li></ul><p>Add:</p><ul><li>system prompt = 200 tokens</li><li>your new message = 100 tokens</li></ul><p>Total = <strong>6,300 tokens</strong> → fits comfortably.</p><p>But if the conversation grows to:</p><ul><li>30 messages × 300 tokens = 9,000 tokens</li><li>plus system + new message = 300 tokens</li></ul><p>Total = <strong>9,300 tokens</strong> → exceeds the 8,000‑token limit.</p><p>At this point, the system must <strong>trim</strong> older messages until the total fits.</p><h3>6. What Happens When the Conversation Gets Too Long</h3><p>This was one of the most interesting parts for me. I always wondered why LLMs sometimes lose track of earlier details in a long chat. After learning how context windows work, the answer became obvious.</p><p>When the conversation grows too long, the system has two options:</p><h4>1. Truncate older messages</h4><p>This is the simplest approach. The system removes the oldest messages until the remaining text fits inside the context window.</p><h4>2. Summarise older messages</h4><p>Some systems generate a short summary of earlier parts of the conversation and include that summary instead of the full text. This helps preserve meaning while reducing token usage.</p><p><strong>The sliding window effect</strong></p><p>The easiest way to visualise this is to imagine a sliding window moving across your conversation:</p><pre>[Old messages fall out]   [New messages come in]<br>        ◄───────────────  CONTEXT WINDOW  ───────────────►</pre><p>The model only sees what’s inside that window at any given moment.</p><h4>A practical example</h4><p>Let’s say the context window is 8,000 tokens.</p><p>Your conversation grows to 9,300 tokens. The system might keep only the last 7,700 tokens, plus:</p><ul><li>system prompt (200 tokens)</li><li>your latest message (100 tokens)</li></ul><p>Total = <strong>8,000 tokens</strong> → fits perfectly.</p><p>Everything older than that is gone.</p><p><strong>Flow diagram: what happens when the limit is reached</strong></p><pre>Full conversation (9,300 tokens)<br>            │<br>            ▼<br>Exceeds context window (8,000 tokens)<br>            │<br>            ▼<br>System trims oldest 1,300 tokens<br>            │<br>            ▼<br>SYSTEM + RECENT HISTORY + NEW MESSAGE = 8,000 tokens<br>            │<br>            ▼<br>Model generates response</pre><blockquote>NOTE: <strong>The model’s <em>output tokens</em> do NOT count toward the context window <em>before</em> the model generates them.</strong> <strong>They only count <em>after</em> they are generated and added back into the conversation history.</strong></blockquote><h3>7. Input Token Limits vs Output Token Limits</h3><p>One thing that confused me early on was the difference between <strong>input token limits</strong> and <strong>output token limits</strong>. I used to think the context window was one big bucket that included both input and output together. But that’s not actually how it works.</p><p>LLMs have <strong>two separate limits</strong>:</p><h4>1. Input token limit</h4><p>This is the maximum number of tokens the model can <em>read</em> at once. It includes:</p><ul><li>system prompt</li><li>conversation history</li><li>your latest message</li></ul><p>All of this must fit inside the context window.</p><h4>2. Output token limit</h4><p>This is the maximum number of tokens the model is allowed to <em>generate</em> in its response.</p><p>These two limits work together, but they’re not the same thing.</p><p><strong>A practical example</strong></p><p>Let’s say a model supports:</p><ul><li><strong>128k input tokens</strong></li><li><strong>4k output tokens</strong></li></ul><p>If your prompt (system + history + your message) is <strong>120k tokens</strong>, the model can still generate up to <strong>4k tokens</strong> in its response.</p><p>But if your prompt is already <strong>128k tokens</strong>, the model has no room to generate a long answer. It might:</p><ul><li>produce a very short response</li><li>or stop early</li><li>or refuse due to token constraints</li></ul><h4>Why this matters</h4><p>Understanding this helped me avoid a common mistake: sending extremely long prompts and expecting long, detailed answers.</p><p>If the input is too large, the output has to shrink.</p><h4>The key takeaway</h4><blockquote>Even if the input completely fills the context window, the model can still generate output because output tokens have a separate limit. However, when the input is extremely large, the model may produce shorter or lower‑quality responses due to reduced internal reasoning capacity. After generating output, the system trims older messages to make room for the new tokens.</blockquote><p>Once I understood this, the whole system felt much more predictable.</p><h3>8. Full End‑to‑End Example (Using Our Conversation)</h3><h4>Step 1: Early conversation (small token usage)</h4><p>You ask:</p><blockquote><em>“Who is the CEO of OpenAI?”</em></blockquote><p>The model replies:</p><blockquote><em>“Sam Altman.”</em></blockquote><p>Then you ask:</p><blockquote><em>“Where did he study?”</em></blockquote><p>Behind the scenes, the system builds this prompt:</p><pre>[System]: You are a helpful assistant.<br><br>[User]: Who is the CEO of OpenAI?<br>[Assistant]: Sam Altman.<br><br>[User]: Where did he study?</pre><p>Let’s assign approximate token counts:</p><pre>Component                     Tokens<br>---------                     ------<br>System prompt                 50<br>First user message            10<br>Assistant reply               5<br>Second user message           6</pre><p>Total = <strong>71 tokens</strong></p><p>This is tiny compared to most context windows, so the model easily handles it.</p><h4>Step 2: Conversation grows (token usage increases)</h4><p>As we keep talking, each message adds more tokens to the history. Eventually, the total might reach something like:</p><ul><li>System prompt: 200 tokens</li><li>History: 7,700 tokens</li><li>Your latest message: 100 tokens</li></ul><p>Total = <strong>8,000 tokens</strong></p><p>If the model’s context window is 8,000 tokens, this fits perfectly.</p><h4>Step 3: Conversation exceeds the limit</h4><p>Now imagine the history grows to 9,300 tokens. The system must trim older messages.</p><p>It might keep:</p><ul><li>System prompt: 200 tokens</li><li>Recent history: 7,700 tokens</li><li>Your latest message: 100 tokens</li></ul><p>Total = <strong>8,000 tokens</strong> (fits again)</p><p>Everything older than that is removed.</p><h4>Step 4: Model generates a response</h4><p>The model now generates its output — say 150 tokens. These 150 tokens get appended to the history for the <em>next</em> turn.</p><h4>Step 5: Next turn repeats the cycle</h4><p>On your next message, the system again:</p><ul><li>collects system prompt</li><li>collects recent history</li><li>adds your new message</li><li>trims if needed</li><li>sends the final prompt to the model</li></ul><p>This cycle repeats indefinitely.</p><h4>Why this example matters</h4><p>Seeing the whole flow end‑to‑end made me realise:</p><ul><li>LLMs don’t remember anything internally</li><li>The “memory” is just text inside the context window</li><li>Older messages fall out as the conversation grows</li><li>Token limits shape everything the model can do</li></ul><h3>9. Practical Tips for Users and Developers</h3><p>After learning how context windows, token limits, and prompt construction actually work, I started adjusting the way I interact with LLMs. These are some practical tips that helped me get better results, both as a user and as someone building small LLM projects.</p><h4>1. Keep prompts focused and clean</h4><p>The more unnecessary text you include, the faster you fill the context window. Short, clear prompts give the model more room to reason.</p><h4>2. Summarise long conversations manually when needed</h4><p>If you’re working on a long chat, occasionally summarising earlier parts helps preserve meaning while reducing token usage.</p><h4>3. Don’t assume the model remembers anything</h4><p>If something is important, restate it. This ensures it stays inside the context window.</p><h4>4. Be aware of output token limits</h4><p>If you need a long, detailed answer, make sure the output limit is high enough. Otherwise, the model may stop early.</p><h4>5. When building apps, control the prompt explicitly</h4><p>If you’re developing with LLMs, you should decide:</p><ul><li>how much history to keep</li><li>when to summarise</li><li>how to structure the system prompt</li><li>how to manage token budgets</li></ul><p>Leaving everything to the default chat interface can lead to unpredictable behaviour.</p><h4>6. Reset the conversation when needed</h4><p>If the model starts giving short or low‑quality answers, it might be because the context window is full. Starting a new chat gives the model a fresh window to work with.</p><h4>7. Use shorter variable names, shorter examples, and concise instructions</h4><p>This is especially important in RAG systems or agent workflows where prompts grow quickly.</p><h4>8. Remember that context windows are not memory</h4><p>They are just temporary text buffers. If you need real memory, you have to build it yourself (e.g., vector stores, summaries, or external state).</p><p>These small adjustments made a noticeable difference in the quality of responses I got from LLMs.</p><p>Some of my other posts you may find interesting</p><ul><li><a href="https://pub.towardsai.net/system-prompts-explained-how-understanding-them-makes-you-a-better-ai-communicator-b9ed72a0f971">System Prompts Explained: How Understanding Them Makes You a Better AI Communicator</a></li><li><a href="https://pub.towardsai.net/the-3-stage-training-pipeline-behind-chatgpt-claude-and-gemini-explained-simply-bbd45b1f7368">The 3‑Stage Training Pipeline Behind ChatGPT, Claude, and Gemini (Explained Simply)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f9ff996ba8b" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/how-llms-actually-process-your-messages-a-clear-guide-to-context-windows-token-limits-and-0f9ff996ba8b">How LLMs Actually Process Your Messages: A Clear Guide to Context Windows, Token Limits, and…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Free AI Research Digest: From arXiv to Your Inbox Using Llama 3.1, Groq, and SendGrid]]></title>
            <link>https://pub.towardsai.net/building-a-free-ai-research-digest-from-arxiv-to-your-inbox-using-llama-3-1-groq-and-sendgrid-5fc92ba6a819?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fc92ba6a819</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 21:45:04 GMT</pubDate>
            <atom:updated>2026-03-17T04:27:37.709Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How I built a free AI research newsletter from scratch — and everything that broke along the way</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orRu9Mg_lSEGViqIH5wX2g.png" /><figcaption>Generated by NotebookLM</figcaption></figure><p>As part of my Applied Gen AI course, I’ve been putting concepts into practice by building real projects.</p><p>This is one of them.</p><h3>Table of Content</h3><p>· <a href="#db3f">1. The Problem I Was Trying to Solve</a><br>· <a href="#dfea">2. What Is AI Research Digest?</a><br>· <a href="#77e3">3. The Architecture — How It Works</a><br>· <a href="#7e0e">4. The Tech Stack</a><br>· <a href="#13db">5. Building Phase by Phase — What Worked First Try</a><br>· <a href="#42d1">6. Everything That Broke</a><br> ∘ <a href="#1289">6.1 Gmail SMTP — Silently Blocked</a><br> ∘ <a href="#b82d">6.2 Resend — Sandboxed to Your Own Email</a><br> ∘ <a href="#5368">6.3 SendGrid — DMARC Rejection</a><br> ∘ <a href="#012c">6.4 The HuggingFace Inference API — The One That Cost the Most Time</a><br>· <a href="#e0d1">7. Under the Hood — The Ranking Algorithm</a><br> ∘ <a href="#205c">The Scoring Factors</a><br> ∘ <a href="#ead0">What I Would Change</a><br>· <a href="#4899">8. Prompt Engineering — Getting Structured Output From an LLM</a><br> ∘ <a href="#99a1">The Problem With Free-Form Prompts</a><br> ∘ <a href="#636a">The Structured Prompt</a><br> ∘ <a href="#f42d">One Limitation Worth Acknowledging</a><br>· <a href="#c485">9. Edge Cases I Had to Handle</a><br> ∘ <a href="#be2c">Edge Case 1 — Too Few Papers Match the User’s Selected Topics</a><br> ∘ <a href="#75a1">Edge Case 2 — All Topics Selected (The Default State)</a><br> ∘ <a href="#56c5">Edge Case 3— Duplicate Papers Across Sources</a><br> ∘ <a href="#f941">Edge Case 54— The LLM Ignores the Prompt Format</a><br>· <a href="#27ef">10. What’s Next</a><br>· <a href="#d368">11. Try It Yourself</a></p><h3>1. The Problem I Was Trying to Solve</h3><p>Every day, hundreds of AI research papers get published on arXiv. Transformer architectures, new fine-tuning techniques, safety benchmarks, diffusion model improvements — the field moves fast, and it shows no signs of slowing down.</p><p><em>Keeping up with it properly is harder than it sounds. It is not just the volume — though 200 papers a day is genuinely unmanageable for anyone with a job. </em><strong><em>It is also the quality of information available about that research.</em></strong><em> Blog posts summarise papers they have not fully read. Social media threads strip findings down to a single provocative sentence, often without linking to the original. Newsletter aggregators pull from other aggregators until the original meaning is diluted beyond recognition. </em><strong><em>By the time an insight reaches most people, it has passed through several layers of reinterpretation — each one introducing a little more noise, a little less accuracy.</em></strong></p><p>If you want to know what the AI research community is actually working on, there is really only one reliable option: go directly to the source.</p><p>What I wanted was straightforward. An email in my inbox every morning pulling directly from arXiv and HuggingFace Papers — the primary sources the research community actually publishes to and cites from — with the most relevant papers from the last 24 hours summarised in plain English. Not reworded abstracts. Not someone else’s interpretation. Something accurate, readable, and trustworthy. Something I could read over coffee, and that a non-technical colleague could understand too.</p><p>I could not find a free tool that did this well. So I built one.</p><p>AI Research Digest is an automated pipeline that fetches papers directly from arXiv and HuggingFace Papers, ranks them using a custom scoring algorithm, summarises each one using Llama 3.1 8B, and delivers a styled HTML newsletter to your inbox every morning. You can choose your topics, the number of papers, and set it on a daily schedule. The entire infrastructure costs approximately <strong>$3</strong> per year.</p><p>This article is not a polished tutorial. It is an honest documentation of the build — <strong>what I designed, what worked, and what broke along the way</strong>. If you are building something similar, I hope the account of the failures is as useful as the account of the solutions.</p><h3>2. What Is AI Research Digest?</h3><p>At its core, AI Research Digest is a personalised newsletter engine. Every morning, it wakes up, scans the latest AI research published in the last 24 hours, picks the most relevant papers based on your interests, and sends you a clean HTML email with each paper summarised in plain English.</p><p>The summaries are not abstracts copy-pasted from the paper, and they are not someone else’s interpretation of someone else’s summary. Each one is generated directly from the original abstract using Llama 3.1 8B, structured into four parts: a headline that captures the key finding in one sentence, a plain explanation of what the research actually does, a note on why it matters in the real world, and an analogy that makes the concept accessible to anyone. Every summary links directly to the original paper — the reader is always one click away from the primary source.</p><p>Here is what a typical digest looks like in your inbox:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*RZlX4HxFVVpTByYluq906g.png" /></figure><p>Two things are worth being explicit about here. First, the pipeline pulls exclusively from arXiv and HuggingFace Papers. arXiv is the de facto standard repository for AI research — it is where the community publishes, where peer review begins, and where every serious citation traces back to. HuggingFace Papers is community-curated by ML practitioners who surface work they consider significant. There are no blog posts in the pipeline, no aggregator middlemen, no summaries of summaries. Every paper in the digest is a primary source.</p><p>Second, the summaries are generated fresh every day from the actual abstract — not cached, not recycled, not editorially filtered by anyone’s agenda. What you read in the digest reflects what the research community published in the last 24 hours, nothing more and nothing less.</p><p>The product is built for two kinds of people. Developers and researchers who want to stay current with the field without spending hours on arXiv every day. And non-technical professionals — managers, product leads, executives — who work alongside AI teams and want to understand what the research community is focused on, without needing a PhD to follow along.</p><p>It runs entirely on <strong>free infrastructure</strong>. The only thing I paid for was a domain name.</p><h3>3. The Architecture — How It Works</h3><p>The application is a four-phase linear pipeline. Each phase has one responsibility, takes a defined input, and produces a defined output. Nothing more.</p><pre>┌──────────────────────────────────────────────────────────────┐<br>│                  GRADIO UI (HuggingFace Space)               │<br>│         [Email Input]   [Send Now / Daily Schedule]          │<br>│         [Live Status Log]   [HTML Email Preview Tab]         │<br>└─────────────────────────┬────────────────────────────────────┘<br>                          │<br>              ┌───────────▼───────────┐<br>              │       app.py          │<br>              │   run_pipeline()      │  Orchestrates all phases<br>              │   handle_submit()     │  Streams progress to UI<br>              └───────────┬───────────┘<br>                          │<br>         ┌────────────────┼────────────────┐<br>         ▼                                 ▼<br>┌─────────────────┐               ┌─────────────────┐<br>│  fetcher_arxiv  │               │   fetcher_hf    │  PHASE 1<br>│  arXiv REST API │               │  BS4 Scraper    │<br>└────────┬────────┘               └────────┬────────┘<br>         └──────────────┬──────────────────┘<br>                ┌───────▼────────┐<br>                │  filter_agent  │  PHASE 2<br>                │  Score &amp; Rank  │<br>                └───────┬────────┘<br>                ┌───────▼────────┐<br>                │summariser_agent│  PHASE 3<br>                │   Groq API     │<br>                │ Llama 3.1 8B   │<br>                └───────┬────────┘<br>                ┌───────▼────────┐<br>                │newsletter_agent│  PHASE 4<br>                │ Jinja2 + HTML  │<br>                │  SendGrid API  │<br>                └───────┬────────┘<br>                        │<br>              ┌─────────▼──────────┐<br>              │   User&#39;s Inbox +   │<br>              │   Gradio Preview   │<br>              └────────────────────┘<br><br>         ┌──────────────────────┐<br>         │   job_scheduler.py   │  OPTIONAL<br>         │    APScheduler       │  Daily cron jobs<br>         │   Daily 08:00 UTC    │  per subscribed email<br>         └──────────────────────┘</pre><p><strong>Phase 1 — Fetch</strong> pulls papers from two sources simultaneously. The arXiv fetcher queries five categories — cs.AI, cs.LG, cs.CL, cs.CV, and stat.ML — using their public REST API, filtering to papers published in the last 48 hours. The HuggingFace fetcher scrapes huggingface.co/papers using BeautifulSoup, doing a two-stage fetch: first the listing page for titles and URLs, then each individual paper page for the full abstract.</p><p><strong>Phase 2 — Filter &amp; Rank</strong> takes the combined pool of up to 100 papers and produces a ranked shortlist. It merges both lists, removes duplicates, filters out low-quality entries, scores every remaining paper using a multi-factor algorithm, and selects the top N while guaranteeing at least one paper from each source.</p><p><strong>Phase 3 — Summarise</strong> sends each selected paper to Llama 3.1 8B via the Groq API with a structured prompt that instructs the model to respond in four labelled sections. The response is parsed back into a structured object.</p><p><strong>Phase 4 — Deliver</strong> passes the summarised papers to a Jinja2 HTML template, renders the final email, and posts it to SendGrid’s REST API for delivery.</p><p>Each phase is a separate Python class in its own file. They share only a common Paper dataclass. This means each phase can be tested, replaced, or debugged in isolation — which turned out to be very useful when things started breaking.</p><p><strong>Why a linear pipeline and not LangChain?</strong></p><p>LangChain is designed for dynamic pipelines where an LLM decides what tools to call and in what order. That is genuinely powerful for open-ended agents. But this pipeline always executes the same four steps in the same order — no branching, no tool selection, no dynamic control flow. Introducing LangChain would add abstractions and dependencies without adding any capability. A linear pipeline is fully deterministic. I know exactly what runs, in what order, and where it fails when something goes wrong. For something that needs to reliably deliver an email every morning, that predictability matters more than flexibility.</p><h3>4. The Tech Stack</h3><p>Every tool in this stack was chosen deliberately — either for a specific technical reason, or because an earlier choice failed and forced a better one. Here is the full picture.</p><p><strong>HuggingFace Spaces — Hosting</strong></p><p>HuggingFace Spaces runs Gradio applications for free with a public URL and direct git-based deployment. No server configuration, no Dockerfile, no cloud billing. You push to a git remote, and it deploys.</p><p>The tradeoff on the free tier is real though. The Space goes to sleep after 15 minutes of inactivity. When it wakes up, anything stored in memory — including scheduled jobs — is gone. For a portfolio project this is acceptable. For production, you would back the scheduler with a persistent store like PostgreSQL or Redis so jobs survive restarts.</p><p><strong>Gradio — User Interface</strong></p><p>Gradio is native to HuggingFace Spaces and needs zero additional setup. The UI has four components: an email input, a Send Now / Daily Schedule toggle, a live status log, and an HTML email preview tab.</p><p>The feature that made Gradio particularly suitable here is generator-based streaming. The submit handler uses Python’s yield keyword to push status updates to the UI after each pipeline phase completes. Without this, a user clicks Send and stares at a blank screen for 60 to 90 seconds with no indication anything is happening. With it, they see something like this in real time:</p><pre><br>📡 Phase 1 of 4 — Fetching papers...<br>   Querying arXiv API...<br>   ✅ arXiv: 85 papers fetched<br>   Scraping HuggingFace Papers...<br>   ✅ HuggingFace: 20 papers fetched<br>   📊 Total collected: 105 papers<br><br>🔍 Phase 2 of 4 — Filtering &amp; ranking 105 papers...<br>   ✅ Top 5 papers selected:<br>      [1] MedMASLab: A Unified Orchestration Framework for Ben...<br>      [2] Omni-Diffusion: Unified Multimodal Understanding and...<br>      [3] Reading, Not Thinking: Understanding and Bridging th...<br>      [4] Influencing LLM Multi-Agent Dialogue via Policy-Para...<br>      [5] SignalMC-MED: A Multimodal Benchmark for Evaluating ...<br><br>🤖 Phase 3 of 4 — Summarising with Llama 3.1 8B via Groq...<br>   (~15 sec per paper × 5 papers)<br>   ⏳ [1/5] Summarising: MedMASLab: A Unified Orchestration Framework for B...<br>   ✅ [1/5] Done in 2.6s<br>   ⏳ [2/5] Summarising: Omni-Diffusion: Unified Multimodal Understanding a...<br>   ✅ [2/5] Done in 0.4s<br>   ⏳ [3/5] Summarising: Reading, Not Thinking: Understanding and Bridging ...<br>   ✅ [3/5] Done in 0.6s<br>   ⏳ [4/5] Summarising: Influencing LLM Multi-Agent Dialogue via Policy-Pa...<br>   ✅ [4/5] Done in 0.6s<br>   ⏳ [5/5] Summarising: SignalMC-MED: A Multimodal Benchmark for Evaluatin...<br>   ✅ [5/5] Done in 0.5s<br>   ⏱ Total summarisation time: 4.6s<br><br>📧 Phase 4 of 4 — Sending newsletter to *******@gmail.com...</pre><p>That live feedback is the difference between a tool that feels alive and one that feels broken.</p><p><strong>arXiv REST API — Primary Paper Source</strong></p><p>arXiv provides a free, unauthenticated REST API returning structured Atom XML. No API key, no rate limit worries for reasonable usage, well-documented. The fetcher queries five categories</p><pre>cs.AI  — Artificial Intelligence<br>cs.LG  — Machine Learning<br>cs.CL  — Computation and Language<br>cs.CV  — Computer Vision<br>stat.ML — Statistics / Machine Learning</pre><p>The query window is set to 48 hours rather than 24 to account for weekends and publication delays. Papers are deduped later in Phase 2, so pulling slightly more than needed is not a problem.</p><p><strong>HuggingFace Papers — Secondary Paper Source</strong></p><p>HuggingFace Papers has no public API, so BeautifulSoup scraping was the only option. The fetch is two-stage by necessity: the listing page at huggingface.co/papers contains titles and URLs but not full abstracts. A second request to each individual paper page retrieves the abstract. This is slower than the arXiv API but the community-curation signal is worth it — papers that make it to HuggingFace Papers were surfaced by someone in the ML community as worth reading.</p><p><strong>Llama 3.1 8B Instruct via Groq — Summarisation</strong></p><p>This was not my original choice. The full story is in Section 6. Llama 3.1 8B is Meta’s open-source model fine-tuned for instruction following. It produces clean structured output when given explicit labels in the prompt — which is exactly what this pipeline needs. The Groq API uses OpenAI-compatible chat completion format:</p><pre>{<br>    &quot;model&quot;: &quot;llama-3.1-8b-instant&quot;,<br>    &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>    &quot;max_tokens&quot;: 700,<br>    &quot;temperature&quot;: 0.7<br>}</pre><p>Groq runs Llama on custom LPU hardware. Responses come back in one to two seconds. The free tier gives 14,400 requests per day — more than sufficient for a daily digest pipeline.</p><p><strong>SendGrid — Email Delivery</strong></p><p>Also not my original choice. Three providers failed before this one. SendGrid’s free tier sends up to 100 emails per day over HTTPS (port 443 — never blocked by hosting platforms), and supports proper DKIM and DMARC domain authentication, which is non-negotiable for Gmail deliverability. The API integration is a single POST request:</p><pre>requests.post(<br>    &quot;https://api.sendgrid.com/v3/mail/send&quot;,<br>    headers={&quot;Authorization&quot;: f&quot;Bearer {SENDGRID_API_KEY}&quot;},<br>    json={&quot;personalizations&quot;: [...], &quot;from&quot;: {...}, &quot;content&quot;: [...]}<br>)</pre><p>A 202 response means accepted and queued. Not 200 — SendGrid does not confirm delivery synchronously. The email is queued and sent within seconds.</p><p><strong>Porkbun — Domain</strong></p><p>airesearchdigest.cv registered for approximately $3. The domain exists for one reason: email authentication. Gmail will not deliver emails where the From domain is not authenticated with the sending server. You cannot use a Gmail address as the From field in SendGrid because Google owns gmail.com. Owning your own domain lets you add SendGrid&#39;s CNAME records to your DNS, prove ownership, and send authenticated email that lands in inboxes rather than spam.</p><p><strong>Jinja2 — Email Templating</strong></p><p>Industry-standard Python templating — the same engine used in Flask and Django. The HTML email template is entirely separate from the pipeline logic. It loops over papers, renders source badges, formats dates, and handles the dark-themed layout. Changing the email design requires touching only email_template.html, nothing else in the pipeline.</p><p><strong>APScheduler — Scheduling</strong></p><p>A lightweight Python library that registers background cron jobs. One call to scheduler.add_job() sets up a daily run at 08:00 UTC for a given subscriber, storing their preferences — paper count, sources, and topics — as arguments on the job so every scheduled run respects what they configured.</p><p><strong>The Full Cost Breakdown</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*CyW0qRAAHaYZvoRmqsVccA.png" /></figure><h3>5. Building Phase by Phase — What Worked First Try</h3><p>Not everything in this project was a struggle. Before getting to what broke, it is worth documenting what worked cleanly from the start — partly for completeness, and partly because understanding the stable parts makes the failures easier to isolate.</p><p><strong>The arXiv Fetcher</strong></p><p>The arXiv REST API is one of the most developer-friendly public APIs I have worked with. No authentication, no rate limit headaches for reasonable usage, well-structured Atom XML responses. The fetcher queries five categories with a 48-hour window, parses the response into a list of Paper dataclass objects, and returns them. It worked correctly on the first run and never needed revisiting.</p><p>The 48-hour window rather than 24 was a deliberate choice. arXiv does not publish on weekends, and submission timestamps can lag. A 24-hour window on a Monday morning would miss everything published Friday. The filter agent handles duplicates downstream, so pulling a slightly wider window costs nothing.</p><p><strong>The HuggingFace Papers Fetcher</strong></p><p>The scraper required a bit more care. HuggingFace Papers has no public API, so BeautifulSoup was the only option. The two-stage fetch — listing page first for titles and URLs, then individual paper pages for full abstracts — added complexity but worked reliably once the correct CSS selectors were identified. The community-curation signal this source provides is worth the extra fetch overhead. Papers that appear on HuggingFace Papers were put there by ML practitioners who considered them significant — a quality filter that no algorithm can fully replicate.</p><p><strong>The Filter and Ranking Algorithm</strong></p><p>The scoring model came together cleanly. Each paper receives points across four independent factors: recency (max 30 points), title keyword relevance (max 25 points), abstract keyword relevance (max 20 points), and abstract length as a proxy for detail (max 15 points). A topic personalisation bonus of up to 15 additional points is applied when the user has filtered by specific topics.</p><p>After scoring, a balanced selection algorithm guarantees at least one paper from each source before filling remaining slots by score. This prevents a situation where all five papers in a digest come from the same provider on a given day — source diversity is enforced structurally, not left to chance.</p><p>The algorithm is simple by design. A more sophisticated approach — TF-IDF weighting, semantic embeddings, learned ranking — would produce marginally better results but would also introduce model dependencies, latency, and maintenance overhead. For a daily digest of five papers, a well-tuned linear scoring model is entirely sufficient and far easier to reason about when something behaves unexpectedly.</p><p><strong>The Email Template</strong></p><p>The Jinja2 HTML template worked on the first render. Dark-themed, paper cards with source badges, a gradient read button for each paper, and a clean footer. Keeping the template entirely separate from the pipeline logic paid off immediately — iterating on the email design meant editing one HTML file, with no risk of touching pipeline code.</p><p><strong>The Gradio UI</strong></p><p>The streaming UI came together without major issues. The generator-based yield pattern in the submit handler streams phase-by-phase status updates to the live log in real time. The interface has four components — email input, mode toggle (Send Now vs Daily Schedule), a paper count slider from 3 to 10, and topic and source filter checkboxes. Validation runs before the pipeline starts: if no sources are selected, or no topics are selected, the pipeline does not run and the user sees an immediate error rather than a silent failure partway through.</p><p>One design decision worth noting: the topic filter includes a graceful fallback. If a user selects only niche topics — say, only Science &amp; Healthcare — and fewer than three papers match on a given day, the pipeline automatically falls back to the full paper pool rather than sending a near-empty digest. The topic bonus in the scoring model still pushes matching papers to the top, so on-topic papers rank above off-topic ones even in fallback mode. The user gets a useful digest regardless of how narrow their topic selection is.</p><h3>6. Everything That Broke</h3><p>This is the section I wish existed when I was building. Every problem below cost time that it should not have — not because the solutions were complicated, but because the root causes were not obvious from the surface symptoms. Here is the honest account.</p><h4>6.1 Gmail SMTP — Silently Blocked</h4><p><strong>What I tried</strong></p><p>The original plan for email delivery was Gmail SMTP. Simple, free, no new accounts or API keys. Configure the host, port, credentials, and send. It is the standard approach most tutorials suggest.</p><p><strong>What happened</strong></p><p>Every connection attempt timed out. No error message, no rejection notice — just silence. The code appeared to run correctly. Nothing arrived.</p><p><strong>The root cause</strong></p><p>HuggingFace Spaces blocks outbound connections on port 587 — the standard SMTP port — as a platform-level security policy to prevent spam from their infrastructure. The connection was dying at HuggingFace’s firewall before it ever reached Gmail’s servers. There was nothing wrong with the SMTP configuration. The port was simply not available.</p><p><strong>The fix</strong></p><p>Switch to an email provider that operates entirely over HTTPS on port 443 — the same port used by every website on the internet, which hosting platforms never block. That meant moving away from SMTP entirely and towards an API-based email service.</p><p>The lesson here is not specific to HuggingFace. Any managed hosting platform — Heroku, Railway, Render — is likely to have similar port restrictions. If you are building an application that sends email and you plan to host it on a managed platform, assume SMTP is blocked and design around an API provider from the start.</p><h4>6.2 Resend — Sandboxed to Your Own Email</h4><p><strong>What I tried</strong></p><p>Resend is a modern email API built for developers. It operates over HTTPS, has a clean API, good documentation, and a free tier. It looked like the right solution after the SMTP failure.</p><p><strong>What happened</strong></p><p>Emails delivered successfully in testing. The moment I tried sending to any email address other than my own verified address, delivery silently failed.</p><p><strong>The root cause</strong></p><p>Resend’s free tier operates in sandbox mode. You can only send to email addresses you have personally verified in their dashboard. To send to anyone else — including real users — you need to verify a domain. This limitation is not prominently documented during onboarding. It only becomes apparent when you test with a second email address and nothing arrives.</p><p><strong>The fix</strong></p><p>Switch to SendGrid, which allows sending to any email address on the free tier once your sender domain is verified. The domain verification requirement is the same — you still need to own a domain and authenticate it — but there is no sandbox restriction on recipients.</p><h4>6.3 SendGrid — DMARC Rejection</h4><p><strong>What I tried</strong></p><p>After switching to SendGrid, I configured the From address as my personal Gmail address. SendGrid accepted the request and returned a 202 response. The email appeared to send successfully.</p><p><strong>What happened</strong></p><p>The email never arrived. No bounce notification, no error from SendGrid — just a clean 202 and then nothing in the inbox.</p><p><strong>The root cause</strong></p><p>DMARC alignment failure. Gmail has strict authentication rules: the domain in the From address must match a domain that has been authenticated with the sending server via DNS records. Google owns gmail.com. When SendGrid sends an email claiming to be from a Gmail address, Gmail’s servers look up the DNS records for gmail.com, find no authorisation for SendGrid, and silently reject the message.</p><p>The 202 from SendGrid does not mean the email was delivered — it means SendGrid accepted it into their queue. What happens after that depends entirely on whether the receiving mail server trusts the sender. In this case, it did not.</p><p><strong>The fix</strong></p><p>Register a domain you actually own and authenticate it with SendGrid. The process involves adding three CNAME records to your domain’s DNS settings — records that SendGrid provides — which prove to receiving mail servers that SendGrid is authorised to send email on behalf of that domain. Once those records are in place and verified, emails from your custom domain pass DMARC checks and land in inboxes.</p><p>The domain airesearchdigest.cv was registered on Porkbun for approximately $1. Three CNAME records added in Porkbun&#39;s DNS panel, verified in SendGrid, and the problem was resolved. This is now the only paid component in the entire stack.</p><h4>6.4 The HuggingFace Inference API — The One That Cost the Most Time</h4><p>This is the failure worth telling in detail.</p><p><strong>What I tried</strong></p><p>The summarisation phase was originally built on the HuggingFace Inference API — a free service at api-inference.huggingface.co that allowed you to call any hosted model by name. No separate account, no additional API key beyond the HuggingFace token already in use for the paper fetcher. I used Zephyr-7B initially, then switched to Mistral-7B when Zephyr produced inconsistent output formatting.</p><p><strong>What happened</strong></p><p>After deploying to HuggingFace Spaces, the pipeline ran on schedule and emails arrived as expected. The summaries were structured. Everything looked correct.</p><p>Except every single paper had the exact same summary:</p><blockquote>“This research contributes to the advancement of artificial intelligence.”</blockquote><blockquote>“Think of it like researchers finding a better way to solve a complex puzzle that computers face.”</blockquote><p>My first assumption was a parsing bug. The model was presumably generating output, but my parser was failing to extract the labelled sections correctly. I rewrote the parser with multiple fallback strategies — primary label splitting, paragraph position fallback, regex variations. The output did not change. Every paper still showed the same two sentences.</p><p>I then assumed the prompt format was wrong — that Mistral was ignoring the structured labels entirely and generating free-form text that the parser could not handle. I rewrote the prompt. Same result.</p><p>It was only when I opened the raw logs from HuggingFace Spaces that the actual error became visible. It had been there from the first run:</p><pre>HTTP 410: {&quot;error&quot;: &quot;https://api-inference.huggingface.co is no longer <br>supported. Please use https://router.huggingface.co&quot;}</pre><p><strong>The root cause</strong></p><p><strong>HuggingFace has permanently shut down the free tier of its Inference API.</strong> HTTP 410 does not mean temporarily unavailable — it means gone, permanently. Every API call had been failing from the first run. The pipeline never crashed because the summariser had retry logic with a hardcoded fallback: three attempts, each returning 410, then silently inject generic sentences and continue. The design intended to make the pipeline resilient had instead made a fatal failure completely invisible.</p><p>The fallback text looked plausible enough to pass a quick glance. The emails arrived, the structure was there, the pipeline reported success. Only reading the raw logs revealed that the LLM had never run at all.</p><p><strong>The fix</strong></p><p>Switch the summarisation layer entirely to Groq. Groq is a cloud AI provider that runs open-source models — Llama, Mixtral, Gemma — on custom LPU hardware. <strong>Their free tier provides 14,400 requests per day.</strong> Responses come back in <strong>one to two seconds</strong>, compared to fifteen or more on standard GPU inference.</p><p>The pipeline was back up within the hour. The summaries that arrived in the next test run were genuinely generated by the model — specific to each paper, structured correctly, different every time.</p><p><strong>The broader lesson</strong></p><p>There are three things this incident made clear.</p><p>The first is to read the logs before touching the code. The root cause was visible in the logs from run one. I spent time rewriting the parser and the prompt before I looked at the actual error. In hindsight, the correct first response to any unexpected behaviour is always to read the raw logs — not to start modifying code based on assumptions.</p><p>The second is that HTTP status codes carry specific meaning. 410 is not 404. 404 means not found — the resource may exist elsewhere or may return later. 410 means permanently gone — do not retry, do not look for it somewhere else, find an alternative. Understanding the distinction saved significant time once I knew where to look.</p><p>The third is that silent failures are more dangerous than loud ones. A pipeline that crashes with a clear error on run one is caught immediately. A pipeline that silently degrades and produces plausible-looking output can run undetected for days. The fallback mechanism that kept the pipeline running was the right instinct for transient failures — a temporary API timeout, a network blip. It was the wrong instinct for permanent failures. The fix is to distinguish between the two: retry and fall back gracefully for transient errors, but fail loudly and immediately for permanent ones like 410.</p><h3>7. Under the Hood — The Ranking Algorithm</h3><p>With up to 100 papers fetched every morning and only 5 slots in the digest, the ranking algorithm is one of the most consequential parts of the pipeline. A poor ranking means the wrong papers get summarised, the wrong topics reach the reader, and the digest loses its value quickly.</p><p>The algorithm I built is a <strong>Linear Additive Scoring Model</strong>. Each paper receives points independently across a set of weighted factors, those points are added together into a single score, and papers are sorted highest to lowest. The top N are selected, subject to a source diversity guarantee described below.</p><p>It is not the most sophisticated approach possible. Semantic embeddings, learned ranking models, and TF-IDF weighting would all produce more nuanced results. But for a daily digest of five papers, a well-tuned linear model is entirely sufficient, fully transparent, and easy to debug when something ranks unexpectedly. Every decision in the scoring can be traced to a single number.</p><h4>The Scoring Factors</h4><p><strong>Factor 1 — Recency (max 30 points)</strong></p><p>Recency is the highest-weighted factor because freshness is the primary value of a daily digest. A paper published today is worth more to the reader than an equally relevant paper published five days ago. The scoring uses a step decay:</p><pre>Published today        →  30 points<br>Published yesterday    →  20 points<br>Published within 3 days →  10 points<br>Published within a week →   5 points<br>Older than a week      →   0 points</pre><p>The 48-hour fetch window means almost all papers score 20 or 30 on recency. The decay primarily differentiates papers when the fetcher picks up older entries near the edge of the window.</p><p><strong>Factor 2 — Title Keyword Relevance (max 25 points)</strong></p><p>The title is the strongest signal for what a paper is actually about. A paper with the term “large language model” or “alignment” or “diffusion” in its title is explicitly about that topic — not just tangentially related to it. The scorer checks the title against a list of approximately 30 high-signal AI keywords and awards 5 points per match, capped at 25.</p><p>Title matches are weighted higher than abstract matches because the title represents the author’s own summary of the paper’s primary contribution.</p><p><strong>Factor 3 — Abstract Keyword Relevance (max 20 points)</strong></p><p>The same keyword list is applied to the abstract. Abstract matches confirm that the paper genuinely covers the relevant topic rather than merely mentioning it in the title. Weighted slightly lower than title matches — 5 points per match, capped at 20.</p><p>The keyword list itself covers the current landscape of AI research: model types and architectures (transformer, diffusion, multimodal), active research areas (rlhf, chain of thought, hallucination, emergent), and high-attention applications (code generation, robotics, safety, evaluation). The list is intentionally maintained as a flat constant in the codebase — easy to update as the field evolves.</p><p><strong>Factor 4 — Abstract Length (max 15 points)</strong></p><p>Abstract length serves as a proxy for the depth and completeness of the paper’s self-description. Longer abstracts give the summariser more material to work with and tend to correlate with more thoroughly written papers. The scoring uses three thresholds:</p><pre>800+ characters   →  15 points<br>600+ characters   →  10 points<br>300+ characters   →   5 points<br>Below 300         →   0 points  (but above the 100-char quality filter minimum)</pre><p><strong>Topic Personalisation Bonus (max 15 points)</strong></p><p>When a user has selected specific topics — for example, only LLMs &amp; NLP and Safety &amp; Alignment — papers matching those topics receive up to 15 additional points based on keyword hit count within the selected topic definitions. This bonus matters most in fallback mode: when fewer than three papers match the user’s selected topics and the pipeline falls back to the full paper pool, the bonus ensures that on-topic papers still float to the top of the ranking above off-topic ones.</p><p><strong>Source Diversity — The Balanced Selection Algorithm</strong></p><p>Scoring alone does not guarantee a useful digest. On any given day, arXiv might publish a cluster of highly relevant papers that dominate the top scores entirely — resulting in a digest with zero HuggingFace Papers. That would mean losing the community-curation signal that makes HuggingFace Papers worth including in the first place.</p><p>The balanced selection algorithm enforces source diversity structurally. After scoring and sorting, it reserves one slot for the top-scoring arXiv paper and one slot for the top-scoring HuggingFace paper before filling the remaining slots by score across both sources. This guarantees at least one paper from each source in every digest, regardless of how the scores distribute on a given day.</p><p>The result is a shortlist that is both high quality — ranked by a transparent, tunable scoring model — and meaningfully diverse across the two most trusted sources of AI research available.</p><h4><strong>What I Would Change</strong></h4><p>The most significant limitation of keyword matching is that it is lexical, not semantic. A paper about “instruction tuning” scores well. A paper that covers the same concept but uses the phrase “supervised fine-tuning on human demonstrations” scores zero on that keyword, even though the two are describing closely related ideas.</p><p>The natural next step is to replace keyword matching with sentence embeddings — representing each paper’s abstract as a vector and measuring cosine similarity against topic definitions. This would handle synonyms, related concepts, and domain-specific phrasing that no keyword list can fully anticipate. The tradeoff is added latency and a dependency on an embedding model. For a future version, it is the right direction.</p><h3>8. Prompt Engineering — Getting Structured Output From an LLM</h3><p>Summarising a research paper in plain English sounds straightforward. In practice, getting a language model to do it consistently, in a parseable format, across hundreds of papers with varying writing styles and levels of technical complexity — that requires more thought than the task initially suggests.</p><h4>The Problem With Free-Form Prompts</h4><p>The first version of the prompt was simple:</p><pre>Summarise this research paper in plain English for a non-technical audience.<br><br>Title: {title}<br>Abstract: {abstract}</pre><p>Llama followed the instruction. It produced readable summaries. But every summary was different in structure — sometimes a single paragraph, sometimes bullet points, sometimes a numbered list, sometimes starting with “This paper presents…” and sometimes with “Researchers have developed…”. Readable for a human, but impossible to parse programmatically into the four labelled sections the email template expected.</p><p>A newsletter that renders correctly requires consistent, predictable output. Free-form prompts do not produce that.</p><h4>The Structured Prompt</h4><p>The solution was to give the model an explicit role, a clear task, and — most importantly — mandatory output labels that the parser could reliably detect:</p><pre>You are a research assistant summarising AI research for non-technical readers.<br><br>Paper: {paper.title}<br>Abstract: {paper.abstract[:800]}<br><br>Reply using EXACTLY these 4 labels. Do not skip any. Do not add anything else.<br><br>HEADLINE: [one sentence capturing the key finding]<br>WHAT IT DOES: [2 sentences explaining what was built or discovered, no jargon]<br>WHY IT MATTERS: [1 sentence on real-world impact]<br>ANALOGY: [one sentence starting with: Think of it like]</pre><p>Several decisions in this prompt are deliberate.</p><p><strong>Explicit labels in uppercase.</strong> Uppercase labels are visually distinct from the body text and easier to detect with a simple string search. They also tend to be reproduced faithfully by instruction-tuned models because they look like structural markers rather than natural language.</p><p><strong>Hard constraints on length.</strong> “One sentence” and “Two sentences maximum” prevent the model from writing paragraphs when brevity is needed. Without these constraints, Llama will often write as much as it can — which is not what a digest reader wants.</p><p><strong>The analogy instruction.</strong> Requiring the analogy to start with “Think of it like” gives the parser a reliable anchor. It also produces more concrete, grounded analogies than an open-ended instruction like “provide an analogy” — the fixed opening forces the model to complete a sentence rather than introduce one.</p><p><strong>Abstract truncated to 800 characters.</strong> Llama 3.1 8B has a context window large enough to handle full abstracts, but longer inputs do not meaningfully improve summary quality for this use case. Most of the signal in an abstract is in the first few sentences. Truncating at 800 characters keeps token usage efficient and response times fast without sacrificing quality.</p><h4>One Limitation Worth Acknowledging</h4><p>Summarising from the abstract alone introduces an inherent constraint. Abstracts are written by the paper’s authors to represent their work — but they are also written to attract readers, which means they can overstate findings, omit caveats, or frame results more broadly than the paper’s body supports. The digest summarises what the abstract says, not what the full paper proves.</p><p>This is a known limitation. The link to the original paper is always present precisely because the digest is intended as a starting point, not a final verdict. Readers who want to evaluate the research properly should read the paper. The digest exists to help them decide which papers are worth that time.</p><h3>9. Edge Cases I Had to Handle</h3><p>Building a pipeline that runs autonomously every day against live data sources means edge cases are not hypothetical — they happen on real runs, often on the first week of deployment. Here are the ones that required explicit handling and the reasoning behind each solution.</p><h4>Edge Case 1 — Too Few Papers Match the User’s Selected Topics</h4><p><strong>The scenario</strong></p><p>A user subscribes and selects only one niche topic — say, Science &amp; Healthcare. On a given day, the AI research community published heavily in LLMs and Computer Vision, and only one paper touched on medical AI. The pipeline now has a choice: send a one-paper digest, or do something smarter.</p><p><strong>Why it matters</strong></p><p>A one-paper digest is a bad experience. The user will either think the tool is broken or unsubscribe. Worse, silently sending a thin digest with no explanation erodes trust in the product.</p><p><strong>The fix</strong></p><p>A minimum threshold of three papers — MIN_PAPERS_STRICT = 3 — is enforced before topic filtering is applied. If fewer than three papers match the selected topics after filtering, the pipeline falls back to the full unfiltered paper pool and proceeds with normal scoring. The topic personalisation bonus in the scoring model still applies, which means on-topic papers rank above off-topic ones even in fallback mode. The user gets a full, useful digest. The most relevant papers to their interests still appear at the top.</p><p>The fallback is logged clearly in the pipeline output so the behaviour is visible and traceable:</p><pre>⚠️ Only 1 paper matched topics [&#39;🔬 Science &amp; Healthcare&#39;]<br>   — falling back to full pool of 68 papers</pre><h4>Edge Case 2 — All Topics Selected (The Default State)</h4><p><strong>The scenario</strong></p><p>A user has not changed the default topic selection — all six topics are ticked. Running the full topic filter against all keywords on every paper in the pool is unnecessary work that produces the same result as no filtering at all.</p><p><strong>The fix</strong></p><p>Before running the topic filter, the pipeline checks whether the selected topics equal the full topic list. If they do, the filter step is skipped entirely and the full paper pool is passed directly to the scoring stage. This avoids scanning 100 papers against 100+ keywords on every run when the output would be identical to skipping the scan. A small optimisation, but a clean one.</p><h4>Edge Case 3— Duplicate Papers Across Sources</h4><p><strong>The scenario</strong></p><p>The same paper appears on both arXiv and HuggingFace Papers. This happens regularly — a paper gets submitted to arXiv and the same day someone surfaces it on HuggingFace Papers. Without deduplication, the same paper could appear twice in the same digest.</p><p><strong>The fix</strong></p><p>Deduplication runs as the first step in Phase 2, checking both normalised paper IDs and normalised titles. When a duplicate is detected, the arXiv version is kept. The reasoning: arXiv entries have richer metadata — longer abstracts, structured author lists, full category tags — which gives the summariser more to work with. The HuggingFace community-curation signal has already served its purpose by confirming the paper is worth including; the arXiv version is the better raw material for summarisation.</p><p>Title normalisation strips punctuation, collapses whitespace, and lowercases before comparison — so minor title variations between the two sources do not result in duplicates slipping through.</p><h4>Edge Case 54— The LLM Ignores the Prompt Format</h4><p><strong>The scenario</strong></p><p>Llama 3.1 8B does not always reproduce the exact output format the prompt specifies. Common deviations include: bold markdown labels (**HEADLINE:** instead of HEADLINE:), lowercase labels (headline: instead of HEADLINE:), numbered labels (1. HEADLINE:), preamble before the first label (Sure! Here is the summary: HEADLINE:...), and occasionally a completely free-form response with no labels at all.</p><p><strong>The fix</strong></p><p>The multi-strategy parser handles this with three levels of fallback as described in Section 8. What is worth adding here is the failure boundary: if all three parsing strategies fail to extract at least two coherent sections from the model’s response, the pipeline does not crash or skip the paper. It substitutes the paper’s abstract directly as the summary content, logs the parsing failure with the raw model output for inspection, and continues to the next paper.</p><p>The digest sends. One paper has an abstract instead of a structured summary. That is an acceptable degradation — far better than a broken pipeline or a missing paper.</p><h3>10. What’s Next</h3><p>The current version of AI Research Digest works. It fetches, ranks, summarises, and delivers reliably every morning. But there are several directions I would take it with more time, and it is worth being honest about which limitations are minor polish and which are genuine architectural gaps.</p><p><strong>Semantic Ranking With Embeddings</strong></p><p>The most impactful improvement to the pipeline would be replacing keyword matching in the ranking and topic filter with sentence embeddings. The current keyword approach is lexical — it matches exact strings. A paper about “instruction tuning” scores well. A paper covering the same concept under the phrase “supervised fine-tuning on human demonstrations” scores zero on that keyword despite being directly relevant.</p><p>Sentence embeddings would represent each paper’s abstract as a vector in a high-dimensional space and measure cosine similarity against topic definitions. This handles synonyms, domain-specific phrasing, and conceptual overlap that no keyword list can anticipate. The tradeoff is a dependency on an embedding model and added latency per paper. For a future version, it is the right direction.</p><p><strong>Persistent Scheduling</strong></p><p>The current scheduler stores jobs in memory. When the HuggingFace Space restarts — which happens regularly on the free tier after periods of inactivity — all scheduled jobs are lost. Subscribers who set up a daily digest have to re-register.</p><p>The fix is straightforward: APScheduler supports persistent job stores backed by PostgreSQL or Redis. Migrating to a persistent store means jobs survive restarts and subscribers do not lose their preferences. This is the most important production-readiness gap in the current architecture.</p><p><strong>Summary Quality Evaluation</strong></p><p>There is currently no objective measure of whether the summaries are good. They look reasonable, they are structured correctly, and informal feedback has been positive — but that is not the same as a measured quality signal. Adding automated evaluation using ROUGE scores, or an LLM-as-judge approach where a second model scores each summary against the original abstract, would give a basis for improving the prompt over time rather than relying on qualitative impression.</p><p><strong>Full Paper Parsing</strong></p><p>Summarising from the abstract alone has a fundamental ceiling. Abstracts are written to attract readers, which means they can overstate findings or omit caveats that the paper’s body makes clear. Fetching and parsing the full PDF — using a library like PyMuPDF — and summarising from the introduction and conclusion sections would produce more accurate, more nuanced summaries. The tradeoff is significantly higher token usage per paper and longer pipeline run times. Worth exploring for a premium tier.</p><h3>11. Try It Yourself</h3><p>AI Research Digest is live on HuggingFace Spaces and fully open source. If you work in AI, follow the field, or simply want a quieter way to stay informed without spending an hour on arXiv every morning — it is worth trying.</p><p>The setup takes about thirty seconds. Enter your email, choose your topics, set the number of papers, and either send a digest immediately or schedule one for 08:00 UTC every morning. No account required. No subscription. No data stored beyond what is needed to send your scheduled digest.</p><p>🔗 <strong>Try it here:</strong> <a href="https://huggingface.co/spaces/SivaSai8143/ai-research-digest">HuggingFace Space</a></p><p>🔗 <strong>Source code:</strong> <a href="https://github.com/sivasaiyadav8143/ai-research-digest/tree/main">GitHub Repo</a></p><p>If you found this article useful — or if something in your own build broke in a way I did not cover — I would genuinely like to hear about it. The comments are open.</p><p>And if you are curious what topic you would want in your daily digest, drop it below. It is a good way to find out whether Science &amp; Healthcare actually has enough daily paper volume to avoid the fallback threshold.</p><p>Some of my other posts you may find interesting</p><ul><li><a href="https://pub.towardsai.net/system-prompts-explained-how-understanding-them-makes-you-a-better-ai-communicator-b9ed72a0f971">System Prompts Explained: How Understanding Them Makes You a Better AI Communicator</a></li><li><a href="https://pub.towardsai.net/the-3-stage-training-pipeline-behind-chatgpt-claude-and-gemini-explained-simply-bbd45b1f7368">The 3‑Stage Training Pipeline Behind ChatGPT, Claude, and Gemini (Explained Simply)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fc92ba6a819" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/building-a-free-ai-research-digest-from-arxiv-to-your-inbox-using-llama-3-1-groq-and-sendgrid-5fc92ba6a819">Building a Free AI Research Digest: From arXiv to Your Inbox Using Llama 3.1, Groq, and SendGrid</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Word Embeddings in NLP: From Bag-of-Words to Transformers (Part 1)]]></title>
            <link>https://pub.towardsai.net/word-embeddings-in-nlp-from-bag-of-words-to-transformers-part-1-4688627a728f?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/4688627a728f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 20:42:51 GMT</pubDate>
            <atom:updated>2026-02-06T04:46:29.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmY1ZEzWxRFj0-HuYRBimg.png" /><figcaption>Image generated with Microsoft Copilot</figcaption></figure><p>· <a href="#8c19">1. Introduction: Why Computers Struggle with Language</a><br>· <a href="#d452">2. What Are Word Embeddings and Why Do We Need Them?</a><br> ∘ <a href="#606d">The Map Analogy</a><br> ∘ <a href="#8f7f">Why We Need Them</a><br> ∘ <a href="#ca81">Word embeddings fix this by encoding meaning:</a><br> ∘ <a href="#79f2">The Core Idea</a><br> ∘ <a href="#4390">Why This Revolutionized NLP</a><br>· <a href="#5162">3. Types of Word Embeddings: From Simple to Sophisticated</a><br> ∘ <a href="#da23">The Three Generations</a><br> ∘ <a href="#d7c6">Why This Progression Matters</a><br>· <a href="#8dca">3.1 Frequency-Based Embeddings (The Starting Point)</a><br> ∘ <a href="#ec9c">3.1.1. Bag-of-Words (BoW)</a><br> ∘ <a href="#f4a1">3.1.2. TF-IDF (Term Frequency-Inverse Document Frequency)</a><br> ∘ <a href="#7931">3.1.3. N-grams</a><br>· <a href="#8b18">4. Choosing Between Frequency-Based Methods: Quick Guide</a><br> ∘ <a href="#f8eb">The Decision Tree</a><br> ∘ <a href="#67ee">Quick Comparison Table</a><br> ∘ <a href="#0c00">Decision Guide by Task Type</a><br> ∘ <a href="#e51c">Common Mistakes to Avoid</a><br> ∘ <a href="#501a">Quick Checklist: Have You Chosen Right?</a><br>· <a href="#8db7">5. Final Thoughts</a><br> ∘ <a href="#837e">What I’ve Learned</a><br> ∘ <a href="#ff97">What’s Next</a><br>· <a href="#ebad">6. Resources &amp; Further Learning</a></p><h3>1. Introduction: Why Computers Struggle with Language</h3><p>I’ll never forget my first attempt at building a sentiment analysis model. I had a dataset of product reviews, some Python knowledge, and a lot of confidence. The plan seemed simple: count the words, feed them to a model, and boom — instant sentiment classifier.</p><p>It failed miserably.</p><p>The model couldn’t understand the relationships between words. It had no idea that “awful” and “terrible” express similar negativity, or that “awesome” and “excellent” both mean strong positivity. To the model, every word was just an isolated feature with no connection to any other word. And when someone wrote “This product isn’t bad,” the model saw “bad” and classified it as negative, ignoring the “isn’t.”</p><p>That’s when I realised: <strong>computers don’t understand language the way we do.</strong></p><p>We humans, get meaning instantly. We know “king” relates to “queen,” that “huge” and “gigantic” mean similar things, and that “bank” means something different in “river bank” versus “bank account.” We understand context, nuance, and relationships between words.</p><p>But computers? They only understand numbers. And the obvious way to convert words to numbers — just assigning each word a unique number — doesn’t capture any of this meaning. To a computer, “cat” as number 5 and “dog” as number 10 have no relationship, even though we know they’re both animals, both pets, both commonly discussed together.</p><p>This is the fundamental problem that word embeddings solve: <strong>they turn words into numbers in a way that preserves meaning and relationships.</strong></p><p>During my Gen AI course, learning about word embeddings was one of those “everything clicks” moments. Suddenly, I understood why my early NLP attempts failed and how modern systems like ChatGPT can actually understand language. Word embeddings bridge the gap between how computers process information (numbers) and how language actually works (meaning and relationships).</p><p><strong>In this article, I’ll walk you through:</strong></p><ul><li>What word embeddings actually are and why they’re crucial</li><li>The evolution from simple frequency-based methods to sophisticated contextual embeddings</li><li>Every major type of embedding: when to use it, its strengths, and its limitations</li><li>How to choose the right embedding for your specific task</li><li>Common mistakes I’ve seen (and made) and how to avoid them</li></ul><p>Whether you’re building your first NLP model or just trying to understand how modern AI handles language, this guide will give you the foundation you need.</p><p>Let’s start with the basics.</p><h3>2. What Are Word Embeddings and Why Do We Need Them?</h3><p>Here’s the simplest way I can explain word embeddings: they represent words as points in a multi-dimensional space, where the <strong>distance and direction</strong> between points capture meaning.</p><p>That probably sounds abstract, so let me use an analogy.</p><h4>The Map Analogy</h4><p>Think about a map of your city. Every location has coordinates — two numbers that tell you exactly where it is. For example:</p><pre>Coffee Shop: (40.7580, -73.9855)<br>Bakery next door: (40.7582, -73.9853)<br>Your home: (44.7128, -77.0060)</pre><p>Here’s the interesting part: the distance between coordinates tells you something meaningful. The coffee shop at (40.7580, -73.9855) and the bakery at (40.7582, -73.9853) have very similar coordinates because they’re actually next to each other. Your home at (44.7128, -77.0060) has quite different coordinates because it’s miles away.</p><p>The coordinates themselves might look like random numbers, but the <em>relationships</em> between them capture real‑world proximity.</p><p>Word embeddings work the same way, but instead of mapping physical locations, we’re mapping words in a “meaning space”. Words with similar meanings end up close to each other. Words that appear in similar contexts are nearby. And the direction between words can even capture relationships.</p><p>Here’s a real example that blew my mind when I first saw it:</p><pre>vector(&quot;king&quot;) - vector(&quot;man&quot;) + vector(&quot;woman&quot;) ≈ vector(&quot;queen&quot;)</pre><p>The mathematical relationship between these word vectors actually captures the conceptual relationship between the words. The difference between “king” and “man” is similar to the difference between “queen” and “woman” — both represent a gender relationship in royalty.</p><h4>Why We Need Them</h4><p>Let’s go back to my sentiment analysis failure. When I first tried it, I was essentially doing this:</p><pre>&quot;good&quot; → 1<br>&quot;bad&quot; → 2<br>&quot;awesome&quot; → 3<br>&quot;terrible&quot; → 4</pre><p>Just random numbers. The computer had no idea that “good” and “awesome” are similar, or that “bad” and “terrible” are similar. Every word was equally different from every other word.</p><h4>Word embeddings fix this by encoding meaning:</h4><pre>&quot;good&quot; → [0.2, 0.8, 0.1, ...]<br>&quot;awesome&quot; → [0.3, 0.9, 0.1, ...]<br>&quot;bad&quot; → [-0.2, -0.7, 0.1, ...]<br>&quot;terrible&quot; → [-0.3, -0.8, 0.0, ...]</pre><p>These aren’t random numbers — each dimension captures some aspect of meaning. Now, when the computer processes these vectors, it can see that “good” and “awesome” are similar (their vectors are close), and both are opposite to “bad” and “terrible” (notice the negative values).</p><h4>The Core Idea</h4><p>Word embeddings capture three crucial things:</p><ol><li><strong>Semantic Similarity</strong> <br>Words with similar meanings have similar embeddings. “huge,” “gigantic,” and “enormous” all cluster together in the embedding space.</li><li><strong>Contextual Relationships</strong> <br>Words that appear in similar contexts are represented similarly. If “coffee” and “tea” often appear in similar sentences (“I’ll have a ___”), their embeddings will be close.</li><li><strong>Analogical Reasoning</strong> <br>The relationships between words are captured in the geometry of the space. Not just king→queen, but also:</li></ol><ul><li>Paris→France ≈ London→England (capital-country relationships)</li><li>Walking→Walked ≈ Swimming→Swam (verb tense relationships)</li><li>Fast→Faster ≈ Strong→Stronger (comparative relationships)</li></ul><h4>Why This Revolutionised NLP</h4><p>Before word embeddings, every NLP task was harder than it needed to be. Models had to learn from scratch that “happy” and “joyful” mean similar, or that “phone” and “smartphone” are related. Knowledge about one word didn’t transfer to another.</p><p>With embeddings, models get a head start. They start with an understanding that similar words have similar meanings(vectors). This means:</p><ul><li><strong>Better performance</strong> with less training data</li><li><strong>Generalisation</strong> to words they’ve never seen in specific contexts</li><li><strong>Transfer learning</strong> where knowledge from one task helps another</li><li><strong>Semantic search</strong> where you can find documents by meaning, not just keyword matching</li></ul><p>When I rebuilt that sentiment analyser using proper word embeddings instead of random numbers, the difference was huge. The model actually understood that “This isn’t bad” is positive, that “terrible” is worse than “poor,” and that “amazing product” and “awesome item” express similar sentiments even though they share no common words.</p><p>That’s the power of word embeddings — they give computers a way to understand language that actually reflects how language works.</p><p>Now let’s look at how we actually create these embeddings, starting from the simplest approaches and building up to the sophisticated methods used in modern AI systems.</p><h3>3. Types of Word Embeddings: From Simple to Sophisticated</h3><p>Before we dive deep into each approach, let me give you the lay of the land. Word embeddings have evolved through <strong>three major generations</strong>, each solving problems the previous generation couldn’t handle.</p><h4>The Three Generations</h4><p><strong>Generation 1: Frequency-Based Embeddings (The Starting Point)</strong> <br>These are the earliest and simplest approaches — count-based methods that look at how often words appear and co-occur. They’re fast, easy to interpret, and surprisingly effective for many tasks. We’ll cover these in detail in this article:</p><ul><li><strong>Bag-of-Words (BoW)</strong>: The most basic — just count word occurrences</li><li><strong>TF-IDF</strong>: Improves on BoW by giving more weight to important words</li><li><strong>N-grams</strong>: Captures word sequences instead of individual words</li></ul><p><strong>Generation 2: Predictive Embeddings (Neural Embeddings — The Breakthrough)<br></strong>These methods use neural networks to learn dense vector representations by predicting words from their context. This is where embeddings got really powerful. We’ll explore these in <strong>Part 2</strong> of the series:</p><ul><li><strong>Word2Vec (CBOW &amp; Skip-Gram)</strong>: The technique that sparked the modern embedding revolution</li><li><strong>GloVe</strong>: Combines global statistics with local context</li><li><strong>FastText</strong>: Handles rare words by using subword information</li></ul><p><strong>Generation 3: Contextual Embeddings (Modern NLP — The Revolution)<br></strong>These models generate different embeddings for the same word depending on context — the foundation of modern AI systems like ChatGPT. We’ll cover these in <strong>Part 3</strong>:</p><ul><li><strong>ELMo</strong>: The first major contextual embedding approach</li><li><strong>BERT</strong>: Bidirectional transformers that changed everything</li><li><strong>GPT-style embeddings</strong>: Autoregressive transformer‑based embeddings</li><li><strong>Sentence-BERT</strong>: Embeddings designed for entire sentences and semantic search</li></ul><h4>Why This Progression Matters</h4><p>Each generation emerged to solve specific limitations:</p><ul><li><strong>Frequency-based → Neural:</strong> <br>Frequency methods couldn’t capture semantic relationships. “King” and “queen” were just two different words with no mathematical connection.</li><li><strong>Neural → Contextual:<br></strong>Static neural embeddings gave every word a single fixed representation. “Bank” had the same embedding, whether you meant a riverbank or a financial institution.</li></ul><p>Understanding this evolution helps you choose the right tool. Sometimes the simplest method (frequency-based) is all you need. Other times, you need the full power of contextual embeddings.</p><p>In this article, we’ll focus on <strong>Generation 1: Frequency-Based Embeddings</strong> — the foundation that everything else builds upon.</p><h3>3.1 Frequency-Based Embeddings (The Starting Point)</h3><p>Let’s start with the basics. Frequency-based embeddings are exactly what they sound like: they represent text based on how frequently words appear and co-occur.</p><p>These might seem primitive compared to BERT or GPT, but here’s the thing I learned the hard way: <strong>sometimes simple is exactly what you need.</strong> I’ve seen developers jump straight to BERT for tasks where TF-IDF would’ve worked just as well, run faster, and been easier to debug.</p><p>Let me show you each frequency-based approach, when to use it, and what its limitations are.</p><h4>3.1.1. Bag-of-Words (BoW)</h4><p><strong>What It Is &amp; How It Works</strong></p><p>Bag-of-Words is the most straightforward approach to converting text into numbers. The idea is simple:</p><ol><li>Create a vocabulary of all unique words in your dataset</li><li>Represent each document as a vector showing how many times each word appears.</li></ol><p>Here’s the key insight: <strong>we completely ignore word order and grammar</strong>. We literally treat the text as a “bag” of words — dump all the words in, shake them up, and just count them.</p><p><strong>Example in Action</strong></p><p>Let’s say we have two product reviews:</p><pre>Review 1: &quot;This phone is great. Great camera, great battery.&quot;<br>Review 2: &quot;This phone is okay. Camera is good.&quot;<br><br>Step 1: Build vocabulary<br>Vocabulary: [this, phone, is, great, camera, battery, okay, good]<br><br>Step 2: Count occurrences<br>Review 1: [1, 1, 1, 3, 1, 1, 0, 0]<br>         (this appears 1 time, phone appears 1 time, great appears 3 times, etc.)<br><br>Review 2: [1, 1, 2, 0, 1, 0, 1, 1]<br>         (this appears 1 time, is appears 2 times, great appears 0 times, etc.)</pre><p>Now each review is a vector of numbers that a machine learning model can process.</p><p><strong>Advantages</strong></p><ul><li><strong>Simple to understand and implement</strong>: You can code this in 10 lines</li><li><strong>Fast</strong>: No training required, just counting</li><li><strong>Works surprisingly well for simple tasks</strong>: Document classification, spam detection</li><li><strong>Interpretable</strong>: You can see exactly which words matter</li><li><strong>Small vocabulary = small vectors</strong>: Efficient for memory</li></ul><p><strong>Disadvantages</strong></p><ul><li><strong>No semantic understanding</strong>: “good” and “excellent” are completely different words</li><li><strong>Loses word order</strong>: “not good” and “good” look identical after shuffling</li><li><strong>Ignores context</strong>: Can’t distinguish different meanings of the same word<br>( “bank” (river) vs “bank” (finance))</li><li><strong>Sparse vectors</strong>: Most values are zero (imagine a 10,000-word vocabulary where each document uses maybe 50 words)</li><li><strong>Sensitive to document length</strong>: Longer documents have higher counts, which can skew results</li></ul><p><strong>When to Use It</strong></p><p>Use BoW when:</p><ul><li>You have a simple classification task (spam vs not spam)</li><li>You need a quick baseline to beat</li><li>Interpretability matters more than accuracy</li><li>You’re working with small datasets or limited computational resources</li><li>Word order genuinely doesn’t matter for your task</li></ul><p><strong>Real-World Use Case</strong></p><p>For a support ticket classifier to route tickets to the right team (billing, technical, sales). BoW with a simple logistic regression works perfectly:</p><ul><li>“refund,” “payment,” “charge” → Billing team</li><li>“error,” “bug,” “crash” → Technical team</li><li>“demo,” “pricing,” “upgrade” → Sales team</li></ul><p>For a hands-on implementation, check out my <a href="https://github.com/sivasaiyadav8143/NLP/tree/main/frequency_embeddings/Bag-of-Words">BoW notebook on GitHub</a>.</p><h4>3.1.2. TF-IDF (Term Frequency-Inverse Document Frequency)</h4><p><strong>What It Is &amp; Why It’s Better Than BoW</strong></p><p>TF-IDF improves on Bag-of-Words by addressing a crucial question: <strong>not all words are equally important.</strong></p><p>Think about it — if you’re analysing product reviews, the word “<em>product</em>” probably appears in every single review. It tells you nothing. But the word “<em>defective</em>” is rare and highly informative. TF‑IDF captures this by giving:</p><ul><li><strong>low weight</strong> to common, uninformative words</li><li><strong>high weight</strong> to rare, meaningful words</li></ul><p><strong>Think of TF-IDF like a resume keyword scanner:</strong></p><p>When a recruiter searches for candidates, they look at resumes. If a resume mentions “Python” 10 times and every other resume also mentions Python, that’s not distinctive (low importance). But if a resume mentions “TensorFlow” and only 5% of resumes have it, that’s highly distinctive (high importance).</p><p>TF-IDF does the same for documents — it finds the words that make each document unique.</p><p><strong>How It Works</strong></p><p>TF-IDF has two components:<br><strong>a. Term Frequency (TF)</strong>: How often does this word appear in this document?</p><pre>TF = (Number of times term appears in document) / (Total terms in document)</pre><p><strong>b. Inverse Document Frequency (IDF)</strong>: How rare is this word across all documents?</p><pre>IDF = log(Total number of documents / Number of documents containing the term)</pre><p><strong>Final TF-IDF score:</strong></p><pre>TF-IDF = TF × IDF</pre><p>A word gets a <strong>high TF‑IDF</strong> when it is:</p><ul><li>frequent in this document (high TF)</li><li>rare across other documents (high IDF)</li></ul><p><strong>Example in Action<br></strong>Let’s say we have 100 product reviews.</p><p>Example 1: Common word — “product”</p><pre>Review 1: &quot;This product is amazing. Best product ever.&quot;<br>- Total words in review: 7<br>- &quot;product&quot; appears: 2 times<br>- &quot;product&quot; appears in: 95 out of 100 reviews (very common)<br><br>TF = 2 / 7 = 0.28<br>IDF = log(100 / 95) = log(1.05) = 0.05<br>TF-IDF = 0.28 × 0.05 = 0.014 ← LOW SCORE</pre><p>Example 2: Rare word “defective”</p><pre>Review 3: &quot;Defective product. Very disappointed.&quot;<br>- Total words in review: 4<br>- &quot;defective&quot; appears: 1 time<br>- &quot;defective&quot; appears in: only 3 out of 100 reviews (very rare)<br><br>TF = 1 / 4 = 0.25<br>IDF = log(100 / 3) = log(33.33) = 1.52<br>TF-IDF = 0.25 × 1.52 = 0.38 ← HIGH SCORE</pre><p>Even though “product” appears more times in its review, “defective” gets a score <strong>30x higher</strong> because it’s distinctive. This is exactly what we want — rare, meaningful words should stand out.</p><p><strong>Advantages</strong></p><ul><li><strong>Handles common words intelligently</strong>: Words like “the,” “is,” “a” get low scores automatically</li><li><strong>Highlights distinctive terms</strong>: Rare, meaningful words get higher weights</li><li><strong>Better than BoW for most tasks</strong>: Usually improves accuracy significantly</li><li><strong>Still interpretable</strong>: You can see which words are deemed important</li><li><strong>No training needed</strong>: Just statistics on your dataset</li></ul><p><strong>Disadvantages</strong></p><ul><li><strong>Still no semantic understanding</strong>: “good” and “excellent” are unrelated</li><li><strong>Still loses word order</strong>: “not good” problem persists</li><li><strong>Sensitive to dataset</strong>: IDF values change if you add/remove documents</li><li><strong>Struggles with very short documents</strong>: Statistics become unreliable</li><li><strong>Can over-weight rare typos or errors</strong>: A misspelled word becomes “distinctive”</li></ul><p><strong>When to Use It</strong></p><p>Use TF-IDF when:</p><ul><li>You’re doing document search or retrieval (finding similar documents)</li><li>You need better accuracy than BoW without much complexity</li><li>You have a reasonable amount of documents (dozens to millions)</li><li>Common words drown out the meaningful ones in BoW.</li><li>You want an interpretable baseline before trying neural methods</li></ul><p><strong>Real-World Use Case</strong></p><p>A common use of TF‑IDF is in documentation or knowledge‑base search systems. When users type queries like “how to configure SSL certificates,” the system needs to identify the most relevant documents.</p><p>TF‑IDF works well here because:</p><ul><li>Common words like “how,” “to,” “the” got low scores (not useful for search)</li><li>Distinctive technical terms like “SSL,” “certificates,” and “configure” got high scores</li><li>We could rank documents by TF-IDF similarity to the query</li></ul><p>This makes TF‑IDF a strong baseline for search and information‑retrieval tasks.</p><p>For a hands-on implementation, check out my <a href="https://github.com/sivasaiyadav8143/NLP/blob/main/frequency_embeddings/TF-IDF/tfidf_doc_search.ipynb">TF-IDF notebook on GitHub</a>.</p><h4>3.1.3. N-grams</h4><p><strong>What They Are &amp; How They Work</strong></p><p>N-grams solve a critical problem with BoW and TF-IDF: <strong>word order matters.</strong></p><p>“Not good” and “good” mean very different things, but both BoW and TF-IDF treat them identically after shuffling the words. N-grams fix this by considering sequences of words instead of individual words.</p><p>Here’s the terminology:</p><ul><li><strong>Unigram</strong>: Single words (what BoW and TF-IDF use)</li><li><strong>Bigram</strong>: Sequences of 2 consecutive words</li><li><strong>Trigram</strong>: Sequences of 3 consecutive words</li><li><strong>N-gram</strong>: Sequences of N consecutive words</li></ul><p><strong>Example in Action</strong></p><p>Let’s look at the sentence: “This product is not good”</p><pre>Unigrams (1-grams):<br>[&quot;This&quot;, &quot;product&quot;, &quot;is&quot;, &quot;not&quot;, &quot;good&quot;]<br><br>Bigrams (2-grams):<br>[&quot;This product&quot;, &quot;product is&quot;, &quot;is not&quot;, &quot;not good&quot;]<br><br>Trigrams (3-grams):<br>[&quot;This product is&quot;, &quot;product is not&quot;, &quot;is not good&quot;]</pre><p>Now, when we count, “not good” is captured as a single unit with its own meaning — something unigrams cannot capture.</p><p>Here’s a concrete comparison:</p><pre>Sentence 1: &quot;This product is good&quot;<br>Sentence 2: &quot;This product is not good&quot;<br><br>With unigrams (BoW):<br>Both contain: [This, product, is, good] + [not] for sentence 2<br>The sentences look very similar<br><br>With bigrams:<br>Sentence 1: [This product, product is, is good]<br>Sentence 2: [This product, product is, is not, not good]<br>Now &quot;is good&quot; and &quot;not good&quot; are distinct features!</pre><p><strong>Advantages</strong></p><ul><li><strong>Captures word order and phrases</strong>: “not good” vs “good” are different</li><li><strong>Detects meaningful phrases</strong>: “New York” vs “New” and “York” separately</li><li><strong>Improves accuracy</strong>: Usually beats pure unigram approaches</li><li><strong>Works with existing methods</strong>: Can combine with TF‑IDF on bigrams, which is common</li><li><strong>Language-specific patterns</strong>: Captures idiomatic expressions</li></ul><p><strong>Disadvantages</strong></p><ul><li><strong>Massive vocabulary explosion</strong>: 10,000 unigrams → millions of bigrams</li><li><strong>Extreme sparsity</strong>: Most n-gram combinations never appear</li><li><strong>Computational cost</strong>: Much slower to process and store</li><li><strong>Data hungry</strong>: Need lots of text for rare n-grams to appear enough times</li><li><strong>Diminishing returns</strong>: Trigrams often don’t help much more than bigrams</li></ul><p><strong>When to Use It</strong></p><p>Use N-grams when:</p><ul><li>Word order is crucial (sentiment analysis, where “not good” ≠ “good”)</li><li>You’re dealing with phrases or multi-word expressions</li><li>You have enough data to support the vocabulary explosion</li><li>You’ve tried unigrams and need better accuracy</li><li>Bigrams specifically — they give the best accuracy-to-complexity ratio</li></ul><p>Avoid N-grams when:</p><ul><li>You have limited data (too many rare n-grams)</li><li>Computational resources are constrained</li><li>You’re already getting good results with unigrams</li></ul><p><strong>Common Pitfall: The Curse of Dimensionality</strong></p><p>Here’s a mistake I made early on: I used trigrams on a small dataset, thinking “more context = better results.”</p><p>The problem:</p><pre>Vocabulary with unigrams: 5,000 words<br>Vocabulary with bigrams: 50,000 combinations<br>Vocabulary with trigrams: 200,000+ combinations<br><br>My dataset: 1,000 documents<br><br>Result: 99% of trigrams appeared only once. The model couldn&#39;t learn anything <br>meaningful from them. Performance actually got worse.</pre><p><strong>Rule of thumb:</strong> Stick to <strong>bigrams</strong> unless you have a very large dataset and a specific need for longer context.</p><p><strong>Real-World Use Case</strong></p><p>In a hotel review sentiment analyzer where n-grams made a huge difference:</p><pre>Review: &quot;The location was not great, but the staff was really good.&quot;<br><br>With unigrams:<br>- Sees: &quot;not&quot;, &quot;great&quot;, &quot;good&quot; <br>- Confusing mixed signal<br><br>With bigrams:<br>- Sees: &quot;not great&quot; (negative), &quot;really good&quot; (positive)<br>- Clear mixed sentiment—location bad, staff good</pre><p>This let us break down reviews into aspects (location, staff, cleanliness) with separate sentiment scores. Bigrams captured the negations and intensifiers that unigrams missed.</p><p><strong>For a hands-on implementation showing unigram vs bigram comparison, check out my </strong><a href="https://github.com/sivasaiyadav8143/NLP/blob/main/frequency_embeddings/N-grams/ngrams_hotel_review.ipynb"><strong>N-grams notebook on GitHub</strong></a>.</p><h3>4. Choosing Between Frequency-Based Methods: Quick Guide</h3><p>Here’s how I decide which frequency-based method to use:</p><h4>The Decision Tree</h4><p>Here’s a practical decision tree based on my real-world experience:</p><pre>START HERE: Always start with TF-IDF on unigrams as your baseline<br>            (Takes 30 minutes, gives you a benchmark)<br>                   ↓<br>            Measure accuracy<br>                   ↓<br>┌───────────────────────────────────────────────┐<br>│ Is accuracy acceptable for your task?         │<br>│ (e.g., &gt;85% for most classification tasks)    │<br>└───────────────────────────────────────────────┘<br>            ↓<br>    ┌───────┴───────┐<br>    │               │<br>   YES             NO<br>    │               │<br>    ↓               ↓<br>┌─────────┐    ┌──────────────────────┐<br>│ DEPLOY  │    │ Does word order or   │<br>│ TF-IDF  │    │ negation matter?     │<br>└─────────┘    │ (e.g., &quot;not good&quot;)   │<br>               └──────────────────────┘<br>                        ↓<br>                ┌───────┴───────┐<br>                │               │<br>               YES             NO<br>                │               │<br>                ↓               ↓<br>        ┌────────────────┐  ┌─────────────────┐<br>        │ Try TF-IDF +   │  │ Try increasing  │<br>        │ bigrams        │  │ max_features or │<br>        │                │  │ tune parameters │<br>        └────────────────┘  └─────────────────┘<br>                │                    │<br>                ↓                    ↓<br>        ┌────────────────┐  ┌─────────────────┐<br>        │ Better?        │  │ Better?         │<br>        └────────────────┘  └─────────────────┘<br>                │                    │<br>        ┌───────┴───────┐    ┌───────┴───────┐<br>       YES             NO    YES             NO<br>        │               │     │               │<br>        ↓               │     ↓               │<br>    ┌─────────┐         │  ┌─────────┐        │<br>    │ DEPLOY  │         │  │ DEPLOY  │        │<br>    └─────────┘         │  └─────────┘        │<br>                        │                     │<br>                        └──────────┬──────────┘<br>                                   ↓<br>                    ┌──────────────────────────────┐<br>                    │ Frequency-based methods      │<br>                    │ might not be enough.         │<br>                    │ Consider neural embeddings   │<br>                    │ (Word2Vec) - See Part 2      │<br>                    └──────────────────────────────┘<br><br>SPECIAL CASES:<br><br>Need extreme speed (&lt; 10ms)?<br>└─&gt; Try BoW (faster than TF-IDF, slightly less accurate)<br><br>Very short text (tweets, chat)?<br>└─&gt; TF-IDF may not work well, try character n-grams<br><br>Huge dataset (100k+ docs) + bigrams not enough?<br>└─&gt; Try trigrams cautiously (watch for vocabulary explosion)</pre><h4>Quick Comparison Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*TCdbeoQl1Cyy8UrLyBcxLw.png" /><figcaption>Image generated with Claude</figcaption></figure><h4>Decision Guide by Task Type</h4><p><strong>Task 1</strong>: Spam Email Filter</p><ul><li><strong>Recommended</strong>: TF-IDF + Logistic Regression</li><li><strong>Why</strong>: Clear keyword patterns (“urgent,” “prize,” “click here”)</li><li><strong>Alternative</strong>: BoW if speed is absolutely critical</li><li><strong>Avoid</strong>: Trigrams (overkill, too sparse)</li></ul><p><strong>Task 2: </strong>Product Review Sentiment</p><ul><li><strong>Recommended</strong>: TF-IDF with bigrams</li><li><strong>Why</strong>: Captures negation (“not good”) and intensifiers (“very bad”)</li><li><strong>Alternative</strong>: Just TF-IDF if the dataset is small</li><li><strong>Avoid</strong>: BoW (will miss negations)</li></ul><p><strong>Task: </strong>Document Search/Similarity</p><ul><li><strong>Recommended</strong>: TF-IDF</li><li><strong>Why</strong>: Designed exactly for this — ranks by term importance</li><li><strong>Alternative</strong>: None — TF-IDF is the standard</li><li><strong>Avoid</strong>: BoW (all words weighted equally)</li></ul><p><strong>Task: </strong>Topic Classification</p><ul><li><strong>Recommended</strong>: TF-IDF</li><li><strong>Why</strong>: Different topics have different vocabularies</li><li><strong>Alternative</strong>: BoW if topics are very distinct</li><li><strong>Avoid</strong>: N-grams (adds complexity without much gain)</li></ul><p><strong>Task: </strong>Short Text (tweets, chat)</p><ul><li><strong>Recommended</strong>: BoW or TF-IDF with careful preprocessing</li><li><strong>Why</strong>: Not enough text for reliable TF-IDF statistics</li><li><strong>Alternative</strong>: Character n-grams</li><li><strong>Avoid</strong>: Word trigrams (way too sparse)</li></ul><h4>Common Mistakes to Avoid</h4><p>Mistake 1: Starting with the most complex method</p><pre>❌ &quot;I&#39;ll use trigrams because more context is better&quot;<br>✅ &quot;I&#39;ll start with TF-IDF, measure performance, then add bigrams if needed&quot;</pre><p>Mistake 2: Not considering production constraints</p><pre>❌ &quot;This works great on my laptop (takes 10 seconds per prediction)&quot;<br>✅ &quot;Can this handle 1000 requests/second in production?&quot;</pre><p>Mistake 3: Ignoring interpretability</p><pre>❌ &quot;Trigrams give 2% better accuracy, let&#39;s use them&quot;<br>✅ &quot;Can I explain to my manager why this classified a customer email wrong?&quot;</pre><h4>Quick Checklist: Have You Chosen Right?</h4><p>Before implementing, ask:</p><p>✅ Did I try TF-IDF first as a baseline? <br>✅ Is my method appropriate for my data size? <br>✅ Can I explain why this method fits my task? <br>✅ Have I considered production constraints (speed, memory)? <br>✅ Am I adding complexity only when simpler methods failed? <br>✅ Can I debug and explain the results to stakeholders?</p><h3>5. Final Thoughts</h3><p>When I started learning NLP, I thought I needed to jump straight to neural embeddings or BERT to build anything useful. I was completely wrong.</p><p><strong>Frequency-based methods (BoW, TF-IDF, N-grams) are surprisingly powerful.</strong> They solve real problems, run fast, and just work.</p><h4>What I’ve Learned</h4><ul><li>TF-IDF beats more complex methods when the vocabulary is distinctive</li><li>Always get a TF-IDF baseline first</li><li>Only move to complex methods if accuracy isn’t acceptable</li><li>Measure everything — don’t assume complexity helps</li><li>Speed, memory, and interpretability matter as much as accuracy</li><li>90% accuracy with 10ms latency often beats 95% with 1s latency</li><li>Being able to explain decisions has real business value</li></ul><h4>What’s Next</h4><p>We’ve covered the foundation — frequency-based embeddings.<br><strong>In Part 2</strong>, we’ll explore neural embeddings (Word2Vec, GloVe, FastText)</p><h3>6. Resources &amp; Further Learning</h3><ul><li><strong>CountVectorizer</strong> (Bag-of-Words) : <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html">https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html</a><br><strong>Kaggle</strong> <strong>Notebook</strong>: <a href="https://www.kaggle.com/code/anucool007/multi-class-text-classification-bag-of-words">https://www.kaggle.com/code/anucool007/multi-class-text-classification-bag-of-words</a></li><li><strong>TfidfVectorizer</strong> (TF-IDF) : <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html</a><br><strong>Kaggle</strong> <strong>Notebook</strong>: <a href="https://www.kaggle.com/code/viroviro/sentiment-analysis-tf-idf-logistic-regression#Vectorization">https://www.kaggle.com/code/viroviro/sentiment-analysis-tf-idf-logistic-regression#Vectorization</a></li><li>Complete Text Feature Extraction Guide : <a href="https://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction">https://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction</a><br><strong>Kaggle</strong> <strong>Notebook</strong>: <a href="https://www.kaggle.com/code/thecobbler/n-grams-and-bi-grams">https://www.kaggle.com/code/thecobbler/n-grams-and-bi-grams</a></li></ul><p>#NLP #WordEmbeddings #MachineLearning #AI #TFIDF #BagOfWords #DataScience #Python #TextMining</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4688627a728f" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/word-embeddings-in-nlp-from-bag-of-words-to-transformers-part-1-4688627a728f">Word Embeddings in NLP: From Bag-of-Words to Transformers (Part 1)</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Prompts Explained: How Understanding Them Makes You a Better AI Communicator]]></title>
            <link>https://pub.towardsai.net/system-prompts-explained-how-understanding-them-makes-you-a-better-ai-communicator-b9ed72a0f971?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9ed72a0f971</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 21:16:37 GMT</pubDate>
            <atom:updated>2026-01-07T04:55:26.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIS8aXKhALWmXkJ51wGjeg.png" /><figcaption>Source: Google Gemini</figcaption></figure><h3>Hook</h3><p>Most people think AI responds only to the words they type. But the truth is far more interesting: <strong>every AI response you see is shaped by a hidden set of instructions you never wrote and never even see.</strong></p><p>These invisible rules quietly control how the model thinks, talks, reasons, refuses, explains, and even how it interprets <em>your</em> prompts. Once you understand them, AI becomes easier to use, more predictable, and dramatically more powerful.</p><p>· <a href="#536b">1. Introduction: The Hidden Instructions Controlling Every AI Response</a><br>· <a href="#819f">2. What Are System Prompts? (Explained Simply)</a><br> ∘ <a href="#7a87">What They Actually Are</a><br> ∘ <a href="#0212">Why They Exist</a><br>· <a href="#b46d">3. Inside a System Prompt: The 5 Key Components</a><br> ∘ <a href="#4cfd">Component 1: Identity and Role</a><br> ∘ <a href="#4b09">Component 2: Behavioural Guidelines</a><br> ∘ <a href="#6762">Component 3: Response Format</a><br> ∘ <a href="#fd52">Component 4: Tone and Style</a><br> ∘ <a href="#c451">Component 5: Safety Guidelines</a><br> ∘ <a href="#3b08">How these five components work together</a><br>· <a href="#4ece">4. Real Examples: System Prompts from ChatGPT, Claude &amp; Others</a><br> ∘ <a href="#2c51">ChatGPT’s Approach</a><br> ∘ <a href="#b7e5">Claude’s Approach</a><br> ∘ <a href="#2905">The Side-by-Side Difference</a><br>· <a href="#92ac">5. How System Prompts Teach You to Write Better Prompts</a><br> ∘ <a href="#78d5">Lesson 1: Be Extremely Explicit</a><br> ∘ <a href="#54fe">Lesson 2: Define Roles Precisely</a><br> ∘ <a href="#6ca5">Lesson 3: Request Step-by-Step Thinking</a><br>· <a href="#0c0f">6. The Two-Layer Conversation: Your Prompt + The System Prompt</a><br> ∘ <a href="#d447">The Actual Structure</a><br> ∘ <a href="#e7eb">When They Cooperate vs. Conflict</a><br> ∘ <a href="#9a1c">Working With Both Layers</a><br>· <a href="#d812">7. 5 Practical Techniques to Use System Prompts to Your Advantage</a><br> ∘ <a href="#7019">Technique 1: The “Role + Task + Constraints” Framework</a><br> ∘ <a href="#76d1">Technique 2: The “Clarifying Questions First” Approach</a><br> ∘ <a href="#3523">Technique 3: The “Format Specification” Method</a><br> ∘ <a href="#8155">Technique 4: The “Think Step-by-Step” Trigger</a><br> ∘ <a href="#f59a">Technique 5: The “Reframe for Safety” Strategy</a><br>· <a href="#dbf7">8. Before &amp; After: Real Examples of System Prompt-Aware Prompting</a><br> ∘ <a href="#f121">Example 1: Getting Technical Help</a><br> ∘ <a href="#672d">Example 2: Content Creation</a><br>· <a href="#8e7d">9. Final Thoughts</a><br>· <a href="#5600">Resources &amp; Further Learning</a></p><h3>1. Introduction: The Hidden Instructions Controlling Every AI Response</h3><p>I’ve been working with AI models for a while now, but there was this moment that really frustrated me. I asked ChatGPT a straightforward technical question about implementing a specific algorithm, and it refused. The weird part? I’d asked similar questions before and got great answers.</p><p>That’s when I started digging into system prompts during my Applied Gen AI course, and everything clicked.</p><p>Here’s what most people don’t realise: <strong>you’re not actually having a direct conversation with the AI model.</strong> Every single message you send gets combined with a hidden set of instructions that you never see. These instructions — called <em>system prompts </em>— control the tone, the boundaries, what the model will discuss, and how it structures every response.</p><p>Think of it like talking to a customer service rep. You ask them a question, but they’re following a company handbook you’ve never read. Understanding that handbook changes how you communicate with them.</p><p>After learning about system prompts, my interactions with AI models completely transformed. I stopped guessing and started understanding. I realised system prompts are basically <strong>expert‑level prompt‑engineering lessons</strong>, written by people who’ve spent millions optimising them.</p><p><strong>Here’s what understanding system prompts gives you:</strong></p><ol><li><strong>Better communication</strong> — You’ll understand why AI behaves the way it does and work with it instead of fighting it</li><li><strong>Better prompt writing</strong> — You can learn from the patterns and structures in these expert-crafted prompts</li></ol><h3>2. What Are System Prompts? (Explained Simply)</h3><p>The simplest way I can explain this: imagine you’re ordering food at a restaurant. You tell the waiter, “I’d like the pasta.” That’s your order.</p><p>But in the kitchen, the chef has a whole manual of restaurant rules you never see:</p><ul><li>Use only fresh ingredients</li><li>No peanut oil (allergy safety)</li><li>Every dish needs presentation standards</li><li>Suggest alternatives if something is unavailable</li><li>Always maintain the restaurant’s reputation</li></ul><p>You never see this manual, but it shapes everything that comes out of that kitchen. <strong>That’s exactly how AI works.</strong></p><h4><strong>What They Actually Are</strong></h4><p>A system prompt is a set of instructions that companies like OpenAI or Anthropic give to their models before you start talking. These instructions:</p><ul><li>Go with every single message you type</li><li>Are completely invisible to you</li><li>Override or shape how the model responds</li><li>Cost companies millions to optimise</li></ul><p>Here’s what actually happens:</p><pre>What you see:<br>You: &quot;Explain quantum computing&quot;<br>AI: [gives response]<br><br>What really happens:<br>System Prompt: [Hidden instructions about tone, safety, format, etc.]<br>You: &quot;Explain quantum computing&quot;<br>AI: [response shaped by BOTH]</pre><h4>Why They Exist</h4><p>I used to wonder why we even need these. Why not just let the model respond directly?</p><p>Here’s the thing: base models (just after pre-training) are smart but unpredictable. Without system prompts, <strong><em>they might be rude, provide dangerous info without context, or give wildly inconsistent responses</em></strong>. System prompts give every model a consistent personality and guidelines — like a training manual for a new employee.</p><p>The insight that changed my perspective: <strong>Every time AI seems “difficult” or refuses something, it’s not being stubborn. It’s following instructions you can’t see.</strong></p><p>Once you understand those instructions, everything makes more sense.</p><h3>3. Inside a System Prompt: The 5 Key Components</h3><p>Now that we know what system prompts are, let’s look at what typically goes inside them. Companies don’t publish their full system prompts, but from patterns, behaviour, and public hints, we can infer five core components that show up almost everywhere.</p><h4>Component 1: Identity and Role</h4><pre>&quot;You are ChatGPT, a large language model trained by OpenAI.&quot;<br>&quot;You are Claude, an AI assistant created by Anthropic.&quot;</pre><p>This tells the model <em>who</em> it is and <em>how</em> to behave. It’s like giving someone a job description.</p><p><strong>What you can learn: </strong>Defining a role in your own prompts works wonders. Instead of:</p><blockquote>“Explain marketing.”</blockquote><p>Try:</p><blockquote>“You are an experienced marketing professor. Explain marketing strategy to a college freshman.”</blockquote><h4>Component 2: Behavioural Guidelines</h4><pre>&quot;Be helpful, harmless, and honest.&quot;<br>&quot;If you don&#39;t know something, say you don&#39;t know.&quot;<br>&quot;Do not provide medical, legal, or financial advice.&quot;</pre><p>These are the hard boundaries. The rules the model can’t break, no matter how you phrase your request.</p><p><strong>What you can learn:</strong> Being explicit about constraints helps. “Explain this concept, but avoid technical jargon” or “Give me three options, ranked by cost” sets clear boundaries.</p><h4>Component 3: Response Format</h4><pre>&quot;Provide clear, well-structured responses.&quot;<br>&quot;Use markdown formatting when appropriate.&quot;<br>&quot;When writing code, include comments.&quot;</pre><p>This is why AI responses often feel formatted a certain way — numbered lists, clear sections, step-by-step breakdowns. The system prompt explicitly asks for this.</p><p><strong>What you can learn:</strong> Specify your format. “Give me a step-by-step guide” or “Format this as a table” leverages the model’s training.</p><h4>Component 4: Tone and Style</h4><pre>&quot;Be conversational but professional.&quot;<br>&quot;Use a friendly, approachable tone.&quot;<br>&quot;Be encouraging and supportive.&quot;</pre><p>This shapes the personality you experience. ChatGPT feels different from Claude partly because their system prompts define different tones.</p><p><strong>What you can learn:</strong> Request specific tones. “Explain this casually” or “Write this formally for a business context” gets you the style you need.</p><h4>Component 5: Safety Guidelines</h4><pre>&quot;Do not generate harmful content.&quot;<br>&quot;If asked about sensitive topics, provide balanced information.&quot;<br>&quot;Decline requests that could enable illegal activities.&quot;</pre><p>This is why you sometimes get refusals. The model isn’t being difficult — it’s following safety rules.</p><p><strong>What you can learn:</strong> If you get refused, your phrasing might have triggered safety guidelines. Reframe with clear intent.</p><p>Instead of:</p><blockquote>“How do I hack a website?”</blockquote><p>Try:</p><blockquote>“I’m a security researcher learning about vulnerabilities. Explain common web security issues.”</blockquote><h4>How these five components work together</h4><p>Let’s put it all together with a simple example.</p><p><strong>Your prompt: </strong>“Help me with this Python code.”</p><p><strong>What the model actually receives:</strong></p><pre>[Identity] You are a helpful programming assistant<br>[Behavior] Be patient, don&#39;t just give answers<br>[Format] Explain code line-by-line<br>[Tone] Be encouraging with beginners<br>[Safety] Don&#39;t write malicious code<br><br>User: &quot;Help me with this Python code&quot;</pre><p>The response is shaped by all five components at once.</p><h3>4. Real Examples: System Prompts from ChatGPT, Claude &amp; Others</h3><p>Let me show you what different platforms actually use. Companies don’t publish complete system prompts, but we can piece together what they contain from documentation and observation.</p><h4>ChatGPT’s Approach</h4><pre>You are ChatGPT, a large language model trained by OpenAI.<br><br>Key instructions:<br>- Be helpful, creative, clever, and friendly<br>- Answer concisely when possible<br>- Use Markdown formatting<br>- If you don&#39;t know, say so<br>- Avoid harmful, illegal, or explicit content<br>- For sensitive topics, provide balanced information</pre><p><strong>What makes ChatGPT distinctive:</strong></p><ul><li>Emphasis on being concise</li><li>Strong formatting preferences</li></ul><h4>Claude’s Approach</h4><pre>You are Claude, an AI assistant created by Anthropic to be helpful, <br>harmless, and honest.<br><br>Core principles:<br>- Think step-by-step before responding<br>- Be thorough and actionable<br>- Avoid content that could cause harm<br>- Acknowledge uncertainty clearly<br>- Ask clarifying questions when needed</pre><p><strong>What makes Claude distinctive:</strong></p><ul><li>“Think step-by-step” encourages reasoning</li><li>More emphasis on asking questions</li><li>Three-pillar philosophy (helpful, harmless, honest)</li></ul><h4><strong>The Side-by-Side Difference</strong></h4><p>Let me show you how these different system prompts shape responses to the same question.</p><p><strong>Question:</strong> “I’m stressed about my exams.”</p><p><strong>ChatGPT style (concise, structured):</strong></p><pre>I understand exam stress. Here are some quick strategies:<br><br>1. Study in focused 25-minute sessions<br>2. Prioritize high-impact topics first  <br>3. Get enough sleep—it helps retention<br>4. Practice with past exams if available<br><br>What subject are you most worried about?</pre><p><strong>Claude style (thorough, asks questions):</strong></p><pre>Exam stress is really common. Let me help you think through this.<br><br>First, it would help to understand your situation:<br>- When are your exams?<br>- What subjects are you studying?<br>- What&#39;s causing the most stress—time, understanding material, or test anxiety?<br><br>In the meantime, here&#39;s what typically helps: Breaking study time into <br>manageable chunks works better than marathon sessions. <br>Active recall (testing yourself) beats re-reading notes. <br>And practice exams reduce anxiety by familiarizing you with the format.<br><br>Would you like to work through a study schedule together?</pre><p>See the difference? Both are helpful; ChatGPT jumps to concise advice while Claude asks questions first. That’s system prompts at work.</p><h3>5. How System Prompts Teach You to Write Better Prompts</h3><p>Here’s something that really hit me: <strong>system prompts are written by world‑class prompt engineers who’ve spent millions of dollars and thousands of hours refining them.</strong> Why figure this out from scratch when you can learn from the best?</p><p>Let me share the key lessons I’ve extracted.</p><h4>Lesson 1: Be Extremely Explicit</h4><p>System prompts don’t assume anything. They state every expectation clearly: what to do, how to do it, what to avoid, and who it’s for.</p><p><strong>Example:</strong></p><p>Instead of:</p><blockquote>“Write about marketing”</blockquote><p>Try:</p><blockquote>“Write a 500-word blog post about digital marketing for small businesses.</blockquote><blockquote><strong>Target audience</strong>: Small business owners with limited budgets<br><strong>Tone</strong>: Practical and encouraging<br><strong>Include</strong>: 3 specific, actionable strategies<br><strong>Avoid</strong>: Technical jargon, expensive tools”</blockquote><p>The second prompt leaves nothing to chance. That’s the system prompt approach.</p><h4>Lesson 2: Define Roles Precisely</h4><p>System prompts always establish a clear identity: “You are X.”</p><p><strong>Example:</strong></p><p>Instead of:</p><blockquote>“Explain blockchain”</blockquote><p>Try:</p><blockquote>“You are a technology teacher explaining to high school students.</blockquote><blockquote>Explain blockchain using an everyday analogy they’d understand. Avoid technical terms, and check if they’d like clarification on any part.”</blockquote><p>The role gives the model a framework for how to approach the task.</p><h4>Lesson 3: Request Step-by-Step Thinking</h4><p>Many system prompts include “think step-by-step” instructions. You can trigger this yourself.</p><p><strong>Example:</strong></p><p>Instead of:</p><blockquote>“Should I buy or lease a car?”</blockquote><p>Try:</p><blockquote>“I’m deciding whether to buy or lease a car. Think through this step-by-step:</blockquote><blockquote><strong>Context</strong>:<br>- Budget: $30k<br>- Drive 20k miles/year <br>- Keep cars 7+ years typically</blockquote><blockquote><strong>Process</strong>:<br>1. Explain key financial differences<br>2. Analyse how my situation affects each option<br>3. Calculate approximate costs<br>4. Provide recommendation with reasoning</blockquote><blockquote>Show your thinking so I understand the trade-offs.”</blockquote><p>This activates the model’s analytical mode and gets much more thorough responses.</p><h3>6. The Two-Layer Conversation: Your Prompt + The System Prompt</h3><p>Understanding how these two layers interact changed how I write prompts. Let me show you the structure.</p><h4>The Actual Structure</h4><p>Every conversation looks like this:</p><pre>┌─────────────────────────────────────┐<br>│     SYSTEM PROMPT (Hidden)          │<br>│  - Identity &amp; Role                  │<br>│  - Behavioral Guidelines            │<br>│  - Safety Constraints               │<br>└─────────────────────────────────────┘<br>              ↓<br>┌─────────────────────────────────────┐<br>│     YOUR PROMPT (Visible)           │<br>└─────────────────────────────────────┘<br>              ↓<br>┌─────────────────────────────────────┐<br>│     RESPONSE                        │<br>│  Shaped by BOTH layers              │<br>└─────────────────────────────────────┘</pre><p>Your prompt doesn’t exist alone — it’s always filtered through the system prompt.</p><h4>When They Cooperate vs. Conflict</h4><p><strong>Cooperation (smooth):</strong></p><pre>System: &quot;Be educational and encouraging&quot;<br>You: &quot;I&#39;m learning Python. Can you explain functions with a simple example?&quot;<br><br>Result: Perfect alignment. You get a clear, helpful response.</pre><p><strong>Conflict (friction):</strong></p><pre>System: &quot;Do not provide medical diagnoses&quot;<br>You: &quot;I have a headache and fever. What disease do I have?&quot;<br><br>Result: Refusal or redirect. The system prompt&#39;s safety rules override <br>your request.</pre><p><strong>The Priority Hierarchy</strong></p><p>When your prompt conflicts with the system prompt, here’s what wins:</p><ol><li><strong>Safety constraints</strong> — highest priority, never overridden</li><li><strong>Core behavioural guidelines</strong> — very high priority</li><li><strong>Format preferences</strong> — medium priority, flexible</li><li><strong>Tone and style</strong> — lowest priority, easily adapted</li></ol><p>This is why “talk like a pirate” works (low‑priority, harmless), but trying to bypass safety rules doesn’t (highest priority).</p><h4>Working With Both Layers</h4><p>The key is reinforcing what the system prompt values.</p><p>If it emphasises clarity and structure, lean into that:</p><pre>&quot;Explain quantum entanglement.<br><br>Please:<br>- Start with a simple analogy<br>- Then the technical explanation  <br>- Include a real-world application<br>- End with common misconceptions<br><br>Use clear headers for each section.&quot;</pre><p>This works <em>with</em> the system prompt’s preferences, not against them.</p><h3>7. 5 Practical Techniques to Use System Prompts to Your Advantage</h3><p>Let me give you five techniques I use constantly now.</p><h4>Technique 1: The “Role + Task + Constraints” Framework</h4><p>Structure your prompts like system prompts structure instructions.</p><p><strong>Example:</strong></p><p>Instead of:</p><blockquote>“Help me write a business email”</blockquote><p>Try:</p><blockquote><strong>ROLE</strong>: You are a professional business communication expert</blockquote><blockquote><strong>TASK</strong>: Help me write an email to a client explaining a project delay</blockquote><blockquote><strong>CONSTRAINTS</strong>:<br>- Professional but warm tone<br>- Take responsibility without over-apologizing <br>- Provide new timeline<br>- Keep under 200 words</blockquote><blockquote><strong>Context</strong>: Long-term client, generally understanding, but this is our second delay</blockquote><p>This mirrors the structure system prompts use, which the model is optimised for.</p><h4>Technique 2: The “Clarifying Questions First” Approach</h4><p>Ask the model to gather info before responding, just like system prompts often instruct.</p><p><strong>Example:</strong></p><p>Instead of:</p><blockquote>“Recommend a career path”</blockquote><p>Try:</p><blockquote>“I need career advice, but I want you to have enough context first.</blockquote><blockquote>Before making recommendations, ask me:<br>1. About my current skills and experience<br>2. About my interests and values <br>3. About my constraints (location, salary needs, etc.)</blockquote><blockquote>Then provide 2–3 tailored recommendations with reasoning.”</blockquote><p>You’re explicitly triggering the “ask clarifying questions” behaviour that the system prompts encourage.</p><h4>Technique 3: The “Format Specification” Method</h4><p>Be specific about the output format.</p><p><strong>Example:</strong></p><p>Instead of:</p><blockquote>“Compare iPhone and Android”</blockquote><p>Try:</p><blockquote>“Compare iPhone and Android using this format:</blockquote><blockquote>## Price<br>iPhone: [pros/cons]<br>Android: [pros/cons] <br>Winner: [which and why]</blockquote><blockquote>## Ecosystem<br>[same structure]</blockquote><blockquote>## Customization<br>[same structure]</blockquote><blockquote>## Final Recommendation<br>Based on: [user type/needs]”</blockquote><p>System prompts train models to follow formatting precisely. Specific format requests get very consistent results.</p><h4>Technique 4: The “Think Step-by-Step” Trigger</h4><p>Explicitly request the reasoning process.</p><p><strong>Example:</strong></p><blockquote>“My computer is running slowly. Help me diagnose and fix it.</blockquote><blockquote>Process:<br>1. Ask diagnostic questions to narrow down the cause<br>2. Based on my answers, explain what might be wrong<br>3. Provide solutions ranked from easiest to most complex<br>4. For each solution, explain why it might help</blockquote><blockquote>Let’s start with your questions.”</blockquote><p>Many system prompts include “think step-by-step.” By requesting this explicitly, you activate the model’s analytical mode.</p><h4>Technique 5: The “Reframe for Safety” Strategy</h4><p>When you get a refusal, understand it’s system prompt safety constraints, then reframe with legitimate context.</p><p><strong>Example:</strong></p><p>Gets refused:</p><blockquote>“How do hackers break into systems?”</blockquote><p>Reframed:</p><blockquote>“I’m studying for my Cybersecurity+ certification and need to understand attack vectors to protect systems.</blockquote><blockquote>For educational purposes, explain:<br>1. Common web application vulnerabilities<br>2. How security professionals test for these<br>3. Best practices for prevention</blockquote><blockquote>I want to build more secure systems in my work as a developer.”</blockquote><p>The safety constraints look for harmful intent. Providing an educational context satisfies the safety requirements while getting you the information you need.</p><h3>8. Before &amp; After: Real Examples of System Prompt-Aware Prompting</h3><p>Let me show you real before-and-after examples from my own work.</p><h4>Example 1: Getting Technical Help</h4><p><strong>❌ BEFORE:</strong></p><blockquote>“My Python code doesn’t work. Here’s the code: [paste code]”</blockquote><p><strong>Response:</strong> Gets a fix, but misses learning opportunity and context.</p><p><strong>✅ AFTER:</strong></p><blockquote>“I’m learning Python and wrote this code to [describe goal]. Getting this error: [error message]</blockquote><blockquote>Here’s the code:<br>[paste code]</blockquote><blockquote>Can you:<br>1. Help me understand what the error means<br>2. Guide me to identify where the bug is (don’t just tell me)<br>3. Explain WHY it’s a bug (help me learn the concept)<br>4. Show the fix with explanation<br>5. Suggest how to avoid this in the future</blockquote><blockquote>I want to get better at debugging on my own.”</blockquote><p><strong>Response:</strong> Get a teaching-focused answer that helps you learn debugging skills, not just fixes this one bug.</p><p><strong>What changed:</strong> Framed as learning, requested step-by-step process, aligned with system prompt’s educational tendencies.</p><h4>Example 2: Content Creation</h4><p><strong>❌ BEFORE:</strong></p><blockquote>“Write a LinkedIn post about productivity”</blockquote><p><strong>Response:</strong> Generic productivity tips that could be from anyone.</p><p><strong>✅ AFTER:</strong></p><blockquote>“Help me write a LinkedIn post about productivity.</blockquote><blockquote><strong>Context</strong>:<br>- Audience: Mid-career software engineers<br>- My voice: Practical, slightly contrarian, avoids clichés <br>- Angle: Productivity through simplification, not adding tools</blockquote><blockquote><strong>Requirements</strong>:<br>- Hook: Start with surprising statement or question<br>- Body: One specific practice I use (not generic advice)<br>- Length: 150–200 words<br>- CTA: Ask a question to drive engagement</blockquote><blockquote><strong>Constraints</strong>:<br>- No buzzwords like “synergy,” “leverage,” “game-changer”<br>- No generic advice like “wake up at 5am”<br>- Include personal example</blockquote><blockquote>Give me 2 options to choose from.”</blockquote><p><strong>Response:</strong> Get tailored options that match your brand, speak to your audience, and avoid generic content.</p><p><strong>What changed:</strong> Extensive context, specific constraints, format specifications, requested options.</p><h3>9. Final Thoughts</h3><p>Understanding system prompts has completely changed how I interact with AI models. What seemed like random or frustrating behaviour now makes perfect sense — the models are just following instructions I couldn’t see.</p><p>Here’s what matters:</p><p><strong>The core insight:</strong> Every AI response is shaped by hidden instructions (system prompts) that define <strong>identity, behaviour, format, tone, and safety</strong>. You’re never just talking to the model — you’re talking through a carefully designed layer of rules.</p><p><strong>The dual benefit:</strong> Understanding system prompts helps you communicate better with AI AND teaches you to write better prompts. These system prompts are masterclasses in prompt engineering written by experts who’ve spent millions optimising them.</p><p><strong>The practical takeaway:</strong> Structure your prompts like system prompts do — be explicit, define roles, specify format, request step-by-step thinking, and provide context. Work with the system, not against it.</p><p><strong>The mindset shift:</strong> Stop typing randomly and hoping for good results. Start crafting prompts strategically, knowing that the AI is following a structured set of instructions you can learn from and align with.</p><p>System prompts will keep evolving, but the principles remain. Every conversation with AI is an opportunity to practice and refine your approach. Start applying what you’ve learned today — the difference in your results will be immediate.</p><h3>Resources &amp; Further Learning</h3><ol><li><strong>GitHub — System Prompts Leaks (Unofficial Collection)</strong><br><a href="https://github.com/asgeirtj/system_prompts_leaks">https://github.com/asgeirtj/system_prompts_leaks</a><br><a href="https://github.com/0xeb/TheBigPromptLibrary/blob/main/SystemPrompts/README.md">https://github.com/0xeb/TheBigPromptLibrary/blob/main/SystemPrompts/README.md</a><br><a href="https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools">https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools</a></li><li><strong>OpenAI Documentation</strong>: System messages guide <a href="https://platform.openai.com/docs/guides/text">https://platform.openai.com/docs/guides/text</a> <a href="https://learn.microsoft.com/en-us/azure/ai-foundry/openai/concepts/system-message">https://learn.microsoft.com/en-us/azure/ai-foundry/openai/concepts/system-message</a></li><li><strong>Anthropic’s Constitutional AI</strong>: Claude’s approach to system prompts and alignment. <br><a href="https://platform.claude.com/docs/en/release-notes/system-prompts">https://platform.claude.com/docs/en/release-notes/system-prompts</a><br>Paper:<a href="https://arxiv.org/abs/2212.08073">https://arxiv.org/abs/2212.08073</a><br>Blog: <a href="https://www.anthropic.com/research/constitutional-ai-harmlessness-from-ai-feedback">https://www.anthropic.com/research/constitutional-ai-harmlessness-from-ai-feedback</a><br>Claude’s Constitution: <a href="https://www.anthropic.com/news/claudes-constitution">https://www.anthropic.com/news/claudes-constitution</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9ed72a0f971" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/system-prompts-explained-how-understanding-them-makes-you-a-better-ai-communicator-b9ed72a0f971">System Prompts Explained: How Understanding Them Makes You a Better AI Communicator</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 3‑Stage Training Pipeline Behind ChatGPT, Claude, and Gemini (Explained Simply)]]></title>
            <link>https://pub.towardsai.net/the-3-stage-training-pipeline-behind-chatgpt-claude-and-gemini-explained-simply-bbd45b1f7368?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbd45b1f7368</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 09:28:34 GMT</pubDate>
            <atom:updated>2025-12-24T04:37:32.785Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple, beginner‑friendly guide to how modern LLMs like ChatGPT are trained using pre‑training, SFT, and RLHF.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlaEeWhZZ4RiGDNDJ5uaOQ.png" /><figcaption>Source: ChatGPT</figcaption></figure><p>· <a href="#d591">Introduction</a><br>· <a href="#fa58">Perspective 1: The Intuitive View 🧠</a><br> ∘ <a href="#1323">Stage 1: Medical School (Pre-training)</a><br> ∘ <a href="#1442">Stage 2: Residency Training (Supervised Fine-Tuning)</a><br> ∘ <a href="#faf5">Stage 3: Years of Practice with Feedback (RLHF)</a><br>· <a href="#2cc1">Perspective 2: The Technical View 🔧</a><br> ∘ <a href="#35d9">Stage 1: Pre-training — Self‑Supervised Learning</a><br> ∘ <a href="#a25f">Stage 2: Supervised Fine-Tuning (SFT) — Teaching It to Be Helpful</a><br> ∘ <a href="#1086">Stage 3: Reinforcement Learning from Human Feedback (RLHF) — Learning What People Actually Prefer</a><br>· <a href="#1475">The Complete Training Pipeline (Visual Overview)📊</a><br>· <a href="#1528">How to Identify Models at Different Training Stages</a><br> ∘ <a href="#bf16">1. Pre-trained Models (Base Models):</a><br> ∘ <a href="#4e39">2. Supervised Fine-Tuned Models (SFT):</a><br> ∘ <a href="#4c58">3. RLHF-Aligned Models (Full Alignment):</a><br>· <a href="#3448">To summarise</a><br>· <a href="#b7c5">Resources &amp; Further Learning</a></p><h3>Introduction</h3><p>Ever wondered how models like ChatGPT, Claude, or Gemini became so good at having conversations? I mean, these models can write code, explain complex topics, help with creative writing, and even crack jokes.</p><p>But they don’t just magically appear this way.</p><p>When I started learning about LLMs in my Applied Gen AI course, I thought training was straightforward — just feed the model a bunch of text and boom, you’re done. Turns out, I was completely wrong. The reality is way more interesting.</p><p><strong>LLMs go through three distinct training stages</strong></p><ol><li><strong>Pre-training</strong></li><li><strong>Supervised Fine-Tuning(SFT)</strong></li><li><strong>Reinforcement Learning from Human Feedback(RLHF)</strong></li></ol><p>Each one solves a specific problem.</p><p>Think of it like this: you can’t just throw someone into a job and expect them to be great at it. They need education, then specific job training, then ongoing feedback to really excel. LLMs work the same way.</p><p>Let me walk you through how this actually works, and more importantly, <em>why</em> each stage is necessary.</p><h3>Perspective 1: The Intuitive View 🧠</h3><p>The Three-Stage Journey</p><p>Think about how a doctor becomes truly great at their job. It’s not just one step — it’s a journey:</p><h4><strong>Stage 1: Medical School (Pre-training)</strong></h4><p>A medical student spends years reading textbooks, research papers, case studies, and attending lectures. They’re absorbing enormous amounts of information: anatomy, diseases, treatments, drug interactions, surgical procedures, research findings. They’re building a massive knowledge base.</p><p>But here’s the thing — after all that reading, they can’t actually treat patients yet. <strong>They know <em>about</em> medicine, but they don’t know <em>how to practice</em> medicine.</strong> If you put them in front of a real patient, they might recite textbook definitions instead of asking the right questions or explaining things in a way the patient understands.</p><p><strong>In LLM terms:</strong> <em>This is pre-training</em>. The model reads billions of web pages, books, and articles. It learns patterns, facts, and relationships. It understands “pneumonia is a lung infection” and “antibiotics treat bacterial infections,” but it doesn’t know how to use this knowledge to actually help someone asking about their symptoms.</p><h4><strong>Stage 2: Residency Training (Supervised Fine-Tuning)</strong></h4><p>Now the medical graduate enters residency. They work alongside experienced doctors who show them exactly how to handle real situations:</p><ul><li>“When a patient describes chest pain, here are the specific questions you ask”</li><li>“This is how you explain a diagnosis without using jargon”</li><li>“When delivering bad news, use this tone and structure”</li></ul><p>They’re learning the <em>format</em> and <em>practice</em> of being a doctor. They shadow mentors, observe hundreds of patient interactions, and practice under supervision. They’re not learning new medical facts — they’re learning how to apply their knowledge effectively.</p><p><strong>In LLM terms:</strong> This is supervised fine-tuning. The model is shown thousands of examples of how to properly respond to queries. Instead of just continuing text, it learns: “When someone asks to classify sentiment, give a one-word answer. When someone asks for code, provide working examples with explanations. When someone needs help, structure your response with clear steps.”</p><h4><strong>Stage 3: Years of Practice with Feedback (RLHF)</strong></h4><p>Even after residency, doctors keep improving. Every case teaches them something:</p><ul><li>A patient didn’t understand their first explanation, so they learned to simplify more</li><li>One approach worked better than another for anxious patients</li><li>Some treatment plans get better compliance than others</li></ul><p>Through years of real-world feedback — from patients, colleagues, and outcomes — they develop judgment. They learn the subtle art of knowing when to be detailed vs. brief, when to reassure vs. be direct, and which explanations resonate with which patients.</p><p><strong>In LLM terms:</strong> This is RLHF. The model generates multiple possible responses, and humans rank them: “Response A was too technical,” “Response B was perfect — clear and helpful,” “Response C was too vague.” Through thousands of these comparisons, the model learns subtle preferences about what makes responses genuinely better, not just technically correct.</p><h3>Perspective 2: The Technical View 🔧</h3><p>Now, let’s get into the actual mechanics of how this works.</p><h4><strong>Stage 1: Pre-training — Self‑Supervised Learning</strong></h4><p><strong>The model starts as a blank slate — billions of randomly initialised parameters</strong> that mean nothing. Then you feed it massive amounts of text from the internet, books, code repositories, articles, and more. We’re talking about hundreds of billions or even trillions of words(tokens).</p><p>But here’s the clever part: you don’t need humans to label any of this data. The model learns through a simple task called <strong>next token prediction</strong>.</p><p><strong>How Next Token Prediction Works:</strong></p><p>You show the model part of a sentence, and it has to guess what comes next.</p><p><strong>Example 1</strong>:</p><pre>Given: &quot;The cat sat on the&quot;<br>Model predicts: &quot;mat&quot;</pre><p><strong>Example 2</strong>:</p><pre>Given: &quot;In Python, you can create a list using&quot;<br>Model predicts: &quot;[&quot;</pre><p>Every time the model predicts wrong, you adjust its billions of parameters slightly to make the correct answer more likely. Do this trillions of times, and something amazing happens: the model learns grammar, facts, reasoning patterns, how code works, and much more.</p><p><strong>The Training Process:</strong></p><p>This takes weeks or months on thousands of powerful GPUs. The model sees so much text that it starts internalising patterns:</p><ul><li>Grammar and syntax rules</li><li>How do different topics relate to each other</li><li>Common sense relationships (fire is hot, water is wet)</li><li>Programming syntax and logic</li><li>Multiple languages</li><li>Writing styles</li></ul><p><strong>What You End Up With:</strong></p><p>After pre-training, you have a base (or foundation) model that’s incredibly good at predicting what comes next in text. <strong>But here’s the problem: <em>it’s not particularly helpful</em>.</strong></p><p>Here’s a perfect example of what goes wrong. Let’s say you want to use the model for sentiment analysis:</p><p><strong>User asks</strong>: “Classify the sentiment of this text: <em>‘I absolutely loved the movie! The acting was brilliant.’</em>”</p><p>A pre-trained (base) model might respond:</p><pre>&quot;Classify the sentiment of this text: &#39;I absolutely loved the movie! The acting was brilliant.&#39;<br>This is a positive review. Many people on review sites like IMDB and Rotten Tomatoes express <br>similar sentiments when they enjoy films. Positive reviews often mention...&quot;</pre><p>See the issue? Instead of simply classifying it as “Positive,” the model continues generating text like it’s writing a blog post or forum discussion. It’s doing what it was trained to do — predict the next probable words — but that’s not what you asked for.</p><p>You wanted: “Positive”</p><p>You got: A continuation of text that sounds like movie review articles it read during training.</p><p>The base model has the knowledge to understand sentiment, but it doesn’t know how to <em>use</em> that knowledge in the way you need. It’s simply mimicking patterns from the internet, not functioning as a helpful assistant that follows your instructions or gives concise, task‑specific answers.</p><p>A base model can recognise meaning, but it can’t <em>apply</em> that meaning to your goal. It doesn’t know that you want a short label like ‘Positive’ — it only knows how to continue text in a statistically likely way.</p><p>This is exactly why we need the next stage.</p><h4><strong>Stage 2: Supervised Fine-Tuning (SFT) — Teaching It to Be Helpful</strong></h4><p><strong>The Problem We’re Solving:</strong></p><p>After pre-training, <strong>the base model knows a lot but doesn’t know how to have a useful conversation</strong>. It doesn’t understand that:</p><ul><li>it should <strong>answer your question directly</strong> instead of simply continuing the text</li><li>it should <strong>format responses clearly</strong>, with structure and intention</li><li>it should <strong>admit when it doesn’t know</strong> something instead of guessing</li><li>it should prioritise being helpful, not just statistically probable</li><li>it should f<strong>ollow instructions</strong> like ‘summarise,’ ‘translate,’ or ‘classify’</li><li>it should <strong>stay on topic</strong> and maintain context across turns</li><li>it should <strong>avoid unsafe, inappropriate, or overly confident answers</strong></li><li>it should know when to stop instead of rambling</li></ul><p>Let me give you another concrete example of the problem:</p><p><strong>User</strong> <strong>asks:</strong> “<em>Can you help me debug this code?</em>”</p><p>Pre-trained model might respond:</p><pre>&quot;Can you help me debug this code? Sure, I&#39;ve been coding for years. <br>First, let me tell you about my experience with debugging. I remember when I first started...&quot;</pre><p>It’s continuing in a conversational pattern it saw online, but it’s not being helpful. It doesn’t even ask to see the code! It’s just generating text that sounds like forum posts or blog articles.</p><p><strong>What We Actually Want:</strong></p><pre>&quot;I&#39;d be happy to help debug your code! Could you share:<br>1. The code snippet<br>2. The error message you&#39;re seeing<br>3. What you expected to happen<br><br>This will help me identify the issue quickly.&quot;</pre><p>See the difference? It’s structured, helpful, and action-oriented. This is what supervised fine-tuning teaches.</p><p><strong>How Supervised Fine-Tuning Works:</strong></p><p>You create a dataset of high-quality conversations — usually tens of thousands of examples where humans demonstrate exactly how the model should respond to different types of questions.</p><p>Human experts write these conversation pairs:</p><p><strong>Example 1:</strong></p><p>User asks: “<em>Explain recursion in simple terms</em>”</p><p>Assistant responds: “<em>Recursion is when a function calls itself to solve a problem. Think of it like looking in a mirror that reflects another mirror — you see infinite copies.</em></p><p><em>Here’s a simple example: imagine you need to count down from 5.</em></p><p><em>Instead of using a loop, a recursive function would:</em></p><ol><li><em>Print 5</em></li><li><em>Call itself to count down from 4</em></li><li><em>Which prints 4, then calls itself to count down from 3</em></li><li><em>And so on until it reaches 0</em></li></ol><p><em>The important part is having a stopping point (called the base case), or it would go on forever!</em>”</p><p><strong>Example 2:</strong></p><p>User asks: “<em>What’s the difference between machine learning and deep learning?</em>”</p><p>Assistant responds: “<em>Great question! Here’s the key difference:</em></p><p><em>Machine Learning is the broad field where computers learn from data without being explicitly programmed for every scenario. This includes many techniques like decision trees, random forests, and neural networks.</em></p><p><em>Deep Learning is a subset of machine learning that specifically uses neural networks with multiple layers (hence ‘deep’). It’s particularly powerful for complex tasks like image recognition or language understanding because it can automatically learn features from raw data.</em></p><p><em>Think of it this way: all deep learning is machine learning, but not all machine learning is deep learning. Deep learning is like a specialised tool within the larger machine learning toolkit.</em>”</p><p>Above examples teach the model:</p><ul><li>How to structure explanations clearly</li><li>When to use analogies</li><li>How to break down complex topics</li><li>The appropriate level of detail</li><li>A friendly, helpful tone</li></ul><p><strong>The Training Process:</strong></p><p>You take your pre-trained model and train it on these conversation examples. The model learns to match this style and format. Crucially, you use a much lower learning rate than pre-training because you don’t want the model to forget everything it learned — you’re just adjusting its behaviour.</p><p><strong>What Changes:</strong></p><p>After supervised fine-tuning, the same model now responds completely differently:</p><p><strong>Before SFT:</strong></p><pre>User: &quot;How do I learn Python?&quot;<br>Model: &quot;How do I learn Python? is a common question. Many resources exist...&quot;</pre><p><strong>After SFT:</strong></p><pre>User: &quot;How do I learn Python?&quot;<br>Model: &quot;Here&#39;s a structured approach to learning Python:<br><br>1. Start with basics: Learn syntax, variables, data types, and control flow<br>2. Practice with small projects: Build a calculator, to-do list, or simple game<br>3. Learn key libraries: Get familiar with NumPy, Pandas for data work<br>4. Build real projects: This is where learning really sticks<br><br>I&#39;d recommend starting with Python.org&#39;s official tutorial or a course on Coursera. Would you like specific resource recommendations based on your background?&quot;</pre><p>Completely different behaviour, right? The model now understands its role as an assistant.</p><p><strong>But There’s Still a Problem:</strong></p><p>Even with all these high-quality examples, the model doesn’t really understand what makes one response <em>better</em> than another in subtle ways. It knows the format, but when there are multiple valid responses, it doesn’t know which one people would actually prefer.</p><p>For example, should an explanation be detailed or concise? Technical or simple? Include code examples or stick to concepts? The demonstration examples can’t cover every nuance, so the model has no way to choose the <em>best</em> response — only a plausible one.</p><p>This is where the third stage comes in.</p><h4>Stage 3: Reinforcement Learning from Human Feedback (RLHF) — Learning What People Actually Prefer</h4><p><strong>The Problem We’re Solving:</strong></p><p>After supervised fine-tuning, the model can hold conversations and be helpful. But here’s the thing: there are often many ways to answer a question, and some are just… better. Not wrong vs. right, but more helpful, clearer, or more appropriate for the situation.</p><p>Think about explaining “what is an API” to someone. You could:</p><ul><li>Give a highly technical definition with protocols and specifications</li><li>Use a restaurant analogy (the menu is the API, the kitchen is the server)</li><li>Provide a simple explanation with a code example</li><li>Give a detailed explanation covering multiple use cases</li></ul><p>All of these are correct, but depending on the user’s background and needs, one might be way more helpful than the others. How do you teach a model this kind of judgment?</p><p>Let me explain this with an example.</p><p><strong>User asks:</strong> “<em>Why is my code running slow?</em>”</p><p>The model might generate several different responses:</p><p>Response A (Too technical):</p><pre>&quot;Performance issues typically stem from algorithmic complexity. You&#39;re likely experiencing O(n²) time complexity. Consider implementing memoization or utilizing more efficient data structures like hash tables for O(1) lookup times...&quot;</pre><p>Response B (Too vague):</p><pre>&quot;Your code might be slow for various reasons. It could be the algorithm, the data structures, or maybe your computer. Try to optimize it.&quot;</pre><p>Response C (Just right):</p><pre>&quot;Let me help you identify the slowdown. Common causes include:<br><br>1. Inefficient loops (nested loops especially)<br>2. Loading too much data into memory at once<br>3. Not using appropriate data structures<br><br>Could you share your code? I&#39;ll point out specific bottlenecks and suggest optimizations.&quot;</pre><p>Response C is clearly the best — it’s specific, actionable, and asks for the right information. But how do you teach the model to prefer responses like C?</p><p><strong>How RLHF Works:</strong></p><p>This is a three-step process that’s pretty clever.</p><p><strong>Step 1: Collecting Human Preferences</strong></p><p>You show human evaluators the same question with multiple different model responses. They don’t write responses themselves — they just rank which ones are better.</p><p>Example ranking task:</p><pre>Question: &quot;Why is my code running slow?&quot;<br><br>Response 1: &quot;Performance issues typically stem from algorithmic complexity. You&#39;re likely experiencing O(n²) time complexity. Consider implementing memoization or utilizing more efficient data structures like hash tables for O(1) lookup times...&quot;<br><br>Response 2: &quot;Your code might be slow for various reasons. It could be the algorithm, the data structures, or maybe your computer. Try to optimize it.&quot;<br><br>Response 3: &quot;Let me help you identify the slowdown. Common causes include:<br><br>1. Inefficient loops (nested loops especially)<br>2. Loading too much data into memory at once<br>3. Not using appropriate data structures<br><br>Could you share your code? I&#39;ll point out specific bottlenecks and suggest optimizations.&quot;<br><br>Human ranks: Response 3 &gt; Response 1 &gt; Response 2</pre><p>Why this ranking? Response 3 is structured, specific, actionable and offers follow-up help. Response 1 is technically correct but generic. Response 2 is vague and doesn’t offer meaningful guidance.</p><p>You collect tens of thousands of these rankings across all kinds of questions.</p><p><strong>Step 2: Training a Reward Model</strong></p><p>Now here’s where it gets interesting. You build a separate neural network called a <strong>reward model</strong>. This model’s job is to predict how much a human would like a given response.</p><p>You train it on all those rankings:</p><ul><li>Input: A question + a response</li><li>Output: A score (how good humans think this response is)</li></ul><p>The reward model learns patterns like:</p><ul><li>Responses with a clear structure score higher</li><li>Overly technical jargon without explanation scores lower</li><li>Responses that offer follow-up help score higher</li><li>Vague, generic advice scores lower</li></ul><p>Once trained, this reward model can score any response automatically. It’s learned to approximate human judgment.</p><p><strong>Step 3: Optimising the Model Using Reinforcement Learning</strong></p><p>Now comes the final step. You let your fine-tuned model generate responses, and you use the reward model to score how good they are.</p><p>The process:</p><ol><li>The model generates a response to a question</li><li>Reward model scores it (higher score = better response)</li><li>You update the model’s parameters to make it more likely to generate high-scoring responses</li><li>Repeat thousands of times</li></ol><p>This optimisation is traditionally done using an algorithm called PPO (Proximal Policy Optimisation), though newer approaches like DPO (Direct Preference Optimisation) are also widely used. The key insight is you’re not just telling the model “this exact response is good” — you’re teaching it the <em>characteristics</em> that make responses good.</p><p>There’s an important limitation: <em>you don’t want the model to change too much from the fine-tuned version</em>, or it may start producing strange answers that try to ‘cheat’ the scoring system instead of genuinely improving. So the training process must balance two goals — increasing reward scores while keeping the model close to its original behaviour.</p><p><strong>What the Model Learns:</strong></p><p>Through this process, the model learns subtle preferences:</p><ul><li>When to be detailed vs. concise</li><li>When to use technical terms vs. simple language</li><li>How to balance helpfulness with accuracy</li><li>When to ask clarifying questions</li><li>How to handle uncertainty gracefully</li></ul><p><strong>The Result:</strong></p><p>After RLHF, responses become noticeably better. The model doesn’t just follow instructions — it understands what makes a response genuinely helpful.</p><p>Before RLHF:</p><pre>User: &quot;What&#39;s the best way to learn data structures?&quot;<br>Model: &quot;Study algorithms textbooks and practice coding problems daily.&quot;</pre><p>After RLHF:</p><pre>User: &quot;What&#39;s the best way to learn data structures?&quot;<br>Model: &quot;Here&#39;s a learning path I&#39;d recommend:<br>- Week 1-2: Arrays and Linked Lists (LeetCode easy problems)<br>- Week 3-4: Stacks, Queues, Hash Tables (build small projects using each)<br>- Week 5-6: Trees and Graphs (visualize with drawings)<br>- Week 7-8: Practice mixed problems<br><br>Start with visualizations on sites like VisuAlgo, then implement each structure from scratch in your preferred language. Would you like resources for any specific structure?&quot;</pre><p>The second response is more helpful — it provides steps, explains the context, and offers to help further. That’s the power of RLHF.</p><h3>The Complete Training Pipeline (Visual Overview)📊</h3><p>Here’s a simple visual overview of the entire training pipeline, from raw data to production‑ready models.</p><pre>┌──────────────────────────────────────────────┐<br>│ Raw text data from internet, books, and code │<br>└──────────────────────────────────────────────┘<br>                     ↓<br>┌──────────────────────────────────────────────┐<br>│              [PRE‑TRAINING]                  │<br>│  Predict next token → learn language patterns│<br>└──────────────────────────────────────────────┘<br>                     ↓<br>┌──────────────────────────────────────────────┐<br>│ Base model (understands language but         │<br>|              not helpful)                    │<br>└──────────────────────────────────────────────┘<br>                     ↓<br>┌──────────────────────────────────────────────┐<br>│         [SUPERVISED FINE‑TUNING (SFT)]       │<br>│  Learns to follow instructions &amp; tasks       │<br>└──────────────────────────────────────────────┘<br>                     ↓<br>┌──────────────────────────────────────────────┐<br>│ Helpful model (structured, task‑aware)       │<br>└──────────────────────────────────────────────┘<br>                     ↓<br>┌──────────────────────────────────────────────┐<br>│                  [RLHF]                      │<br>|       learns from human preferences          │<br>└──────────────────────────────────────────────┘<br>                     ↓<br>┌──────────────────────────────────────────────┐<br>│ Production model (ChatGPT, Claude, Gemini)   │<br>└──────────────────────────────────────────────┘</pre><h3>How to Identify Models at Different Training Stages</h3><p>When you’re browsing models on Hugging Face it’s useful to know which training stage a model has completed. Here’s how to identify them:</p><h4><strong>1. Pre-trained Models (Base Models):</strong></h4><p>These are raw language models trained only on massive text data — no instruction-following or alignment.</p><p><strong>How to spot them:</strong></p><ul><li><strong>Names</strong> often include -base, -raw, or no suffix at all</li><li><strong>Model card</strong> mentions only pre-training (e.g., “trained on Common Crawl”)</li><li><strong>Behaviour</strong>: They continue text but don’t follow instructions</li></ul><p><strong>Examples:</strong></p><ul><li>meta-llama/Llama-2-7b</li><li>mistralai/Mistral-7B-v0.1</li><li>EleutherAI/gpt-neo-2.7B</li><li>bert-base-uncased</li><li>roberta-base</li></ul><h4><strong>2. Supervised Fine-Tuned Models (SFT):</strong></h4><p>These have completed Stage 1 (pre-training) + Stage 2 (supervised fine-tuning).</p><p><strong>How to spot them:</strong></p><ul><li><strong>Names</strong> often include -instruct, -chat, -sft, or -it</li><li><strong>Model card</strong> mentions “instruction tuning” or “fine-tuned on dialogue/tasks”</li><li><strong>Behaviour</strong>: They answer questions, follow prompts, but may lack nuance</li></ul><p><strong>Examples:</strong></p><ul><li>meta-llama/Llama-2-7b-chat</li><li>mistralai/Mistral-7B-Instruct-v0.2</li><li>OpenAssistant/oasst-sft-4-pythia-12b</li></ul><h4><strong>3. RLHF-Aligned Models (Full Alignment):</strong></h4><p>These have completed all three stages: Pre-training + SFT + RLHF.</p><p><strong>How to spot them:</strong></p><ul><li><strong>Names</strong> may include -rlhf, -aligned, -chat-hf, or version numbers like v2, v3</li><li><strong>Model card</strong> mentions “RLHF”, “DPO”, “reward model”, or “preference learning”</li><li><strong>Behaviour</strong>: They respond helpfully, adapt tone, and offer follow-up suggestions</li></ul><p><strong>Examples:</strong></p><ul><li>HuggingFaceH4/zephyr-7b-beta (DPO-aligned)</li><li>meta-llama/Llama-2-7b-chat-hf (has RLHF)</li><li>jxrma/Qwen2.5–7B-Instruct-RLHF-Abstention-v2</li><li>API-only models: gpt-4, claude-3-opus, gemini-pro</li></ul><h3><strong>To summarise</strong></h3><ul><li><strong>Pre-training</strong> gives the model language understanding and knowledge. It learns to predict text, which teaches it grammar, facts, and patterns. But it doesn’t know how to be helpful — it just continues text like it saw on the internet.</li><li><strong>Supervised Fine-Tuning</strong> teaches the model to be an assistant. Through high-quality conversation examples, it learns the format and structure of being helpful. It now knows to answer questions directly, provide clear explanations, and use an appropriate tone.</li><li><strong>RLHF</strong> teaches the model judgment. It learns what makes one response better than another through human feedback. It develops an understanding of subtle preferences — when to be detailed, when to be concise, how to handle uncertainty.</li><li>Each stage builds on the previous one, solving a specific problem:<br>- <strong>Pre-training solves: “How do we teach language understanding?”</strong><br>- <strong>SFT solves: “How do we teach it to be helpful?”</strong><br>- <strong>RLHF solves: “How do we teach it what ‘better’ means?”</strong></li></ul><blockquote>“Each stage builds on the last — and together, they turn raw text prediction into intelligent conversation.”</blockquote><h3><strong>Resources &amp; Further Learning</strong></h3><ol><li><strong>Andrej Karpathy’s “State of GPT”</strong> (Microsoft Build 2023) — Brilliant overview of the entire pipeline<br>YouTube: <a href="https://www.youtube.com/watch?v=bZQun8Y4L2A">https://www.youtube.com/watch?v=bZQun8Y4L2A</a></li><li><strong>3Blue1Brown’s Deep Learning Series:</strong></li></ol><ul><li>“Transformers, the tech behind LLMs” (Chapter 5)<br>YouTube: <a href="https://www.youtube.com/watch?v=wjZofJX0v4M">https://www.youtube.com/watch?v=wjZofJX0v4M</a></li><li>“Attention in transformers, step-by-step” (Chapter 6)<br>YouTube: <a href="https://www.youtube.com/watch?v=eMlx5fFNoYc">https://www.youtube.com/watch?v=eMlx5fFNoYc</a></li></ul><p>3. <strong>Training ChatGPT</strong></p><ul><li><a href="https://openai.com/index/chatgpt/">https://openai.com/index/chatgpt/</a></li></ul><p><em>This article is part of my Applied Gen AI learning journey. Follow along as I break down complex AI concepts into understandable pieces.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbd45b1f7368" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/the-3-stage-training-pipeline-behind-chatgpt-claude-and-gemini-explained-simply-bbd45b1f7368">The 3‑Stage Training Pipeline Behind ChatGPT, Claude, and Gemini (Explained Simply)</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Potential: ChatGPT’s Empowerment of Software Engineers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://sivasai-yadav.medium.com/unlocking-the-potential-chatgpts-empowerment-of-software-engineers-d662e50e33fd?source=rss-c615257004ff------2"><img src="https://cdn-images-1.medium.com/max/1400/1*86PvwdDdJwCcrCP3OWJzUQ.jpeg" width="1400"></a></p><p class="medium-feed-snippet">Software engineers can benefit from ChatGPT in a number of ways.</p><p class="medium-feed-link"><a href="https://sivasai-yadav.medium.com/unlocking-the-potential-chatgpts-empowerment-of-software-engineers-d662e50e33fd?source=rss-c615257004ff------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://sivasai-yadav.medium.com/unlocking-the-potential-chatgpts-empowerment-of-software-engineers-d662e50e33fd?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/d662e50e33fd</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 08:13:00 GMT</pubDate>
            <atom:updated>2023-07-14T08:13:00.713Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[10 Python Frameworks for Parallel and distributed Machine Learning Tasks.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/10-python-frameworks-for-parallel-and-distributed-machine-learning-tasks-c0215269cfd?source=rss-c615257004ff------2"><img src="https://cdn-images-1.medium.com/max/1920/1*msDR7MbMd9ZLJSReq4BL2w.jpeg" width="1920"></a></p><p class="medium-feed-snippet">Python Libraries that Enable Capabilities to Distribute and Parallelize ML Tasks.</p><p class="medium-feed-link"><a href="https://medium.com/swlh/10-python-frameworks-for-parallel-and-distributed-machine-learning-tasks-c0215269cfd?source=rss-c615257004ff------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/10-python-frameworks-for-parallel-and-distributed-machine-learning-tasks-c0215269cfd?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0215269cfd</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Mon, 01 Mar 2021 18:54:43 GMT</pubDate>
            <atom:updated>2021-03-02T23:33:18.525Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[10 Useful Jupyter Notebook Extensions for a Data Scientist.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/10-useful-jupyter-notebook-extensions-for-a-data-scientist-bd4cb472c25e?source=rss-c615257004ff------2"><img src="https://cdn-images-1.medium.com/max/1280/1*VKrT5CAhLkFf_OErZAJamw.jpeg" width="1280"></a></p><p class="medium-feed-snippet">These Jupyter Notebook Extensions make Data Scientist life easier.</p><p class="medium-feed-link"><a href="https://medium.com/data-science/10-useful-jupyter-notebook-extensions-for-a-data-scientist-bd4cb472c25e?source=rss-c615257004ff------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/10-useful-jupyter-notebook-extensions-for-a-data-scientist-bd4cb472c25e?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd4cb472c25e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 18:48:59 GMT</pubDate>
            <atom:updated>2021-02-15T15:45:27.999Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[9 Most Useful String Methods for a Data Scientist]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/9-most-useful-string-methods-for-a-data-scientist-bd75756b8ca2?source=rss-c615257004ff------2"><img src="https://cdn-images-1.medium.com/max/1920/1*yip9QAxgsH00qvbg4lD4yg.jpeg" width="1920"></a></p><p class="medium-feed-snippet">Most useful string methods for a Data Scientist during data preprocessing.</p><p class="medium-feed-link"><a href="https://medium.com/swlh/9-most-useful-string-methods-for-a-data-scientist-bd75756b8ca2?source=rss-c615257004ff------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/9-most-useful-string-methods-for-a-data-scientist-bd75756b8ca2?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd75756b8ca2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Thu, 28 Jan 2021 10:58:16 GMT</pubDate>
            <atom:updated>2021-02-15T14:44:45.521Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Feature Selection Methods in Machine Learning]]></title>
            <link>https://medium.com/swlh/feature-selection-methods-in-machine-learning-67d71a6bce21?source=rss-c615257004ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/67d71a6bce21</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sivasai Yadav Mudugandla]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 16:53:09 GMT</pubDate>
            <atom:updated>2026-03-02T11:47:22.875Z</atom:updated>
            <content:encoded><![CDATA[<h3>3 Top Feature Selection Techniques in Machine Learning (part -1)</h3><p>Improve your model performance with features that contribute more to predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkHHaZEjjyCTosH4QkQMVQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/qimono-1962238/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1690423">Arek Socha</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1690423">Pixabay</a></figcaption></figure><h3>Introduction</h3><p>When do you say a model is good? When a model performs well on unseen data then we say its a good model. As a Data Scientist, we perform various operations in order to make a good Machine Learning model. The operations include data pre-processing (dealing with NA’s and outliers, column type conversions, dimensionality reduction, normalization etc), exploratory data analysis (EDA), hyperparameter tuning/optimization (the process of finding the best set of hyper-parameters of the ML algorithm that delivers the best performance), feature selection etc.</p><blockquote>“Garbage in, Garbage out.”<br>If data fed into an ML model is of poor quality, the model will be of poor quality</blockquote><p>Below articles are related to hyperparameter tuning techniques, open-source frameworks for hyperparameter tuning and data leakage in hyperparameter tuning.</p><ul><li><a href="https://medium.com/swlh/4-hyper-parameter-tuning-techniques-924cb188d199">4 Hyper-Parameter Tuning Techniques</a></li><li><a href="https://towardsdatascience.com/10-hyperparameter-optimization-frameworks-8bc87bc8b7e3">10 Hyperparameter optimization frameworks.</a></li><li><a href="https://towardsdatascience.com/data-leakage-with-hyper-parameter-tuning-c57ba2006046">Data Leakage with Hyper-Parameter Tuning</a></li></ul><h3>Feature Selection</h3><p>Feature Selection is the process of selecting the best subset from the existing set of features that contribute more in predicting the output. This helps to improve the performance of the model (i.e removes redundant or/and irrelevant features that are carrying noise and decreasing the accuracy of the model). One of the major advantages of feature selection is it rescues the model from the high risk of overfitting when we have datasets with high dimensionality. By reducing the number of features, it actually reduces the training time of the ML algorithm i.e. computational cost involved.</p><p>There are 3 main feature selection techniques</p><ol><li>Filter methods</li><li>Embedded methods</li><li>Wrapper methods</li></ol><pre>import numpy as np<br>import pandas as pd <br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>sns.set(style=”whitegrid”) <br>import warnings<br>warnings.filterwarnings(‘ignore’) </pre><pre># load Iris dataset <br>sklearn.datasets import load_iris </pre><pre># create input and output features<br>feature_names = load_iris().feature_names<br>X_data = pd.DataFrame(load_iris().data, columns=feature_names)<br>y_data = load_iris().target</pre><h3>1. Filter methods</h3><p>Filter methods use statistical techniques to compute the relationship between features and the target variable. Filter methods generally use scores in statistical test and variances, to rank the importance of individual features.</p><p>Advantages:</p><ol><li>Filter methods are independent of any machine learning algorithms. So, they can be used as the input of any machine learning models.</li><li>Filter methods are very fast.</li></ol><p>Three types of filter methods:</p><h4>1. ANOVA F-value</h4><p>ANOVA F-value estimates the degree of linearity between the input feature (i.e., independent features) and the output feature (i.e., dependent feature). A high F-value indicates a high degree of linearity and a low F-value indicates a low degree of linearity.</p><p>Scikit-learn provides two functions to calculate F-value:</p><ol><li><strong>sklearn.feature_selection.f_regression</strong> for regression problems</li><li><strong>sklearn.feature_selection.f_classif </strong>for classification problems</li></ol><pre># import f_classif<br>from sklearn.feature_selection import f_classif</pre><pre># create f_classif object<br>f_value = f_classif(X_data, y_data)</pre><pre># print the name and F-value of each feature<br>for feature in zip(feature_names, f_value[0]):<br>    print(feature)</pre><pre>OUTPUT:<br>------<br>(&#39;sepal length (cm)&#39;, 119.26450218449871) <br>(&#39;sepal width (cm)&#39;, 49.16004008961098) <br>(&#39;petal length (cm)&#39;, 1180.1611822529776) <br>(&#39;petal width (cm)&#39;, 960.0071468018025)</pre><p>Let&#39;s visualize the same</p><pre># Create a bar chart<br>plt.figure(figsize=(4,4))</pre><pre>plt.bar(x=feature_names, height=f_value[0], color=’red’)</pre><pre>plt.xticks(rotation=’vertical’)</pre><pre>plt.ylabel(‘F-value’)</pre><pre>plt.title(‘F-value Comparison’)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Rs6m2h96FFFgnIUR0TzUSg.png" /></figure><p>Disadvantage:</p><p>ANOVA F-value only captures the linear relationships between input and output feature.</p><h4>2. Variance Threshold</h4><p>Variance Threshold removes the features whose variance is below the pre-defined <em>threshold </em>value. By default, it removes all zero-variance features, i.e. features that have the same value in all samples.</p><pre># import VarianceThreshold<br>from sklearn.feature_selection import VarianceThreshold</pre><pre># create VarianceThreshold object<br>selector = VarianceThreshold(threshold=0.0)</pre><pre># train and transform<br>selector.fit_transform(X_data)</pre><pre># print the name and variance of each feature<br>for feature in zip(feature_names, selector.variances_):<br>    print(feature)</pre><pre>OUTPUT:<br>------<br>(&#39;sepal length (cm)&#39;, 0.6811222222222222) <br>(&#39;sepal width (cm)&#39;, 0.1887128888888887) <br>(&#39;petal length (cm)&#39;, 3.0955026666666674) <br>(&#39;petal width (cm)&#39;, 0.5771328888888888)</pre><p>Let’s visualize the same</p><pre># create a bar chart<br>plt.figure(figsize=(4,4))</pre><pre>plt.bar(x=feature_names, height=selector.variances_, color=’red’)</pre><pre>plt.xticks(rotation=’vertical’)</pre><pre>plt.ylabel(‘Variance’)</pre><pre>plt.title(‘Variance Comparison’)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*_tUbi0iImR2BWe06M34g8Q.png" /></figure><p><strong>Advantage:</strong></p><p>This can be used for unsupervised learning.</p><p><strong>Disadvantage:</strong></p><p>Variance Threshold only considers the relationship among the features but not the relationship between input features with the output feature.</p><h4>3. Mutual information</h4><p>Mutual information (MI) measures the dependence of one variable to another by quantifying the amount of information obtained about one feature, through the other feature. MI is symmetric and non-negative and is equal to zero if and only if two random variables are independent, and higher values mean higher dependency.</p><p>Scikit-learn provides two functions to calculate F-value:</p><ol><li><strong>sklearn.feature_selection.mutual_info_classif </strong>for regression problems</li><li><strong>sklearn.feature_selection.mutual_info_regression </strong>for classification problems</li></ol><pre># import mutual_info_classif<br>from sklearn.feature_selection import mutual_info_classif</pre><pre># create mutual_info_classif object<br>MI_score = mutual_info_classif(X_data, y_data, random_state=0)</pre><pre># Print the name and mutual information score of each feature<br>for feature in zip(feature_names, MI_score):<br>    print(feature)</pre><pre>OUTPUT:<br>------<br>(&#39;sepal length (cm)&#39;, 0.4738732342805525) <br>(&#39;sepal width (cm)&#39;, 0.28607227699171767) <br>(&#39;petal length (cm)&#39;, 0.9895851732491787) <br>(&#39;petal width (cm)&#39;, 0.9749379656705233)</pre><p>Let’s visualize the same</p><pre># create a bar chart <br>plt.figure(figsize=(4,4))</pre><pre>plt.bar(x=feature_names, height=MI_score, color=’red’)</pre><pre>plt.xticks(rotation=’vertical’)</pre><pre>plt.ylabel(‘Mutual Information Score’)</pre><pre>plt.title(‘Mutual Information Score Comparison’)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*6U4JFNA0vhBMDlVznop86Q.png" /></figure><p><strong>Advantage:</strong></p><p>MI can capture non-linear relationships between input and output feature.</p><h4><strong>4. Scikit-learn’s SelectKBest</strong></h4><p>SelectKBest selects the features using a function (in this case ANOVA F-value) and then “removes all but the k highest scoring features”.</p><pre># import SelectKBest<br>from sklearn.feature_selection import SelectKBest</pre><pre># create a SelectKBest object<br>skb = SelectKBest(score_func=f_classif, k=2) </pre><pre># set f_classif as ANOVA F-value<br># Select top 2 features based on the criteria</pre><pre># train and transform<br>X_data_new = skb.fit_transform(X_data, y_data)</pre><pre># print the name of the selected features<br>for feature_list_index in skb.get_support(indices=True):<br>    print(feature_names[feature_list_index])</pre><pre>OUTPUT:<br>------<br>petal length (cm) <br>petal width (cm)</pre><p>In my next article, I will talk about Embedded and Wrapper methods.</p><h3>Thank you for reading!</h3><p>Any feedback and comments are, greatly appreciated!</p><p>Some of my other posts you may find interesting,</p><ul><li><a href="https://towardsdatascience.com/normality-tests-in-python-31e04aa4f411">10 Normality Tests in Python (Step-By-Step Guide 2020)</a></li><li><a href="https://medium.com/swlh/is-and-in-python-f084f36cbc0e">“is” and “==” in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67d71a6bce21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/feature-selection-methods-in-machine-learning-67d71a6bce21">Feature Selection Methods in Machine Learning</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>