<?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 Sahil Arora on Medium]]></title>
        <description><![CDATA[Stories by Sahil Arora on Medium]]></description>
        <link>https://medium.com/@sahilarora240792?source=rss-d34bc6b9ab84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TLI8DXFyQ3IGhv3pSft22g.jpeg</url>
            <title>Stories by Sahil Arora on Medium</title>
            <link>https://medium.com/@sahilarora240792?source=rss-d34bc6b9ab84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:23:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sahilarora240792/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[What is Claude Code? A Plain English Guide]]></title>
            <link>https://medium.com/@sahilarora240792/what-is-claude-code-a-plain-english-guide-2fb52c1e2d2d?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fb52c1e2d2d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 11:34:11 GMT</pubDate>
            <atom:updated>2026-03-21T11:34:11.383Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>No jargon. No confusing tech-speak. Just a simple explanation of the AI tool that can actually write and fix code for you.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*ijYvQFKasSVC0-bIrD2Euw.png" /></figure><p><strong><em>Claude Code runs right inside your terminal the place developers type commands.</em></strong></p><p><strong>Have you ever wished you could just tell a computer what you want, and have it write the code for you?</strong></p><h3><strong>That’s exactly what Claude Code does.</strong></h3><p>Claude Code is an AI tool made by Anthropic the same company behind the Claude AI chatbot. But Claude Code isn’t just a chatbot. It’s more like a coding partner that can read your files, write new code, fix bugs, and even run commands all on its own.</p><p>And the best part? You just talk to it in plain English. No special commands. No complicated setup. Just sentences like you’d say to a friend.</p><p><em>“Imagine hiring a brilliant developer who already knows your entire project, never gets tired, and always asks before making a change. That’s Claude Code.”</em></p><p><strong>Okay, But What Does It Actually Do?</strong></p><p>Here’s a quick example. Instead of spending an hour tracking down a bug yourself, you can just type:</p><p><strong><em>“There’s a bug in my login page — users can’t sign in. Can you find and fix it?”</em></strong></p><p>Claude Code will read your code, find the problem, explain it to you in simple words, and fix it — all in under a minute.</p><p><strong><em>Claude Code can do the work of a developer — reading, writing, fixing, testing, all from a simple instruction.</em></strong></p><p><strong>Here’s everything it can do:</strong></p><ul><li>🔍<strong> </strong>Reads and understands your whole project (not just one file)</li><li>🐛<strong> </strong>Finds and fixes bugs when you describe the problem</li><li>✍️<strong> </strong>Writes brand-new features from your description</li><li>🧪<strong> </strong>Creates and runs tests to make sure things work</li><li>♻️<strong> </strong>Cleans up messy or outdated code</li><li>🔀<strong> </strong>Handles Git — commits, branches, version history</li></ul><h3><strong>Where Do You Use It?</strong></h3><p>One of the nicest things about Claude Code is that it fits into how you already work. You don’t have to change your setup.<em>Claude Code works in the terminal, inside VS Code and JetBrains, or even on the web with no setup needed.</em></p><blockquote><strong>In the Terminal: </strong>This is where Claude Code lives by default. You open your project folder, type claude, and start chatting.</blockquote><blockquote><strong>In VS Code or JetBrains: </strong>If you use a code editor, there’s a plugin that brings Claude Code right into your sidebar. You can see suggested changes highlighted before accepting them.</blockquote><blockquote><strong>On the Web: </strong>No installation at all. Just open a browser, and Claude Code runs in a safe cloud environment. Great for trying it out.</blockquote><p><strong>How Is It Different From Just Chatting With Claude?</strong></p><p>Great question! When you chat with Claude on claude.ai, you paste your code in, it gives you a suggestion, and you copy it back yourself. It’s helpful but it’s still a lot of work on your end.</p><p>Claude Code is different. It has direct access to your project. Here’s a side-by-side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK8krlV8Em9hD0caWZtZAg.png" /></figure><p><strong>“But Will It Break My Code?”</strong></p><p>This is the number one thing people worry about — and honestly, it’s a fair concern. If an AI is writing and editing your code, what if it makes things worse?Anthropic thought of that. Here’s how Claude Code keeps your work safe:</p><p><em>Claude Code always asks before making changes — and has a full rewind feature if anything goes wrong.</em></p><p>It asks before every change. Claude Code won’t silently edit your files. It shows you what it wants to do and waits for your approval.</p><p>It saves checkpoints. Before every action, it automatically saves your code’s current state. Think of it like an auto-save.</p><p>You can rewind anytime. Just type /rewind and everything goes back to exactly how it was. Like Ctrl+Z, but for everything Claude did.</p><h3><strong>Who Is It Really For?</strong></h3><p>You might think Claude Code is only for expert programmers. But honestly, it’s useful for a much wider group of people:</p><ul><li>🧑‍💻<strong> Developers — </strong>You’re a developer who wants to move faster and skip the boring parts</li><li>📚<strong> Learners — </strong>You’re learning to code and want a patient tutor who explains things clearly</li><li>💡<strong> Beginners — </strong>You have a project idea but don’t know where to start</li><li>🚀<strong> Teams — </strong>Your team needs to clean up or modernise a big codebase</li></ul><h3><strong>How Do You Get Started? (4 Easy Steps)</strong></h3><p><strong>Getting Claude Code up and running takes less than 5 minutes. Here’s all you need to do:</strong></p><ol><li><strong>Get a Claude plan</strong></li></ol><p>You need Claude Pro, Max, Team, or Enterprise — or an Anthropic API account. Check claude.ai for current plan options.</p><p><strong>2. Download Claude Code</strong></p><p>Head to Anthropic’s website, download the tool, and sign in with your Claude account.</p><p><strong>3. Open your project folder</strong></p><p>In your terminal, navigate to your project and just type claude. That’s it.</p><p><strong>4. Start talking to it</strong></p><p>Describe what you need in plain English — “fix this bug”, “add a search bar”, “explain this function”. Claude Code takes care of the rest.</p><h3><strong>The Bottom Line</strong></h3><p>Claude Code is one of those tools that sounds almost too good to be true — until you actually use it.You talk to it like a person. It reads your code, fixes what’s broken, builds what you need, and checks with you before every step. Whether you’ve been coding for 10 years or 10 days, it makes the whole process faster, less stressful, and honestly… a lot more fun.</p><p>If you spend any part of your day writing, debugging, or even just thinking about code — Claude Code is worth trying.</p><p><em>Try it yourself → claude.ai · Full docs → docs.claude.com</em></p><p><em>Tags: #ClaudeCode #AI #Coding #Programming #Anthropic #LearnToCode #ArtificialIntelligence</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fb52c1e2d2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain Simplified: Turning LLMs into Real Apps]]></title>
            <link>https://medium.com/@sahilarora240792/langchain-simplified-turning-llms-into-real-apps-cdf01e5f9780?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdf01e5f9780</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 06:22:25 GMT</pubDate>
            <atom:updated>2026-01-03T06:22:25.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>From NLP to GenAI: Enter LangChain (Part 1)</h3><p>Over the past few weeks, we’ve explored the core foundations of NLP from <strong>Word2Vec</strong>, <strong>RNNs</strong>, and <strong>LSTMs</strong>, all the way to <strong>transformers</strong>. These building blocks laid the groundwork for modern <strong>Generative AI (GenAI) </strong>the technology powering today’s intelligent chatbots, virtual assistants, summarizers, and copilots.</p><p>As we wrap up this series on NLP and GenAI fundamentals, it’s time to explore a tool that helps <strong>bridge the gap between raw language models and real-world applications </strong>say hello to <strong>LangChain</strong>.</p><h3>What is LangChain?</h3><p><strong>LangChain</strong> is an open-source framework designed to help developers build applications using <strong>language models</strong> like GPT, Claude, and other LLMs. Imagine you’ve learned how to use a large language model via an API like OpenAI. But now you want to build something bigger:</p><ul><li>A chatbot that can answer questions based on your company docs</li><li>An app that summarizes articles and sends them via email</li><li>A code assistant that uses tools and remembers previous steps</li></ul><p>To build this, you need more than just calling the model. You need tools to handle:</p><ul><li>Inputs and outputs</li><li>Memory (to remember past conversations)</li><li>Logic (to use tools or conditionally take steps)</li><li>External data (search, databases, vector stores)</li><li>Deployment (making it available as a REST API)</li></ul><p>LangChain gives you <strong>everything you need to build full GenAI workflows</strong> on top of LLMs all in a clean, modular way.</p><h3>LangChain Core Components:</h3><p>LangChain helps you build advanced applications using <strong>LLMs</strong> by giving you reusable, composable building blocks. These blocks are called <strong>components</strong>.</p><h3>1. Chains</h3><h4>What it is:</h4><p>A <strong>Chain</strong> is a sequence of steps where each step can be a prompt, a model call, a function, or another chain.</p><blockquote>Think of it like a pipeline: input → processing → output</blockquote><h4>Use Case Example:</h4><p>Let’s say you want to summarize a document and then translate the summary into French.</p><p>You can build a <strong>chain</strong> like:</p><p><em>Input Text → [LLM: Summarize it] → [LLM: Translate to French] → Output</em></p><h3>2. Agents</h3><h3>What it is:</h3><p>Agents are <strong>smart decision-makers</strong>. Instead of hardcoding steps, agents <strong>decide which tools to use</strong> at runtime based on user input.</p><blockquote>The LLM plays the role of the “brain” and selects tools like search, calculator, or database.</blockquote><h3>Use Case Example:</h3><p>Imagine a chatbot that can:</p><ul><li>Answer math questions using a calculator</li><li>Search current events using a web search tool</li><li>Tell the weather using a weather API</li></ul><p>The <strong>agent</strong> chooses the right tool based on your question.</p><h3>3. Tools</h3><h3>What it is:</h3><p>Tools are <strong>functions or external APIs</strong> your LLM can call. LangChain wraps them so the agent can use them when needed.</p><blockquote>Think of them as “superpowers” for your LLM.</blockquote><h3>Common Examples:</h3><ul><li>Google Search tool</li><li>Calculator tool</li><li>SQL Database tool</li><li>File reader tool (PDF, CSV)</li></ul><h3>4. Memory</h3><h4>What it is:</h4><p>Memory allows your app to <strong>remember past interactions</strong> — making your chatbot or assistant <strong>stateful</strong>.</p><blockquote>Without memory, every prompt is treated like a brand-new conversation.</blockquote><h4>Use Case Example:</h4><p>User: “Who is Elon Musk?”<br> Bot: “Elon Musk is the CEO of Tesla and SpaceX.”<br> User: “Where does he live?”<br> Bot (with memory): “Elon Musk lives in Texas.”</p><h4>Types of Memory:</h4><ul><li>ConversationBufferMemory: Stores the whole chat history</li><li>SummaryMemory: Keeps a summarized version of past chats</li><li>VectorStoreMemory: Stores past conversations as vectors for retrieval</li></ul><h3>5. Retrieval</h3><h4>What it is:</h4><p>Retrieval lets you <strong>connect your LLM to your own data</strong> — like PDF files, websites, databases, or vector stores.</p><blockquote>It enables RAG (Retrieval-Augmented Generation) — combining model knowledge with external documents.</blockquote><h4>Use Case Example:</h4><p>You upload your company’s policy PDFs. Now your chatbot can answer:<br> <strong>“What’s our maternity leave policy?”</strong></p><h4>Tools used:</h4><ul><li>FAISS / Chroma / Weaviate (vector stores)</li><li>Loaders (PDF, CSV, HTML)</li><li>Retrievers</li></ul><h3>LangChain Ecosystem:</h3><p>As your app grows, you’ll need more than just components. That’s why the <strong>LangChain ecosystem</strong> includes <strong>supporting tools</strong> for debugging, deployment, and production use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*FhAsyuMhrcZBE5of.png" /><figcaption>LangChain Ecosystem</figcaption></figure><h3>1. LangSmith</h3><blockquote>Think of it as your <strong>debugger, logger, and evaluator</strong> for GenAI apps.</blockquote><p>It helps you:</p><ul><li>Trace every prompt and response step-by-step</li><li>Monitor latency, model output, and errors</li><li>Evaluate performance (automated or human)</li></ul><p><strong>Example</strong>: <br> You want to test if prompt A performs better than prompt B — LangSmith lets you run both and compare the results.</p><h3>2. LangServe</h3><blockquote>Helps you <strong>deploy your LangChain app as an API</strong> using FastAPI.</blockquote><p>You can:</p><ul><li>Deploy your LangChain logic as an API</li><li>Call it from a web app, mobile app, or another backend</li><li>Share it with others via endpoints</li></ul><p>With one command (lc-serve deploy), your LangChain logic becomes a running backend API — perfect for frontend apps or other systems to call.</p><p><strong>Example</strong>: You created a LangChain chain for summarizing news articles. Using LangServe, you expose it at <a href="http://localhost:8000/invoke.">http://localhost:8000/invoke</a></p><h3>3. LangGraph — Build Multi-Step Workflows with Control</h3><blockquote>LangGraph lets you build “state machine”-like workflows with LLMs.</blockquote><p>LangGraph is useful when:</p><ul><li>You need <strong>loops</strong>, <strong>branches</strong>, or <strong>complex flows</strong></li><li>You want <strong>control</strong> over how steps connect</li><li>You’re building something <strong>bigger than a chain</strong> or agent</li></ul><p><strong>Example use case</strong>:<br> A customer support bot checks issue type → gathers details → escalates or resolves → loops if needed.</p><p>It uses a <strong>graph of nodes</strong> (each node can be a chain/tool/model), and <strong>edges</strong> that define transitions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0enO0xAtoVyJucMghFQQsg.png" /></figure><h3>Why This Ecosystem Matters</h3><p>The LangChain ecosystem allows you to go <strong>beyond simple prompts</strong>. You can now build apps that:</p><ul><li>Connect to your data</li><li>Use logic and flow</li><li>Call tools and APIs</li><li>Remember user input</li><li>Run reliably in production</li><li>Scale and evolve over time</li></ul><p>Whether you’re a solo dev building a side project or an enterprise deploying AI at scale, the LangChain ecosystem covers your full app lifecycle:<br> <strong>Build → Debug → Evaluate → Deploy → Scale</strong></p><p>With this blog, you’ve taken your first step into the LangChain world understanding its core components like Chains, Agents, Tools, Memory, and how they all come together to create powerful GenAI applications. You also got a glimpse into the broader LangChain ecosystem with tools like <strong>LangSmith</strong>, <strong>LangServe</strong>, and <strong>LangGraph</strong>, which help take your ideas from prototype to production.</p><p>But this is just the beginning.</p><p>In <strong>Part 2</strong>, we’ll dive deeper into:</p><ul><li>How to build your <strong>first LangChain app</strong></li><li>Code examples for chaining, memory, and retrieval</li><li>Using LangSmith for debugging and LangServe for deployment</li><li>And how to architect workflows with LangGraph</li></ul><p><em>If you liked this post, </em><strong><em>don’t forget to like, share, and clap 👏👏👏</em></strong><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdf01e5f9780" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Documents, Vector Stores, and Retrievers in LangChain]]></title>
            <link>https://medium.com/@sahilarora240792/understanding-documents-vector-stores-and-retrievers-in-langchain-6141c7749f75?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/6141c7749f75</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[document]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 06:22:26 GMT</pubDate>
            <atom:updated>2026-01-02T06:22:26.323Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve started exploring LangChain for building RAG (Retrieval-Augmented Generation) applications, you’ll quickly come across three important concepts: <strong>Document</strong>, <strong>Vector Store</strong>, and <strong>Retriever</strong>.</p><p>They might look similar, but each plays a distinct role in the pipeline. Let’s break it down with examples and show how they connect together.</p><h3>1. Document:</h3><p>A <strong>Document</strong> is just a wrapper around text with optional metadata. Think of it as a <strong>unit of knowledge</strong> that you can store, retrieve, and pass to an LLM.<br><strong>Structure</strong>:</p><pre>{<br>    &quot;page_content&quot;: &quot;The Eiffel Tower is in Paris.&quot;,<br>    &quot;metadata&quot;: {&quot;source&quot;: &quot;wiki&quot;, &quot;id&quot;: 123}<br>}</pre><ul><li>page_content → The actual text chunk.</li><li>metadata → Extra info (source, author, page number, etc.).</li></ul><p><strong>Example:</strong></p><pre>from langchain_core.documents import Document<br>doc = Document(<br>    page_content=&quot;LangChain is a framework for developing applications powered by language models.&quot;,<br>    metadata={&quot;source&quot;: &quot;blog&quot;, &quot;author&quot;: &quot;LangChain Team&quot;}<br>)<br>print(doc.page_content)   # The text<br>print(doc.metadata)       # Extra info</pre><p>➡ <strong>Document = container for text + metadata</strong></p><h3>2. Vector Store</h3><p>A <strong>Vector Store</strong> is a database for storing and searching Documents based on <strong>embeddings</strong> (numeric vectors representing meaning).<br><strong>How it works</strong></p><ol><li>Each document → converted into an embedding vector.</li><li>Stored in the vector database (e.g., FAISS, Pinecone, Weaviate, Chroma).</li><li>Queries → also embedded → compared to stored vectors using similarity measures.</li></ol><p><strong>Example</strong></p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores import FAISS<br>from langchain_core.documents import Document<br># Create some documents<br>docs = [<br>    Document(page_content=&quot;The Eiffel Tower is in Paris.&quot;, metadata={&quot;city&quot;: &quot;Paris&quot;}),<br>    Document(page_content=&quot;The Statue of Liberty is in New York.&quot;, metadata={&quot;city&quot;: &quot;New York&quot;}),<br>]<br># Convert docs to vectors &amp; store<br>embeddings = OpenAIEmbeddings()<br>vectorstore = FAISS.from_documents(docs, embeddings)<br># Search<br>results = vectorstore.similarity_search(&quot;Where is the Eiffel Tower?&quot;, k=1)<br>print(results[0].page_content)  # → &quot;The Eiffel Tower is in Paris.&quot;</pre><p>➡<strong>Vector Store = database that stores documents as vectors and supports semantic search</strong></p><h3>3. Retriever:</h3><p>A <strong>Retriever</strong> is an interface for fetching relevant documents.</p><ul><li>Input → query string</li><li>Output → list of Documents</li></ul><p>It usually <strong>sits on top of a vector store</strong>, but could also fetch from SQL, APIs, or hybrid systems.</p><p><strong>Why separate from Vector Store? </strong>Because you might want different retrieval strategies:</p><ul><li>Similarity search</li><li>Keyword search</li><li>Hybrid search</li><li>Max Marginal Relevance (MMR)</li><li>BM25</li></ul><p>The retriever abstracts <em>how</em> documents are chosen.<br><strong>Example</strong></p><pre># Turn vector store into retriever<br>retriever = vectorstore.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 1})<br># Run retriever<br>results = retriever.invoke(&quot;What city has the Eiffel Tower?&quot;)<br>print(results[0].page_content)  # → &quot;The Eiffel Tower is in Paris.&quot;</pre><p>➡<strong>Retriever = query interface that fetches documents (often backed by a vector store)</strong></p><h3>4. How They Fit Together: Think of the pipeline like this:</h3><pre>Document → (stored in) → Vector Store → (queried via) → Retriever → (returned to) → LLM</pre><ul><li><strong>Document</strong> = raw knowledge chunks</li><li><strong>Vector Store</strong> = storage &amp; search engine</li><li><strong>Retriever</strong> = the API to fetch relevant docs</li><li><strong>LLM</strong> = uses the retrieved context to answer questions</li></ul><h3>5. Full Mini Example</h3><pre>from langchain_core.documents import Document<br>from langchain_openai import OpenAIEmbeddings, ChatOpenAI<br>from langchain_community.vectorstores import FAISS<br># Step 1: Create Documents<br>docs = [<br>    Document(page_content=&quot;The Eiffel Tower is in Paris.&quot;, metadata={&quot;city&quot;: &quot;Paris&quot;}),<br>    Document(page_content=&quot;The Statue of Liberty is in New York.&quot;, metadata={&quot;city&quot;: &quot;New York&quot;}),<br>]<br># Step 2: Store in Vector Store<br>embeddings = OpenAIEmbeddings()<br>vectorstore = FAISS.from_documents(docs, embeddings)<br># Step 3: Create Retriever<br>retriever = vectorstore.as_retriever()<br># Step 4: Retrieve relevant documents<br>query = &quot;Where is the Eiffel Tower?&quot;<br>retrieved_docs = retriever.invoke(query)<br>print(&quot;Retrieved Document:&quot;, retrieved_docs[0].page_content)</pre><p><strong>Output:</strong></p><pre>Retrieved Document: The Eiffel Tower is in Paris.</pre><h3>6. Why Retriever is a Runnable but Document is not</h3><p>LangChain 0.2+ introduces the <strong>Runnable interface</strong>:</p><ul><li>.invoke() → run once</li><li>.batch() → run on multiple inputs</li><li>.stream() → stream outputs</li><li><strong>Retriever</strong> implements Runnable → you can plug it into chains, batch it, or stream results.</li><li><strong>Document</strong> is just a data object (text + metadata). It doesn’t have .invoke() → so it <strong>can’t</strong> be used as a retriever.</li></ul><p>Example:</p><pre># retriever is a Runnable<br>docs = retriever.invoke(&quot;Tell me about Paris&quot;)</pre><pre># document is NOT a Runnable<br># doc.invoke(&quot;query&quot;)  # will throw an error</pre><p>➡That’s why in a RAG chain, you <strong>compose retrievers, not documents</strong>.</p><h3>🎯 Final Summary</h3><ul><li><strong>Document</strong> → Small unit of knowledge (text + metadata).</li><li><strong>Vector Store</strong> → Stores documents as embeddings &amp; supports similarity search.</li><li><strong>Retriever</strong> → Runnable interface that fetches documents for a query (often backed by a vector store).</li></ul><p>Together, they form the foundation of RAG in LangChain 🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6141c7749f75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing (NLP) Part 6: Understanding LSTMs (Long Short-Term Memory Networks)]]></title>
            <link>https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-6-understanding-lstms-long-short-term-memory-networks-5bbcf843df5c?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bbcf843df5c</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[lstm]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 06:22:24 GMT</pubDate>
            <atom:updated>2026-01-01T06:22:24.985Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous part, we explored <strong>Recurrent Neural Networks (RNNs)</strong> and understood how they handle sequential data using hidden states and feedback connections. While RNNs allow networks to “remember” past information, we also uncovered their major weakness: <strong>vanishing gradients</strong>, which makes it hard to capture long-term dependencies.</p><p>This is where <strong>LSTMs (Long Short-Term Memory networks)</strong> come in — a special type of RNN designed to remember information for longer periods and solve the memory problem.</p><h3>Why LSTMs? (The Limitation of RNNs)</h3><p>Recall that in a basic RNN:</p><ul><li>The hidden state at time <em>t</em> depends on the current input (<em>xₜ</em>) and the hidden state from the previous step (<em>hₜ₋₁</em>).</li><li>During training, Back propagation<strong> Through Time (BPTT)</strong> computes gradients over multiple time steps.</li><li>Because of repeated multiplications in the chain rule, gradients tend to either shrink towards zero (<strong>vanishing gradient</strong>) or grow uncontrollably large (<strong>exploding gradient</strong>).</li></ul><p>➡️ <strong>Result:</strong> RNNs are good at remembering short-term dependencies, but struggle with <strong>long-term context</strong> (e.g., predicting “shepherd” based on “brown dog” many words earlier).</p><p>To overcome this, Hochreiter &amp; Schmidhuber (1997) introduced the <strong>LSTM architecture</strong>, specifically designed to <strong>control the flow of information</strong> with <strong>gates</strong>.</p><h3>The LSTM Architecture</h3><p>At the heart of an LSTM is a <strong>memory cell</strong> that acts as a conveyor belt for long-term information. Instead of allowing information to vanish quickly, the cell state is carefully updated through <strong>three gates</strong> and a <strong>candidate memory</strong>.</p><p><strong>Components of an LSTM unit:</strong></p><ol><li><strong>Cell State (Cₜ):</strong> Long-term memory that flows through the sequence.</li><li><strong>Hidden State (hₜ):</strong> Short-term memory and output at each time step.</li><li><strong>Gates:</strong> Neural network layers that control what to keep, add, or remove.</li></ol><p>The three gates are:</p><ul><li><strong>Forget Gate:</strong> Decides what information to erase from the cell state.</li><li><strong>Input Gate + Candidate Memory:</strong> Decides what new information to store.</li><li><strong>Output Gate:</strong> Decides what part of the cell state to reveal as output.</li></ul><p>Each gate uses a <strong>sigmoid activation</strong> (values between 0 and 1) to create a selector vector, while the candidate memory uses <strong>tanh</strong> (values between -1 and 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xct0iam4AgUzqQ7rqT601Q.png" /><figcaption>Figure 1: LSTM Architecture</figcaption></figure><h3>Step-by-Step Flow of Information</h3><p>At each time step <em>t</em>, the LSTM takes as input:</p><ul><li>Current input vector <strong>xₜ</strong></li><li>Previous hidden state <strong>hₜ₋₁</strong></li><li>Previous cell state <strong>Cₜ₋₁</strong></li></ul><p>It outputs:</p><ul><li>Updated hidden state <strong>hₜ</strong> (short-term memory + external output)</li><li>Updated cell state <strong>Cₜ</strong> (long-term memory)</li></ul><p>Let’s break this down gate by gate.</p><h3>1. Forget Gate</h3><p>The <strong>forget gate</strong> decides what fraction of the previous cell state should be kept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fENlU7PMOE3Ng_Wa6F8P5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ug4fUI79NGVwcvazaXuVaA.png" /><figcaption>Figure 2: Forget Gate</figcaption></figure><h3>2. Input Gate + Candidate Memory</h3><p>Next, we decide what <strong>new information</strong> to add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7msfDsKf2oQw6mt43zsEg.png" /></figure><p>Here iₜ​ decides <strong>which candidate values to keep</strong>, and they get added to the updated cell state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5sy_r55Tq7Pq_nA7xpSDQ.png" /></figure><h3>3. Output Gate</h3><p>Now we compute the hidden state hthₜht​, which is also the <strong>output</strong> of the LSTM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*0yO7-458WOAaj-HDdZAZIw.png" /></figure><p>So the hidden state is essentially a <strong>filtered version of the cell state</strong>, controlled by the output gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrnh3J_kJgmTYAQTxlDJbg.png" /></figure><h3>Putting It All Together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3OsMQw2qek_EXzEW-vjdw.png" /></figure><h3>Why LSTMs Solve the Vanishing Gradient Problem</h3><ul><li>In RNNs, gradients shrink because they are multiplied repeatedly through non-linearities over many steps.</li><li>In LSTMs, the <strong>cell state ©</strong> acts like a highway for gradients, with <strong>controlled updates</strong> via gates.</li><li>The forget gate ensures irrelevant info is removed, while useful info persists over time.</li><li>During backpropagation, the gradient flows more smoothly through CtCₜCt​, reducing the risk of vanishing.</li></ul><p>➡️ <strong>Result:</strong> LSTMs can remember dependencies across <strong>dozens or even hundreds of time steps</strong>.</p><h3>Applications of LSTMs</h3><p>LSTMs are widely used in tasks where <strong>long-term dependencies</strong> matter:</p><p><strong>Natural Language Processing:</strong></p><ul><li>Machine Translation (English → French)</li><li>Sentiment Analysis</li><li>Named Entity Recognition (NER)</li><li><strong>Speech Recognition</strong></li><li><strong>Music &amp; Text Generation</strong></li><li><strong>Time-Series Forecasting</strong> (stock prices, weather)</li></ul><h3>Conclusion</h3><p>Recurrent Neural Networks introduced the concept of memory into neural networks, but their limitations (vanishing and exploding gradients) restricted them to short-term dependencies. LSTMs overcame these limitations with their gating mechanism, enabling networks to model complex long-range patterns in data such as text, speech, and time series.</p><p>🚀 In the <strong>next lecture</strong>, we’ll start our journey into <strong>Generative AI and LangChain</strong> — connecting everything we’ve learned so far to real-world AI applications.</p><p>👉 Don’t forget to <strong>share</strong> this post and <strong>clap</strong> if you found it helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bbcf843df5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Features in Machine Learning: A Key Prerequisite Before You Begin]]></title>
            <link>https://medium.com/@sahilarora240792/understanding-features-in-machine-learning-a-key-prerequisite-before-you-begin-104ac90f6d0c?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/104ac90f6d0c</guid>
            <category><![CDATA[semi-supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 05:00:07 GMT</pubDate>
            <atom:updated>2025-10-01T05:00:07.665Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to this module on <strong>Machine Learning Prerequisites</strong>. Before diving into core machine learning topics like <strong>classification</strong>, <strong>regression</strong>, <strong>time series analysis</strong>, <strong>clustering</strong>, or <strong>association rule learning</strong>, it’s crucial to understand a few foundational concepts. One of the most fundamental — and often misunderstood — is the concept of <strong>features</strong>.</p><h3>Why Prerequisites Matter in ML</h3><p>Machine learning (ML) is a part of the broader field of <strong>data science</strong> and <strong>artificial intelligence (AI)</strong>. At its core, ML is about <strong>predictive analytics</strong> — using past data to make future predictions. Before you even train your first model, you need to get comfortable with some key concepts like:</p><ul><li><strong>Supervised vs. Unsupervised learning</strong></li><li><strong>Features and target variables (X and y)</strong></li><li><strong>Types of data and how it’s represented</strong></li></ul><p>Let’s zoom into one of the most used terms in ML: <strong>features</strong>.</p><h3>What Are Features?</h3><p>In the world of machine learning, <strong>features</strong> are the input variables used to make predictions. These are the <strong>columns in your dataset</strong> that contain information about each observation.</p><p>Imagine you’re analyzing customer data. Your dataset might look like this:</p><p>Customer ID, Age, Gender, Salary, Internet, Churn<br>1001, 28, Male, 55000, High, Yes<br>1002, 45, Female, 82000, Low, No</p><p>In this example:</p><ul><li><strong>Features (X variables)</strong>: Age, Gender, Salary, Internet Usage</li><li><strong>Target (y variable)</strong>: Churn (Yes/No)</li></ul><p>Features are also known as:</p><ul><li><strong>Independent variables</strong></li><li><strong>Predictors</strong></li><li><strong>X variables</strong></li></ul><p>The <strong>target variable</strong> (like Churn here) is what you&#39;re trying to predict — also called the:</p><ul><li><strong>Dependent variable</strong></li><li><strong>Response variable</strong></li><li><strong>Y variable</strong></li></ul><h3>Example: Customer Churn Prediction</h3><p>Let’s say you’ve just joined <strong>Vodafone</strong> as a <strong>data scientist</strong>. One of your first tasks is to solve a common business problem: <strong>customer churn</strong>.</p><h3>The Problem</h3><p>Vodafone has observed that about <strong>25% of their customers are churning</strong> — i.e., leaving their services and switching to competitors like Jio or Airtel. Your task? Build a model to <strong>predict which customers are likely to churn</strong>.</p><h3>The Data</h3><p>The customer dataset includes:</p><ul><li>Age</li><li>Gender</li><li>Salary</li><li>Call usage</li><li>Internet usage</li><li>Location</li><li>Churn status (whether the customer has exited)</li></ul><p>Now, ask yourself:</p><ul><li>What am I trying to predict? → <strong>Churn status</strong></li><li>What data do I use to make the prediction? → <strong>All other columns</strong></li></ul><p>This means:</p><ul><li><strong>Churn</strong> = Y variable (target/dependent)</li><li><strong>All others</strong> = X variables (features/independent)</li></ul><p>So, features are everything <strong>you use to make the prediction</strong>, while the target is <strong>what you’re predicting</strong>.</p><h3>Another Example: Temperature Forecasting</h3><p>Imagine you’re working on predicting future temperatures based on past weather data.</p><p>Date, Precipitation, Rainfall, Temperature<br>Jan 10, 0.2, 10mm, 32°C<br>Jan 20, 0.1, 8mm, 31°C<br>Jan 30, 0.0, 0mm, 30°C</p><p>Here:</p><ul><li>You want to <strong>predict temperature</strong> → That’s your <strong>y variable</strong></li><li>You use date, precipitation, and rainfall as <strong>features (x variables)</strong></li></ul><p>This is another example of using <strong>independent variables (features)</strong> to predict a <strong>dependent variable</strong> (target).</p><h3>Conclusion</h3><p>Features are <strong>the building blocks of machine learning models</strong>. Without properly understanding what features are, it’s difficult to make sense of how models are built and how they make predictions.</p><p>Whether you’re predicting <strong>customer churn</strong>, <strong>stock prices</strong>, <strong>temperature</strong>, or <strong>house prices</strong>, identifying and working with the right features is critical to your model’s success.</p><p><strong>Up Next:</strong> In the next post, we’ll cover another important prerequisite that sets the foundation for machine learning success. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=104ac90f6d0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Different Types of Machine Learning: A Beginner’s Guide]]></title>
            <link>https://medium.com/@sahilarora240792/understanding-the-different-types-of-machine-learning-a-beginners-guide-c8205dfc90b4?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8205dfc90b4</guid>
            <category><![CDATA[semi-supervised-learning]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 04:58:31 GMT</pubDate>
            <atom:updated>2025-10-01T04:58:31.896Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Machine Learning (ML)</strong> is a subset of Artificial Intelligence (AI) that enables machines to automatically learn from data, improve from experience, and make predictions without being explicitly programmed for every scenario.</p><p>At its core, ML uses a set of algorithms that work on huge amounts of data historical or real-time. Data is fed to these algorithms so they can <strong>learn patterns, build models, and perform specific tasks</strong>. This ability is used to solve business problems like <strong>regression, classification, and forecasting</strong>, depending on the algorithm and approach.</p><p>But how are machine learning problems categorized? Let’s break it down.</p><h3>Types of Machine Learning</h3><p><strong>Machine Learning is typically divided into three main categories:</strong></p><ol><li><strong>Supervised Learning</strong></li><li><strong>Unsupervised Learning</strong></li><li><strong>Reinforcement Learning</strong></li></ol><p>Some sources mention a fourth type:<br> 4. <strong>Semi-Supervised Learning</strong> (a blend of supervised and unsupervised).</p><p>Let’s understand each type, with practical examples.</p><h3>1. Supervised Learning</h3><p>Supervised learning uses <strong>labeled data</strong> to train models. That means the input data is already tagged with the correct output. The goal is to learn a mapping from inputs to outputs so the model can make predictions on new, unseen data.</p><h4>What does “labeled data” mean?</h4><p>Suppose you have a dataset of <strong>10,000 financial transactions</strong>:</p><ul><li>9,000 are NOT fraudulent</li><li>1,000 are fraudulent</li></ul><p>You split the data into training and testing sets — say, 8,000 for training and 2,000 for testing.</p><ul><li>During training, the model <em>knows</em> which transactions are fraud and which are not.</li><li>During testing, you <strong>don’t</strong> provide the answer column (label) to the model — you just provide the transaction details.</li><li>The model predicts which are fraud/not fraud. You then compare predictions against the actual labels (that you kept hidden) to evaluate performance.</li></ul><p>This is supervised learning: <strong>the model learns from labeled data and is evaluated on its ability to predict labels for new, unseen data</strong>.</p><h4>Types of Supervised Learning</h4><p><strong>A. Classification</strong></p><p>Classification algorithms predict categories, like:</p><ul><li>Fraud vs. Not Fraud</li><li>Churned vs. Not Churned (will a customer leave?)</li><li>Disease vs. No Disease</li><li>Spam vs. Not Spam</li></ul><p><strong>Common Classification Algorithms:</strong></p><ul><li>K-Nearest Neighbors (KNN)</li><li>Decision Trees</li><li>Random Forest</li><li>Logistic Regression</li><li>Naive Bayes</li><li>XGBoost, CatBoost, AdaBoost, and more</li></ul><p><strong>B. Regression</strong></p><p>Regression is used when the output is a <strong>continuous value</strong> (not a category).</p><p>Examples:</p><ul><li>Predicting house prices based on area</li><li>Forecasting rainfall or temperature</li><li>Estimating a person’s weight from their height</li></ul><p><strong>How does regression work?</strong><br> Let’s say you have data on house area (in sq ft) and price:</p><ul><li>500 sq ft → 2 million</li><li>1,000 sq ft → 4 million</li><li>600 sq ft → 3 million</li></ul><p>You plot the data and fit a line that best describes the relationship.<br> If someone asks the price for 200 sq ft, you look up the value on your line — maybe ~1.5 million.</p><p><strong>Regression</strong> predicts continuous values, like weight from height, or sales from advertising spend.</p><p><strong>C. Time Series Forecasting</strong></p><p>Forecasting is an extension of regression, but with a key difference: <strong>time</strong> is the most important feature.</p><ul><li>Example: Predicting next month’s sales or temperature, given a series of past values.</li></ul><p>If your dataset includes dates and you want to predict future values based on time, that’s a <strong>time series forecasting problem</strong>.</p><h4>Advantages of Supervised Learning</h4><ul><li><strong>Works with labeled data </strong>you know exactly what you’re trying to predict</li><li><strong>Can use prior experience</strong> learns from historical data to predict future cases</li><li><strong>Great for classification and regression tasks</strong></li></ul><h4>Drawbacks</h4><ul><li>If your dataset is imbalanced (e.g., only a few frauds, mostly non-frauds), the model may not learn the minority class well</li><li>Requires lots of computational power and memory for big datasets</li><li>Model performance drops if test data is very different from training data eg: If your fraud detection training set has 7900 non-fraud and only 100 fraud examples, the model might fail to recognize fraud properly.</li></ul><h3>2. Unsupervised Learning</h3><p><strong>Unsupervised learning</strong> works with <strong>unlabeled data</strong> — there’s no “answer column.”</p><p>Imagine you have <strong>10,000 transactions</strong> but don’t know which are fraud or not.<br> You can’t directly train a model to predict fraud, because you don’t know the correct answer.</p><p><strong>What can you do?</strong></p><ul><li>Use domain expertise to manually label some data (then use supervised learning)</li><li>Or, use <strong>unsupervised learning techniques</strong> to find hidden patterns (e.g., clusters of similar transactions)</li></ul><p><strong>Classic Examples:</strong></p><ul><li>Customer segmentation: Find groups of customers who behave similarly</li><li>News grouping: Organize articles by topic, even if you don’t know what the topics are beforehand</li><li>Fraud detection (when you don’t know what fraud looks like, but want to find outliers)</li></ul><p><strong>Popular Unsupervised Algorithms:</strong></p><ul><li>K-Means Clustering</li><li>DBSCAN</li><li>Hierarchical Clustering (Agglomerative)</li><li>PCA, LDA (for dimensionality reduction)</li></ul><h3>3. Reinforcement Learning</h3><p><strong>Reinforcement learning</strong> is all about <strong>learning by feedback</strong>.</p><ul><li>Think of a chatbot that gets better at answering questions the more you talk to it.</li><li>Or a self-driving car learning to navigate by trial and error, improving after each attempt.</li></ul><p>In RL, an agent interacts with an environment, gets feedback (“reward” or “penalty”), and adjusts its actions to maximize rewards.</p><ul><li><strong>Use Cases:</strong> Robotics, game AI, advanced chatbots</li></ul><blockquote>RL is like learning by trial and error. It continuously improves based on rewards from its past actions.</blockquote><h3>4. Semi-Supervised Learning</h3><p>As the name suggests, semi-supervised learning combines <strong>a small amount of labeled data with a large amount of unlabeled data</strong>. It is useful when labeling is expensive or time-consuming.</p><h3>Example:</h3><p>If you have 10,000 transactions but only 1,000 are labeled, you can:</p><ul><li>You use the labeled data to train a model (supervised)</li><li>Use the model to label some of the unlabeled data (pseudo-labeling)</li><li>Retrain the model on the expanded dataset</li></ul><p>This approach is common when labeling data is expensive or time-consuming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sk7RiWp2QfCnRhk6kt_bYA.png" /></figure><p>In the upcoming blogs, we’ll dive deeper into supervised learning — starting with classification models and their applications.</p><p><em>Found this helpful? Leave a comment or share your thoughts!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8205dfc90b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing (NLP) Part 5:Understanding RNNs (Recurrent Neural Networks)]]></title>
            <link>https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-5-understanding-rnns-recurrent-neural-networks-6a3d671968bf?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a3d671968bf</guid>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 19:27:08 GMT</pubDate>
            <atom:updated>2025-08-08T19:27:08.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hHhXZ3tfRTztfVIk.png" /></figure><p>Before we dive in, <strong>make sure you’ve followed </strong><a href="https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-4-how-neural-networks-actually-learn-6f4e5a34032a"><strong>Part 4</strong></a> of this series, where we uncovered how neural networks learn using weights, biases, gradients, and backpropagation. That foundation is essential as we now move into models designed to handle sequences and time-based data.</p><h3>First, Let’s Recap What We’ve Learned So Far:</h3><p>In traditional neural networks like ANNs, the model takes an input, processes it, and produces an output — all in a single step, with <strong>no memory of what came before</strong>. This setup works great for static tasks like image classification or predicting a single value.</p><p>But what if <strong>order matters</strong>?</p><p>What if you’re working with data that unfolds over time, such as:</p><ul><li>Predicting the next word in a sentence</li><li>Understanding the full meaning of a sentence</li><li>Forecasting tomorrow’s temperature based on past weather</li><li>Analyzing user behavior over a browsing session</li></ul><p>For these kinds of problems, we need models that can <strong>remember</strong> what happened earlier — and that’s exactly what <strong>Recurrent Neural Networks (RNNs)</strong> were built for.</p><h3>What Makes RNNs Different?</h3><p>RNNs introduce a <strong>loop</strong> within the network, allowing it to <strong>pass information forward</strong> through time steps. This gives the network a sense of memory, enabling it to learn patterns that depend on previous inputs — perfect for sequences like text, music, or time series data.</p><p>In this part, we’ll explore:</p><ul><li>Why ANNs aren’t suited for sequential data</li><li>How RNNs handle ordered inputs</li><li>What’s happening at each time step inside an RNN</li><li>The limitations of basic RNNs (spoiler: memory doesn’t last forever)</li></ul><h3>What is an RNN?</h3><p>An <strong>RNN (Recurrent Neural Network)</strong> is a type of neural network that <strong>remembers past inputs</strong> and uses them to influence the current output. It’s like having a memory while solving a problem.</p><p>Think of it like this:</p><h3>Real-Life Analogy:</h3><p>Imagine you’re reading a storybook. To understand what’s happening on Page 5, you need to remember what happened on Page 4.<br> If you forgot everything before, Page 5 won’t make much sense. That’s how RNNs work they <strong>remember previous information</strong> (words, events, etc.) while processing the current step.</p><p><strong>How is RNN Different from ANN?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuU1v3bpzoN-ALuySmeO8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z6NyrWO9E8ByLD_F.png" /><figcaption>ANN architecture</figcaption></figure><p>In an ANN: input → hidden layer → output<br>In an RNN: input → hidden layer (with memory) → output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0VXE2sAzt_oa5J0D.png" /><figcaption>RNN architecture</figcaption></figure><blockquote><strong><em>Left</em></strong><em>: Shorthand notation often used for RNNs</em></blockquote><blockquote><strong><em>Right</em></strong><em>: Unfolded notation for RNNs</em></blockquote><p><em>Don’t worry if this doesn’t make sense, we’re going to break down all the variables and go through a forward propagation and backpropagation in a little bit! Just focus on the flow of variables at first glance.</em></p><h3>A breakdown of the architecture</h3><p>The green blocks are called <strong><em>hidden states</em></strong>. The blue circles, defined by the <strong>vector</strong> <strong><em>a</em></strong><em> </em>within each block, are called <strong><em>hidden nodes </em></strong><em>or</em><strong><em> hidden units</em></strong><em> </em>where the number of nodes is decided by the hyper-parameter <strong><em>d</em></strong><em>. </em>Similar to activations in MLPs, think of each green block as an activation function that acts on each blue node. <strong>We’ll talk about the calculations within the hidden states in the forward propagation section of this article.</strong></p><p><strong>Vector <em>h</em></strong><em> — </em>is the output of the hidden state after the activation function has been applied to the hidden nodes. As you can see at time <em>t,</em> the architecture takes into account what happened at <em>t-1</em> by including the <em>h </em>from the <em>previous</em> hidden state as well as the input <em>x</em> at time <em>t</em>. This allows the network to account for information from previous inputs that are sequentially behind the current input. It’s important to note that the zeroth <em>h </em>vector will always start as a vector of 0’s because the algorithm has no information preceding the first element in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*MlsNAMc80w-5uPYu.png" /></figure><p>The hidden state at t=2, takes as input the output from t-1 and x at t.</p><p><strong>Matrices <em>Wx, Wy, Wh</em></strong> — are the weights of the RNN architecture which are <em>shared</em> throughout the entire network. The model weights of <em>Wx</em> at <em>t=1</em> are the exact same as the weights of <em>Wx</em> at <em>t=2</em> and every other time step.</p><p><strong>Vector <em>xᵢ</em></strong><em> — </em>is the input to each hidden state where i=1, 2,…, n for each element in the input sequence. Recall that text must be encoded into numerical values. For example, every letter in the word “dogs” would be a one-hot encoded vector with dimension <em>(4x1). </em>Similarly, x can also be word embedding or other numerical representations.</p><p>One-Hot Encoding of the word “dogs”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2fdy_LcElgptv7o9.png" /></figure><p><strong>RNN Equations</strong></p><p>Now that we know what all the variables are, here are all the equations that we’re going to need in order to go through an RNN calculation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*opXIZElf0bwVymtT.png" /></figure><p>These are the only three equations that we need, pretty sweet! The<strong> hidden nodes </strong>are a concatenation of the previous state’s output weighted by the weight matrix <em>Wh</em> and the input <em>x</em> weighted by the weight matrix <em>Wx. </em>The <em>tanh</em> function is the <strong>activation function</strong> that we mentioned earlier, symbolized by the green block. The <strong>output of the hidden state</strong> is the activation function applied to the hidden nodes.<strong> </strong>To make a <strong>prediction</strong>, we take the output from the current hidden state and weight it by the weight matrix <em>Wy </em>with a soft max activation.</p><h3>A Trivial Example — Predicting the Last Letter in “dogs”</h3><p>Let’s walk through a concrete example to understand how an RNN works step-by-step.</p><h3>Goal:</h3><p>Train an RNN to predict the final letter <strong>“s”</strong> in the word <strong>“dogs”</strong>, given the input sequence:<br> &quot;d&quot; → &quot;o&quot; → &quot;g&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G80MXvGbD76Fg_qa.png" /></figure><p>We’ll simplify the problem so it’s easy to understand and trace:</p><ul><li>Vocabulary: {<strong>d</strong>, <strong>o</strong>, <strong>g</strong>, <strong>s</strong>}</li><li>Input encoding: Each letter is a <strong>one-hot vector</strong> of size 4</li><li>Hidden layer size (<strong>d</strong>) = 3</li><li>The RNN will use randomly initialized weight matrices:</li><li><strong>Wx</strong>: Input-to-hidden weights</li><li><strong>Wh</strong>: Hidden-to-hidden (recurrent) weights</li><li><strong>Wy</strong>: Hidden-to-output weights</li><li>Activation function: <strong>tanh</strong></li><li>Output: Softmax over the vocabulary</li></ul><h3>Forward Propagation</h3><p>Let’s see how a forward propagation would work at time <em>t=1. </em>First, we have to calculate the hidden nodes <strong><em>a</em></strong>, then apply the activation function to get <strong><em>h</em></strong>, and finally calculate the <strong>prediction</strong>. Easy!</p><p><strong>At t = 1</strong></p><ul><li><strong>Input</strong>: “d” (x₁)</li><li><strong>Previous hidden state</strong>: h₀ = [0, 0, 0] (since it’s the first time step)</li><li>Calculate <strong>hidden state h₁</strong> using:</li><li>h1=tanh(Wx⋅x1+Wh⋅h0)h₁ = tanh(Wx · x₁ + Wh · h₀) h1​=tanh(Wx⋅x1​+Wh⋅h0​)</li></ul><p>Generate output y₁:</p><ul><li>y1=softmax(Wy⋅h1)y₁ = softmax(Wy · h₁) y1​=softmax(Wy⋅h1​)</li><li>Output is a prediction over the next letter.<br> <strong>Expected target</strong>: “o”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZSGAjPXiFjUbaBr6.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1UDshYZfc86tWjWa.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VbEEU8rwozwGjBvF.png" /></figure><p>To make the example concrete, I’ve initialized random weights for the matrices <strong><em>Wx, Wy, </em></strong>and<em> </em><strong>Wh </strong>to provide an example with numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LzerdrOo9YkOccvi.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dc98Xauaxzx0hlch.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eUYoGbzhqsYFCEZS.png" /></figure><p>At t=2 and t=3, the workflow would be analogous except that the <em>vector h </em>from <em>t-1</em> would no longer be a vector of 0’s, but a vector of non-zeros based on the inputs before time <em>t. (As a reminder, the weight matrices Wx, Wh, and Wy remain the same for t=1,2, and 3.</em> )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAFR2cPM5Ua4nobKmbq4nQ.png" /></figure><h3>Backpropagation — How RNNs Learn</h3><p>Just like regular neural networks (like MLPs), RNNs <strong>learn by adjusting their weights</strong> to reduce prediction errors. But there’s a twist.</p><p>Since RNNs deal with <strong>sequences</strong>, the learning process must account for how <strong>errors accumulate over time</strong>. That’s where <strong>Backpropagation Through Time (BPTT)</strong> comes in.</p><h3>The Learning Workflow (High-Level Steps)</h3><p>Here’s a simplified step-by-step overview of how training works in an RNN:</p><ol><li><strong>Initialize Weights Randomly</strong></li></ol><ul><li>Input weights Wx</li><li>Recurrent weights Wh</li><li>Output weights Wy</li></ul><p>2. Forward Pass Through Time</p><ul><li>Process the input sequence step by step (e.g., letters in “dog”)</li><li>Compute hidden states h₁, h₂, h₃...</li><li>Compute predictions y₁, y₂, y₃... at each step</li></ul><p>3. Compute Loss</p><ul><li>Compare predicted output vs. actual target at each time step</li><li>Use a suitable loss function (like <strong>cross-entropy</strong>) to measure error</li></ul><p>4. Backpropagation Through Time</p><ul><li>Calculate how each weight contributed to the total error</li><li>Gradients are computed not just for the current time step, but also for how earlier steps influenced later predictions</li></ul><p>5. Update Weights</p><ul><li>Use gradient descent (or a variant) to update Wx, Wh, and Wy</li><li>Repeat the cycle for multiple epochs</li></ul><p><strong><em>Note:</em></strong><em> that the output h from the hidden unit is not learned, it is merely the information gained by concatenating the learned weights to previous output h and current input x.</em></p><p>Because this example is a classification problem where we’re trying to predict four possible letters (“d-o-g-s”), it makes sense to use the <strong>multi-class cross entropy loss function</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jyMngq-50RGpCFXY.png" /></figure><p>Taking into account all time steps, the <strong>overall loss is</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AudU82K8CPmEIq3W.png" /></figure><p>Visually, this can be seen as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lFpy7MCBHYkubMo5.png" /></figure><p>Given our loss function, we need to calculate the gradients for our three weight matrices <em>Wx, Wy, Wh, </em>and update them<em> </em>with a learning rate η. Similar to normal backpropagation, the gradient gives us a sense of how the loss is changing with respect to each weight parameter. We update the weights to minimize loss with the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XCW307SuktdmmnO-.png" /></figure><p>where i = x, y, and h as a shorthand for the 3 weight matrices</p><p>Now here comes the tricky part, calculating the gradient for <em>Wx, Wy, and Wh. </em>We’ll start by calculating the gradient for <em>Wy</em> because it’s the easiest. As stated before, the effect of the weights on loss spans over time. The weight gradient for <em>Wy </em>is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3irdXU5YjTjIe94J.png" /></figure><p>That’s the gradient calculation for <em>Wy</em>. Hopefully, pretty straight forward, <strong>the main idea is chain rule and to account for the loss at each time step.</strong></p><p>The weight matrices <em>Wx</em> and W<em>h </em>are analogous to each other, so we’ll just look at the gradient for <em>Wx</em> and leave <em>Wh</em> to you. One of the trickiest parts about calculating <em>Wx </em>is the recursive dependency on the previous state, as stated in line (2) in the image below. We need to account for the derivatives of the current error with respect to each of the previous states, which is done in (3). Finally, we again need to account for the loss at each time step (4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ewFIlic6GE0hItqv.png" /></figure><h3>One major problem: vanishing gradients</h3><p>A problem that RNNs face, which is also common in other deep neural nets, is the <strong>vanishing gradient problem</strong>. Vanishing gradients make it difficult for the model to learn long-term dependencies. For example, if an RNN was given this sentence:</p><p>Zoom image will be displayed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*450FRNE-P4_mG-Gn.png" /></figure><p>and had to predict the last two words “german” and “shepherd,” the RNN would need to take into account the inputs “brown”, “black”, and “dog,” which are the nouns and adjectives that describe a german shepherd. However, the word “brown” is quite far from the word “shepherd.” From the gradient calculation of <em>Wx</em> that we saw earlier, we can break down the backpropagation error of the word “shepherd” back to “brown” and see what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vrN_MP8c0cLPY9V1.png" /></figure><p>The partial derivative of the state corresponding to the input “shepherd” respective to the state “brown” is actually a chain rule in itself, resulting in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8LvrAa8ZK2jWHHz1.png" /></figure><p>That’s a lot of chain rule! These chains of gradients are troublesome because if less than 1 they can cause the loss from the word shepherd with respect to the word brown to approach 0, thereby <em>vanishing</em>. This makes it difficult for the weights to take into account words that occur at the start of a long sequence. So the word “brown” when doing a forward propagation, may not have any effect in the prediction of “shepherd” because the weights weren’t updated due to the vanishing gradient. This is one of the major disadvantages of RNNs.</p><h3>Types of RNN Architectures</h3><p>Recurrent Neural Networks (RNNs) can be categorized based on the <strong>number of inputs and outputs</strong> they handle. Different types of tasks require different RNN structures. Depending on whether you’re generating a sequence or classifying one, the structure will vary.</p><p>Let’s break down the <strong>five key types of RNNs</strong> and understand when to use each — with simple examples.</p><h3>1. One-to-One</h3><p><strong>(Single Input → Single Output)</strong></p><p>This is the classic architecture used in traditional feedforward neural networks — technically not a true RNN in the sequential sense, but still relevant when input and output are both fixed.</p><h4>Example:</h4><ul><li><strong>Image Classification</strong><br> Input: One image<br> Output: One label (e.g., “Cat”)</li></ul><h3>2. One-to-Many</h3><p><strong>(Single Input → Sequence Output)</strong></p><p>Here, a single input produces <strong>a sequence of outputs</strong>. This is useful when you want the model to generate a series of items based on one starting point.</p><h4>Example:</h4><ul><li><strong>Music Generation</strong><br> Input: A musical key or genre (e.g., “C major”)<br> Output: A sequence of notes (e.g., melody)</li><li><strong>Image Captioning</strong><br> Input: An image<br> Output: A sequence of words (caption)</li></ul><h3>3. Many-to-One</h3><p><strong>(Sequence Input → Single Output)</strong></p><p>In this structure, the model takes a sequence as input and returns a <strong>single output</strong>. It’s great for classification problems where the <strong>entire sequence needs to be understood</strong> before making a decision.</p><h4>Example:</h4><ul><li><strong>Sentiment Classification</strong><br> Input: A sentence or tweet<br> Output: Sentiment (Positive or Negative)</li><li><strong>Spam Detection</strong><br> Input: Email text<br> Output: Label (Spam / Not Spam)</li></ul><h3>4. Many-to-Many</h3><p><strong>(Sequence Input → Sequence Output, Equal Length)</strong></p><p>Here, each input step corresponds to one output step. This type of RNN is used when each input in a sequence maps to a specific output.</p><h4>Example:</h4><ul><li><strong>Named Entity Recognition (NER)</strong><br> Input: “Google is based in California.”<br> Output: [ORG, O, O, LOC]</li></ul><h3>5. Many-to-Many (Encoder–Decoder)</h3><p><strong>(Sequence Input → Sequence Output, Unequal Length)</strong></p><p>In this advanced variant, the input and output are both sequences, but their lengths may <strong>not be the same</strong>. This is where <strong>Encoder-Decoder</strong> models come into play — the encoder processes the input sequence into a fixed-size context vector, and the decoder generates the output sequence from that.</p><h4>Example:</h4><ul><li><strong>Machine Translation</strong><br> Input: “I love you” (English, 3 words)<br> Output: “Te amo” (Spanish, 2 words)</li></ul><p>Here, the model understands the meaning of the entire sentence before starting to translate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pK0Ohujrnp-qjO-u.png" /></figure><h3>Wrapping Up Part 5</h3><p>By now, you should have a clear understanding of <strong>why we need RNNs</strong> and how they enable neural networks to handle sequences by learning from the <strong>past</strong>. But RNNs also come with some serious limitations — like struggling to remember information over long sequences.</p><p>That’s where <strong>LSTM (Long Short-Term Memory)</strong> networks come in.</p><p>In the <strong>next part (Part 6)</strong>, we’ll explore how <strong>LSTMs solve the memory problem</strong> in RNNs giving models a more powerful and stable way to capture long-term dependencies in sequential data.</p><p><em>If you liked this post, </em><strong><em>don’t forget to like, share, and clap 👏👏👏</em></strong><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a3d671968bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing (NLP) Part 4: How Neural Networks Actually Learn]]></title>
            <link>https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-4-how-neural-networks-actually-learn-6f4e5a34032a?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f4e5a34032a</guid>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 14:32:53 GMT</pubDate>
            <atom:updated>2025-08-08T06:15:35.539Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back, fellow NLP adventurers!</p><p>In the last post <a href="https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-3-beyond-bags-of-words-introduction-to-word-embeddings-1c0e770d206e"><strong>Part 3: Beyond Bags of Words — Introduction to Word Embeddings</strong></a><strong> </strong>we explored how models like Word2Vec use context to capture the meaning of words, turning them into <strong>dense, powerful vectors</strong> that represent semantic relationships.</p><blockquote><em>📌 If you haven’t read Part 3 yet, </em><strong><em>we highly recommend starting there</em></strong><em> — it lays the foundation for everything you’re about to learn in this part.<br> 👉 </em><a href="https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-3-beyond-bags-of-words-introduction-to-word-embeddings-1c0e770d206e"><em>Read Part 3 here before continuing →</em></a></blockquote><h3>Ready to Enter the World of Neural Networks?</h3><p>Now that we’ve introduced embeddings — which are the <strong>input to many deep learning models</strong> — it’s time to answer a bigger question:</p><blockquote><strong><em>How do neural networks actually learn anything at all?</em></strong></blockquote><p>Step into the world of <strong>neural networks</strong>, where a clever mix of <strong>math, logic, and a pinch of magic</strong> allows machines to <strong>make decisions, learn patterns, and even understand language</strong> (well, almost like humans!).</p><p>This part of the series is your <strong>hands-on intro to neural networks</strong> — but don’t worry, we’ll keep things beginner-friendly, clear, and full of intuitive explanations.</p><p>Step into the world of neural networks where clever math and a pinch of magic come together to create systems that (almost) learn like humans. Whether you’re just getting started or are already a data science enthusiast, this guide will walk you through how neural networks really learn. Expect vivid analogies, relatable examples, and just the right amount of math to spark your curiosity (without overwhelming you).</p><p><strong>But before we jump into the inner workings of a neural network, let’s get comfortable with some basic building blocks. These core concepts will help everything make sense once we connect the dots.</strong></p><h3>First, Let’s Understand Some Basics:</h3><ol><li><strong>What Are Weights and Biases?</strong></li><li><strong>How Do They Work in Neural Networks?</strong></li><li><strong>The Knobs of Learning: What Are Parameters?</strong></li><li><strong>How Does a Neural Network Know It’s Wrong?</strong></li><li><strong>The Gradient: Sensing Which Way to Improve</strong></li><li><strong>Backpropagation: How the Network Blames Each Weight</strong></li><li><strong>Gradient Descent: Learning, Step by Step</strong></li><li><strong>What Is an Artificial Neural Network (ANN)?</strong></li></ol><h3>1. What Are Weights and Biases?</h3><p>Let’s start with a tasty analogy: <strong>imagine baking a cake</strong> — but instead of flour, sugar, and eggs, you’re mixing numbers to predict something. Say you want to predict how well a student will score on a test based on how many hours they studied.</p><p><strong>In this recipe:</strong></p><ul><li><strong>Weights</strong> decide how important each ingredient (input) is.</li><li><strong>Biases</strong> act like a baseline bonus, no matter what ingredients you have.</li></ul><h4>Recipe Analogy: Predicting a Test Score</h4><p>Let’s say:</p><ul><li><strong>Input:</strong> Hours Studied = 10</li><li><strong>Weight:</strong> The network learns how much each hour matters (say, 2 points per hour)</li><li><strong>Bias:</strong> Maybe there’s a “natural talent” bonus of 5 points, regardless of study hours.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32jGfuR8X15s4-BmtBryxQ.png" /></figure><h4>Why Do We Need Biases?</h4><p>Without a bias, if you studied 0 hours, you’d always get a score of 0 — totally unrealistic! Bias lets the model start from a non-zero point, making predictions much more flexible.</p><h4>Weights: Like Volume Knobs</h4><ul><li><strong>High Weight:</strong> Cranks up the volume — “This input matters a lot!”</li><li><strong>Low Weight:</strong> Turns it down — “Meh, not that important.”</li><li><strong>Zero Weight:</strong> Mutes it entirely.</li></ul><p><strong>During training, the network “twists” these knobs to find out which inputs really affect the outcome.</strong><br> Example: If coffee doesn’t help your test scores, the model can set its weight to 0!</p><h3>2. How Do They Work in Neural Networks?</h3><p>Every connection between “neurons” (think: tiny decision-makers) has a weight. Each neuron has its own bias.<br> <strong>A neuron:</strong></p><ul><li>Multiplies inputs by weights</li><li>Adds the bias</li><li>Passes the result through an “activation function” (think: a decision filter, like ReLU or sigmoid)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UF3CyKxpb8XZHak0dQqApQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzwXCteNr6HiWKSyvMRoGg.png" /></figure><h3>3. The Knobs of Learning: What Are Parameters?</h3><p>Now let’s zoom out: <strong>weights and biases are called parameters</strong> — they’re the settings the network learns during training.</p><p><strong>Parameters = Weights + Biases</strong></p><p>Think of the entire neural network as a giant control panel full of dials (parameters). Training is just twisting these dials to make the network smarter.</p><h4>Counting Parameters: Simple Example</h4><p>Suppose you have this tiny neural network:</p><ul><li><strong>Inputs:</strong> 3 (e.g., hours studied, hours slept, cups of coffee)</li><li><strong>Hidden Layer:</strong> 4 neurons</li><li><strong>Output:</strong> 1 neuron (final test score)</li></ul><p><strong>Let’s count the parameters:</strong></p><h4>Step 1: Inputs to Hidden Layer</h4><ul><li>Each input connects to all 4 hidden neurons.</li><li><strong>Weights:</strong> 3 inputs × 4 neurons = 12</li><li><strong>Biases:</strong> Each hidden neuron has 1 bias = 4</li></ul><h4>Step 2: Hidden Layer to Output</h4><ul><li>Each hidden neuron connects to the output neuron.</li><li><strong>Weights:</strong> 4</li><li><strong>Bias:</strong> Output neuron has 1 bias</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEVZ9h9VUSdTA8poBxcvIg.png" /></figure><h4>Scaling Up: Billion-Parameter Models</h4><p>Big models (like GPT-3 or LLaMA) might have hundreds of layers and thousands of neurons per layer:</p><ul><li>Each connection is a weight.</li><li>Each neuron has a bias.</li><li>GPT-3 has ~175,000,000,000 (175B) parameters!</li></ul><h4>Why So Many Parameters?</h4><ul><li><strong>More parameters</strong> = can capture more complex patterns (like language, vision, etc.).</li><li>Each extra layer/connection adds new weights and biases.</li><li>Example: Just <strong>doubling the neurons</strong> in a layer more than doubles the total parameters (because of all the new connections).</li></ul><h4>The Big Model Trade-Off</h4><p><strong>PRO:</strong> More parameters = more “brainpower” = can solve trickier problems.</p><p><strong>CON:</strong></p><ul><li>Needs way more data and time to train</li><li>Costs millions in compute</li><li>Risk of overfitting (memorizing, not generalizing)</li><li>After a point, adding more parameters = smaller gains</li></ul><p>That’s why today’s research is about making models smarter <em>without</em> always making them bigger.<br> Techniques like pruning (removing unneeded weights) and distillation (teaching a small model using a big one) are like making a tiny dog do big tricks!</p><h3>4. How Does a Neural Network Know It’s Wrong?</h3><h4>The Cost Function: The Ultimate Judge</h4><p>Imagine you’re learning to play darts. Each throw (prediction) gets you close to the bullseye (the correct answer), but sometimes you miss. The <strong>cost function</strong> (also called the loss function) is your scorekeeper — it tells you exactly how far off you were on every throw, helping you get better.</p><h4>What is a Cost Function, Really?</h4><p>The cost function is a mathematical tool that measures the difference between the network’s prediction and the true answer.</p><ul><li>If the cost is high, the prediction was way off.</li><li>If the cost is low, you were pretty close!</li></ul><p><strong>Example:</strong><br> Let’s say you’re predicting a student’s test score.</p><ul><li><strong>True score:</strong> 90</li><li><strong>Predicted score:</strong> 85</li><li><strong>Error:</strong> 90–85 = 5</li></ul><p>But instead of just looking at the difference, we often square it. Why? Squaring punishes bigger mistakes even more (a 10-point error is much worse than a 2-point error), and keeps the math positive.</p><h4>Mean Squared Error (MSE) — For Number Predictions</h4><p>For regression (number prediction) tasks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*9nSM3EtjLHgqYj5QLruQ7w.png" /></figure><p>Example: If your predictions for 3 students are 85, 92, and 87, and the true scores are 90, 94, and 90, then</p><ul><li>MSE = [(90–85)² + (94–92)² + (90–87)²] / 3 = [25 + 4 + 9] / 3 = 38 / 3 ≈ <strong>12.67</strong></li></ul><h4>Cross-Entropy Loss — For Choices or Categories</h4><p>For classification (like “cat” vs. “dog”), we use cross-entropy loss. It’s like asking, “How confidently did you bet on the right answer?”</p><ul><li>If your network is sure it’s a cat but it’s actually a dog, the penalty is huge!</li></ul><h4>Where Does the Cost Function Live?</h4><p>The cost function sits <strong>at the end</strong> of the network.<br> <strong>Workflow:</strong></p><ol><li>Input (e.g., an image) goes through the network.</li><li>Network makes a prediction (e.g., “dog” with 70% confidence).</li><li>Cost function compares the prediction to the true label (“dog” is correct).</li><li>The cost (loss) is calculated and sent backward to help the network learn.</li></ol><p><strong>Analogy:</strong> The cost function is like a strict coach at the finish line, saying, “Here’s how far you missed — let’s fix it next time.”</p><h4>Why It’s the Compass of Learning</h4><p>Without the cost function, the network is flying blind. It needs this feedback to know what to improve and by how much. It’s the compass, guiding every learning step.</p><h3>5. The Gradient: Sensing Which Way to Improve</h3><p>A <strong>gradient</strong> tells the neural network, “If you tweak this weight or bias just a little, will things get better or worse?”</p><ul><li>Think of it as the “slope” on the cost function’s landscape.</li></ul><h4>Analogy:</h4><p>Imagine you’re hiking in fog, trying to find the lowest point in a valley (the minimum loss). You can’t see far, but you can feel the slope with your feet.</p><ul><li>If it slopes down, take a step that way!</li><li>The steeper the slope (bigger gradient), the bigger step you should take.</li></ul><h4>Math Behind Gradients</h4><p>For each parameter (say, weight w), the gradient is:</p><p>∂Loss∂w\frac{\partial \text{Loss}}{\partial w} ∂w∂Loss​</p><p>It answers, “If I change w a little, how much does the loss change?”</p><h4>Key Point:</h4><ul><li><strong>Weights and biases</strong> are the positions (where you currently are).</li><li><strong>Gradients</strong> are the directions to move to get closer to the minimum (lower loss).</li></ul><h4>Example:</h4><ul><li>If the gradient is <strong>positive</strong>: increasing w increases the loss → so decrease w.</li><li>If it’s <strong>negative</strong>: increasing w decreases the loss → so increase w.</li></ul><p><strong>Practical Scenario:</strong><br> Suppose the network predicts 85 (instead of 90), and the gradient with respect to a weight is -12. That means increasing this weight will <strong>decrease the loss</strong> (good!). The network should update the weight upward.</p><h3>6. Backpropagation: How the Network Blames Each Weight</h3><p><strong>Backpropagation</strong> is how the network figures out which weights (and biases) are responsible for mistakes and by how much.<br> It’s like retracing your steps after making a wrong turn, so you know where you went off course.</p><h4>How Does It Work?</h4><ol><li>Start at the end: compute the cost (loss).</li><li>Move backward through the network, calculating <strong>gradients</strong> for every parameter using the <strong>chain rule</strong> from calculus.</li><li>Each layer gets “blame” based on how much it contributed to the final error.</li></ol><h4>Why Chain Rule?</h4><p>In math, the chain rule lets us figure out how changes in earlier steps affect the final result, even when the journey is complicated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uebJtiRpktt8hfRPQnuW4Q.png" /></figure><h4>Step-by-Step Example: Image Classifier</h4><p>Let’s say the network is trying to classify an image as a cat or dog:</p><ol><li><strong>Forward Pass:</strong> Image goes through the network, producing a “70% dog” prediction.</li><li><strong>Loss Calculation:</strong> Cross-entropy loss compares “70% dog” to the true label (“dog”).</li><li><strong>Backpropagation:</strong></li></ol><ul><li>Calculate how much the output layer’s weights caused the error.</li><li>Move backward, repeating for each layer.</li><li>Each parameter gets a gradient (its share of blame).</li></ul><p>4<strong>. Gradient Descent:</strong> Use those gradients to update the weights and biases.</p><h4>Why It’s Powerful</h4><p>Before backprop, tuning millions of parameters was guesswork. Now, we can calculate precise, targeted adjustments — like having a coach tell each player exactly what to work on after every game.</p><h3>7. Gradient Descent: Learning, Step by Step</h3><h4>How Does the Network Actually Improve?</h4><p>After calculating all the gradients (directions and amounts to change), the network updates each weight and bias to (hopefully) do better next time.</p><h4>Gradient Descent Update Rule</h4><p>For each parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*dIs2ytE9fFhQEi4jvpa3cg.png" /></figure><ul><li><strong>Learning rate</strong> controls how big each step is. Too big = overshoot. Too small = painfully slow.</li></ul><h4>Analogy:</h4><ul><li><strong>Big learning rate:</strong> Like jumping down the hill — fast but risky!</li><li><strong>Small learning rate:</strong> Like shuffling — safe but slow.</li></ul><h4>Variants to Help Gradient Descent:</h4><ul><li><strong>Momentum:</strong> Like rolling a ball down a hill — builds speed to escape flat spots.</li><li><strong>Adam:</strong> A smart optimizer that adjusts learning rates for each parameter, making learning faster and more stable.</li></ul><h4>Example Walkthrough:</h4><p>Suppose after backprop, the gradient for a weight is -10, and the learning rate is 0.1.</p><ul><li><strong>Update:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*g_OtnAypmcF6PD9ZXzynCw.png" /></figure><ul><li>The weight increases by 1, helping the network improve its prediction next time.</li></ul><p>So far, we’ve explored the key ingredients that help neural networks learn: <strong>weights, biases, cost functions, gradients, backpropagation, and gradient descent</strong>. But how do these pieces come together in a real network? That’s where <strong>Artificial Neural Networks (ANNs)</strong> step in!</p><h3>8. ANN: The Simple Building Block of Deep Learning</h3><p>Think of an ANN as a <em>team of mini-mathematicians</em> (neurons) working together to solve a problem. Inspired by the human brain, each “neuron” in an ANN takes in some numbers, does a quick calculation (using weights and biases), and passes the result to the next layer of neurons.</p><h3>Structure: Layers and Neurons</h3><ul><li><strong>Input layer</strong> — Where information enters (e.g., hours studied, hours slept)</li><li><strong>Hidden layers</strong> — Where the magic happens; these neurons combine inputs in different ways to find patterns</li><li><strong>Output layer</strong> — Gives the final answer (e.g., predicted test score)</li></ul><h4>Simple Example: Predicting a Student’s Exam Score</h4><p>Let’s put it all together with a real-life example.</p><p><strong>Say you want to predict a student’s exam score based on two things:</strong></p><ul><li>Hours studied</li><li>Hours slept</li></ul><p>You set up an ANN like this:</p><ul><li><strong>Input Layer:</strong> 2 neurons (one for each input)</li><li><strong>Hidden Layer:</strong> Let’s use 2 neurons here for simplicity</li><li><strong>Output Layer:</strong> 1 neuron (the predicted score)</li></ul><p><strong>Here’s how it works:</strong></p><ol><li><strong>Inputs (hours studied/slept) go in.</strong></li><li>Each input is <em>multiplied by a weight</em>, and each neuron <em>adds a bias</em>.</li><li>Hidden layer neurons pass their results to the output neuron.</li><li>The output neuron does one final calculation and spits out a prediction like “88 marks”.</li></ol><p>Every step uses the <em>learning ingredients</em> we discussed:</p><ul><li><strong>Weights &amp; biases</strong> are adjusted as the network learns.</li><li><strong>Cost function</strong> checks if the prediction was good.</li><li><strong>Gradients &amp; backpropagation</strong> figure out what needs to be fixed.</li><li><strong>Gradient descent</strong> tweaks the numbers to get a little better each time.</li></ul><h4>Visualizing It:</h4><p>Imagine a small factory assembly line:</p><ul><li>Each worker (neuron) adds their touch.</li><li>If the product (prediction) isn’t perfect, the manager (cost function) points out the flaws.</li><li>Workers (neurons) get feedback, retrain, and improve with every batch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AaXBSD7gORWzojwSxdMOg.png" /></figure><h3>Next Up: When ANNs Aren’t Enough</h3><p>ANNs are great when your data is straightforward, like a table of numbers. But what if your data is a <em>sequence</em> — like text, music, or time series?</p><ul><li>For that, we need models that can “remember” what happened before — enter <strong>Recurrent Neural Networks (RNNs)</strong>.</li></ul><p><em>In the next post </em><strong><em>PART 5</em></strong><em>, we’ll explore how neural networks can handle sequences — think sentences, songs, or sensor data with Recurrent Neural Networks (RNNs).</em></p><p><em>If you liked this post, </em><strong><em>don’t forget to like, share, and clap 👏👏👏</em></strong><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f4e5a34032a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing (NLP) Part 3: Beyond Bags of Words Introduction to Word Embeddings]]></title>
            <link>https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-3-beyond-bags-of-words-introduction-to-word-embeddings-1c0e770d206e?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c0e770d206e</guid>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[word2vec]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 14:27:34 GMT</pubDate>
            <atom:updated>2025-08-04T09:56:38.834Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been following along, you’ve already made great progress in understanding how machines process language. In <a href="https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-2-from-words-to-numbers-3739c16b2806"><strong>Part 2</strong></a>, we walked through foundational techniques like:</p><ul><li><strong>One-Hot Encoding</strong></li><li><strong>Bag of Words (BoW)</strong></li><li><strong>TF-IDF (Term Frequency–Inverse Document Frequency)</strong></li></ul><p>These methods help convert raw text into numbers — the first step in teaching machines to understand language. But you might have noticed some limitations like how these methods don’t really “understand” that “king” and “queen” are related, or that “good” and “great” might mean something similar.</p><p>So…<br> <strong>How do we teach machines to actually <em>understand</em> word meaning and relationships?</strong></p><p>That’s where <strong>word embeddings</strong> come in!</p><h3>Why Do We Need Something Better?</h3><p>Let’s recap some pain points with BoW and TF-IDF:</p><ul><li><strong>No meaning or context:</strong> “Apple” (the fruit) and “Apple” (the company) look exactly the same to the algorithm.</li><li><strong>Massive, sparse vectors:</strong> Each word or document is a super-long vector filled with mostly zeroes.</li><li><strong>No relationship awareness:</strong> “Paris” and “France” are just as far apart as “Paris” and “Potato”.</li></ul><p>Clearly, we need something smarter!</p><h3>Introducing Word Embeddings</h3><p>To solve this problem, we need a way to <strong>capture the meaning of words</strong>, not just their identities.</p><p>This is where <strong>word embeddings</strong> come into play.</p><p>Instead of using sparse, meaningless binary vectors, <strong>word embeddings</strong> map each word into a <strong>dense vector space</strong>, where:</p><ul><li>Words that appear in similar contexts have similar vectors.</li><li>Relationships between words (like “king” and “queen”) are preserved as geometric relationships.</li></ul><p>In short, embeddings allow our models to <strong>understand language more like humans do.</strong></p><h3>Types of Word Embeddings</h3><p>Let’s walk through the major categories as technology has evolved:</p><h4>1. Count-Based Embeddings:</h4><p>These use statistics about word occurrence.</p><ul><li><strong>TF-IDF,BOW and One-hot encoding</strong>: They represent words based on how often they appear and which words they appear with, but they don’t understand the actual context or deeper meanings behind the words.</li></ul><h4>2. <strong>Prediction-Based Embeddings:</strong></h4><p>Here’s where things get interesting!<br> These models learn embeddings by training a simple neural network to <em>predict</em> context.</p><p><strong>Word2Vec (Google): </strong>Words that appear in similar <strong>contexts</strong> tend to have similar meanings.</p><blockquote>A Classic Example: “King”, “Queen”, “Man”, “Girl”, “Prince”</blockquote><blockquote>Let’s consider a set of words:<br> <strong>king, queen, man, girl, prince</strong></blockquote><p>Now imagine that in an ideal vector space, we have axes for abstract concepts like:</p><ul><li>Royalty</li><li>Gender (masculinity/femininity)</li><li>Age</li></ul><p>In this space:</p><ul><li><strong>“King”</strong>, <strong>“Queen”</strong>, and <strong>“Prince”</strong> might share high scores on the <strong>royalty</strong> dimension.</li><li><strong>“Queen”</strong> and <strong>“Girl”</strong> might score similarly on <strong>femininity</strong>.</li><li><strong>“Prince”</strong> and <strong>“King”</strong> might differ only by <strong>age</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAHjxwOSZ2K_UUl3ybv_Zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jr5gwC1-_EaDLiJX.png" /></figure><p>In other words, the model has learned to <strong>encode relationships</strong> between words in a meaningful way — without being explicitly told what “gender” or “royalty” are.</p><p>What we then observe is:</p><ul><li>As expected, “king”, “queen”, “prince” have similar scores for “royalty” and “girl”, “queen” have similar scores for “femininity”.</li><li>An operation that removes “man” from “king”, would yield in a vector very close to “queen” ( “king”- “man” = “queen”)</li><li>Vectors “king” and “prince” have the same characteristics, except for age, telling us how they might possibly be semantically related to each other.</li></ul><h4>How Does Word2Vec Learn Word Embeddings?</h4><p>Word2Vec has two primary training strategies:</p><ol><li><strong>CBOW (Continuous Bag of Words)</strong></li><li><strong>Skip-Gram</strong></li></ol><p>Both are shallow neural networks trained to predict words based on context. However, they operate in <strong>opposite directions</strong>.</p><p>Let’s break both down in <strong>simple everyday terms</strong>, with an example sentence:</p><blockquote><em>&quot;I love the new movie&quot;</em></blockquote><p>We’ll use this same sentence for both methods.</p><h3>CBOW (Continuous Bag of Words):</h3><p><strong>“Guess the middle word from the nearby words”</strong></p><p>Imagine you’re solving a <strong>fill-in-the-blank</strong> problem. You’re given the words around a missing word, and you have to guess what that missing word is.</p><h4>Let’s say the target word is:</h4><blockquote><em>&quot;the&quot;</em></blockquote><p>And we look at 2 words before and 2 words after it. That gives us:</p><ul><li><strong>Context words:</strong> &quot;I&quot;, &quot;love&quot;, &quot;new&quot;, &quot;movie&quot;</li><li><strong>Target (missing) word:</strong> &quot;the&quot;</li></ul><p>CBOW works by taking these 4 context words and saying:</p><blockquote><em>“Based on these words, what’s the most likely word that should be in the middle?”</em></blockquote><p>It <strong>averages</strong> the information from these surrounding words and learns to <strong>predict the target word</strong>.</p><h4>In essence:</h4><blockquote><em>CBOW is like:<br> “If I hear </em><strong><em>I</em></strong><em>, </em><strong><em>love</em></strong><em>, </em><strong><em>new</em></strong><em>, </em><strong><em>movie</em></strong><em>, I’m probably talking about </em><strong><em>‘the’</em></strong><em>.”</em></blockquote><p>This method is <strong>fast</strong> and works well when the word appears often in the dataset (common words).</p><h3>Skip-Gram:</h3><p><strong>“Guess the nearby words from the middle word”</strong></p><p>Now imagine the opposite situation:<br> You’re given a word, and you’re asked:</p><blockquote><em>“Which words usually appear close to this one in a sentence?”</em></blockquote><h4>Let’s take the word:</h4><blockquote><em>&quot;love&quot;</em></blockquote><p>With a window size of 2, we’ll look at the 2 words before and 2 words after:</p><ul><li><strong>Input word:</strong> &quot;love&quot;</li><li><strong>Predicted context words:</strong> &quot;I&quot;, &quot;the&quot;, &quot;new&quot;, &quot;movie&quot;</li></ul><p>So Skip-Gram asks:</p><blockquote><em>“Given the word </em><strong><em>love</em></strong><em>, what are the likely words around it?”</em></blockquote><p>It trains a model to <strong>predict all the surrounding words</strong> one by one.</p><h4>In essence:</h4><blockquote><em>Skip-Gram is like:<br> “If I see </em><strong><em>‘love’</em></strong><em>, the words around it are likely to be </em><strong><em>I</em></strong><em>, </em><strong><em>the</em></strong><em>, </em><strong><em>new</em></strong><em>, or </em><strong><em>movie</em></strong><em>.”</em></blockquote><p>Skip-Gram is <strong>slower</strong> but better at learning from <strong>rare words</strong>, because it focuses on each word and its specific surroundings.</p><h3>Why Does This Work?</h3><p>Think about how we learn language as humans:</p><ul><li>We understand a missing word when we know the context:<br> “She ___ to the market.” → Probably “went”<br> That’s CBOW.</li><li>We can guess the kind of words that typically appear near a word we know:<br> “Birthday” is often near “cake”, “gift”, or “party”<br> That’s Skip-Gram.</li></ul><p>Word2Vec learns these patterns by looking at <strong>millions of sentences</strong>, so it becomes very good at mapping words into a space where similar meanings are close together.</p><h3>What’s Next?</h3><p>Word embeddings like Word2Vec are foundational in modern NLP. They power:</p><ul><li>Translation tools</li><li>Recommendation systems</li><li>Smart assistants</li><li>Chatbots</li><li>Sentiment analysis</li></ul><p>But all of this is just the beginning.</p><h3>Ready to Dive Deeper?</h3><p>If you’re curious about <strong>how Word2Vec is built under the hood</strong> or want to learn the <strong>neural network behind it</strong>, you’re in luck!</p><p>👉 <a href="https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-4-how-neural-networks-actually-learn-6f4e5a34032a"><strong>Follow the link to Part 4: Introduction to Neural Networks</strong></a><br> Where we’ll build the foundations of neural networks — the brains behind models like Word2Vec, BERT, and GPT!</p><p><em>If you liked this post, </em><strong><em>don’t forget to like, share, and clap 👏👏👏</em></strong><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c0e770d206e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing (NLP) — Part 2: From Words to Numbers]]></title>
            <link>https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-2-from-words-to-numbers-3739c16b2806?source=rss-d34bc6b9ab84------2</link>
            <guid isPermaLink="false">https://medium.com/p/3739c16b2806</guid>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[bag-of-words]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Sahil Arora]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 17:59:32 GMT</pubDate>
            <atom:updated>2025-08-03T14:28:21.023Z</atom:updated>
            <content:encoded><![CDATA[<h3>Natural Language Processing (NLP) Part 2: From Words to Numbers</h3><p><em>Understanding Text Representations: One-Hot, Bag of Words, and More</em></p><p>Welcome back to the <strong>NLP journey!</strong> <br>In <a href="https://medium.com/@sahilarora240792/introduction-to-nlp-a-roadmap-for-beginners-08fe14702a48">Part 1</a> we discussed the basics of text preprocessing: <strong>Tokenization</strong>, <strong>Stop Words</strong>, <strong>Stemming</strong>, and <strong>Lemmatization</strong>. If you haven’t read that yet, I highly recommend checking it out before diving into this one.</p><p>In <strong>Part 2</strong>, we’re moving forward to understand how we can represent text <strong>numerically</strong> a crucial step before feeding it into machine learning models for tasks like <strong>Sentiment Analysis</strong>, <strong>Spam Detection</strong> and more.</p><h3>Terminologies to Understand First</h3><p>Before we jump into actual representations, let’s clarify a few key terms you’ll hear frequently:</p><ul><li><strong>Corpus</strong>: A collection of text documents. Think of it as your entire dataset.</li><li><strong>Document</strong>: A single text entry in your corpus. It could be a sentence, paragraph, tweet, or full article.</li><li><strong>Vocabulary</strong>: The set of <strong>unique words</strong> across your entire corpus.</li><li><strong>Word (or Token)</strong>: An individual unit of text after tokenization.</li></ul><h3>Typical NLP Pipeline for Text Classification</h3><p>Let’s say your problem is <strong>Sentiment Analysis</strong> — figuring out whether a review is <strong>positive</strong> or <strong>negative</strong>.</p><blockquote>The common pipeline looks like this:<br>Dataset → Text Processing (1) → Text Processing (2) → Model</blockquote><p>Let’s expand that:</p><h3>Text Processing 1</h3><ul><li><strong>Tokenization</strong>: Split text into words/tokens.</li><li><strong>Stop Word Removal</strong>: Remove frequent, uninformative words (like “the”, “is”, “and”).</li><li><strong>Lemmatization</strong>: Reduce words to their base forms (e.g., “running” → “run”).</li></ul><h3>Text Processing 2</h3><p>Once we have clean tokens, we need to convert them into <strong>numbers</strong> that models understand. This step includes:</p><ul><li><strong>One Hot Encoding</strong></li><li><strong>Bag of Words (BoW)</strong></li><li><strong>TF-IDF</strong></li><li><strong>Word2Vec, GloVe, BERT</strong>, etc. (more advanced)</li></ul><p>In this part, we’ll focus on <strong>One-Hot Encoding</strong> ,<strong>Bag of Words </strong>and<strong> TF-IDF</strong> explore them with practical code.</p><h3>One-Hot Encoding: First Step Toward Numeric Representation</h3><p>One-Hot Encoding is the <strong>simplest</strong> technique to represent words as numbers.</p><h3>How It Works:</h3><p>Assume our vocabulary is:<br><em>[“love”, “machine”, “learning”, “fun”]</em></p><p>Each word is represented by a binary vector of size equal to the vocabulary size. Only the index of the word is <strong>1</strong>, the rest are <strong>0</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Tx8Xjk1kp9jB5mqOH0H-w.png" /></figure><p>This technique is easy to understand but not memory-efficient for large vocabularies, and doesn’t capture relationships between words (e.g., “good” and “great” are unrelated here).</p><h3>Bag of Words (BoW)?</h3><p>The <strong>Bag of Words</strong> model represents text as a <strong>“bag” of individual words</strong>, <strong>ignoring grammar and word order</strong>, and focusing only on whether known words occur in the text.</p><h4>Step-by-step Example</h4><p>Let’s take three simple sentences (we’ll treat each sentence as a document):</p><p>Doc1: <em>“I love data science”</em><br>Doc2: <em>“Data science is fun”</em><br>Doc3: <em>“I love fun”</em></p><h4>Step 1: Build the Vocabulary</h4><p>First, we extract all <strong>unique words</strong> across all documents.<br>Vocabulary = <em>[“I”, “love”, “data”, “science”, “is”, “fun”]<br></em>We assign an index to each word:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*EBAQtQIAjVDgG1aWij-frQ.png" /></figure><h4>Step 2: Create Document Vectors</h4><p>Each document is now represented as a <strong>vector of word counts</strong>, based on the vocabulary order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvCP8GWh_dFxr-FaqJt9GA.png" /></figure><p>So,</p><ul><li>“I love data science” becomes [1, 1, 1, 1, 0, 0]</li><li>“Data science is fun” becomes [0, 0, 1, 1, 1, 1]</li><li>“I love fun” becomes [1, 1, 0, 0, 0, 1]</li></ul><p>This is your <strong>Bag of Words matrix</strong>.</p><h4>Pros of BoW</h4><ul><li>Simple and easy to implement.</li><li>Works well for basic models like Naive Bayes.</li></ul><h4>Limitations of BoW</h4><ul><li><strong>Ignores context and order</strong>: “I love science” and “science love I” get the same representation.</li><li><strong>Common words dominate</strong>: Frequent but unimportant words (like “is”) might bias the results.</li></ul><p>Before proceeding further lets compare Bag of Words vs One-Hot Encoding:</p><p><em>docs = [“I like play”,“I play cricket”] <br>and now v</em>ocabulary <em>= [‘I’, ‘like’, ‘play’, ‘cricket’]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJH4x_mbA7wLSGUP-4-bwA.png" /></figure><p>One-Hot Encoding Representation (Word-Level): For word &quot;play&quot; (position 3 in vocabulary):</p><p><em>play = [0, 0, 0, 1]</em></p><p>For word &quot;like&quot;:</p><p><em>like = [0, 0, 1, 0]</em></p><p>This does <strong>not</strong> represent the whole sentence — just the word.</p><h3>TF-IDF: Smarter Word Weighting</h3><p><strong>TF-IDF (Term Frequency — Inverse Document Frequency)</strong> makes BoW smarter by reducing the weight of <strong>common</strong> words and increasing the importance of <strong>rare but meaningful</strong> ones.</p><h4>Key Idea:</h4><p>A word gets a <strong>high score</strong> if:</p><ul><li>It appears <strong>often</strong> in a document (<strong>TF</strong> part),</li><li>But appears in <strong>few</strong> documents overall (<strong>IDF</strong> part).</li></ul><h4>Let’s Break It Down</h4><h4>Step 1: Term Frequency (TF)</h4><p>How often a word appears in the document.</p><p><em>Doc1: “I love machine learning” <br>Doc2: “I love deep learning” <br>Doc3: “deep learning is amazing”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYQvNkWqtnsRg7qsPAMWig.png" /></figure><h4>Step 2: Inverse Document Frequency (IDF)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lihAYYPpm54gTK2QfThYnQ.png" /></figure><h4>Step 3: TF-IDF = TF × IDF</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5eAFulvn1lzxdlhVdtEh2g.png" /></figure><p><strong>Doc1 TF-IDF Vector</strong>:<br><em> </em><em>[0.10125, 0.10125, 0.27465, 0.0, 0.0, 0.0, 0.0]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRgqt9AhMBjVD7pV3fzIxw.png" /></figure><p><strong>Doc2 TF-IDF Vector</strong>:<br> <em>[0.10125, 0.10125, 0.0, 0.0, 0.10125, 0.0, 0.0]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RcWK5i_6ZWc02FM0CxsgOQ.png" /></figure><p><strong>Doc3 TF-IDF Vector</strong>:<br> <em>[0.0, 0.0, 0.0, 0.0, 0.10125, 0.27465, 0.27465]</em></p><h4>Final Summary Table:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ja8QQDvama-GQNtMRC953g.png" /></figure><h3>Code Time: Practice BoW on Google Colab</h3><p>To make this hands-on, I’ve prepared a <strong>Colab notebook</strong> where you can explore:</p><ul><li>Tokenization</li><li>One-Hot Encoding</li><li>Bag of Words</li></ul><p>👉 <a href="https://colab.research.google.com/drive/1TZk0yzT77wUU08JZGBh1NziVolx2g3Fm#scrollTo=bfSTzv5O_0Z7"><strong><em>Click here to open the notebook</em></strong></a></p><p>Inside, you’ll find:</p><ul><li>Cleaned dataset</li><li>Step-by-step BoW implementation using CountVectorizer from scikit-learn</li><li>Visualization of vocabulary and document-term matrix</li></ul><h3>What’s Next?</h3><p>In <a href="https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-3-beyond-bags-of-words-introduction-to-word-embeddings-1c0e770d206e"><strong>Part 3</strong>,</a> we’ll discuss:</p><ul><li>An introduction to <strong>Word Embeddings</strong> like Word2Vec that capture meaning and context.</li></ul><blockquote>If you liked this post, <strong>don’t forget to like, share, and clap 👏👏👏</strong>.<br>Follow along for <a href="https://medium.com/@sahilarora240792/natural-language-processing-nlp-part-3-beyond-bags-of-words-introduction-to-word-embeddings-1c0e770d206e"><strong>Part 3</strong></a><strong> of this NLP Journey!</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3739c16b2806" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>