<?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 Ruma Sinha on Medium]]></title>
        <description><![CDATA[Stories by Ruma Sinha on Medium]]></description>
        <link>https://medium.com/@rumasinha?source=rss-fa06e50d2167------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_wbjWnSN8cDT8d7V9eMFpg.jpeg</url>
            <title>Stories by Ruma Sinha on Medium</title>
            <link>https://medium.com/@rumasinha?source=rss-fa06e50d2167------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:04:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rumasinha/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[An Agentic Marketing Analyst with Google ADK and Gemini: From Idea to Prototype (Part 1)]]></title>
            <link>https://rumasinha.medium.com/an-agentic-marketing-analyst-with-google-adk-gemini-from-idea-to-prototype-part-1-a9b54b9966c9?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9b54b9966c9</guid>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 21:16:31 GMT</pubDate>
            <atom:updated>2026-01-19T14:36:58.513Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Moving from “What happened?” to “Who do I target?” using Hybrid Segmentation and Agentic AI.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5335qowsDw0HPNu_THJcew.png" /></figure><p><strong>From Raw Customer Data to Real Marketing Decisions</strong></p><p>Most companies today face a paradox: they have <strong>huge volumes of customer data</strong>, yet they still don’t know <strong>who to target, how to prioritize, or why customers are behaving differently</strong>.</p><p>Marketing teams constantly ask questions like:</p><ul><li><em>Who are my best customers right now?</em></li><li><em>Which groups should I target for this campaign?</em></li><li><em>Why are some high-value customers suddenly buying less?</em></li></ul><p>The data exists. The models exist. What’s missing is a <strong>system that connects them into a decision engine</strong>.</p><p>That’s what we built.</p><p><strong>The Business Problem</strong></p><p>In most organizations, customer intelligence is fragmented:</p><ul><li>Data science teams build <strong>models</strong> (RFM, clustering, churn models)</li><li>Marketing teams build <strong>playbooks</strong> (who to target, what to offer, what KPIs to track)</li><li>Business users ask <strong>natural-language questions</strong></li></ul><p>But these three worlds rarely talk to each other.</p><p>The result? Dashboards show numbers but don’t suggest actions. Models produce clusters that no one knows how to use. Marketers rely on static segments that quickly become outdated.</p><p>I wanted to build something different: a system that understands business questions, picks the right analytical lens, and returns actionable answers.</p><p>My idea was to build an <strong>Agentic Marketing Analyst</strong> — an AI that doesn’t just chat, but <em>reasons</em>, queries a 95k+ customer database in Snowflake, remembers context, and delivers actionable targeting lists in seconds.</p><p>In this post, I’ll walk you through how I took this idea from concept to working prototype using <strong>Agentic AI, Google Gemini 2.5 Flash, and Python.</strong></p><p><strong>The Core Idea: Different Questions Need Different Views</strong></p><p>We designed the platform around one simple principle:</p><p><strong>Different business questions require different views of the customer.</strong></p><p>There is no single “best” way to segment customers. Instead, we use three complementary views:</p><ol><li><strong>Value-based segments (RFM)</strong> — These tell us <em>how important</em> a customer is to the business (Champions, Loyal Customers, At Risk, Lost, etc.)</li><li><strong>Behavioral clusters (Machine Learning)</strong> — These tell us <em>how customers behave</em> (what they buy, what categories they prefer, how similar customers act)</li><li><strong>A business playbook</strong> — This defines <em>what to do</em> for each group (budgets, campaigns, KPIs, priorities)</li></ol><p>The intelligence of the platform comes from knowing <strong>which one to use for which question</strong>.</p><p><strong>How the System Thinks</strong></p><p>When a business user asks a question, the system first tries to understand <strong>what kind of decision they are trying to make</strong>.</p><p><strong>Business Question</strong></p><p><strong>What It Really Means</strong></p><p><em>“Show me our best customers”</em></p><p><strong>Strategic overview</strong></p><p>“Who should we target for electronics?”</p><p><strong>Campaign targeting</strong></p><p>“Why are some VIPs behaving strangely?”</p><p><strong>Anomaly detection</strong></p><p>Each of these requires a different lens:</p><ul><li><strong>Strategic questions</strong> → Value-based segments (RFM)</li><li><strong>Targeting questions</strong> → Behavioral clusters (HDBSCAN)</li><li><strong>Risk &amp; anomaly questions</strong> → Both together</li></ul><p>The platform automatically routes each question to the right intelligence layer. The user never has to think about RFM, clustering, or database tables. They just ask questions.</p><p><strong>A business user asks a question</strong></p><p><em>“Show me our best performing customer groups.”</em></p><p><strong>2. The system classifies the intent</strong> Is this about strategy, targeting, or anomalies?</p><p><strong>3. The system selects the right customer view</strong></p><ul><li>RFM for full business coverage</li><li>Clusters for behavior and personalization</li><li>Both for risk and outliers</li></ul><p><strong>4. The data is pulled from the right source</strong></p><ul><li>Aggregated segment data</li><li>Machine-learning cluster profiles</li><li>Individual customer records</li></ul><p><strong>5. The business playbook is applied</strong> Each group is enriched with goals, actions, KPIs, and budget priorities.</p><p><strong>6. The final result is returned</strong> Not just numbers, but <strong>business-ready insights</strong>: who the group is, why they matter, and what to do next.</p><p>This transforms raw data into <strong>marketing intelligence</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwHtJZ7b12CrHZSIn_5NKA.png" /></figure><p><strong>The Hybrid Segmentation Approach</strong></p><p>In Data Science, we often face a tension between <strong>Rules</strong> and <strong>Machine Learning</strong>:</p><ul><li><strong>Rules (RFM)</strong> are safe but rigid. A “Champion” is defined by high spend — period.</li><li><strong>ML (HDBSCAN)</strong> is smart but messy. It finds hidden patterns like “Weekend Tech Buyers,” but it also generates noise.</li></ul><p>Our agent uses a <strong>Hybrid Approach</strong> — combining both to create a safety net for the AI.</p><p><strong>The Strategy Layer (RFM Cohorts)</strong></p><p>This answers: <em>“Who is valuable?”</em></p><p>We use rigid RFM (Recency, Frequency, Monetary) scores to define strategic cohorts.</p><ul><li><strong>Input:</strong> User asks, <em>“How are my VIPs?”</em></li><li><strong>Agent Action:</strong> Routes to RFM segment logic</li><li><strong>Result:</strong> 100% customer coverage. No hallucinations.</li></ul><p><strong>The Tactical Layer (HDBSCAN Clusters)</strong></p><p>This answers: <em>“What do they like?”</em></p><p>We use HDBSCAN (unsupervised learning) to find behavioral niches.</p><ul><li><strong>Input:</strong> User asks, <em>“Find customers interested in electronics.”</em></li><li><strong>Agent Action:</strong> Routes to HDBSCAN cluster logic</li><li><strong>Result:</strong> Identifies “Cluster 51” (High Affinity for Tech) even if they’re new customers</li></ul><p><strong>The Safety Net</strong></p><p>Here’s the critical rule: If a customer is in a high-value RFM Segment (e.g., “Champions”) but is flagged as HDBSCAN Cluster -1 (Noise), <strong>prioritize the RFM Segment</strong>. Never discard a VIP as “Noise.”</p><p><strong>The Architecture</strong></p><p>Our system is built on a “Neuro-Symbolic” architecture — combining the flexibility of LLMs with the safety of deterministic code.</p><pre><strong>Component</strong>               <strong>Purpose</strong><br>The Agent               Google Gemini 2.5 Flash (via Google ADK)<br>The Tools               Python Tool Executors running secure, parameterized SQL<br>The Memory              Local SQLite vector store for conversation context<br>The Data                Snowflake (holding RFM scores and Behavioral Clusters)</pre><p><strong>The Routing System</strong></p><pre><strong>Component</strong>               <strong>Purpose</strong><br>marketing_agent.py      LLM-based orchestrator<br>detect_query_intent()   Converts English → Business intent<br>ColumnSelection         Chooses RFM vs. HDBSCAN vs. Both<br>Confidence scoring      Determines reliability of routing</pre><p><strong>The Data Layer</strong></p><p>We use <strong>three independent data brains</strong>:</p><pre><strong>Layer</strong>                             <strong>What It Contains</strong><br>marketing_playbook.json           Business definitions, segments, KPIs, budgets<br>Snowflake.customer_intelligence   95K customers with RFM + clusters<br>Snowflake.cluster_profiles        ML-generated behavioral clusters</pre><p><strong>Under the Hood: Tracing a Hybrid Query</strong></p><p>To truly understand the power of this agent, let’s trace a complex, real-world query that combines both layers.</p><p><strong>User Input:</strong> <em>“Show me top electronics customers who are behaving strangely.”</em></p><p><strong>Step 1: LLM Orchestrator</strong></p><p>The main script (marketing_agent.py) receives the natural language input and passes it to the smart_query() router.</p><p><em>Show me top electronics customers who are behaving strangely.</em></p><p><strong>Step 1: LLM Orchestrator</strong></p><p>The main script (marketing_agent.py) receives the natural language input and passes it to the smart_query() router.</p><p><strong>Step 2: Intent Detection (The “Switchboard”)</strong></p><p>The detect_query_intent() function scans the string for specific signals:</p><ul><li>“Electronics” → <strong>Targeting</strong> Signal</li><li>“Top” → <strong>Strategic</strong> Signal</li><li>“Strangely” → <strong>Anomaly</strong> Signal</li></ul><p>It classifies the intent as <strong>ANOMALY</strong> and selects <strong>BOTH</strong> columns (RFM + HDBSCAN).</p><p><strong>Step 3: AI Routing</strong></p><p>The system executes the hybrid handler logic:</p><pre>result = self._handle_hybrid_query(query, analysis)</pre><p>This triggers the detect_anomalies() tool within the Data Loader.</p><p><strong>Step 4: ML + Data Fusion (Snowflake)</strong></p><p>The system constructs a precise SQL query to find the value-behavior mismatch:</p><pre>WHERE rfm_segment IN (&#39;Champions&#39;, &#39;Loyal Customers&#39;, &#39;At Risk&#39;)<br>AND (hdbscan_cluster = -1 OR cluster_probability &lt; 0.5)</pre><p>This query looks for <strong>High-Value Customers</strong> (Champions) who are behaving <strong>unlike their cluster</strong> (Noise/Low Probability). This is exactly how fraud, churn, and VIP drift detection works in advanced SaaS companies.</p><p><strong>Step 5: Business Output</strong></p><p>The system returns a structured payload:</p><pre>{<br>&quot;type&quot;: &quot;anomaly_detection&quot;,<br>&quot;anomalies&quot;: […],<br>&quot;recommended_actions&quot;: [<br>&quot;Review purchase history&quot;,<br>&quot;Personal outreach&quot;,<br>&quot;VIP intervention&quot;<br>]<br>}</pre><p><strong>Context Engineering and Memory</strong></p><p>The agent maintains conversation context, enabling natural follow-up questions:</p><ol><li><strong>User:</strong> <em>“Show me top 3 segments”</em></li><li><strong>Agent:</strong> Returns Champions, Loyal, At Risk</li><li><strong>Memory:</strong> Stores context: [‘Champions’, ‘Loyal’, ‘At Risk’]</li><li><strong>User:</strong> <em>“Tell me more about the first one.”</em></li><li><strong>Memory:</strong> Retrieves context</li><li><strong>System Prompt:</strong> Instructions trigger: <em>“If user says ‘first one’, look at context.”</em></li><li><strong>Agent Reasoning:</strong> <em>“First one is Champions. I will call get_segment_details(‘Champions’).”</em></li><li><strong>Output:</strong> The Agent drills down into the correct data without needing explicit specification.</li></ol><p>This ability to maintain context and resolve pronouns is what makes the agent feel intelligent and conversational.</p><p><strong>The Prototype in Action</strong></p><p>Here’s actual output from the CLI demo, showing the transition from broad query to specific drill-down using natural language:</p><pre>Query 1: Show me top 3 segments<br>→ Intent: strategic<br>→ Column: rfm_segment<br>→ Context: [&#39;Champions&#39;, &#39;Loyal&#39;, &#39;At Risk&#39;]<br>Response:<br>- Champions: 6596 customers, $331 avg<br>Goal: Retain and grow<br>Actions: VIP loyalty program enrollment…<br>- At Risk: 28718 customers, $210 avg<br>Goal: Win back immediately<br>Actions: Aggressive win-back offer (30–40%)…<br>- Loyal Customers: 16356 customers, $119 avg<br>Goal: Increase basket size<br>Actions: Cross-sell recommendations…<br>========================================<br>Query 2: Tell me more about the first one<br>→ Resolved &#39;first one&#39; to segment: Champions<br>→ Tool: get_segment_details<br>Response:<br>Segment: Champions<br>- Priority: 10<br>- Customers: 6,596<br>- Avg Value: $331<br>- Description: Best customers - recent, frequent, high-value buyers<br>- Goal: Retain and grow<br>- Budget: 20%<br>Recommended Actions:<br>1. VIP loyalty program enrollment<br>2. Early access to new products<br>3. Exclusive discounts (15–20%)<br>4. Personal account manager<br>5. Referral program with premium rewards<br>========================================<br>Query 3: Compare Champions and At Risk<br>→ Comparison query detected<br>→ Tool: compare_segments<br>Comparison Insights:<br>Champions has 1.6x higher average spend<br>Champions has higher marketing priority</pre><p><strong>The Marketing Playbook: Decoupled Business Logic</strong></p><p>One key design choice was to decouple the <strong>Business Logic</strong> from the <strong>ML Logic</strong>.</p><p><strong>The Problem:</strong> In many systems, marketing rules like “Budget Allocation” are hardcoded. If the business wants to change the strategy for “Champions,” they need an engineer to redeploy the codebase.</p><p><strong>The Solution:</strong> Designed the system to ingest a configuration file defining the <em>static</em> rules — priorities, KPIs, and goals.</p><p><strong>The Process:</strong> The hdbscan_clustering script acts as a “compiler.” It takes the <strong>Real-Time Clustering Results</strong> (who is in what group <em>today</em>) and merges them with the <strong>Business Configuration</strong>.</p><p><strong>The Output:</strong> The marketing_playbook.json ensures that when the Agent answers a question, it uses fresh data (from the ML pipeline) but speaks with the approved voice of the business (from the Config).</p><p>This architecture ensures the AI is helpful, accurate, and always “on brand” with the company’s marketing strategy.</p><p><strong>Why This Is Different</strong></p><p>Most analytics platforms do one of two things: they show dashboards, or they show model outputs.</p><p>We built something that connects:</p><p><strong>Data → Models → Business Strategy → Actions</strong></p><p>The system knows:</p><ul><li>When to use stable business segments</li><li>When to use dynamic machine-learning clusters</li><li>When to combine both to detect risk</li></ul><pre>Question Type                   What to Use Why<br>&quot;How is the business doing?&quot;    RFM segments Complete, stable, business-aligned<br>&quot;Who should I target?&quot;          HDBSCAN clusters Behavior &gt; labels<br>&quot;Why are good customers <br>acting weird?&quot;                  Both Value vs. behavior mismatch</pre><p><strong>Technical Benefits</strong></p><ol><li><strong>Safety Guardrails:</strong> The Agent cannot “accidentally” delete data or run a bad query because it’s restricted to pre-defined paths.</li><li><strong>Explainability:</strong> Every response includes a reasoning field, allowing the Agent to say, <em>“I checked this because you mentioned X…”</em>, making the AI transparent and trustworthy.</li><li><strong>Resilience:</strong> If the database connection drops, the Agent can switch to “Offline Mode” and still answer strategic questions by reading the local playbook file.</li></ol><p><strong>Conclusion</strong></p><p>This Phase 1 prototype proves that an AI can act as a <strong>Read-Only Analyst</strong>. It can query, reason, and safeguard VIP data while delivering actionable insights in natural language.</p><p>The key innovations:</p><ul><li><strong>Hybrid Segmentation</strong> combining RFM (value) with HDBSCAN (behavior)</li><li><strong>Intelligent Routing</strong> that matches questions to the right data source</li><li><strong>Context Memory</strong> for natural, conversational interactions</li><li><strong>Decoupled Business Logic</strong> for maintainability and brand consistency</li></ul><p>In <strong>Phase 2</strong>, we’ll bring in sentiment analysis from customer reviews and incorporate the action layer — campaign generation, email text creation, and integration with marketing platforms.</p><p>The vision is an <strong>Agentic Customer Intelligence &amp; Action Platform</strong> that doesn’t just analyze, but acts — turning insights into campaigns with human oversight.</p><p><em>Stay tuned for Part 2, where we’ll add recommendation engines, sentiment analysis, and agent-to-agent collaboration using Google ADK’s full capabilities.</em></p><p><strong>Github link</strong>: <a href="https://github.com/rumsinha/agentic-marketing-system">https://github.com/rumsinha/agentic-marketing-system</a></p><p><strong>Dataset</strong> used is from Kaggle Brazilian ecommerce public <strong>dataset</strong> of orders made at <strong>Olist</strong> Store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*LgJsj_CMQdnJ1mjsiPzqyw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9b54b9966c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data pipeline with n8n, Text2SQL, FastAPI, Postgres and Snowflake]]></title>
            <link>https://rumasinha.medium.com/data-pipeline-with-n8n-text2sql-fastapi-postgres-and-snowflake-9245ea27a2fa?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/9245ea27a2fa</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[n8n]]></category>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 23:36:52 GMT</pubDate>
            <atom:updated>2025-12-14T23:36:52.029Z</atom:updated>
            <content:encoded><![CDATA[<p>Data pipeline with n8n, Text2SQL, FastAPI, Postgres and Snowflake</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5O7csM7q7D5OkoR5OhH-g.png" /><figcaption>n8n workflow</figcaption></figure><p>Meet Alex. Alex is a Finance Manager with a nemesis: The Month-End Report. Every month, he submits a ticket and waits 3 days for data. I decided to build an intelligent agent to fix Alex’s problem.</p><p>In the old world, this request triggers so many steps. You write a SQL query against your transactional database (Postgres). You export a CSV. You clean it up in Excel. You write a Python script to upload it to Snowflake.</p><p>And then, tomorrow, they ask: <em>“Actually, can we see </em><strong><em>Products</em></strong><em> instead of Users?”</em> And you have to rewrite everything.</p><p>What if we didn’t have to rewrite the code? What if the pipeline could <strong>rewrite itself</strong>?</p><p>In this post, I’ll share how I built an autonomous, low-code “Agentic” workflow that connects our operational data (OLTP) to our data warehouse (OLAP) using <strong>n8n</strong>, <strong>Gemini AI</strong>, and a local <strong>Python</strong> worker.</p><h3>The Architecture:</h3><p>The philosophy behind this tool is simple: <strong>Don’t make the low-code tool do the heavy lifting.</strong></p><p>I used n8n as the <strong>Orchestrator</strong> (The Manager) and Python on my local Mac as the <strong>Execution Layer</strong> (The Worker).</p><p>Here is how the flow works, step-by-step.</p><p><strong>The Analyst Agent (Text-to-SQL)</strong></p><p>Everything starts with a natural language prompt. I type: <em>“Show me users with sales over $100.”</em></p><p>Instead of me writing SQL, my <strong>First AI Agent</strong> (Gemini) acts as a Data Analyst. It takes my English question and translates it into a precise Postgres SQL query.</p><ul><li><strong>Input:</strong> “High revenue users”</li><li><strong>Output:</strong> SELECT id, email, SUM(sales) FROM users GROUP BY id, email HAVING SUM(sales) &gt; 100;</li></ul><p><strong>Crucial Detail:</strong> The computation happens inside <strong>Postgres</strong>, not n8n. By pushing the “heavy math” down to the database, we only fetch the relevant rows, keeping our pipeline fast and lightweight.</p><p><strong>The Engineer Agent (Self-Writing Python)</strong></p><p>This is where the architecture becomes adaptive. Once we have the data (as a CSV), we need to load it into Snowflake. A static Python script would break if the columns changed (e.g., from “Users” to “Products”).</p><p>So, I built a <strong>Second AI Agent</strong> — the “Data Engineer.” This agent looks at the CSV headers and writes a <strong>custom Python script</strong> on the fly. It uses the <strong>Snowpark</strong> library to:</p><ol><li>Infer the schema automatically.</li><li>Create a temporary stage.</li><li>Bulk load the data into Snowflake.</li></ol><p>It’s a “Self-Healing” pipeline. If the data changes, the code changes automatically.</p><p><strong>The “Smart” Optimization (Schema Hashing)</strong></p><p>Generating Python code with an LLM costs money and time. We don’t want to re-write the <em>exact same script</em> every time we run the report.</p><p>I implemented a <strong>Schema Hashing</strong> mechanism to solve this.</p><ol><li><strong>Fingerprint:</strong> When a new CSV arrives, n8n reads the headers and creates a unique “Fingerprint” (Hash).</li><li><strong>Check Cache:</strong> The workflow checks my local disk: <em>“Do I already have a script for this fingerprint?”</em></li></ol><ul><li><strong>Yes?</strong> Reuse the existing script. (<strong>Cost: $0</strong>, Time: Instant).</li><li><strong>No?</strong> Wake up the AI Agent to write a new one.</li></ul><p>This means the system gets faster and cheaper the more you use it.</p><p><strong>The Tech Stack in Action</strong></p><p>Here is how the pieces fit together to create a seamless bridge between systems:</p><ul><li><strong>The Orchestrator (n8n):</strong> The visual brain. It connects the API, the AI, and the local file system.</li><li><strong>The Source (Postgres / OLTP):</strong> Our transactional database. It handles the raw queries and aggregations efficiently.</li><li><strong>The Compute (Local Mac):</strong> My local machine runs the Python scripts. This avoids the need for expensive cloud compute (like AWS Lambda) for simple batch jobs.</li><li><strong>The Destination (Snowflake / OLAP):</strong> The final home for the data, ready for heavy analytics.</li></ul><h3><strong>Why This Matters</strong></h3><p>By combining the flexibility of AI (Text-to-SQL) with the stability of Code (Python scripts), we built a tool that allows non-technical users to interact with complex data systems.</p><p>They can ask questions in English. The system handles the SQL, the Python, the API calls, and the Snowflake loading — autonomously.</p><p>Let’s look at the flow node by node and code by code:</p><ol><li><strong>The Source (Postgres)</strong></li></ol><p>First, we need a source of truth. I spun up a local Postgres instance and seeded it with synthetic user data. users is the table we will be querying.</p><pre>brew services restart postgresql@17 # starts the postgres database<br>psql postgres  # opens the postgres sql in the terminal<br>postgres=# select * from users limit 5; # query the 5 records from the table</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fdi1FuZuTeGetLc652mceQ.png" /></figure><p>2. <strong>The API (FastAPI)</strong></p><p>Since n8n needs a way to talk to our local database, I wrapped it in a lightweight <strong>FastAPI</strong> service. This acts as our ‘Gateway’.</p><p>Notice the security check in the code (forbidden_words). This prevents the AI from accidentally dropping tables!</p><pre>import asyncpg<br>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel<br><br># define the FastAPI application<br>app = FastAPI(title=&quot;Revenue API for n8n&quot;)<br>DB_CONFIG = {<br>    &quot;user&quot;: &lt;&gt;,    <br>    &quot;database&quot;: &quot;postgres&quot;,  <br>    &quot;host&quot;: &quot;localhost&quot;,<br>    &quot;port&quot;: &quot;5432&quot;<br>}<br>class QueryRequest(BaseModel):<br>    sql_query: str<br>@app.post(&quot;/adhoc_query&quot;)<br>async def run_dynamic_query(request: QueryRequest):<br>    &quot;&quot;&quot;<br>    Executes raw SQL provided by the client (n8n).<br>    Ensure the DB user is READ-ONLY.<br>    &quot;&quot;&quot;<br>    # Simple security check to prevent any unwanted action<br>    forbidden_words = [&quot;DROP&quot;, &quot;DELETE&quot;, &quot;INSERT&quot;, &quot;UPDATE&quot;, &quot;ALTER&quot;, &quot;TRUNCATE&quot;]<br>    if any(word in request.sql_query.upper() for word in forbidden_words):<br>        raise HTTPException(status_code=400, detail=&quot;Read-only queries allowed only.&quot;)<br><br>    conn = await asyncpg.connect(**DB_CONFIG)<br>    try:<br>        print(f&quot;🤖 Executing: {request.sql_query}&quot;)<br>        rows = await conn.fetch(request.sql_query)<br>        <br>        # Convert rows to generic list of dicts<br>        results = [dict(row) for row in rows]<br>        return results<br>    finally:<br>        await conn.close()<br><br>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    # Run on localhost:8000<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>Running a FastAPI application with Uvicorn. When uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000) is executed, it starts a persistent server that listens on port 8000 and keeps running until manually stopped. This allows the n8n HTTP Request node to make requests to the API endpoint.</p><pre>python main.py<br>INFO:     Started server process [86486]<br>INFO:     Waiting for application startup.<br>INFO:     Application startup complete.<br>INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)</pre><p>3. <strong>Starting n8n locally once installed with npm</strong>.</p><pre>n8n start <br><br># we will see the below message:<br><br>Editor is now accessible via:<br>http://localhost:5678<br><br>Press &quot;o&quot; to open in Browser.<br><br># on pressing &quot;o&quot;, it opens the application</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ao-SqWqs9FgHNLiKFKxaww.png" /></figure><p>Clicking ‘<strong>Create workflow</strong>’ takes <strong>you</strong> to the canvas to start <strong>building</strong> the new workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BozN6gpu0Qob95EqIAYMkA.png" /></figure><p>On clicking “<strong>first_workflow</strong>”, it opens the workflow as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGRhqkMwCnoOcCziYsB1Kw.png" /></figure><p>We can edit and test by executing individual nodes or executing the workflow end to end.</p><p><strong>The Analyst Agent (Text-to-SQL)</strong></p><p>This is the <strong>Analyst Agent</strong>. I used the <strong>Google Gemini</strong> node with a specific ‘System Instruction’ that forces it to act like a Postgres expert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StNLZD8U_YadkgAx5KD_NQ.png" /></figure><p>Clicking on the “Message a model” node, the below window opens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*PRBrH0oMJjK6D2UUtKIDeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*oUpYxXXRbrPb2Wrs5L409Q.png" /></figure><p>Let’s look at the strict rules we set in the System Message:</p><blockquote><strong>Output:</strong> Raw SQL only (no markdown).</blockquote><blockquote><strong>Logic:</strong> Always aggregate sales by User ID.</blockquote><blockquote><strong>Safety:</strong> Read-only queries (SELECT only).</blockquote><p>The user message: show me all users with sales over $100.</p><p>On executing the “Execute step” we see the below output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNNiGN6AHzY9egNiHCXRGA.png" /></figure><p>Lets modify the user message to: Provide me the top users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpAi5nQmIls1sYbkVLWo8Q.png" /></figure><p>4. <strong>Building the HTTP request node for the API endpoint.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MC3-6ysZeKiWYUrPVKqAFQ.png" /></figure><p>On clicking the HTTP Request node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NP_h8Ujs1a1A0hgchK8d9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJ8dENEHHiXO_26GQcsrDQ.png" /></figure><p>The sql query is the output of the previous node. When this node gets executed, the API endpoint connection is established, the sql query to execute is fetched, the postgres database connection is established, the sql query is executed in the database. The result is fetched back as response.</p><p>5. <strong>Converting to CSV</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l-aLxDdSTDSe6Mqt_ihNSg.png" /></figure><p>The next node is “Convert to File”. This takes response data and convert to csv file. Added the options for enabling the header row and providing the delimiter type and the file name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*duEm8cFHti7OjNLJ8e4GvQ.png" /></figure><p>6. <strong>Saving to Local Disk</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ue1PvLTXhviIuqKbXnmsIg.png" /></figure><p>In the next step we write the csv file to the local file system with “Read/Write files from disk”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYS2FGMvcDCtHHGM6DUfkw.png" /></figure><p>7. <strong>The ‘Smart’ Optimization (Schema Hashing)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zskh3wUQHShMIoW5pQBAog.png" /></figure><p>Here is the cost-saving trick. Generating Python code with an LLM is expensive and slow. We don’t want to rewrite the script if the data hasn’t changed.</p><ul><li><strong>Fingerprint:</strong> I use a Code Node to read the CSV headers…</li><li><strong>The Cache Check:</strong> n8n checks my disk…</li><li><strong>The Decision: (A) Yes:</strong> Reuse existing script ($0 cost). (B) <strong>No:</strong> Wake up the AI to write a new one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljqhKUKoJvez4rxXRXSUMA.png" /></figure><p>8. <strong>The Cache Check</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-zVOSmb7JDKF0un6jhNGw.png" /></figure><p>The execute command node checks for the file presence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gu9uDRWGdn48X8VrxAA96g.png" /></figure><p>9. <strong>The Branching Logic</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dRJw08vu1Z1RR7VmOkm8sg.png" /></figure><p>If the file is NOT present, the ‘Execute Command’ node returns an error. The subsequent ‘If’ node detects this error and routes the workflow to the ‘False’ path, triggering the AI to generate the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nbY4iRPbpz08ccUU38mig.png" /></figure><p>On the first run, the file is not present, so the false condition is met and the gemini node for creating the python code gets generated.</p><p>10. <strong>The Engineer Agent (Python Generation)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNpQck9fVd2aCmKfkB_geQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5dECWPd-bPpViitdfpURA.png" /></figure><p>If we encounter a new schema (e.g., ‘Products’ instead of ‘Users’), this node acts as the <strong>Data Engineer</strong>. It writes a custom Snowpark script on the fly. Notice the prompt rule: option(&#39;infer_schema&#39;, True). This ensures the script adapts to whatever columns the CSV contains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*Ys9NSRlhnkwaqzqmXCMrRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*ZEVRheoOYYQ99LAfPG7_5Q.png" /></figure><p>Here is the actual code the ‘Engineer Agent’ wrote for me automatically. Notice how it correctly inferred the schema and handled the Snowflake connection:</p><pre>You are an expert Python Data Engineer using the &#39;snowflake-snowpark-python&#39; library.<br><br>### Your Mission<br>Write a complete, executable Python script to load a CSV file into Snowflake. The script must be self-contained and ready to run.<br><br>### Input Data<br>- Source: &#39;/Users/rumasinha/Documents/high_revenue_users.csv&#39;<br>- Target Table: &#39;ANALYSIS_RESULT&#39;<br><br>### Critical Engineering Requirements<br>1. **Schema Inference:** Do NOT hardcode columns. You must use `option(&quot;infer_schema&quot;, True)` and `option(&quot;parse_header&quot;, True)` so the script adapts to ANY csv structure automatically.<br>2. **Stage Management:**<br>   - Create a temporary stage named &#39;n8n_dynamic_stage&#39;.<br>   - **CRITICAL SYNTAX RULE:** When running the SQL `CREATE STAGE`, do NOT use the &#39;@&#39; symbol. (e.g., `CREATE STAGE my_stage`).<br>   - When referencing the stage in `PUT` or `read`, you MUST use the &#39;@&#39; symbol (e.g., `@my_stage`).<br>3. **Execution:** Use `mode=&quot;overwrite&quot;` to replace the table data each time.<br><br>### Credentials<br>When writing the script, use exactly these connection parameters:<br>connection_parameters = {<br>    &quot;account&quot;: &quot; &quot;, <br>    &quot;user&quot;: &quot; &quot;,<br>    &quot;password&quot;: &quot; &quot;,<br>    &quot;role&quot;: &quot;ACCOUNTADMIN&quot;,<br>    &quot;warehouse&quot;: &quot;COMPUTE_WH&quot;,<br>    &quot;database&quot;: &quot;SNOWFLAKE_LEARNING_DB&quot;,<br>    &quot;schema&quot;: &quot;PUBLIC&quot;<br>}<br><br>### Output<br>Return ONLY the raw Python code. Do not wrap in markdown.</pre><p>11. <strong>Cleaning the Code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cfg66e3mKteqwwtKUstt3A.png" /></figure><p>The code node gets the text from Gemini and Clean Markdown (Remove ```python and ```).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e22pMQKsfjM5n4v5-O7fag.png" /></figure><p>12. <strong>Saving the Script</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cfg66e3mKteqwwtKUstt3A.png" /></figure><p>The python file is written to disk with the Read/Write to disk node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*JadYciElx4jcuu8Xgpu4wQ.png" /></figure><p>Once this node gets executed, the file is written to the path as mentioned.</p><p>13. <strong>Executing the Load</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TVmaIFLdqt8-Xngx5hJaQg.png" /></figure><p>Finally, n8n triggers the local Python worker. Because we are using <strong>Snowpark</strong>, the heavy lifting (creating stages, bulk loading) happens on the Snowflake cloud, not on my local laptop.</p><pre>from snowflake.snowpark import Session<br>import os<br><br># Define connection parameters<br>connection_parameters = {<br>    &quot;account&quot;: &quot;&quot;, <br>    &quot;user&quot;: &quot;&quot;,<br>    &quot;password&quot;: &quot;&quot;,<br>    &quot;role&quot;: &quot;ACCOUNTADMIN&quot;,<br>    &quot;warehouse&quot;: &quot;COMPUTE_WH&quot;,<br>    &quot;database&quot;: &quot;SNOWFLAKE_LEARNING_DB&quot;,<br>    &quot;schema&quot;: &quot;PUBLIC&quot;<br>}<br><br># Define input/output paths and names<br>local_csv_path = &#39;/Users/rumasinha/Documents/high_revenue_users.csv&#39;<br>target_table_name = &#39;ANALYSIS_RESULT&#39;<br>stage_name = &#39;n8n_dynamic_stage&#39;<br><br>session = None<br>try:<br>    # 1. Create a Snowpark Session<br>    print(&quot;Attempting to create Snowpark session...&quot;)<br>    session = Session.builder.configs(connection_parameters).create()<br>    print(&quot;Snowpark session created successfully.&quot;)<br>    print(f&quot;Current database: {session.get_current_database()}, schema: {session.get_current_schema()}&quot;)<br><br>    # 2. Stage Management - Create a temporary stage<br>    # CRITICAL SYNTAX RULE: Do NOT use &#39;@&#39; in CREATE STAGE SQL<br>    create_stage_sql = f&quot;CREATE TEMPORARY STAGE {stage_name};&quot;<br>    print(f&quot;Executing SQL: {create_stage_sql}&quot;)<br>    session.sql(create_stage_sql).collect()<br>    print(f&quot;Temporary stage &#39;{stage_name}&#39; created.&quot;)<br><br>    # Upload the local CSV file to the temporary stage<br>    # CRITICAL SYNTAX RULE: Use &#39;@&#39; when referencing the stage in PUT<br>    print(f&quot;Uploading &#39;{local_csv_path}&#39; to &#39;@{stage_name}&#39;...&quot;)<br>    session.file.put(local_csv_path, f&quot;@{stage_name}&quot;, overwrite=True)<br>    print(f&quot;File &#39;{os.path.basename(local_csv_path)}&#39; uploaded to stage &#39;@{stage_name}&#39;.&quot;)<br><br>    # 3. Read CSV from the stage into a DataFrame with schema inference<br>    # CRITICAL SYNTAX RULE: Use &#39;@&#39; when referencing the stage in read<br>    print(f&quot;Reading CSV from &#39;@{stage_name}/{os.path.basename(local_csv_path)}&#39; with schema inference...&quot;)<br>    df = (<br>        session.read<br>        .option(&quot;infer_schema&quot;, True)  # Automatically infer column names and types<br>        .option(&quot;parse_header&quot;, True)  # Treat the first row as header<br>        .csv(f&quot;@{stage_name}/{os.path.basename(local_csv_path)}&quot;)<br>    )<br>    print(&quot;CSV data loaded into DataFrame with inferred schema:&quot;)<br>    df.show(3) # Show first 3 rows and inferred schema<br><br>    # 4. Write the DataFrame to the target table in Snowflake<br>    print(f&quot;Writing DataFrame to table &#39;{target_table_name}&#39; with &#39;overwrite&#39; mode...&quot;)<br>    df.write.mode(&quot;overwrite&quot;).save_as_table(target_table_name)<br>    print(f&quot;Data successfully loaded into table &#39;{target_table_name}&#39;.&quot;)<br><br>    # Verify the load by selecting from the table<br>    print(f&quot;Verifying data in &#39;{target_table_name}&#39;:&quot;)<br>    result_df = session.table(target_table_name)<br>    result_df.show(5) # Show first 5 rows of the target table<br>    print(f&quot;Total rows in &#39;{target_table_name}&#39;: {result_df.count()}&quot;)<br><br>except Exception as e:<br>    print(f&quot;An error occurred: {e}&quot;)<br>finally:<br>    # Close the Snowpark session<br>    if session:<br>        print(&quot;Closing Snowpark session...&quot;)<br>        session.close()<br>        print(&quot;Snowpark session closed.&quot;)</pre><p>In the next run onwards, if the csv header does not change then the gemini node for creating the python file does not get invoked and the already generated code is reused to load the data.</p><p><strong>The Snowflake database and table:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9p3DONOuFWWph5jOY6SbQ.png" /><figcaption>Snowflake schema</figcaption></figure><p>By combining the creativity of Generative AI with the reliability of Python scripts, we’ve built a pipeline that is flexible, robust, and cost-effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9245ea27a2fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What if you could describe your entire development workflow in plain English and watch as an AI…]]></title>
            <link>https://rumasinha.medium.com/what-if-you-could-describe-your-entire-development-workflow-in-plain-english-and-watch-as-an-ai-1aa215c5901b?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa215c5901b</guid>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 01:25:37 GMT</pubDate>
            <atom:updated>2025-11-23T01:25:37.514Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Building, Containerizing, and Deploying a FastAPI App with Google Antigravity and Gemini 3 Pro</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-HBn9-SqlvBF4ih7JF2qpg.jpeg" /><figcaption>Photo by Kevin Bessat on Unsplash</figcaption></figure><p>What if you could describe your entire development workflow in plain English and watch as an AI agent builds, containerizes, and deploys your application autonomously? Google’s new agentic development platform, powered by Gemini 3 Pro, transforms constant context-switching into high-level delegation. In this walkthrough, we’ll test its full capabilities by having an autonomous agent scaffold a FastAPI app, containerize it with Docker, deploy it to Minikube — all while we observe and approve.</p><h3>The Agent-First Revolution</h3><p>For years, developers have been promised AI-powered assistance. We got intelligent auto-complete, helpful code explanations, and chatbot companions. While useful, these tools kept the human developer firmly in the pilot’s seat, managing a complex cockpit of tools: the editor, the terminal, the browser, and the cloud console.</p><p>This intricate dance of manual context-switching — write code, run a command, check the browser, switch to a deployment manifest, execute Kubernetes commands, check status — represents the true friction point in modern development. It’s the metaphorical “gravity” that slows down the software lifecycle.</p><h3>Escaping Code Gravity</h3><p>We’re now entering the era of agent-first development, and Google Antigravity is leading the charge. This platform isn’t just an AI assistant that serves up code snippets; it’s an AI agent capable of taking complex, multi-step instructions, formulating detailed plans, and executing them autonomously across your entire development environment.</p><p>Antigravity’s mission is to “lift” the burden of manual execution, allowing developers to operate at the level of high-level intent rather than low-level commands. The question is: can it deliver?</p><h3>Defining Antigravity: The Agentic IDE</h3><p>Google Antigravity is a unified, agentic development platform built on an interface that will feel familiar to anyone who uses VS Code. Its core innovation lies in granting foundational models like Gemini 3 Pro access to and control over the three pillars of a developer’s workflow:</p><p><strong>The Editor: </strong>Writing, modifying, and reviewing code.<br> <strong>The Terminal: </strong>Running commands, installing dependencies, and interacting with the system (like Docker or kubectl).<br> <strong>The Browser: </strong>Visually verifying application behavior and testing endpoints.</p><p>The result? A development experience where you delegate full, end-to-end tasks to the agent, which then produces transparent artifacts — the code, terminal output, and verification screenshots — for you to review and approve.</p><p>The antigravity once installed the IDE looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rxryo_fHtf6CTpxbf8JI_A.png" /></figure><p>This is the Editor window where we’ll develop code with agent-assisted coding. Let’s see how this plays out.</p><h3>The Challenge: A Complete DevOps Pipeline</h3><p>To truly test the mettle of this agent-first environment, we’re not asking it to solve a trivial problem. We’re delegating a complex, modern software lifecycle that touches every major developer tool. Our Antigravity agent will complete the following integrated pipeline:</p><p>· FastAPI Development: Scaffold a simple “Hello World” application</p><p>· Docker Containerization: Create the Dockerfile, build the image, and test locally</p><p>· Minikube Deployment: Generate Kubernetes manifests and deploy to a local cluster</p><h3>Step 1: FastAPI Development</h3><p>Let’s begin by giving Antigravity our first high-level instruction: create a FastAPI application. We provide the task details and click the blue action button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVYyiSrN8jeCRD_sVXFsDg.png" /></figure><p>The agent springs into action, generating a substantial amount of output — project structure, application code, configuration files, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bIOY-9h0ZzZJNcQCr_S6Q.png" /></figure><p>Now comes the crucial human-in-the-loop moment: we review each generated file. If everything looks good, we click “Accept.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*Iy7Fy1YdN06_oOYqiCBBbg.png" /></figure><h3>Local Testing</h3><p>With our files accepted, it’s time to install dependencies and test locally. We navigate to our project directory and install the requirements:</p><p>Next, we ask the agent to provide a simple test script. It generates test_main.py and appends the necessary testing dependencies to requirements.txt.</p><pre>cd fastapi_hello_world<br>pip install -r requirements.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*AwKhuDPRnuVmsZd3VW1eNQ.png" /></figure><p>test_main.py file gets created.</p><p>requirements.txt appended with :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*XlohZ9lT_mJ6j2v62zxpXg.png" /></figure><p>On running</p><pre>python test_main.py</pre><p>there is no output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*FweVaJTCMFXNT5ItxHL7xw.png" /></figure><p>The updated file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*lZn6rO687V5ucEaa25ZIyg.png" /></figure><pre>python test_main.py</pre><p>provided the output as shown below which confirms pytest ran the test case successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULovv5887zNfPSy0H43MCA.png" /></figure><h3>Step 2: Docker Containerization</h3><p>Now for the containerization phase. We instruct the agent to create a Docker setup, and it generates both a Dockerfile and a .dockerignore file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*nemSej6xZV06fNl_5njmYw.png" /></figure><p>the docker file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*fSfBvrVxracTxaE5u4-jSA.png" /></figure><p>after reviewing we accept the file.</p><p>.dockerignore file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_A7JAAQe12n9X_KKngUiw.png" /></figure><pre>docker build -t fastapi-hello-world .</pre><p>The docker desktop need to be running. Once the docker build is successful we will find the container image in the docker desktop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZwdMeCyFasdkqs6AOquVg.png" /></figure><p>Lets test the container before we deploy.</p><pre>docker run -p 8000:8000 fastapi-hello-world</pre><p>we get INFO: Uvicorn running on <a href="http://0.0.0.0:8000/">http://0.0.0.0:8000</a> (Press CTRL+C to quit)</p><p>on clicking <a href="http://0.0.0.0:8000:">http://0.0.0.0:8000:</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*qMLl8mHXGxpZOALvbd_6MA.png" /></figure><h3>Step 3: Minikube Deployment</h3><p>Deploying our containerized application to Kubernetes using Minikube. The agent generates our Kubernetes manifest file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*7QJnDSQJLMuTc1AiH-U01w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*qmd5giZirhGEuZfYGvhYjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QWP35Wqz228fMu0tUTvvQ.png" /></figure><p>After reviewing and accepting the changes, we follow the deployment steps:</p><ol><li>from mac terminal, run <strong><em>minikube start</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJwBKo_fLbEpOrKndmU7Nw.png" /></figure><p>2. Since the image built locally, the image need to be loaded into Minikube’s docker daemon with the command:</p><pre>minikube image load fastapi-hello-world</pre><p>3. Apply the configuration.</p><pre>kubectl apply -f k8s-deployment.yaml<br><br>the output:<br>deployment.apps/fastapi-hello-world-deployment created<br>service/fastapi-hello-world-service created</pre><p>4. Access the service.</p><pre>minikube service fastapi-hello-world-service</pre><p>The output:</p><p>When we run the service command, Minikube exposes our application, and we can access it through the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kprsRTi5ifPQbHhhYe20rA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*nBSJxUDp0hBe8AxAq2d3Sg.png" /></figure><h3>Exploring the Dashboard</h3><p>Curious about visualization options, we ask the agent if there’s a dashboard to monitor our running pods. It confirms that Minikube includes a dashboard. We launch it from the terminal. The Kubernetes dashboard opens, providing a visual interface showing our deployment, pods, services, and overall cluster health.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*I9y6nxi1EaB4eaWU59J8TA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNAGBnJYds9YU1FmCtGdsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*add8-nQXzNc93ym5OJK0kA.png" /></figure><h3>Conclusion: The Promise and Reality of Agentic Development</h3><p>What we’ve just completed would typically require juggling multiple tools, terminals, and documentation pages. With Google Antigravity and Gemini 3 Pro, we delegated the entire pipeline — from scaffolding to deployment — while maintaining control through review and approval checkpoints.</p><p>The agent-first paradigm doesn’t eliminate the developer; it elevates them. Instead of executing commands, you’re orchestrating systems. Instead of context-switching, you’re validating outcomes. The “gravity” of manual execution has been lifted, allowing you to focus on architecture, design decisions, and business logic.</p><p>Is this the future of software development? Based on this walkthrough, it’s clear that agentic development platforms like Antigravity are more than just hype — they’re a fundamental shift in how we build software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa215c5901b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with News Category Classification]]></title>
            <link>https://rumasinha.medium.com/getting-started-with-news-category-classification-20ab160ec9d6?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/20ab160ec9d6</guid>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 01:20:53 GMT</pubDate>
            <atom:updated>2025-08-09T01:20:53.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dBMkSsuru5QWaCeg" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybishop?utm_source=medium&amp;utm_medium=referral">Jeremy Bishop</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the age of information, the ability to automatically categorize news articles is a powerful tool for search engines, news aggregators, and data analysts. This process, known as news category classification, falls under the umbrella of natural language processing (NLP) and machine learning. In this article, we’ll walk through a foundational Python script that demonstrates how to load, preprocess, and prepare a news dataset for such a task.</p><p>Kaggle News Category Classification dataset, is provided in a JSON format where each line represents a single news article. Before we can build a machine learning model, we need to handle the data loading and cleaning.</p><p><strong>Loading and Preprocessing the Data:</strong></p><pre># Read the JSON file line by line (each line is a separate JSON object)<br>    data = []<br>    with open(json_file_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>        for line in file:<br>            try:<br>                data.append(json.loads(line.strip()))<br>            except json.JSONDecodeError:<br>                continue  # Skip malformed lines<br><br>    # Convert to DataFrame<br>    df = pd.DataFrame(data)<br><br>    # Ensure required columns exist<br>    if &#39;short_description&#39; not in df.columns or &#39;headline&#39; not in df.columns:<br>        raise ValueError(&quot;Required columns &#39;short_description&#39; and &#39;headline&#39; not found in dataset&quot;)<br><br>    # Handle missing values<br>    df[&#39;short_description&#39;] = df[&#39;short_description&#39;].fillna(&#39;&#39;)<br>    df[&#39;headline&#39;] = df[&#39;headline&#39;].fillna(&#39;&#39;)<br><br>    # Combine text fields<br>    df[&#39;text&#39;] = df[&#39;short_description&#39;] + &#39; &#39; + df[&#39;headline&#39;]<br><br>    # Extract only the required columns<br>    final_df = df[[&#39;text&#39;, &#39;category&#39;]].copy()<br><br>    # Remove empty texts<br>    final_df = final_df[final_df[&#39;text&#39;].str.strip() != &#39;&#39;]</pre><p><strong>From Text to Numbers: Creating Sentence Embeddings</strong></p><p>Once we have our clean dataset, the next step is to transform the textual data into a numerical format that a machine learning model can understand. We can’t feed raw text directly into most algorithms. This is where the concept of sentence embeddings comes into play.</p><p>A sentence embedding is a dense vector representation of a sentence, where semantically similar sentences are mapped to nearby vectors in a high-dimensional space</p><pre>try:<br>        # Load a pre-trained sentence transformer model<br>        model = SentenceTransformer(&#39;all-mpnet-base-v2&#39;)<br><br>        # Convert the short_desc + headline into an embedding<br>        news_df[&#39;embeddings&#39;] = news_df[&#39;text&#39;].apply(lambda x: model.encode(x))<br><br>        print(news_df[[&quot;embeddings&quot;]].shape)<br><br>        # Shape of the first embedding (assuming all embeddings have the same length)<br>        print(np.shape(news_df[&#39;embeddings&#39;].iloc[0]))<br><br>        # Shape of the entire embedding field as a 2D array<br>        embeddings = np.stack(news_df[&#39;embeddings&#39;].values)<br>        print(embeddings.shape)<br><br>        # Display the first few rows<br>        print(news_df.head())<br>    except Exception as e:<br>        print(f&quot;An error occurred: {e}&quot;)<br>        import traceback<br>        traceback.print_exc()</pre><p>The dataset is a rich numerical representation of the news articles’ content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZurlcXsDg9_VCq8IX9NkQ.png" /></figure><p><strong>UMAP</strong></p><p>We’ve successfully converted our news articles into 768-dimensional vectors. While this is great for capturing the semantic richness of the text, working with such high-dimensional data can be computationally expensive and difficult to visualize. The “curse of dimensionality” can also impact the performance of some machine learning models.</p><p>To address this, we’ll use Uniform Manifold Approximation and Projection (UMAP). UMAP is a dimensionality reduction algorithm that is particularly effective at preserving the local and global structure of the data, making it an excellent choice for visualizing and preparing high-dimensional data for downstream tasks.</p><p>The below code transforms the 768-dimensional embeddings into a more manageable 20-dimensional space.</p><pre>try:<br>    # reduce the dimensionality of the embeddings<br>    # Initialize UMAP with the desired parameters<br>    reducer = UMAP(<br>        n_components=20,<br>        min_dist=0.0,<br>        metric=&#39;cosine&#39;,<br>        random_state=123<br>    )<br><br>    &quot;&quot;&quot;<br>    If your embeddings are stored in a pandas DataFrame column as df[&quot;embeddings&quot;], <br>    where each entry is a vector (e.g., a list or numpy array), you should first stack these into a <br>    2D numpy array before applying UMAP. You do not need to loop row by row—UMAP expects the entire matrix at once <br>    for efficiency and correctness<br>    <br>    &quot;&quot;&quot;<br>    # Stack embeddings into a 2D numpy array<br>    embedding_matrix = np.vstack(news_df[&quot;embeddings&quot;].values)<br><br>    # Perform dimensionality reduction<br>    reduced_embeddings = reducer.fit_transform(embedding_matrix)<br><br>    print(reduced_embeddings.shape[1])<br><br>    # Add reduced dimensions as new columns to the DataFrame<br>    for idx in range(reduced_embeddings.shape[1]):<br>        news_df[f&#39;umap_{idx+1}&#39;] = reduced_embeddings[:, idx]<br><br>    # Display the first few rows<br>    print(news_df.head())<br><br>    # Call the function to plot<br>    plot_reduced_embeddings(news_df)<br><br>except Exception as e:<br>    print(f&quot;An error occurred: {e}&quot;)<br>    import traceback<br>    traceback.print_exc()</pre><p><strong>Clustering and Topic Identification: Finding Patterns in the Data</strong></p><p>Using an unsupervised learning technique called clustering to discover patterns and themes that emerge from the text. For this, we’ll use <strong>HDBSCAN</strong>, a robust clustering algorithm that’s great at finding clusters of varying densities and identifying articles that don’t fit into any group (noise points).</p><p>After this step, each row in our news_df DataFrame now has a new column, let&#39;s call it cluster, with a numerical label indicating which group the article belongs to. The outlier articles are marked with -1. Visualizing these clusters on a UMAP plot helps confirm that the clustering is working as expected, with similar articles appearing close together and sharing the same color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwNovP_mGF5FhEspYdtgMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMT8aMjpn8S9ZfOvWcn8XQ.png" /></figure><p>The best parameters include a minimum cluster size of 80, minimum samples of 30, cluster selection epsilon of 0.4, using euclidean distance metric, and the ‘best’ algorithm with a leaf size of 40.</p><p>The final metrics show the analysis identified 19 clusters with 4588 noise points, achieving a noise ratio of 0.4588 (meaning about 46% of data points were classified as noise). The silhouette score of 0.5253243 indicates moderate cluster quality</p><h3>From Clusters to Meaningful Topics with BERTopic</h3><p>Simply having a cluster of articles isn’t enough; we need to understand what each cluster is actually <em>about</em>. This is where <strong>BERTopic</strong> comes in.</p><p>BERTopic is an incredibly powerful topic modeling framework that leverages the sentence embeddings we’ve already created. It follows a simple yet effective workflow:</p><ol><li><strong>Text to Embeddings:</strong> We already did this with SentenceTransformer.</li><li><strong>Embeddings to Reduced Dimensions:</strong> We did this with UMAP.</li><li><strong>Reduced Dimensions to Clusters:</strong> We just did this with HDBSCAN.</li><li><strong>Clusters to Topics:</strong> BERTopic takes the clusters identified by HDBSCAN and performs <strong>c-TF-IDF</strong> (class-based Term Frequency-Inverse Document Frequency).</li></ol><p>c-TF-IDF treats all documents within a single cluster as if they were one large document. It then calculates which words are most distinctive to that “mega-document” compared to all other clusters. The words with the highest c-TF-IDF scores become the keywords that define the topic.</p><p>The code below shows how we can instantiate a BERTopic model using the same components we’ve already prepared (the SentenceTransformer model, the UMAP reducer, and the HDBSCAN clusterer), ensuring perfect alignment between our steps.</p><p>The topic_info DataFrame provides a summary for each topic, including its size, representative words, and the numerical ID. By adding the bertopic_topic column to our main DataFrame, we can now easily analyze which documents belong to which topic.</p><pre>  try:<br>        topic_model = BERTopic(embedding_model=model, umap_model=reducer, hdbscan_model=clusterer)<br>        topics, probabilities = topic_model.fit_transform(news_df[&#39;text&#39;], reduced_embeddings)<br><br>        # Get the topic information and add it to our DataFrame<br>        topic_info = topic_model.get_topic_info()<br>        news_df[&#39;bertopic_topic&#39;] = topics<br><br>        print(&quot;BERTopic clustering complete.&quot;)<br>        print(topic_info.head(10))<br>        print(&quot;\nSample data with BERTopic cluster labels:&quot;)<br>        print(news_df.head())<br><br>    except Exception as e:<br>        print(f&quot;Error is {e}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjCHo2NlB6arxhrXuOjc9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*mpMGPe65Pki66HVsln3L0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*PwsZAF8_uS9o46Bx73PxQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*WVDX3GQ3gisqt-r1sOqa2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ddaXuS7wPpdcgW_fhjEeEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*acocZLR_FCsuJ7YphPWpdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2gNAoiGJcO-MxBm3SXCp8g.png" /></figure><p>The analysis discovered 26 distinct topics from a corpus of 9,388 documents.</p><p><strong>Topic 0 dominates the dataset</strong> with 1,594–1,705 documents (about 20% of the corpus), clearly focused on Donald Trump and politics. The word clouds and bar chart show “trump,” “donald,” “the,” “president,” and “he” as the most prominent terms, with 62.2% topic alignment indicating high coherence within this political theme.</p><p><strong>Topic 11 represents sports content</strong> with 285 documents, featuring terms like “nfl,” “game,” “bowl,” “football,” “super,” and “olympic,” showing the dataset contains substantial sports-related discussions.</p><p><strong>Identifying Meaningful Topic Names with LLM</strong></p><p>The BERTopic model, while excellent at discovering topics and providing a list of keywords, often leaves the final interpretation to the user. For a topic represented by keywords like [&#39;pandemic&#39;, &#39;virus&#39;, &#39;covid&#39;, &#39;health&#39;, &#39;vaccine&#39;], a human can easily infer the topic name &quot;COVID-19 Pandemic.&quot; However, automating this process is crucial for large-scale analysis.</p><p>This is where a locally-run Large Language Model (LLM) like Llama 3, accessed via Ollama, can be a powerful final step. We can “prompt” the LLM with the core information from each BERTopic cluster — the top keywords and a few representative document excerpts — and ask it to generate a concise, human-friendly name. This step enhances the entire pipeline by making the final output immediately understandable to a non-technical audience.</p><p>The process involves these steps:</p><ol><li><strong>Iterate Through Topics:</strong> Loop through each discovered topic (except for the outlier topic, -1).</li><li><strong>Gather Context:</strong> For each topic, collect its most important keywords (from BERTopic’s c-TF-IDF scores) and a small, diverse sample of the news articles belonging to that topic.</li><li><strong>Construct a Prompt:</strong> Craft a clear and specific prompt for the LLM. The prompt should instruct the model to act as a text summarizer and generate a single, concise phrase that captures the essence of the provided keywords and sample texts.</li><li><strong>Query the LLM:</strong> Send the prompt to the local Ollama server, specifying the model (e.g., llama3.2:3b) and a low temperature to ensure a factual, non-creative response.</li><li><strong>Store the Results:</strong> The LLM’s response — the generated topic name — is then stored in a dictionary, mapping the numerical topic ID to the new, descriptive name.</li></ol><pre>prompt = f&quot;&quot;&quot;You are an expert topic analyst. Your task is to create a concise, meaningful topic name based on the provided keywords and sample texts.<br><br>**Keywords:** {keywords_str}<br><br>{sample_text_part}<br><br>**Instructions:**<br>1. Analyze the keywords and sample texts to understand the main theme<br>2. Create a topic name that is:<br>   - Concise (2-4 words maximum)<br>   - Descriptive and specific<br>   - Professional and clear<br>   - Captures the essence of the topic<br>3. Return ONLY the topic name, nothing else<br>4. Do not include phrases like &quot;Topic:&quot;, &quot;The topic is:&quot;, etc.<br><br>**Examples:**<br>Keywords: technology, smartphone, apple, iphone, mobile → &quot;Mobile Technology&quot;<br>Keywords: politics, election, vote, candidate, campaign → &quot;Election Politics&quot; <br>Keywords: health, covid, vaccine, virus, pandemic → &quot;COVID Health&quot;<br><br>Topic Name:&quot;&quot;&quot;</pre><p>This automated topic naming ensures that the output of the entire unsupervised pipeline is not just a list of numbers and keywords, but a set of meaningful, labeled categories, ready for immediate use and interpretation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgOO27KN-4JjnLhI89ldww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qp40d3cHW9Z7dBkgp1nvxg.png" /></figure><p><strong>Political content dominates</strong> with “Trump Policy Disputes” leading at 1,594 documents (19.9%), followed by “Police Transgender Issues” with 1,130 documents (14.1%). These two political topics alone account for about one-third of the entire corpus, indicating a dataset heavily focused on contemporary political discourse and social issues.</p><blockquote><strong>Conclusion</strong></blockquote><blockquote>This article walked through a complete, end-to-end pipeline for unsupervised news category classification. We converted raw text into semantically rich embeddings, reduced their dimensionality with UMAP, and grouped them into coherent topics using HDBSCAN and BERTopic. Finally, we leveraged a local LLM to generate descriptive topic names — turning technical results into a powerful and easily interpretable solution.</blockquote><p><strong>Github code:</strong> <a href="https://github.com/rumsinha/Clustering/blob/master/text_clustering_with_hdbscan.py">https://github.com/rumsinha/Clustering/blob/master/text_clustering_with_hdbscan.py</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20ab160ec9d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Customer Segmentation: A Comprehensive Comparison of HDBSCAN, DBSCAN, and K-Means]]></title>
            <link>https://pub.towardsai.net/advanced-customer-segmentation-a-comprehensive-comparison-of-hdbscan-dbscan-and-k-means-ce3bcaa7f1a2?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce3bcaa7f1a2</guid>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[hdbscan]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 20:34:11 GMT</pubDate>
            <atom:updated>2025-12-16T13:59:38.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5rKlJKw9t-FP2M9jCClpw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@karsten116?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Karsten Winegeart</a> on <a href="https://unsplash.com/photos/an-aerial-view-of-a-car-on-barren-land-eDlJazs87fc?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Customer segmentation is a cornerstone of modern business strategy. By dividing a diverse customer base into distinct, homogeneous groups, companies can tailor their marketing efforts, product development, and customer service to maximize impact and efficiency. While traditional methods like K-Means are popular, they often struggle with the messy reality of real-world data, particularly when customer segments exhibit varying densities or contain significant outliers. Density-based methods like DBSCAN and HDBSCAN offer powerful alternatives.</p><p>In this comprehensive guide, we’ll walk through an end-to-end customer segmentation project using the popular Kaggle Mall Customer dataset, applying three prominent clustering algorithms: K-Means, DBSCAN (Density-Based Spatial Clustering of Applications with Noise), and HDBSCAN (Hierarchical Density-Based Spatial Clustering of Applications with Noise).</p><h3>Dataset Overview: Mall Customer Dataset</h3><p>The Mall Customer Dataset contains 200 customer entries with the following attributes:</p><ul><li><strong>CustomerID</strong>: Unique identifier for each customer</li><li><strong>Genre</strong>: Gender of the customer</li><li><strong>Age</strong>: Age of the customer</li><li><strong>Annual Income (k$)</strong>: Annual income in thousands of dollars</li><li><strong>Spending Score (1–100)</strong>: A score assigned by the mall, reflecting customer behavior and spending patterns</li></ul><p>Our primary objective is to identify distinct customer groups based on Age, Annual Income, and Spending Score.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.metrics import silhouette_score, silhouette_samples<br>from sklearn.cluster import KMeans, DBSCAN<br>from sklearn.neighbors import NearestNeighbors<br>import hdbscan<br>from kneed import KneeLocator<br>import warnings<br>import matplotlib.cm as cm<br><br>warnings.filterwarnings(&#39;ignore&#39;)<br><br># Load and examine the data<br>df = pd.read_csv(&#39;Mall_Customers.csv&#39;)<br><br>print(&quot;Original Data Head:&quot;)<br>print(df.head())<br>print(&quot;\nData Info:&quot;)<br>print(df.info())<br>print(&quot;\nMissing Values:&quot;)<br>print(df.isnull().sum())</pre><p>Output from initial data inspection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eE3jF65zcU4C3nQZ6ricQQ.png" /></figure><p><strong>Initial Findings</strong>: The dataset is clean with no missing values, making it ideal for clustering analysis.</p><h3>Feature Scaling: Essential for Distance-Based Clustering</h3><p>Clustering algorithms that rely on distance metrics (K-Means, DBSCAN, and HDBSCAN) are highly sensitive to feature scales. Features with larger numerical ranges can disproportionately influence distance calculations. To ensure equal contribution from each feature, we standardize our numerical features.</p><pre>features = [&#39;Age&#39;, &#39;Annual Income (k$)&#39;, &#39;Spending Score (1-100)&#39;]<br>X = df[features]<br><br>scaler = StandardScaler()<br>X_scaled = scaler.fit_transform(X)<br><br>print(&quot;\nScaled Data Sample (first 5 rows):&quot;)<br>print(pd.DataFrame(X_scaled, columns=features).head())</pre><p>Output from scaling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*06VFa06H0meFBON1409QJA.png" /></figure><h3>K-Means Clustering: The Centroid-Based Approach</h3><p>K-Means partitions data into k clusters by iteratively assigning points to the nearest centroid and updating centroids based on cluster means.</p><p><strong>Key Concepts:</strong></p><ul><li><strong>Centroid</strong>: The center of a cluster, calculated as the mean of all points in that cluster</li><li><strong>k</strong>: The number of clusters (must be specified beforehand)</li><li><strong>init=’k-means++’</strong>: Intelligent initialization strategy for better convergence</li></ul><h3>Determining Optimal k: The Elbow Method</h3><p>Since K-Means requires pre-specifying k, we use the Elbow Method to find the optimal number of clusters by plotting Within-Cluster Sum of Squares (WCSS) against k values.</p><pre># Determine optimal number of clusters using Elbow Method<br>wcss = []<br>k_range = range(1, 11)<br><br>for k in k_range:<br>    kmeans = KMeans(n_clusters=k, init=&#39;k-means++&#39;, random_state=42, n_init=10)<br>    kmeans.fit(X_scaled)<br>    wcss.append(kmeans.inertia_)<br><br># Plot Elbow Method<br>plt.figure(figsize=(10, 6))<br>plt.plot(k_range, wcss, marker=&#39;o&#39;, linestyle=&#39;--&#39;)<br>plt.title(&#39;K-Means Elbow Method for Optimal Number of Clusters&#39;)<br>plt.xlabel(&#39;Number of clusters (k)&#39;)<br>plt.ylabel(&#39;WCSS (Within-Cluster Sum of Squares)&#39;)<br>plt.grid(True, linestyle=&#39;--&#39;, alpha=0.6)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UdhKkieR1oMdn1P5VE0sA.png" /></figure><p><strong>Interpretation</strong>: The elbow typically occurs around k=5 for this dataset, indicating five distinct customer segments.</p><h3>K-Means Implementation and Evaluation</h3><pre># Perform K-Means with optimal clusters<br>optimal_kmeans_clusters = 5<br>kmeans_model = KMeans(n_clusters=optimal_kmeans_clusters, init=&#39;k-means++&#39;, <br>                     random_state=42, n_init=10)<br>kmeans_clusters = kmeans_model.fit_predict(X_scaled)<br><br># Evaluate clustering quality<br>kmeans_silhouette_avg = silhouette_score(X_scaled, kmeans_clusters)<br>print(f&quot;K-Means Silhouette Score (k={optimal_kmeans_clusters}): {kmeans_silhouette_avg:.4f}&quot;)<br><br># Add cluster labels to original data<br>df[&#39;KMeans_Cluster&#39;] = kmeans_clusters<br><br># Calculate cluster characteristics<br>kmeans_cluster_means = df.groupby(&#39;KMeans_Cluster&#39;)[features].mean()<br>print(&quot;\nK-Means Cluster Characteristics:&quot;)<br>print(kmeans_cluster_means)<br>print(f&quot;\nCluster Distribution:\n{df[&#39;KMeans_Cluster&#39;].value_counts()}&quot;)</pre><p>Example Output from K-Means Clustering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xB-gmBqXWKPRNtH3bhHMdw.png" /></figure><p><strong>Results</strong>: Silhouette Score of 0.4166 indicates reasonably good cluster separation.</p><p>K-Means Visualizations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7o2hUKPpKK4BD5CvfDFUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GX7aSBCXQvcaPhx9wGqHSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tESd9H2Lpj4dDhbWtp7ABw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XB9xiqnQSuTBZ_ll5mtAgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptFGZBkoOVWF_A2ErPkcAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ub2V3fiznsfWRqR_wQe9QA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSfXqhh-Lr0vHxqmOI36ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HccsJYXYrxwALNVIwQlq-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rs8fPcYhQZ6vtoIzKo5I3Q.png" /></figure><h3>K-Means Customer Segmentation Analysis</h3><p>Based on comprehensive analysis of age, income, and spending behavior patterns, the K-means clustering algorithm identified five distinct customer segments with clear behavioral and demographic characteristics.</p><h3>Cluster Profiles</h3><p><strong>Cluster 0 — “Financially Constrained Middle-Aged”</strong><br> <em>Age: 46.2 years | Income: $26.8k | Spending Score: 18.3</em></p><p>This segment represents middle-aged customers facing significant financial constraints. With the lowest income level and minimal spending scores, these individuals likely include those experiencing economic hardship, working in lower-wage positions, or living on fixed incomes. Their purchasing behavior is driven primarily by necessity rather than discretionary wants, focusing on essential goods and services while avoiding non-essential expenditures.</p><p><strong>Cluster 1 — “Young Lifestyle Enthusiasts”</strong><br> <em>Age: 25.2 years | Income: $41.1k | Spending Score: 62.2</em></p><p>Young adults who demonstrate high spending propensity despite moderate income levels characterize this segment. These early-career professionals and young consumers prioritize lifestyle, experiences, and brand-conscious purchases. They represent a paradoxical spending pattern where discretionary purchases take precedence over traditional financial prudence, likely influenced by social media, peer pressure, and investment in personal image and experiences.</p><p><strong>Cluster 2 — “Affluent High-Performers”</strong><br> <em>Age: 32.9 years | Income: $86.1k | Spending Score: 81.5</em></p><p>This segment consists of successful young professionals in their prime earning years who combine high income with equally high spending behavior. These individuals have achieved significant career success early and possess both substantial disposable income and the confidence to spend freely. They represent ideal customers for premium products, luxury services, and high-value discretionary purchases across multiple categories.</p><p><strong>Cluster 3 — “Disciplined High Earners”</strong><br> <em>Age: 39.9 years | Income: $86.1k | Spending Score: 19.4</em></p><p>Despite having identical high income levels to Cluster 2, this segment demonstrates remarkably conservative spending patterns. These middle-aged high earners prioritize financial security, long-term planning, and wealth accumulation over immediate consumption. Their restrained spending likely reflects responsibilities such as mortgage payments, children’s education savings, retirement planning, or debt reduction strategies.</p><p><strong>Cluster 4 — “Mature Pragmatic Consumers”</strong><br> <em>Age: 55.6 years | Income: $54.4k | Spending Score: 48.9</em></p><p>The oldest demographic segment displays balanced, measured consumption patterns that reflect mature financial decision-making. With moderate income and spending levels, these consumers demonstrate practical purchasing behavior that balances current lifestyle needs with long-term financial stability. Their spending patterns likely reflect established preferences, quality-focused purchases, and consideration of approaching retirement.</p><h3>Strategic Implications</h3><p>These five clusters effectively segment the customer base along three critical dimensions: life stage progression, financial capacity, and spending behavioral patterns. Each segment represents distinct consumer archetypes with unique motivations, constraints, and purchasing triggers, providing valuable insights for targeted marketing strategies, product development, and customer relationship management initiatives.</p><p>The segmentation reveals that spending behavior cannot be predicted solely by income level, as evidenced by the stark contrast between Clusters 2 and 3, both high earners with completely different spending philosophies. Age and life stage considerations play equally important roles in determining consumer behavior patterns.</p><h3>DBSCAN: Density-Based Clustering with Noise Detection</h3><p>DBSCAN identifies clusters based on density and can discover arbitrarily shaped clusters while automatically detecting outliers.</p><p><strong>Key Parameters:</strong></p><ul><li><strong>eps (ε)</strong>: Maximum distance between two samples to be considered neighbors</li><li><strong>min_samples</strong>: Minimum number of samples required to form a dense region</li></ul><p><strong>Point Classifications:</strong></p><ul><li><strong>Core Point</strong>: Has at least min_samples within eps radius</li><li><strong>Border Point</strong>: Within eps of a core point but not core itself</li><li><strong>Noise Point</strong>: Neither core nor border point</li></ul><h3>Determining Optimal eps: The Knee Method</h3><pre># Find optimal eps using k-distance graph<br>min_samples = 5<br>neigh = NearestNeighbors(n_neighbors=min_samples)<br>nbrs = neigh.fit(X_scaled)<br>distances, indices = nbrs.kneighbors(X_scaled)<br><br># Sort distances to k-th nearest neighbor<br>distances = np.sort(distances[:, min_samples-1], axis=0)<br><br>plt.figure(figsize=(10, 6))<br>plt.plot(distances)<br>plt.xlabel(&#39;Points ordered by distance&#39;)<br>plt.ylabel(f&#39;Distance to {min_samples}th nearest neighbor&#39;)<br>plt.title(&#39;Knee Method for Optimal Epsilon (DBSCAN)&#39;)<br><br># Find knee point<br>knee = KneeLocator(range(len(distances)), distances, curve=&#39;convex&#39;, direction=&#39;increasing&#39;)<br>plt.axvline(x=knee.knee, color=&#39;r&#39;, linestyle=&#39;--&#39;, label=f&#39;Knee at index {knee.knee:.0f}&#39;)<br>plt.legend()<br>plt.show()<br><br>eps_optimal = distances[knee.knee]<br>print(f&quot;Optimal Epsilon: {eps_optimal:.4f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ae2xB3JjYeOextgO5-CM3g.png" /></figure><p>Optimal epsilon for minimus samples of 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*MOw0Gj46hstYn5EGlZ7Vxg.png" /></figure><h4>Initial DBSCAN Clustering with Knee Method Epsilon</h4><p>Let’s apply DBSCAN with these parameters and observe the initial results.</p><pre># Perform DBSCAN clustering with Knee Method suggested parameters<br>dbscan_knee = DBSCAN(eps=eps_knee, min_samples=5)<br>clusters_knee = dbscan_knee.fit_predict(X_scaled)<br><br># Add the cluster labels to the original data<br>df[&#39;DBSCAN_Knee_Cluster&#39;] = clusters_knee<br><br># Calculate the mean values for each cluster<br>dbscan_knee_cluster_means = df.groupby(&#39;DBSCAN_Knee_Cluster&#39;)[features].mean()<br><br># Display the cluster means<br>print(&quot;\nDBSCAN Cluster Means (Knee Method based):&quot;)<br>print(dbscan_knee_cluster_means)<br><br>print(f&quot;\nDBSCAN Knee Method Cluster Distribution:\n{df[&#39;DBSCAN_Knee_Cluster&#39;].value_counts()}&quot;)<br><br># Calculate Silhouette Score for Knee Method DBSCAN (excluding noise)<br>X_dbscan_knee_clustered = X_scaled[clusters_knee != -1]<br>labels_dbscan_knee_clustered = clusters_knee[clusters_knee != -1]<br><br>dbscan_knee_silhouette_score = np.nan<br>if len(np.unique(labels_dbscan_knee_clustered)) &gt;= 2:<br>    dbscan_knee_silhouette_score = silhouette_score(X_dbscan_knee_clustered, labels_dbscan_knee_clustered)<br>    print(f&quot;Silhouette Score for DBSCAN (Knee Method, excluding noise): {dbscan_knee_silhouette_score:.4f}&quot;)<br>else:<br>    print(&quot;Cannot calculate Silhouette Score for DBSCAN (Knee Method): Less than 2 valid clusters found (excluding noise).&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jw016eRVFtlInEO1uJXBew.png" /></figure><p>Interestingly, using the knee method, DBSCAN identifies only one cluster and a noise cluster (-1). The noise count is 14. Remaining points are segmented in cluster 0.</p><h4>DBSCAN Hyperparameter Optimization</h4><pre># Grid search for optimal DBSCAN parameters<br>eps_values = np.linspace(0.3, 1.0, num=15)<br>min_samples_values = range(3, 15)<br><br>best_score = -1<br>best_params = {}<br>results = []<br><br>for eps in eps_values:<br>    for min_samples in min_samples_values:<br>        dbscan = DBSCAN(eps=eps, min_samples=min_samples)<br>        clusters = dbscan.fit_predict(X_scaled)<br>        <br>        # Calculate silhouette score (excluding noise)<br>        valid_clusters = clusters[clusters != -1]<br>        if len(np.unique(valid_clusters)) &gt;= 2:<br>            score = silhouette_score(X_scaled[clusters != -1], valid_clusters)<br>            results.append({<br>                &#39;eps&#39;: eps, <br>                &#39;min_samples&#39;: min_samples, <br>                &#39;silhouette_score&#39;: score,<br>                &#39;num_clusters&#39;: len(np.unique(valid_clusters)),<br>                &#39;noise_points&#39;: np.sum(clusters == -1)<br>            })<br>            <br>            if score &gt; best_score:<br>                best_score = score<br>                best_params = {&#39;eps&#39;: eps, &#39;min_samples&#39;: min_samples}<br><br>print(f&quot;Best DBSCAN Parameters: {best_params}&quot;)<br>print(f&quot;Best Silhouette Score: {best_score:.4f}&quot;)</pre><p>Example Output from DBSCAN Grid Search:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*pT6_dBx5s_-m8dHszPKxlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cM4M46KO52VtsAYFuoc9IQ.png" /></figure><p><strong>Optimal Results</strong>: eps=0.35, min_samples=8, Silhouette Score=0.7970</p><p>The number of clusters identified as 2 and a noise cluster. The noise cluster is having 175 points.</p><p>The cluster means as show below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5KAHjEm0Ar0O-4am0aKIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4SLQkPmiWiG0e7yC2NbAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpMtKuBEKiudoUz1aqXBmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAezYC6qu5wiPXS45yeZgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksWgPpdqLHURUlXahw1GUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1xWvywQtSnDCmwVpee-vw.png" /></figure><p>Looking at the DBSCAN clustering results, I can see a clear segmentation of the data into three distinct groups plus noise points. Here’s the analysis:</p><h3>Cluster Characteristics</h3><p><strong>Cluster -1 (Noise/Outliers)</strong></p><ul><li><strong>Age</strong>: 39.3 years (middle-aged)</li><li><strong>Income</strong>: $60.8k (moderate income)</li><li><strong>Spending Score</strong>: 50.4 (moderate spending)</li><li><strong>Distribution</strong>: Very wide age range (18–70) with high variability</li><li><strong>Interpretation</strong>: These are outlier customers who don’t fit the main behavioral patterns</li></ul><p><strong>Cluster 0 (Middle-aged Conservatives)</strong></p><ul><li><strong>Age</strong>: 48.5 years (older demographic)</li><li><strong>Income</strong>: $58.3k (moderate income)</li><li><strong>Spending Score</strong>: 46.5 (below-average spending)</li><li><strong>Distribution</strong>: Tightly clustered around age 47–50</li><li><strong>Interpretation</strong>: Established, financially conservative customers who spend cautiously despite having decent income</li></ul><p><strong>Cluster 1 (Young High-Spenders)</strong></p><ul><li><strong>Age</strong>: 21.5 years (young demographic)</li><li><strong>Income</strong>: $60.1k (moderate income)</li><li><strong>Spending Score</strong>: 51.2 (above-average spending)</li><li><strong>Distribution</strong>: Very tight age clustering around 18–25</li><li><strong>Interpretation</strong>: Young customers with relatively high disposable income who are willing to spend</li></ul><h3>Key Insights</h3><ol><li><strong>Age is the Primary Differentiator</strong>: The clusters are primarily separated by age rather than income. Both main clusters have similar income levels (~$58–60k) but very different ages and spending behaviors.</li><li><strong>Spending vs. Age Relationship</strong>: There’s a clear inverse relationship — younger customers (Cluster 1) spend more despite similar incomes, while older customers (Cluster 0) are more conservative spenders.</li><li><strong>Income Consistency</strong>: Interestingly, all clusters have similar income levels, suggesting that spending behavior is more influenced by life stage (age) than earning capacity.</li></ol><h3>Business Implications</h3><ul><li><strong>Cluster 0</strong>: Target with value-focused, practical products and conservative marketing</li><li><strong>Cluster 1</strong>: Target with trendy, lifestyle products and bold marketing campaigns</li><li><strong>Noise Points</strong>: Require individual analysis or specialized micro-segmentation strategies</li></ul><p>The clustering successfully identified two distinct customer personas based primarily on age-driven spending behaviors rather than income levels.</p><h3>HDBSCAN: Hierarchical Density-Based Clustering</h3><p>HDBSCAN extends DBSCAN by building a hierarchy of clusters and selecting the most stable ones, making it robust to varying cluster densities.</p><p><strong>Key Parameters:</strong></p><ul><li><strong>min_cluster_size</strong>: Minimum size for a cluster</li><li><strong>min_samples</strong>: Controls clustering conservativeness (defaults to min_cluster_size)</li></ul><h3>HDBSCAN Hyperparameter Tuning</h3><pre># HDBSCAN parameter optimization<br>param_grid = {<br>    &#39;min_cluster_size&#39;: [5, 10, 15, 20],<br>    &#39;min_samples&#39;: [None, 3, 5, 10]<br>}<br><br>best_score = -1<br>best_params = {}<br>results = []<br><br>for min_cluster_size in param_grid[&#39;min_cluster_size&#39;]:<br>    for min_samples in param_grid[&#39;min_samples&#39;]:<br>        hdbscan_model = hdbscan.HDBSCAN(<br>            min_cluster_size=min_cluster_size,<br>            min_samples=min_samples,<br>            prediction_data=True<br>        )<br>        <br>        clusters = hdbscan_model.fit_predict(X_scaled)<br>        valid_clusters = clusters[clusters != -1]<br>        <br>        if len(np.unique(valid_clusters)) &gt;= 2:<br>            score = silhouette_score(X_scaled[clusters != -1], valid_clusters)<br>            results.append({<br>                &#39;min_cluster_size&#39;: min_cluster_size,<br>                &#39;min_samples&#39;: min_samples,<br>                &#39;silhouette_score&#39;: score,<br>                &#39;num_clusters&#39;: len(np.unique(valid_clusters))<br>            })<br>            <br>            if score &gt; best_score:<br>                best_score = score<br>                best_params = {&#39;min_cluster_size&#39;: min_cluster_size, &#39;min_samples&#39;: min_samples}<br><br>print(f&quot;Best HDBSCAN Parameters: {best_params}&quot;)<br>print(f&quot;Best Silhouette Score: {best_score:.4f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDwQ-uFabvUVXgVchv6qvA.png" /></figure><p><strong>Optimal Results</strong>: min_cluster_size=10, min_samples=None, Silhouette Score=0.6319.</p><p>Applying the Best HDBSCAN Model and Initial Cluster Overview</p><pre># --- Apply HDBSCAN with Best Parameters and Get Final Clusters ---<br>if hdbscan_best_clusters_labels is not None:<br>    final_hdbscan_clusters = hdbscan_best_clusters_labels<br>else:<br>    # Fallback: re-run the model with the best_params if for some reason best_clusters_labels wasn&#39;t captured.<br>    print(&quot;\n--- Re-running HDBSCAN with best parameters to get final clusters (fallback) ---&quot;)<br>    final_hdbscan_model = hdbscan.HDBSCAN(min_cluster_size=hdbscan_best_params[&#39;min_cluster_size&#39;],<br>                                          min_samples=hdbscan_best_params[&#39;min_samples&#39;] if hdbscan_best_params[&#39;min_samples&#39;] is not None else hdbscan_best_params[&#39;min_cluster_size&#39;],<br>                                          prediction_data=True)<br>    final_hdbscan_clusters = final_hdbscan_model.fit_predict(X_scaled)<br><br># Add cluster labels to the original DataFrame<br>df[&#39;HDBSCAN_Cluster&#39;] = final_hdbscan_clusters<br><br>print(f&quot;\nNumber of HDBSCAN clusters found (including noise -1): {len(np.unique(final_hdbscan_clusters))}&quot;)<br>print(f&quot;Number of HDBSCAN noise points (-1 label): {np.sum(final_hdbscan_clusters == -1)}&quot;)<br>print(f&quot;HDBSCAN Cluster distribution:\n{df[&#39;HDBSCAN_Cluster&#39;].value_counts()}&quot;)<br><br># --- Explicitly calculate and display the Silhouette Score for the FINAL HDBSCAN clusters ---<br>X_hdbscan_clustered = X_scaled[final_hdbscan_clusters != -1]<br>labels_hdbscan_clustered = final_hdbscan_clusters[final_hdbscan_clusters != -1]<br><br>final_hdbscan_silhouette_score = np.nan<br>if len(np.unique(labels_hdbscan_clustered)) &gt;= 2:<br>    final_hdbscan_silhouette_score = silhouette_score(X_hdbscan_clustered, labels_hdbscan_clustered)<br>    print(f&quot;\nSilhouette Score for the FINAL HDBSCAN clusters: {final_hdbscan_silhouette_score:.4f}&quot;)<br>else:<br>    print(&quot;\nCannot calculate Silhouette Score for final HDBSCAN clusters: Less than 2 valid clusters found (excluding noise).&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*KLTfpAYN0yN6yGv0NPEJWQ.png" /></figure><p>Here, we observe 3 distinct clusters (0, 1, 2 in actual output) and a significant -1 cluster, which represents <strong>noise</strong>. The final Silhouette Score (0.6319) matches our best score, confirming consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlxL9n73kquxS2sNn9JuYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgkY_GY12PlxD0jsSZ0zXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqqcQ2NS0hTnnEUYAkMusg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUQQqRTQcFy7tx4dLh_Mvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DImt8H7C33zGRAY3hBEfiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ax4pC7f_caJ-tqUlTA5Mzw.png" /></figure><p>HDBSCAN clustering analysis, can see four distinct clusters have been identified based on age, annual income, and spending score. Let‘s’ break down what each cluster represents:</p><h3>Cluster Characteristics</h3><p><strong>Cluster 0 (Blue) — “High Spenders”</strong></p><ul><li>Age: ~33 years (youngest average)</li><li>Income: ~$79k (highest income)</li><li>Spending Score: ~81 (highest spending)</li><li>This represents young, high-income individuals with very high spending behavior</li></ul><p><strong>Cluster 1 (Orange) — “Young Moderate Spenders”</strong></p><ul><li>Age: ~23 years (youngest group)</li><li>Income: ~$59k (moderate income)</li><li>Spending Score: ~50 (moderate spending)</li><li>Young adults with moderate income and spending patterns</li></ul><p><strong>Cluster 2 (Green) — “Mature Conservative Spenders”</strong></p><ul><li>Age: ~52 years (oldest group)</li><li>Income: ~$54k (moderate income)</li><li>Spending Score: ~48 (moderate-low spending)</li><li>Older individuals with moderate income but lower spending</li></ul><h3>Noise Points (Gray):</h3><p>The gray points scattered throughout are outliers that don’t fit the main patterns — they could be:</p><ul><li>Customers with unusual combinations of age/income/spending</li><li>Data entry errors</li><li>Genuinely unique cases that don’t follow typical patterns</li></ul><h3>Key Insights</h3><ol><li><strong>Age-Spending Relationship</strong>: There’s a clear inverse relationship between age and spending score. Younger customers tend to spend more freely.</li><li><strong>Three Distinct Customer Segments Identified</strong>:</li></ol><ul><li><strong>Cluster 0</strong>: Premium customers (high income, high spending) — most valuable segment</li><li><strong>Cluster 1</strong>: Young moderate spenders — potential growth segment with room for increased engagement</li><li><strong>Cluster 2</strong>: Mature conservative spenders — underutilizing their purchasing power despite reasonable income</li></ul><p><strong>Target Segments for Marketing</strong>:</p><ul><li>Cluster 0 represents your premium customers requiring retention strategies</li><li>Clusters 1 and 2 could be targeted for spending increase campaigns</li></ul><p><strong>Cluster Quality</strong>: The scatter plot shows well-separated clusters with clear boundaries, indicating HDBSCAN successfully identified meaningful customer segments. The presence of noise points (gray) suggests either outliers with unique behaviors or potential data quality issues worth investigating.</p><p>This segmentation provides a solid foundation for targeted marketing strategies, with different approaches needed for each distinct customer group based on their age, income, and spending behaviors.</p><h3>Conclusion</h3><p>This comprehensive comparison demonstrates that algorithm choice significantly impacts segmentation outcomes. While HDBSCAN achieved the highest silhouette score, K-Means provided the most interpretable and actionable customer segments for business applications. The key is aligning algorithmic strengths with business objectives and data characteristics.</p><p>For customer segmentation projects, we start with K-Means for baseline insights, then exploring density-based methods when dealing with complex customer behaviors or significant outlier populations.</p><p>Github link: <a href="https://github.com/rumsinha/Clustering">https://github.com/rumsinha/Clustering</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce3bcaa7f1a2" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/advanced-customer-segmentation-a-comprehensive-comparison-of-hdbscan-dbscan-and-k-means-ce3bcaa7f1a2">Advanced Customer Segmentation: A Comprehensive Comparison of HDBSCAN, DBSCAN, and K-Means</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Classification]]></title>
            <link>https://rumasinha.medium.com/text-classification-1e81c83c6f68?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e81c83c6f68</guid>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 22:18:24 GMT</pubDate>
            <atom:updated>2025-06-15T22:18:24.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Text Classification with Embeddings and Logistic Regression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAbEEgCzBOLGB2fOS41aTQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lgnwvr?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">LOGAN WEAVER | @LGNWVR</a> on <a href="https://unsplash.com/photos/a-scenic-view-of-a-house-in-the-mountains-ZWkwOR8WJPI?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Text Classification with Embeddings and Logistic Regression</h3><p>Text classification is a fundamental task in Natural Language Processing (NLP), enabling machines to automatically categorize textual data. Applications range from spam detection and sentiment analysis to identifying authorship patterns. This article explores a practical approach to text classification using text embeddings and logistic regression, demonstrated through the Kaggle Spooky Author Identification dataset.</p><h3>Understanding the Approach</h3><p>Text embeddings transform raw text into numerical vectors that capture semantic meaning, while logistic regression provides a robust and interpretable classification framework. This combination offers several advantages:</p><ul><li><strong>Semantic Understanding</strong>: Embeddings capture contextual relationships between words</li><li><strong>Efficiency</strong>: Logistic regression trains quickly and requires minimal computational resources</li><li><strong>Interpretability</strong>: Results can be easily understood and explained</li><li><strong>Scalability</strong>: The approach works well with datasets of varying sizes</li></ul><h3>The Dataset: Spooky Author Identification</h3><p>The Spooky Author Identification dataset presents an intriguing classification challenge. It contains text excerpts from works by three renowned horror and mystery authors:</p><ul><li>Edgar Allan Poe</li><li>HP Lovecraft</li><li>Mary Wollstonecraft Shelley</li></ul><p>Our goal is to build a model that can accurately identify which author wrote a given text passage based solely on writing style and content patterns.</p><h3>Why Use Embeddings?</h3><p>Raw text data exists in an unstructured format that machine learning models cannot process directly. Traditional approaches like Bag-of-Words or TF-IDF vectors provide numerical representations but often sacrifice crucial semantic information — the actual meaning behind the words and their relationships.</p><p><strong>Embeddings</strong> address this limitation by transforming text into dense, fixed-length vectors that preserve semantic relationships between words and sentences. These vectors are generated using sophisticated pretrained models such as <strong>Sentence Transformers</strong>, which create powerful representations capable of capturing the nuanced meaning within sentences and paragraphs.</p><h3>Our Methodology Overview</h3><ol><li><strong>Data Preparation:</strong> Load the dataset containing literary excerpts from renowned authors along with their corresponding author labels</li><li><strong>Embedding Generation:</strong> Transform text excerpts into vector embeddings using a pretrained Sentence Transformer model</li><li><strong>Model Training:</strong> Train a logistic regression classifier using these semantic embeddings as features</li><li><strong>Evaluation:</strong> Assess model performance on a held-out test set through comprehensive classification metrics and confusion matrix analysis</li></ol><h3>Step 1: Understanding the Dataset</h3><p>The Spooky Author Identification dataset presents a fascinating literary classification challenge. It contains carefully curated text excerpts from three masters of horror and mystery literature:</p><ul><li><strong>Edgar Allan Poe</strong> — Master of gothic horror and psychological thriller</li><li><strong>H.P. Lovecraft</strong> — Pioneer of cosmic horror and weird fiction</li><li><strong>Mary Shelley</strong> — Creator of Frankenstein and gothic romance</li></ul><p>Our objective is to develop a model capable of identifying authorship based solely on writing style, vocabulary choices, and thematic elements present in each excerpt.</p><h3>Step 2: Generating Semantic Embeddings</h3><p>We leverage the <strong>sentence-transformers</strong> Python library, which provides access to state-of-the-art models like <strong>all-MiniLM-L6-v2</strong>. This model strikes an optimal balance between performance and efficiency, making it ideal for text classification tasks.</p><p>The transformation process converts each text excerpt into a 384-dimensional dense vector embedding. Unlike simple word counting methods, these embeddings encode rich semantic information including contextual relationships, thematic content, and stylistic patterns that distinguish one author’s work from another.</p><h3>Step 3: Training the Logistic Regression Classifier</h3><p>Logistic Regression serves as our classification backbone due to its interpretability and robust performance with high-quality features. While conceptually straightforward, it becomes remarkably powerful when paired with semantic embeddings that capture the true essence of the text.</p><p>Our training process involves splitting the dataset into training and test portions, fitting the logistic regression model on the training embeddings, and generating predictions on the test set. This approach ensures we can evaluate genuine predictive performance on unseen data.</p><h3>Step 4: Comprehensive Model Evaluation</h3><p>We assess our classifier’s performance through multiple complementary metrics:</p><p><strong>Classification Report:</strong> Provides detailed precision, recall, and F1-score statistics for each author, revealing how well the model distinguishes between different writing styles.</p><p><strong>Confusion Matrix:</strong> Offers visual insight into classification patterns, highlighting which authors the model tends to confuse and potentially revealing interesting stylistic similarities between writers.</p><h3>Results and Performance Analysis</h3><p>Our logistic regression model, powered by sentence embeddings, demonstrates impressive performance on the test set with strong accuracy and remarkably balanced results across all three authors. This balanced performance indicates that the model successfully learns distinctive features for each writer rather than simply memorizing the most frequent class.</p><p>The confusion matrix analysis reveals fascinating insights into literary similarities. Typical misclassifications often occur between authors who share thematic elements or stylistic approaches, such as the gothic atmosphere common to both Poe and Shelley, or the dark, atmospheric descriptions found in both Poe and Lovecraft’s works.</p><pre># Import required libraries<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from sentence_transformers import SentenceTransformer<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import classification_report, confusion_matrix<br><br>file_path = &#39;./data/spooky_author_data.csv&#39;<br><br>def load_and_prepare_data(filepath=file_path, test_size=0.2, random_state=42):<br>    &quot;&quot;&quot;Load dataset and split into train/test sets with stratification.&quot;&quot;&quot;<br>    df = pd.read_csv(filepath)<br>    return train_test_split(<br>        df,<br>        test_size=test_size,<br>        random_state=random_state,<br>        stratify=df[&#39;author&#39;]<br>    )<br><br>def generate_embeddings(texts, model_name=&#39;all-MiniLM-L6-v2&#39;):<br>    &quot;&quot;&quot;Generate sentence embeddings using SentenceTransformer.&quot;&quot;&quot;<br>    model = SentenceTransformer(model_name)<br>    print(f&quot;Encoding {len(texts)} texts...&quot;)<br>    return model.encode(texts, show_progress_bar=True)<br><br><br>def plot_confusion_matrix(y_true, y_pred, class_names):<br>    &quot;&quot;&quot;Visualize confusion matrix.&quot;&quot;&quot;<br>    cm = confusion_matrix(y_true, y_pred)<br>    plt.figure(figsize=(10, 8))<br>    sns.heatmap(<br>        cm,<br>        annot=True,<br>        fmt=&#39;d&#39;,<br>        cmap=&#39;Blues&#39;,<br>        xticklabels=class_names,<br>        yticklabels=class_names<br>    )<br>    plt.xlabel(&#39;Predicted Label&#39;)<br>    plt.ylabel(&#39;True Label&#39;)<br>    plt.title(&#39;Confusion Matrix&#39;)<br>    plt.tight_layout()<br>    plt.show()<br><br><br>def train_and_evaluate(X_train, X_test, y_train, y_test, class_names):<br>    &quot;&quot;&quot;Train logistic regression and evaluate performance.&quot;&quot;&quot;<br>    # Initialize and train classifier<br>    clf = LogisticRegression(max_iter=1000, random_state=42)<br>    clf.fit(X_train, y_train)<br><br>    # Make predictions<br>    y_pred = clf.predict(X_test)<br><br>    # Generate evaluation metrics<br>    print(&quot;\nClassification Report:&quot;)<br>    print(classification_report(y_test, y_pred, target_names=class_names))<br><br>    # Plot confusion matrix<br>    plot_confusion_matrix(y_test, y_pred, class_names)<br><br>    return clf<br><br>def main():<br>    # Step 1: Load and split data<br>    train_df, test_df = load_and_prepare_data()<br><br>    # Step 2: Generate embeddings<br>    X_train = generate_embeddings(train_df[&#39;text&#39;].tolist())<br>    X_test = generate_embeddings(test_df[&#39;text&#39;].tolist())<br><br>    # Step 3: Encode labels<br>    le = LabelEncoder()<br>    y_train = le.fit_transform(train_df[&#39;author&#39;])<br>    y_test = le.transform(test_df[&#39;author&#39;])<br><br>    # Step 4: Train and evaluate model<br>    _ = train_and_evaluate(X_train, X_test, y_train, y_test, le.classes_)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5hOQzH-LvFoNU_JJZB_Ow.png" /></figure><pre>Classification Report:<br>              precision    recall  f1-score   support<br><br>         EAP       0.71      0.75      0.73      1580<br>         HPL       0.71      0.68      0.69      1127<br>         MWS       0.74      0.70      0.72      1209<br><br>    accuracy                           0.72      3916<br>   macro avg       0.72      0.71      0.71      3916<br>weighted avg       0.72      0.72      0.72      3916</pre><p>Let’s break down the confusion matrix:</p><ul><li><strong>Rows (True Label):</strong> These represent the actual author of the text passages. For example, the top row shows texts that were <em>actually</em> written by Edgar Allan Poe (EAP).</li><li><strong>Columns (Predicted Label):</strong> These represent the author that our model <em>predicted</em> wrote the text. For example, the leftmost column shows texts that the model <em>predicted</em> were written by EAP.</li><li><strong>Diagonal Elements:</strong> The numbers along the main diagonal (from top-left to bottom-right) represent the <strong>correct classifications</strong>. These are instances where the model’s prediction matched the true author.</li><li>For <strong>EAP</strong>, the model correctly identified 1188 texts as belonging to Poe.</li><li>For <strong>HPL</strong>, 765 texts were correctly attributed to H.P. Lovecraft.</li><li>For <strong>MWS</strong>, 851 texts were correctly identified as Mary Wollstonecraft Shelley’s work.</li><li><strong>Off-Diagonal Elements:</strong> These are the most insightful, as they highlight the <strong>misclassifications (errors)</strong>.</li><li><strong>Poe vs. Lovecraft/Shelley:</strong> Looking at the “EAP” row, while 1188 Poe texts were correctly identified, 204 actual Poe texts were mistakenly attributed to H.P. Lovecraft, and 188 actual Poe texts were misclassified as Mary Shelley’s. This suggests some stylistic overlap that can trick the model.</li><li><strong>Lovecraft’s Challenges:</strong> For H.P. Lovecraft (HPL row), we see that 253 of his texts were incorrectly classified as EAP’s, and 109 were mistaken for MWS’s. This aligns with the slightly lower recall for HPL in our classification report (0.68), indicating the model found it a bit harder to identify all of Lovecraft’s works compared to the other authors. The significant number of HPL texts mistaken for EAP could point to shared themes of cosmic dread or gothic atmosphere.</li><li><strong>Shelley’s Misattributions:</strong> In the “MWS” row, 242 of Shelley’s texts were wrongly assigned to EAP, and 116 were attributed to HPL. This further emphasizes the stylistic parallels, particularly with Poe, likely due to their shared ground in gothic literature.</li></ul><p><strong>In essence, the confusion matrix visually confirms the “fascinating insights into literary similarities” we mentioned earlier.</strong> Typical misclassifications often occur between authors who share thematic elements or stylistic approaches, such as the gothic atmosphere common to both Poe and Shelley, or the dark, atmospheric descriptions found in both Poe and Lovecraft’s works. This visual tool not only validates our model’s overall accuracy but also provides actionable insights into its specific strengths and weaknesses in distinguishing between the unique voices of these literary masters.</p><p>Understand the Classification Report:</p><h4>Understanding the Metrics:</h4><p><strong>Precision:</strong></p><ul><li><strong>Definition:</strong> Precision answers the question: “Of all the instances predicted as this class, how many were actually correct?” It is the ratio of true positives to the sum of true positives and false positives.</li><li><strong>Formula:</strong> Precision = TP/(TP+FP)</li><li><strong>EAP (Edgar Allan Poe): 0.71</strong> — When the model predicted a text was written by EAP, it was correct 71% of the time.</li><li><strong>HPL (H.P. Lovecraft): 0.71</strong> — When the model predicted a text was written by HPL, it was correct 71% of the time.</li><li><strong>MWS (Mary Wollstonecraft Shelley): 0.74</strong> — When the model predicted a text was written by MWS, it was correct 74% of the time.</li></ul><p><strong>Recall (Sensitivity):</strong></p><ul><li><strong>Definition:</strong> Recall answers the question: “Of all the actual instances of this class, how many did the model correctly identify?” It is the ratio of true positives to the sum of true positives and false negatives.</li><li><strong>Formula:</strong> Recall = TP/(TP+FN)</li><li><strong>EAP: 0.75</strong> — Of all the texts actually written by EAP, the model correctly identified 75% of them.</li><li><strong>HPL: 0.68</strong> — Of all the texts actually written by HPL, the model correctly identified 68% of them.</li><li><strong>MWS: 0.70</strong> — Of all the texts actually written by MWS, the model correctly identified 70% of them.</li></ul><p><strong>F1-Score:</strong></p><ul><li><strong>Definition:</strong> The F1-score is the harmonic mean of precision and recall. It offers a single metric that balances the trade-off between the two, and is particularly valuable in imbalanced class scenarios where both false positives and false negatives carry significant weight.</li><li><strong>Formula:</strong> F1-Score = 2∗(Precision∗Recall)/(Precision+Recall)</li><li><strong>EAP: 0.73</strong> — This is a good balance between identifying EAP’s texts correctly (recall) and not misclassifying other authors as EAP (precision).</li><li><strong>HPL: 0.69</strong> — This is the lowest F1-score among the authors, suggesting a slightly weaker combined performance for HPL compared to the others. The lower recall (0.68) indicates the model missed identifying a relatively higher proportion of actual HPL texts.</li><li><strong>MWS: 0.72</strong> — A strong F1-score, indicating a good balance of precision and recall for MWS.</li></ul><p><strong>Support</strong> is the number of actual occurrences of each class in the test dataset.</p><p>The F1-scores around 0.7 suggest a good balance between correctly identifying an author’s text and avoiding misclassifications.</p><h3>Why This Approach Excels</h3><p>The synergy between embeddings and logistic regression creates a powerful classification framework:</p><p><strong>Semantic Richness</strong>: Embeddings capture the nuanced semantic context, thematic content, and stylistic patterns that define each author’s unique voice, going far beyond simple word frequency analysis.</p><p><strong>Computational Efficiency</strong>: Logistic regression provides rapid, interpretable classification that effectively leverages the rich feature representations from embeddings without requiring extensive computational resources.</p><p><strong>Practical Accessibility</strong>: This combination eliminates the need for fine-tuning large transformer models, making sophisticated NLP classification accessible to practitioners with limited computational budgets while maintaining high performance standards.</p><h3>Future Exploration Opportunities</h3><p><strong>Alternative Classifiers</strong>: Experiment with ensemble methods like Random Forests or Support Vector Machines to potentially capture different aspects of the embedding space and improve classification robustness.</p><p><strong>Advanced Fine-tuning</strong>: Fine-tune transformer models directly on the literary dataset to create domain-specific representations that might capture even more subtle authorial distinctions.</p><p><strong>Deep Learning Extensions</strong>: Explore neural architectures like multi-layer perceptrons or attention mechanisms if computational resources permit, potentially uncovering more complex patterns in authorial style.</p><p><strong>Feature Engineering</strong>: Investigate combining embeddings with traditional stylometric features like sentence length, punctuation patterns, or vocabulary richness metrics.</p><h3>Conclusion</h3><p>The combination of text embeddings with logistic regression represents a sweet spot in modern NLP applications, delivering the semantic understanding of contemporary language models with the interpretability and efficiency of classical machine learning. This approach successfully balances three critical factors: performance, computational efficiency, and model interpretability.</p><p>For practitioners seeking a robust baseline for text classification tasks, this methodology offers immediate practical value while serving as a solid foundation for more sophisticated approaches. Whether applied to authorship attribution, sentiment analysis, or document categorization, this framework demonstrates how thoughtful combination of modern and classical techniques can yield impressive results without excessive complexity or computational overhead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e81c83c6f68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text classification with LLM]]></title>
            <link>https://rumasinha.medium.com/text-classification-with-llm-00944c169ba0?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/00944c169ba0</guid>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 01:05:45 GMT</pubDate>
            <atom:updated>2025-06-09T01:06:27.719Z</atom:updated>
            <content:encoded><![CDATA[<p>Zero-Shot and Few-Shot Classification on the Spooky Author Dataset using LLaMA 3 and Ollama</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ax2pxw8AK6y52qB_oyuTSg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@karsten116?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Karsten Winegeart</a> on <a href="https://unsplash.com/photos/delicate-arch-stands-proudly-against-the-skyline-rdpsNWwhq8g?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>I wanted to see if I could classify sentences using <strong>Meta’s LLaMA 3 model</strong>, running on my computer with <strong>Ollama</strong>. The text came from <strong>Kaggle’s Spooky Author Identification dataset</strong>, which features short scary passages by <strong>Edgar Allan Poe</strong>, <strong>H.P. Lovecraft</strong>, and <strong>Mary Shelley</strong>.</p><p>This article will show you how I built a simple system to guess the author, using just prompts and local processing.</p><p>You can run LLaMA 3 locally on your system using Ollama, once Ollama is installed in the system.</p><p>Start the ollama server in the terminal.</p><blockquote>ollama serve</blockquote><p>import the needed libraries.</p><pre>import pandas as pd<br>import requests<br>from sklearn.metrics import classification_report, confusion_matrix, f1_score<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from tqdm import tqdm</pre><p>Load the data</p><pre>df = pd.read_csv(&#39;.../spooky_author_data.csv&#39;)  <br>df = df[[&#39;text&#39;, &#39;author&#39;]].dropna()<br>df = df.sample(1000, random_state=42).reset_index(drop=True)  </pre><p>The function takes a string and standardize to short specific code.</p><pre>def normalize_author_name(name):<br>    name = name.strip().lower()<br>    if &quot;poe&quot; in name:<br>        return &quot;EAP&quot;<br>    elif &quot;lovecraft&quot; in name:<br>        return &quot;HPL&quot;<br>    elif &quot;shelley&quot; in name:<br>        return &quot;MWS&quot;<br>    else:<br>        return &quot;Unknown&quot;</pre><p>Prompt engineering</p><p>Zero shot prompt template</p><pre>def build_zero_shot_prompt(text):<br>  return f&quot;&quot;&quot;<br>  Given the following sentence, classify the author as one of the following: <br>  Edgar Allan Poe, H.P. Lovecraft, or Mary Shelley.<br>  <br>  Sentence: &quot;{text}&quot;<br>  <br>  Author:<br>  &quot;&quot;&quot;.strip()</pre><p>Few shot prompt template</p><pre>few_shot_examples = df.groupby(&quot;author&quot;).head(1)<br>few_shot_prompt_base = &quot;\n&quot;.join(<br>    [f&#39;Sentence: &quot;{row.text}&quot;\nAuthor: {row.author}&#39; for _, row in <br>     few_shot_examples.iterrows()]<br>)<br><br>def build_few_shot_prompt(text):<br>    return f&quot;&quot;&quot;<br>You are a literary expert. Based on the writing style and vocabulary, <br>classify the author.<br><br>Examples:<br>{few_shot_prompt_base}<br><br>Now classify this:<br><br>Sentence: &quot;{text}&quot;<br>Author:<br>&quot;&quot;&quot;.strip()</pre><p>Query Ollama</p><pre>def query_ollama(prompt, model=&quot;llama3&quot;):<br>    try:<br>        response = requests.post(<br>            &quot;http://localhost:11434/api/generate&quot;,<br>            json={&quot;model&quot;: model, &quot;prompt&quot;: prompt, &quot;stream&quot;: False}<br>        )<br>        return response.json()[&quot;response&quot;].strip()<br>    except Exception as e:<br>        return str(e)</pre><p>Run Classification</p><pre>y_true = []<br>y_pred = []<br><br>for _, row in tqdm(df.iterrows(), total=len(df)):<br>    text = row[&#39;text&#39;]<br>    actual_author = row[&#39;author&#39;]<br><br>    prompt = build_few_shot_prompt(text) if use_few_shot <br>                  else build_zero_shot_prompt(text)<br><br>    result = query_ollama(prompt)<br>    predicted_author = normalize_author_name(result)<br><br>    y_true.append(actual_author)<br>    y_pred.append(predicted_author)</pre><p>Evaluation</p><pre># Classification Report &amp; Metrics<br>print(&quot;\nClassification Report:&quot;)<br>print(classification_report(y_true, y_pred, zero_division=0))<br><br>print(&quot;\nF1 Score (macro):&quot;, f1_score(y_true, y_pred, average=&#39;macro&#39;))<br><br># Confusion Matrix<br>cm = confusion_matrix(y_true, y_pred, labels=[&quot;EAP&quot;, &quot;HPL&quot;, &quot;MWS&quot;])<br><br>plt.figure(figsize=(6, 5))<br>sns.heatmap(cm, annot=True, fmt=&#39;d&#39;, xticklabels=[&quot;EAP&quot;, &quot;HPL&quot;, &quot;MWS&quot;], <br>             yticklabels=[&quot;EAP&quot;, &quot;HPL&quot;, &quot;MWS&quot;], cmap=&#39;Blues&#39;)<br>plt.xlabel(&#39;Predicted&#39;)<br>plt.ylabel(&#39;Actual&#39;)<br>plt.title(&#39;Confusion Matrix&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*BuagxM-JC3PRV1QwwHV6Xw.png" /></figure><ul><li><strong>Rows: “Actual” Authors:</strong> Each row represents the <em>true</em> author of the passage. For example, the top row shows all the passages that were actually written by EAP (Edgar Allan Poe).</li><li><strong>Columns: “Predicted” Authors:</strong> Each column represents the author our model <em>predicted</em> the passage was written by. So, the leftmost column shows all the passages our model predicted to be by EAP.</li><li><strong>The Numbers:</strong> The numbers within the matrix tell us the count of passages that fall into each category.</li></ul><p><strong>Correct Predictions (The Diagonal):</strong></p><ul><li><strong>EAP:</strong> Out of all the passages actually by EAP, our model correctly identified <strong>175</strong> as EAP.</li><li><strong>HPL:</strong> For passages actually by HPL, our model correctly predicted <strong>132</strong> as HPL.</li><li><strong>MWS:</strong> For passages truly by MWS, our model only correctly identified <strong>14</strong> as MWS.</li></ul><p><strong>Key Takeaways from this Matrix:</strong></p><ul><li>Our model performed <strong>best at identifying Edgar Allan Poe (EAP)</strong> and <strong>H.P. Lovecraft (HPL)</strong>, with a good number of correct predictions for both.</li><li>However, it had significant difficulty with <strong>Mary Shelley (MWS)</strong>. A large proportion of passages written by MWS were incorrectly attributed to EAP. This suggests that the model might find MWS’s writing style to be more similar to Poe’s than to Lovecraft’s, or it might be struggling to distinguish her from Poe in general.</li></ul><p>Classification Report</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*Q3hCP7XjDfmuHFBoYf4Gng.png" /></figure><p>A classification report is a performance evaluation metric in machine learning that shows the precision, recall, and F1-score for each class in a classification model, along with the overall accuracy.</p><p><strong>EAP (Edgar Allan Poe):</strong></p><ul><li><strong>Precision (0.48):</strong> When the model predicts “EAP,” it’s correct about 48% of the time.</li><li><strong>Recall (0.45):</strong> The model identifies about 45% of all actual “EAP” instances.</li><li><strong>F1-Score (0.47):</strong> This is a moderate score, indicating the model has some room for improvement in correctly identifying EAP.</li><li><strong>Support (390):</strong> There are 390 instances of “EAP” in the dataset.</li></ul><p><strong>HPL (H.P. Lovecraft):</strong></p><ul><li><strong>Precision (0.79):</strong> When the model predicts “HPL,” it’s right about 79% of the time, which is quite good.</li><li><strong>Recall (0.47):</strong> However, it only catches 47% of the actual “HPL” instances. This suggests the model is good at not misclassifying other authors as HPL, but it misses a significant portion of true HPL works.</li><li><strong>F1-Score (0.59):</strong> This is a respectable score, but the lower recall pulls it down.</li><li><strong>Support (280):</strong> There are 280 instances of “HPL.”</li></ul><p><strong>MWS (Mary Shelley):</strong></p><ul><li><strong>Precision (0.88):</strong> This is very high, meaning that when the model predicts “MWS,” it’s almost always correct (88% of the time).</li><li><strong>Recall (0.04):</strong> This is extremely low. The model is only identifying 4% of the actual “MWS” instances. This is a major issue! It means the model is hardly ever recognizing Mary Shelley’s works, even if the few times it does, it’s correct.</li><li><strong>F1-Score (0.08):</strong> Due to the abysmal recall, the F1-score is very low, highlighting poor performance for this class.</li><li><strong>Support (330):</strong> There are 330 instances of “MWS.”</li></ul><p>In summary, while the model shows good precision for “HPL” and “MWS,” its overall performance is hampered by very low recall for “MWS,” leading to a low overall accuracy.</p><p>We can try with refining the examples provided in the few shot template and also try with the chain of thought prompting.</p><p><strong>Final Thoughts</strong></p><p>This experiment shows the potential — and the current limitations — of using LLaMA 3 via Ollama for zero-shot and few-shot literary classification. While the model demonstrates strong precision, especially for distinct styles like Lovecraft’s, it struggles with recall — particularly for Mary Shelley — leading to lower overall effectiveness.</p><p>This result highlights a key insight: while prompt-based LLMs are powerful, they are not yet a full replacement for supervised learning when consistent and balanced performance across all classes is needed. However, for rapid prototyping, interpretability, and lightweight deployment, this approach remains a valuable tool in the NLP toolbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00944c169ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function calling]]></title>
            <link>https://medium.com/analytics-vidhya/function-calling-87c2d5851764?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/87c2d5851764</guid>
            <category><![CDATA[llm-function-calling]]></category>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 01:21:48 GMT</pubDate>
            <atom:updated>2025-03-10T02:08:43.483Z</atom:updated>
            <content:encoded><![CDATA[<p>Function calling with Gemini Pro Generative AI model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xY_VYwFR3Ii-0xQYZ-UvSQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alex__grig?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Alexander Grigoryev</a> on <a href="https://unsplash.com/photos/black-and-yellow-telephone-on-black-and-white-textile-BuFz9FvtsmY?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Function calling empowers large language models (LLMs) like Gemini Pro to interact with external tools, APIs, and databases, unlocking more dynamic and practical applications. Gemini Pro, developed by Google, excels at understanding and generating human-like text, answering questions, writing code, and tackling complex reasoning tasks.</p><p>Trained on vast amounts of data, Gemini Pro processes and generates text in a natural and intelligent way. Its ability to connect with external tools and APIs through function calling makes it even more powerful, allowing it to fetch real-time data, interact with databases, and automate tasks seamlessly.</p><p><strong>What is Function Calling in LLMs?</strong></p><p>Function calling allows LLMs like Gemini Pro to produce structured outputs that external systems can interpret as function calls. Instead of generating free-form text, the model outputs a structured JSON object representing an API request or an operation for a program to execute.</p><p>This capability is particularly valuable for:</p><ul><li>Retrieving real-time data (e.g., weather, stock prices, database queries)</li><li>Performing calculations and logical operations</li><li>Executing workflows that interact with external APIs</li></ul><p>In Gemini Pro, function calling enables the model to determine when a user request necessitates executing a function. It can:</p><ul><li>Identify the function to call</li><li>Determine the parameters to pass</li><li>Format the response using the function’s output</li></ul><h3>Why we need Function Calling</h3><p>Function calling enhances the accuracy, capability, and reliability of LLMs by enabling them to:</p><ul><li>Fetch real-time data</li><li>Execute actions</li><li>Interact with external systems</li></ul><p>This eliminates AI hallucinations, simplifies development by automating intent extraction, and bridges the gap between natural language and structured programmatic actions. Consequently, we can build safer, more powerful AI applications that seamlessly integrate with real-world workflows.</p><p>Function calling also facilitates obtaining structured data outputs from generative models. These outputs can then be used to call other APIs, with the relevant response data returned to the model. In essence, function calling connects generative models to external systems, ensuring that generated content includes the most current and accurate information.</p><p>By empowering users to interact with real-time information and services — such as databases, customer relationship management systems, and document repositories — function calling enhances the model’s ability to provide relevant and contextual answers.</p><p><strong>How Function Calling works in Gemini Pro</strong></p><p>Function calling allows the model to use external tools such as APIs and functions. When submitting a prompt to the LLM, you also provide the model with a set of tools that it can use to respond to the user’s prompt. For example, you could provide a function get_medium_article that takes a url parameter and returns information about the article content at the specified url.</p><p>The model does not call the functions directly. Instead, the model provides structured data output that includes the function to call and parameter values to use. For example, for a prompt “Fetch me the medium article from the provided url “<a href="https://medium.com/@rumasinha/the-journey-of-database-from-on-premise-to-cloud-2c99edce15ea">https://medium.com/@rumasinha/the-journey-of-database-from-on-premise-to-cloud-2c99edce15ea</a>”, the model can delegate processing to the get_medium_article function and provide the url parameter value “<a href="https://medium.com/@rumasinha/the-journey-of-database-from-on-premise-to-cloud-2c99edce15ea">https://medium.com/@rumasinha/the-journey-of-database-from-on-premise-to-cloud-2c99edce15ea</a>&quot;.</p><p>You can use the structured output from the model to invoke the function. For example, get_medium_article function can be invoked, providing the url “<a href="https://medium.com/@rumasinha/the-journey-of-database-from-on-premise-to-cloud-2c99edce15ea">https://medium.com/@rumasinha/the-journey-of-database-from-on-premise-to-cloud-2c99edce15ea</a>”, and fetch the article content.</p><p><strong>Using the Gemini API Function Calling feature</strong></p><p>You can provide custom function definitions to the model. The model doesn’t directly invoke these functions but generates structured output specifying a function name and suggested arguments. You then use this information to call an external API and incorporate the API output into a further query to the model, enabling more comprehensive responses and additional actions.</p><p>Using Google’s Gemini API, developers can define <strong>custom function schemas</strong> that the model can invoke when needed. The process typically involves:</p><ol><li><strong>Defining the function schema:</strong> Describe the function’s name, parameters, and expected output in JSON format.</li><li><strong>Passing user queries to Gemini Pro:</strong> The model decides whether a function call is needed.</li><li><strong>Receiving and executing the function call:</strong> The model outputs a structured function call, which the application processes.</li><li><strong>Returning the final response:</strong> The function’s output is integrated into a natural language response for the user.</li></ol><h3>Implementation example</h3><p>Let’s create a simple function that fetches medium article content based on the user prompt, using function calling:</p><p>Step 1: Import the needed libraries and define the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*oDo5YW5lqKGVmF3K6GrO1A.png" /></figure><p>Step2: Python function defined that takes the medium article URL as the argument, reads the text, performs basic cleaning, and returns the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNdkrwobL_B3Z-0vxSQWzQ.png" /></figure><p>Step3: The function declarations provide the name of the API function, explain its purpose, any parameters it supports, and descriptions of those parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRaTp_OVrLs9fy7B2EABZg.png" /></figure><p>Step4: The tool object contains one or more function declarations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-A_Ufw4PaNDBefbdMT5XfA.png" /></figure><p>Step5: Once function declaration is defined, the model can be prompted to use the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lf3jf3ZaYQOHk0fr4MSG7A.png" /></figure><p>The model then returns an object in an OpenAPI compatible schema specifying how to call one or more of the declared functions in order to respond to the user’s question. You can then take the recommended function call parameters, call the actual API, get a response, and provide that response to the user or provide the output as input to the next task.</p><p>Note that the model doesn’t actually call the declared functions. Instead, you use the returned schema object parameters to call the function. If the model determines that a function call is required, it returns a response with function details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aP6EqEyNm5ehcXFY14Eh5A.png" /></figure><p>Step5: Execute the Function call and return the response.</p><p>The function name along with argument names and corresponding values are fetched. The function is invoked with the argument value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kyAX00wCgIQhRdPdJI-9g.png" /></figure><p>Step6: Provide the output to the llm for the next task.For example, we might want the model to summarize the article and provide the response:</p><blockquote>prompt_suffix=”””Summarize the following text in 4–5 sentences:”””</blockquote><blockquote>prompt = f”{prompt_suffix}\n\n{text}”</blockquote><blockquote>response = model.generate_content(text)</blockquote><blockquote>response.text</blockquote><blockquote>summary = response.text.strip()</blockquote><blockquote>cleaned_text=re.sub(r’[^\w\s.,]’,’’,summary)</blockquote><blockquote>cleaned_text=re.sub(r’\s+’,’ ‘,cleaned_text)</blockquote><blockquote>cleaned_text.strip()</blockquote><p><strong>The flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEvIK5f7RMGhNGnhiBI9mQ.png" /></figure><h3>Working with multiple functions</h3><p>Let’s try the approach with multiple functions:</p><h3>Step 1: Define Python functions</h3><p>We’ll define three Python functions.</p><ul><li>calculate_area: Computes the area of a circle.</li><li>calculate_factorial: Computes the factorial of a number.</li><li>calculate_euclidean_distance: Computes the Euclidean distance between two points.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*yMDGP-Aoid6Cn-bhh8hBoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYEAPOaK43-7eIKz5fyDcg.png" /></figure><h3>Step 2: Create function declarations</h3><p>Each function declaration provides the name of the function, the purpose of the function, parameters, and whether the parameter is mandatory by providing the required property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E2hFXeLJmwinmzG5S28Qiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBk6Hym7gGFPCfTZqkUm8w.png" /></figure><p><strong>Step 3: Define the tool with all the functions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTZriTsJOfTPIXuaNuVEsw.png" /></figure><h3>Step 4: Test with various user inputs</h3><p>Let’s see the various user inputs and how the function call is returned as response by the LLM.</p><h4>Example 1: Calculating the area of a circle</h4><p>Based on the user prompt, the response clearly returns the function that needs to be invoked along with the parameter and value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IhTwS7PuClYSy8sZO_C0A.png" /></figure><p>We can fetch the function call name and arguments, then invoke the function with all the details to get the area of the circle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23t3Xz_Ptzvrpfu4sLvDuA.png" /></figure><h4>Example 2: Calculating factorial</h4><p>Next is fetching the factorial of a number based on the user prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*kog3tWL6xwaLbym9toI7ZA.png" /></figure><p>We fetch the function call and arguments, then execute the function with the details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIrkfi5y9lhD2f2CdqX8aw.png" /></figure><h4>Example 3: Calculating Euclidean distance</h4><p>The third function calculates the Euclidean distance for the given coordinates (x1,y1) and (x2,y2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bII9BIQhSRl6bUQJJIDEiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3zCLR06PoE-UKXBWvWkaA.png" /></figure><h4>Example 4: Multiple function invocation</h4><p>Let’s try a user prompt that invokes two functions from the tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTGZBav-x0YGJL0c7MWyFg.png" /></figure><p>We observe that even though the user requests two functions (one for Euclidean distance and the other for factorial), we can see only one function call returned in the response.</p><p>When we switch to the model gemini-1.5-pro-002 and try the same user prompt again:</p><p>model = GenerativeModel(“gemini-1.5-pro-002”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmQ0iOwsKw1ORtvxakqP5Q.png" /></figure><p>With the gemini-1.5-pro-002 model, we can see that both functions calculate_euclidean_distance and calculate_factorial are returned in the response.</p><p>We can fetch the function calls from the response in a list and loop through the list to execute the functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zDhi4317p5aeVlY28lVlNA.png" /></figure><p><strong>Example 5: Another multi-function user prompt</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdkyVJ9XfI8Dw--WMvQEow.png" /></figure><p>There are two parts in the response. Each part corresponds to one function call:</p><ul><li>Parts[0] is the function call for calculate_area</li><li>Parts[1] is the function call for calculate_factorial</li></ul><p>The sequence follows the sequence in the user prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*jTHHD9xrttF6JKphgjhP0Q.png" /></figure><p>Looping through the function list, we invoke each function with the corresponding arguments and return the response:</p><ul><li>The first function invoked is calculate_circle with radius=5. The result returned is 314.16</li><li>The second function invoked is calculate_factorial with the argument as 5. The result returned is 120</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RpP84boDRUpKme0rgoAHA.png" /></figure><h3>Conclusion</h3><p>This approach can be implemented in developing an application where we can define multiple functions, each executing one functionality. These functions are provided to the LLM by defining them as a tool. Based on the user prompt and the list of available functions, one or more functions are returned as part of the function call. These functions can then be executed in the same order. The response can then be passed as input to the next task.</p><h3>References</h3><ul><li><a href="https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling">Function calling in Vertex AI</a></li><li><a href="https://ai.google.dev/gemini-api/docs/function-calling">Gemini API function calling documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87c2d5851764" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/function-calling-87c2d5851764">Function calling</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Text Embeddings]]></title>
            <link>https://rumasinha.medium.com/understanding-text-embeddings-b6f2b5606641?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6f2b5606641</guid>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[semantic-similarity]]></category>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 03:51:34 GMT</pubDate>
            <atom:updated>2025-03-03T03:51:34.306Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What are embeddings?</strong></p><p>Embeddings are <strong>feature vector representations</strong> of text that capture semantic relationships. Words, sentences, and even images are transformed into <strong>high-dimensional vector spaces</strong>. Essentially, embeddings represent data as points in space.</p><p>Tokens, the individual pieces of text, are converted into vectors that encode their meaning. These vectors enable models to analyze relationships between words and perform computations. For example, if “word1” and “word2” have semantically related meanings, their corresponding embeddings will be close together in the vector space. If these embeddings are, for instance, 384-dimensional, the similarity between them can be measured within that 384-dimensional vector space.</p><p><strong>What are the applications of embeddings?</strong></p><p>Embeddings are widely used in various applications, including:</p><ul><li><strong>Semantic search</strong> — Finding relevant information based on meaning rather than exact word matches.</li><li><strong>Classification</strong> — Categorizing text into predefined labels.</li><li><strong>Clustering</strong> — Grouping similar documents or data points.</li><li><strong>Recommendations</strong> — Suggesting content based on similarity.</li><li><strong>Outlier detection</strong> — Identifying anomalies in data.</li></ul><p><strong>How do embeddings work?</strong></p><p>Embeddings encode words or data points into a <strong>continuous vector space</strong>, where semantically similar elements are positioned close to each other.</p><p><strong>Intuition behind vector representation</strong></p><p>Embeddings represent words, sentences, or documents as numerical vectors in a <strong>multi-dimensional space</strong>. The key idea is that similar words or concepts should have similar vector representations. Instead of treating words as isolated entities, embeddings capture their relationships based on how they appear in real-world language data.</p><p>Let’s walk through the process of generating embeddings using the pre-trained <strong>all-MiniLM-L6-v2</strong> model.</p><p>Step1: We start by loading the necessary libraries and preprocessing the sample dataset using <strong>SpaCy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWk7v-wWS01qPy5KT-eo0g.png" /></figure><p>Step2: We use the pre-trained <strong>all-MiniLM-L6-v2</strong> model to generate embeddings for the text data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Sq4JPetHdyieUje0NudSg.png" /></figure><p>Step3: After data wrangling, we have <strong>85 unique tokens</strong>. For each token, a <strong>384-dimensional embedding</strong> is generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrD1E0dR2Bj89yOPBvQauw.png" /></figure><p>Step4: To visualize the embeddings, we reduce the <strong>384-dimensional vectors</strong> to <strong>2 dimensions</strong> using <strong>t-SNE (t-Distributed Stochastic Neighbor Embedding)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7m6K4k0jA_1c4Wm7ps-1g.png" /><figcaption>Visualization of embeddings</figcaption></figure><p>Step5: We then proceed to measure the similarity of the vectors.</p><p>We store the tokens and their corresponding embeddings in a <strong>Pandas DataFrame</strong> and define a function to calculate the similarity between two vectors.</p><p>For example, we calculate the similarity between the vectors for <strong>“bigquery”</strong> and <strong>“bigqueryml”</strong>, which are very close to each other in the vector space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTkYmx5C5fDdik4JcOP4ZA.png" /></figure><p>A function has been defined to calculate the similarity of two vectors. The function incorporates logic to calculate similarity distances using dot product, cosine similarity, and Euclidean distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PAQPnjW2l6fRavw0AnK1Bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lO9O3H5F4zRhmiNR3NMEog.png" /></figure><p>Looking at the function’s output, we find that:</p><blockquote>The dot product is <strong>0.755</strong>, indicating that the vectors are somewhat aligned. <strong>Dot Product</strong>: Measures the alignment of the two vectors.</blockquote><blockquote>The cosine similarity is <strong>0.755</strong>, which indicates that the vectors are <strong>quite similar</strong>.Cosine similarity measures the cosine of the angle between two vectors.</blockquote><blockquote>It ranges from <strong>-1 to 1</strong>, where:</blockquote><blockquote><strong>1</strong>: The vectors are identical.</blockquote><blockquote><strong>0</strong>: The vectors are orthogonal (no similarity).</blockquote><blockquote><strong>-1</strong>: The vectors are diametrically opposed.</blockquote><blockquote>A value close to 1 suggests that the vectors are pointing in a similar direction in the vector space.</blockquote><blockquote>The Euclidean distance is <strong>0.699</strong>, which indicates that the vectors are <strong>relatively close</strong> to each other in the vector space.</blockquote><blockquote>Euclidean distance measures the straight-line distance between two vectors in the vector space.</blockquote><blockquote>It ranges from <strong>0 to infinity</strong>, where:</blockquote><blockquote><strong>0</strong>: The vectors are identical.</blockquote><blockquote>Larger values indicate greater dissimilarity.</blockquote><blockquote>A smaller Euclidean distance suggests that the vectors are more similar.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsrfSNuYOBEa2CDsIbZT5g.png" /></figure><p>Validating the semantic similarity between ‘text’ and ‘csv’ reveals a low cosine similarity of 0.27 and a high Euclidean distance of 1.2, indicating minimal semantic relation.</p><p>Let’s walk through the process of generating embeddings using a pre-trained <strong>BERT model</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ingvx7Mr-SBNYCQpEsE9Bw.png" /><figcaption>Pretrained BERT model</figcaption></figure><p>We use the same cleaned tokens (unique_tokens) to generate embeddings with the BERT model. The embeddings generated are of <strong>768 dimensions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPqOF4sY5KhfGVOHH2LZhA.png" /></figure><p>The embeddings generated are of 768 dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMpbTuOPtpqSKYSlevzj6w.png" /></figure><p>We reduce the <strong>768-dimensional embeddings</strong> to <strong>2 dimensions</strong> using <strong>t-SNE</strong> for visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpuWcYnxnLVUZt_dG9qktQ.png" /><figcaption>Visualization of 768 dimensional embeddings in 2 dimensional space</figcaption></figure><p>The distance measure between bigquery and bigqueryml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-eWCHzLVF4YCgZHV1eoBw.png" /></figure><p><strong>Dot Product</strong>: The value <strong>201.15</strong> suggests that the vectors have a strong relationship.</p><p><strong>Cosine Similarity</strong>: The value <strong>0.958</strong> indicates that the vectors are very similar.</p><p>A value close to <strong>1</strong> suggests that the vectors are pointing in a similar direction in the vector space.</p><p><strong>Euclidean Distance</strong>: The value <strong>4.23</strong> indicates that the vectors are relatively close to each other in the vector space.</p><p><strong>How is semantic meaning captured?</strong></p><p>Semantic meaning in embeddings is captured by analyzing how words appear in context within large text corpora. Embeddings represent data as vectors in a high-dimensional space, capturing relationships and patterns that machines can understand and process.</p><p><strong>Embedding Vectors</strong>: Learned such that similar items (e.g., words with similar meanings or images of the same object) have similar vector representations.</p><p><strong>Mapping Data</strong>: Data is mapped onto a vector space where the distance between vectors represents similarity.</p><p><strong>Word Coordinates</strong>: Each word is assigned a vector that acts as its coordinates on this map. These coordinates are carefully chosen so that words with similar meanings are close together.</p><p><strong>Feature Representation</strong>: Each number in the vector represents a feature or characteristic of the word. For example, one number might represent how much the word relates to database, another to sql, and another to language.</p><p>Semantic meaning is captured in embeddings through a process of learning relationships from vast amounts of data, primarily by analyzing the contexts in which words or concepts appear.</p><p><strong>Dimensionality</strong>: The dimensionality of embedding vectors is typically high, allowing them to capture a wide range of semantic relationships. Each dimension in the vector represents a learned feature or characteristic of the word.</p><p><strong>Proximity</strong>: In embedding space, similarity of meaning is represented by proximity.</p><p><strong>Dimensionality Example</strong>: A <strong>100-dimensional embedding</strong> means each word, image, or piece of context is represented as a vector of 100 numbers.</p><p>Visualizing the semantic relationships captured by the <strong>all-MiniLM-L6-v2</strong> model, the plot below reveals clear distinctions. ‘Spanner’ is positioned far from ‘SQL’, indicating a semantic dissimilarity, while terms like ‘SQL’, ‘NoSQL’, ‘RDBMS’, ‘database’, ‘table’, and ‘relational’ cluster closely, reflecting their strong semantic connections.</p><p><strong>Distance Between “sql” and “spanner”</strong>: These words are far apart in the vector space.</p><p><strong>Distance Between “rdbms” and “database”</strong>: These words are relatively close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiVbckmE6MQYTBLe2seVkA.png" /></figure><p>Examining the distance between ‘SQL’ and ‘Spanner’, we find a cosine similarity of 0.09, which confirms their semantic dissimilarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USPVsp56jbi7l5AslXC9sw.png" /></figure><p>Similarly, the cosine similarity between ‘rdbms’ and ‘database’ is 0.65, confirming their semantic similarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5wGhtcPAkYac-hsyzaxvA.png" /></figure><p>To further validate the semantic relationships, let’s examine the visualization produced by the BERT model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwcIW-EJj-DemN7LflSgaw.png" /></figure><p>In contrast to the <strong>all-MiniLM-L6-v2 </strong>model, which yielded a low cosine similarity between ‘sql’ and ‘spanner’, the <strong>BERT</strong> model shows a significantly higher cosine similarity of 0.9. This indicates that <strong>BERT</strong> has effectively captured the semantic relationship between these terms</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJBnZL4tZ_1TZuNJ-vmFnA.png" /></figure><p>Let us proceed with a comparison of the embeddings generated by the pre-trained GloVe model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyARvoD609Co_Bl6eNE75g.png" /></figure><p>In the plot, ‘sql’ and ‘spanner’ are positioned far apart, and similarly, ‘rdbms’ and ‘database’ are also separated by a significant distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JzrQ_AsmPmrCCfvlfvIMCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9h_T9q5M4GdDFBOboIWVVQ.png" /></figure><p>The calculated cosine similarity scores of 0.017 (sql and spanner) and 0.45 (rdbms and database) reveal that the GloVe model does not capture the semantic relationships between these database terms as accurately as other models. This highlights the importance of choosing an appropriate embedding model for the task at hand.</p><p><strong>How are embeddings captured with Word2Vec, GloVe, and transformer models?</strong></p><p>The process of converting words into embeddings involves several key steps:</p><ol><li><strong>Tokenization</strong> — Breaking text into words or subwords.</li><li><strong>Vectorization</strong> — Mapping tokens to dense numerical vectors.</li><li><strong>Training on Context</strong> — Learning relationships based on large text corpora.</li></ol><p>Different Embedding Models</p><ul><li><strong>Word2Vec</strong> — Assigns a single static vector to each word.</li><li><strong>GloVe</strong> — Learns word representations by analyzing word co-occurrence patterns.</li><li><strong>BERT &amp; Transformer Models</strong> — Generate contextual embeddings, meaning the same word can have different embeddings depending on the sentence.</li></ul><p>General Process of Generating Embeddings</p><p><strong>Text → Embedding Model → Embedding Vectors</strong></p><p>Generating embeddings with pre-trained GloVe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Itvor6ycf0U8YPvfQc41yg.png" /></figure><p>For the tokens <strong>“bigquery”</strong> and <strong>“bigqueryml”</strong>, no embeddings were generated because these tokens were not found in the <strong>GloVe 100d vocabulary</strong>. As a result, both tokens have <strong>100-dimensional embeddings</strong> consisting entirely of zeros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KgZzV9yzb9HUc45G3l5Wg.png" /></figure><p>GloVe Embedding Visualization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ik7MQGdkUEFau-6aEJhjzQ.png" /><figcaption>Embeddings generated with Glove</figcaption></figure><p>A semantic similarity score of 0.77 between ‘build’ and ‘create’ indicates that the relationship between these words has been effectively captured</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8u-SuQvHQzB4lnAiv-fheQ.png" /></figure><p>A semantic similarity score of 0.017 between ‘sql’ and ‘spanner’ suggests that the relationship between these words has not been captured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcPSppgSkPkLH80lPUamfQ.png" /></figure><h3>Measuring Similarity Between Embeddings</h3><p>Once text is converted into embeddings, similarity can be calculated using various mathematical methods.</p><p>Common Similarity Metrics</p><ol><li><strong>Cosine Similarity</strong> — Measures the angle between two vectors.</li><li><strong>Dot Product</strong> — Measures direct vector similarity.</li><li><strong>Euclidean Distance</strong> — Measures the straight-line distance between two points in space.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44D9quzqJVPbv6DzJAQ0pg.png" /></figure><p>These similarity techniques are widely used in <strong>clustering, classification, recommendations, and information retrieval</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6f2b5606641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Latent Dirichlet Allocation and Topic Modelling]]></title>
            <link>https://medium.com/analytics-vidhya/latent-dirichlet-allocation-and-topic-modelling-eea49dc3eea6?source=rss-fa06e50d2167------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea49dc3eea6</guid>
            <category><![CDATA[lda]]></category>
            <category><![CDATA[gensim]]></category>
            <dc:creator><![CDATA[Ruma Sinha]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 00:04:09 GMT</pubDate>
            <atom:updated>2020-12-22T16:30:47.582Z</atom:updated>
            <content:encoded><![CDATA[<p>The objective of the article is to understand the intuition behind LDA, the use cases and implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyfYDxsBv-oLa1zjC4hobQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@edgarraw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Edgar Castrejon</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A topic model is a type of statistical model for discovering the abstract topics that occur in a collection of documents. Topic models provide a simple way to analyze large volumes of unlabeled text. A topic consists of a cluster of words that frequently occur together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqZzULWetmvA8CeOi9SgeQ.png" /></figure><p>The inputs to the algorithm will be a set of documents and the output will be the specified number of topics, each topic will have the relevant terms and the distribution of the topics over all the documents.</p><h4>Some of the algorithms</h4><blockquote>Latent Dirichlet Allocation (LDA)</blockquote><blockquote>Latent Semantic Analysis (LSA) or Latent Semantic Indexing (LSI)</blockquote><blockquote>Non Negative Matrix Factorization (NMF)</blockquote><blockquote>One of the way we do, is with Latent Dirichlet Allocation (LDA) algorithm, and how it can be used to find meaning in text documents. A document contains a set of topics and each topic is a set of words. LDA uses some statistical analysis to figure out what each document is all about.</blockquote><h4>Use Cases</h4><blockquote>Topic discovery</blockquote><blockquote>Sentiment analysis</blockquote><blockquote>Automated document tagging</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYHNRknvrj8lgfE50FcGoA.png" /></figure><p>Documents seen as distribution of topics. Topics seen as distribution of words. A topic is represented as a weighted list of words.</p><p>The above diagram shows how LDA tries to classify documents. Documents are represented as a distribution of topics. Topics, in turn, are represented by a distribution of all tokens in the vocabulary. But we do not know the number of topics that are present in the corpus and the documents that belong to each topic. In other words, we want to treat the assignment of the documents to topics as a random variable itself which is estimated from the data.</p><blockquote>LDA training process broadly consists of,</blockquote><blockquote>A corpus, the collection of documents converted into a bag of words.</blockquote><blockquote>Data preprocessing steps like removal of stop words. Apply stemming to bring all the words to the root word. Tokenize. Choosing the number of topics say k that is we need to specify the number of topics during the training process itself.</blockquote><blockquote>Randomly assign topics to each word. Count the words by topic. Count the topics by document. Reassign the words to the topics. Iterate over all the words in the documents N times.</blockquote><p>The 3 main parameters of the LDA model is the number of topics, the number of words per topic and the number of topics per document.</p><blockquote>A low alpha value places more weight on having each document composed of only a few dominant topics</blockquote><blockquote>A low beta value places more weight on having each topic composed of only a few dominant words</blockquote><h4>Implementation of Gensim LDA model with the Spooky authors dataset from Kaggle.</h4><p>Dataset link:</p><p><a href="https://www.kaggle.com/c/spooky-author-identification/data">Spooky Author Identification</a></p><p>In this notebook we will apply topic modelling and create three topics as given dataset consists of three authors and the excerpts from their horror stories. These authors are Edgar Allan Poe, Mary Shelley, and HP Lovecraft. Dataset contains text from works of fiction written by spooky authors of the public domain: Edgar Allan Poe, HP Lovecraft and Mary Shelley. Edgar Allan Poe work is around tales of mystery and the macabre. Mary Shelley work is around science fiction and HP Lovecraft, best known as a writer of weird fiction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*07h8cWx6vZgmIetCtg4qUw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@korpa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jr Korpa</a> on <a href="https://unsplash.com/s/photos/spooky-season?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>The pipeline will be</blockquote><blockquote>Documents ===&gt; PreProcessing ===&gt; Vector Space (Bag of words, Dictionaries) ===&gt; Model (lda/nmf) ===&gt; Evaluation (metrics, visualizations)</blockquote><p>Reading the dataset and inspecting the same. The dataset contains 19579 observations and 3 feature columns id, text and author.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*5POLYs4g0faKiOArk-ywCg.png" /></figure><p>There are no null columns in this dataset. Will drop the id column.</p><blockquote>#for the topic modelling we will focus only on the text data<br>authors_data_df = authors_data_df.drop(columns = [‘id’], axis=1)</blockquote><p>The distribution of the articles among the three authors as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*-CIvZjkpqf1kLJsT2BN2Mw.png" /></figure><p>Data cleaning and preparation steps where we remove unwanted numbers or characters. We remove the punctuations and convert the text to lower case. Also we remove the stopwords , the words occuring commonly in all the documents and not adding any value to distinctly identify the three subsets of the given collection of the documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeykJ5dy1p833PEI9ARcQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4f3wCrQQmLT2fDFJyMnpfg.png" /></figure><p>Once text cleaning and stopwords removal is done, we can do the Exploratory Data Analysis visually with the wordcloud.</p><p>The wordcloud of the entire corpus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*ENECNtTa9fkhwzjxaUdZbA.png" /></figure><p><em>The words like time, thing, one, came, year, upon, eye, day, man, night, old etc we can observe in this wordcloud.</em></p><p>The top 30 words from the corpus as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYwUMxgWLYfj57RahjJ-8g.png" /></figure><p>We will subset the entire corpus into three different corpus based on the distinct authors and display the wordcloud as well as the top 30 occurring words.</p><blockquote>hplDatadf = authors_data_df[authors_data_df.author==”HPL”]</blockquote><blockquote>mwsDatadf = authors_data_df[authors_data_df.author==”MWS”]</blockquote><blockquote>eapDatadf = authors_data_df[authors_data_df.author==”EAP”]</blockquote><p>HP Lovecraft, wordcloud displays words like night, death, dream, dead, fear, horror, strange, window, ancient which seem to resonate with themes that the author was famous for.</p><p>We also looked into the top 30 occurring words from the works of HP Lovercraft.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*Yv76rj0WMBwXn2p1dg258Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*se76EPfvqhrHDLuvmbRbJA.png" /></figure><p>Mary Shelley, wordcloud displays words as fear, heart, raymond, mind, soul, power, hope, feeling, death, spirit, friend, death. Positive as well as negative words</p><p>We also looked into the top 30 occurring words from the works of Mark Shelley.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*Xc4MeGEusneEdiPgsEx4PA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dpe9Phkd_pKVlZCvNxZ9Tg.png" /></figure><p>Edgar Allan Poe, wordcloud displays words as life, end, friend, night, far, open, eye, great, one, little, time, good, manner, moment etc</p><p>We also looked into the top 30 occurring words from the works of Edgar Allan Poe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*gmXkE6oGt9LM3YppppH_pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6OOuD0RuAGaWDYuDh6O0Q.png" /></figure><p>Next step is preparing data for training the model.</p><h4>Step 1 Processed text to words or tokens</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54xRV2ij54BtjpGvilQzUA.png" /></figure><h4>Step 2 Building N grams</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4mcy3Jl4WoXtHF-myDg_g.png" /></figure><h4>Step 3 Lemmatize Is the process of converting the words to the root words</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqUfrJqnvsIpSUEyj_Nvbw.png" /></figure><h4>Step 4 Building the corpora</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVtD35_nYrcyBhpR2wGQIQ.png" /></figure><p>Above steps 1 to 4 consists of converting text to bag of words.<br>Prior to creating the model, we need to tokenize and lemmatize text to a bag of words which is a dictionary of vocabs where the key is the word and value is the number of times that word occurs in the entire corpus.<br>dictionary = gensim.corpora.Dictionary(processed_text)</p><p>Now for each pre-processed document we use the dictionary object just created to convert that document into a bag of words. i.e for each document we create a dictionary reporting how many words and how many times those words appear.<br>bow_corpus = [dictionary.doc2bow(doc) for doc in processed_text]</p><pre>[[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1)]]</pre><p>Training the LDA model</p><p>Keeping the number of topics as 3 since we know there are three authors and we are interested in seeing if we can use the topic modelling to group the given text into the authors work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHHqoqjPcsttA-amfKEzHA.png" /></figure><p><em>the statistical analysis results displayed as above but how de we interpret these 3 topics and can we map them to the 3 authors?</em></p><p>A topic is represented as a weighted list of words.</p><p>Not all topics are semantically coherent or interpretable. How do we measure the interpretability and goodness of the model? Coherence score, the statistical measure to check the goodness of the topic model.</p><blockquote>Topic coherence</blockquote><blockquote>The degree of semantic similarity between its high scoring words can be measured and based on this we can quantify the coherence of a topic.</blockquote><blockquote>Higher the topic coherence, the topic is more human interpretable.</blockquote><blockquote>The coherence measure can be used to compare different topic models based on their human-interpretability.</blockquote><p>When trained the model with 2 topics then the coherence score dipped to 0.20 because logically one of the author work will overlap with the specified two topics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ujFMJe9GwG6AFYjnLQWgg.png" /></figure><p>A good model must have non overlapping topics, the distance shows how semantically different the topics are. the further they are apart, better the topics are.</p><p>Visualization of the topics with LDAvis. Each bubble represents one topic. When we click on a topic, we get the top most relevant terms for that topic and the distributions. When I hover over one word then I can find which all topics this word occurs and in what frequency.</p><p>When we compare the top 30 words of each topic and the top 30 words from each of the author work, based on the maximum overlap of the subset of words between the two sets, we conclude Topic1 is probably EAP, Topic2 is probably HPL and Topic3 is probably MWS. These topic ids correspond to gensim model of 0, 1 and 2 respectively.</p><p><em>Note# pyLDAvis topic IDs doesn’t correspond to gensim topic IDs</em>.</p><p>Topic#1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTP-XS1jWy-Qs3aTtaQ5Sg.png" /></figure><p>Topic#2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irxhODATH8YNQXScJUJUHg.png" /></figure><p>Topic#3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UbgUv6w2Q64fdGhrOq_GA.png" /></figure><p>github code: <a href="https://github.com/rumsinha/NLP">https://github.com/rumsinha/NLP</a>/<a href="https://github.com/rumsinha/NLP/blob/main/LDA%20and%20Topic%20Modelling.ipynb">LDA and Topic Modelling.ipynb</a></p><h4>Conclusion</h4><p>In this article we tried understanding what is topic modelling and how it works. The role of topic modelling in NLP and industry use cases.</p><p>The various algorithms available for performing topic modelling and we did one implementation with LDA. In future articles we will try exploring the other algorithms as well.</p><p>We saw in detail the various steps in training a LDA model from reading text data to various pre processing steps then tokenization, stemming etc. Next we create the bag of words for input to the model. The output will be the number of topics that we specify.</p><p>We check the coherence score and perform visual evaluation as well with LDAvis plots to make sure if the topics are human interpretable.</p><p>The mapping of the statistical analysis results to the human interpretable topics may not be easy. Hard part of unsupervised learning is the evaluation part as we don’t have pre defined labels hence at this point we may verify with domain experts to make sure the topics generated as part of the statistical analysis map correctly with the human interpretable topics.</p><h4>References</h4><blockquote><a href="http://qpleple.com/topic-coherence-to-evaluate-topic-models/">http://qpleple.com/topic-coherence-to-evaluate-topic-models/</a></blockquote><blockquote><a href="https://www.coursera.org/projects/introduction-to-topic-modeling-for-business">https://www.coursera.org/projects/introduction-to-topic-modeling-for-business</a></blockquote><blockquote><a href="https://www.kaggle.com/arthurtok/spooky-nlp-and-topic-modelling-tutorial">https://www.kaggle.com/arthurtok/spooky-nlp-and-topic-modelling-tutorial</a></blockquote><blockquote><a href="https://www.slideshare.net/g33ktalk/dataengconf-building-the-next-new-york-times-recommendation-engine">https://www.slideshare.net/g33ktalk/dataengconf-building-the-next-new-york-times-recommendation-engine</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea49dc3eea6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/latent-dirichlet-allocation-and-topic-modelling-eea49dc3eea6">Latent Dirichlet Allocation and Topic Modelling</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>