<?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 Preithi Thakur on Medium]]></title>
        <description><![CDATA[Stories by Preithi Thakur on Medium]]></description>
        <link>https://medium.com/@preethithakur?source=rss-b6c66029ce5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a3QdFnLe0E_prD6AANRXuw.png</url>
            <title>Stories by Preithi Thakur on Medium</title>
            <link>https://medium.com/@preethithakur?source=rss-b6c66029ce5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:43:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@preethithakur/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[My Journey From Severe Urticaria to a Hive-Free Life]]></title>
            <link>https://medium.com/@preethithakur/my-journey-from-severe-urticaria-to-a-hive-free-life-965fd5ede82b?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/965fd5ede82b</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[medicine]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 20:57:32 GMT</pubDate>
            <atom:updated>2026-01-26T20:57:32.424Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my journey from severe urticaria to a happy, healthy, hive-free version of me.</p><blockquote>“I’m sharing my experiences so that you don’t feel lost, or scared— like I once did.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgD-Ulbwg4uZmVKpfIp_tg.jpeg" /></figure><p>My hives started in June 2025, after I tried a new haircare product, then my scalp got itchy. Next I spent a whole day under hot sun, with no shade. The next day I decided to try some new recipe, because why not!! Within a couple of days, the itching had spread to my neck and I had hives all over my scalp, neck and face and slowly they started spreading across my body. I spent my <strong>4th of July </strong>in the urgent care, because my eyes and face were extremely swollen, my whole body was covered in hives, they didn’t spare my palms and feet as well. I looked like a <em>Na’Vi from Avatar</em>. I took so many selfies and started comparing pictures with <em>Neytiri…</em></p><p>Coming back to the story, I also felt like I couldn’t breathe properly. At least, that’s how it felt. It was as if my body had hives from the inside. I couldn’t swallow without pain in my chest. So urgent care here I come!</p><p>The doctor prescribed <strong>prednisone(steroid), Benadryl, Zyrtec, </strong>and <strong>Allegra(antihistamines)</strong>. Before this, I had never taken any medication and had no idea what to do. Before you blame me, I have never experienced hives like this in my life so I did not know what they exactly were. I honestly thought they were some heat rashes which will go away on their own, so I drank lot of water.</p><p>Prednisone helped suppress the hives immediately. Wow!! It started working just in an hour. And other antihistamines helped too, Benadryl made me feel drowsy. But this relief was temporary.As soon as I ate something, the hives would come back. Food like the chickpea gave me severe hives and increased my body temperature to 100 degrees. This really scared me to.</p><p>In <strong>September 2025</strong>, I consulted a dermatologist. He told me my autoimmune system was compromised which is why I have these hives he and prescribed some more antihistamines — <strong>Allegra, Claritin, and Zyrtec</strong>. After few weeks, the hives did suppress slightly, but they didn’t stop. And I observed sever hair loss. The doctor said this might be because of urticatia. But I had strong feeling it was because of antihistamines. This was my birthday month. I couldn’t even celebrate it. Because I was covered in hives, with 100 degree fever. This broke me down emotionally.</p><p>Then came <strong>October</strong>, and on my dermatologist’s recommendation, I consulted an allergist. He said the same thing, that my automimmune system is compomised and performed an <strong>IgE test</strong> and ran other blood work to check what I’m allergic to and what is triggering these hives. I passed the IgE test with flying colors! Wish I did the same in my undergrads! The results implied I’m allergic to almost nothing, which is NOT TRUE. The doctor agreed this test did not work on me and we decided to wait for blood reports. Meanwhile he prescribed <strong>Allegra and Pepcid</strong>. And this combination worked wonders on me! My hives were completely suppressed. I could finally eat most of the food again. By <strong>November</strong>, my life was slowly returning to normal. <em>Yay!</em></p><p>However, I could see my immune system hadn’t fully recovered. Certain food still triggered hives — chickpea, sugar, processed and packaged food, soy, dairy, nuts, eggs, some sauces, tomatoes, etc., etc…</p><p>I started doing some research on urticaria cases and treatments. I read so many articles, blogs, watched zillions of videos, spoke with health advisors, I was already logging — my hives, what I ate, what triggered hives (not just food, but my daily activities, stress, emotional changes), I prepared diet chart to make sure I don’t eat anything that triggered these hives. I wanted to explore <strong><em>Naturotherapy.</em></strong> I learnt that naturotherapy can heal the condition by treating the root cause which can help from urticaria coming back. And finally, at the end of <strong>November</strong>, I consulted an amazing Ayurvedic doctor. A decision that completely changed my life, <em>positively</em>.</p><p>He recommended lifestyle changes along with treatment:</p><ul><li>Dietary adjustments based on my body type.</li><li>Regular meditation</li><li>Daily yoga, this is something I had done occasionally since childhood, but now I made it consistent.</li><li>He also prescribed Ayurvedic supplements like C<strong>urcumin and Quercetin</strong> to alleviate allergy symptoms, P<strong>robiotics</strong>, <strong>Triphala</strong>, and <strong>Livit</strong> to support gut and liver health.</li></ul><p>Within a month, I noticed a huge improvement in my health. By the end of <strong>December</strong>, I was able to eat anything freely, without the fear of hives.</p><p><strong>January 2026</strong> began with a positive hope! I had brownies, Ahhh!! not the one you are thinking. Only butter, milk, eggs and Ghirardelli brownie mix! I ate like half of tha whole brownie and felt itchy here and there but no hives. After couple of weeks I reduced Allegra and Pepcid to once a day. Soon after, I started taking them on alternate days. In the coming months, I hope to stop them completely and be able to eat everything like before and stay healthy. And do you remember I mentioned I was losing lot of hair and it might be because of antihistamines? Turns out that was absolutely true. As I’ve reduced Allegra dosage, now, I have seen significance difference in hairloss.</p><p>I still experience mild itching occasionally, but the severe urticaria is gone.</p><h3>What I Want You to Know</h3><p>Healing takes time. It may take a while to understand which treatment truly works for you. Don’t give up.</p><p>Before blindly following any treatment, try to understand the root cause of your hives. Don’t fall into the maze of urgency or impatience.</p><p>Keep a log of:</p><ul><li>What you eat</li><li>What triggers hives</li><li>Your diet</li><li>Your daily activities</li><li>Your emotions — be optimistic, this works wonders</li></ul><p>Study your symptoms, Research, Advocate for yourself. Then decide what suits your body best.</p><p>Medication can help temporarily (and yes, this may not apply to everyone), but <strong>lifestyle changes make healing sustainable</strong>.</p><p>Be consistent. Be persistent. Make yourself healthy again. Temporary relief is not the same as true healing.</p><p>And most importantly — <br> You’ve got this.<br> You’ve survived worse.<br> You are stronger than you think.<br> You are ready for a healthy life.</p><blockquote><strong>Disclaimer: </strong>This article is based on my personal experience and is not intended as medical advice. Every body is different, and what worked for me may not work for others. Please consult a qualified healthcare professional before starting, stopping, or changing any medication or treatment.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=965fd5ede82b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Practical Ways Business Analysts are Using Generative AI to Streamline Process Modeling — Bonus…]]></title>
            <link>https://medium.com/@preethithakur/6-practical-ways-business-analysts-are-using-generative-ai-to-streamline-process-modeling-bonus-9ce67a847884?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ce67a847884</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 03:41:44 GMT</pubDate>
            <atom:updated>2025-11-24T06:41:25.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>6 Practical Ways Business Analysts are Using Generative AI to Streamline Process Modeling — Bonus Prompts Included</h3><p>Generative AI is everywhere, but for the Business Analyst, the conversation often shifts quickly from “what’s possible with AI” to “how do I actually use this today to make my work better, faster, and more impactful?”</p><p>Business Process Modeling (BPM) is a perfect arena for AI integration. It’s a field rich in documentation, analysis, and communication — tasks where AI can provide immediate, tangible value.</p><p>This post cuts through the hype to provide five practical, actionable ways Business Analysts are leveraging GenAI to enhance their process modeling workflows right now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*6No32fyyxtWCgpQHCvMZRw.jpeg" /></figure><h3>1. Accelerating Initial Process Documentation from Stakeholder Interviews</h3><p><strong>The Traditional Challenge:<br></strong>You schedule interviews with half a dozen stakeholders, frantically scribble notes or record conversations, then spend hours transcribing and synthesizing that information into coherent process documentation. You can require additional three to four hours of follow-up work to transform raw notes into a structured process flow.</p><p><strong>How Generative AI Helps?<br></strong>Modern AI tools can now transcribe interview recordings with remarkable accuracy, then go several steps further. By feeding transcripts into generative AI platforms, you can:</p><ul><li>Extract key process steps automatically from conversational language</li><li>Identify decision points and business rules mentioned during discussions</li><li>Flag inconsistencies or gaps in the described process</li><li>Generate first-draft process narratives in standardized formats</li></ul><p><strong>The Prompt (Example):</strong></p><pre>Analyze the following stakeholder interview transcript and extract:<br>1. All process steps in sequential order<br>2. Actors/roles responsible for each step<br>3. Inputs required for each step<br>4. Outputs produced by each step<br>5. Decision points and the criteria used<br>6. Exception scenarios mentioned<br>7. Systems or tools referenced</pre><p><strong>The Value: </strong>This approach creates a <em>draft</em> process flow quickly, reducing manual effort in synthesizing information. Frees BA time to focus on validation, refinement, and stakeholder engagement rather than administrative documentation tasks.</p><p><strong>Pro Tip:</strong> Create reusable prompt templates that align with your organization’s process documentation standards. Include specific instructions about format, level of detail, and terminology to ensure consistent outputs.</p><h3>2. Generating Multiple Process Model Formats from a Single Source</h3><p><strong>The Traditional Challenge:<br></strong>Different stakeholders need different views, executives want swim lanes, technical teams need BPMN, training needs procedures. Traditional approaches mean either maintaining separate documents with version control issues or spending significant time manually reformatting.</p><p><strong>How Generative AI Helps?<br></strong>Generative AI excels at transformation tasks. By providing a comprehensive process description or existing model, BAs can now instantly generate:</p><ul><li>BPMN notation from narrative descriptions</li><li>Swim lane diagrams from detailed process steps</li><li>Flowcharts optimized for different audiences</li><li>Written procedures from visual models</li><li>User stories or test cases derived from process flows</li></ul><p><strong>The Prompt ( Example):<br></strong>Narrative to BPMN Prompt</p><pre>Convert the following process description into BPMN 2.0 notation. Include:<br>- Start and end events<br>- Tasks (with clear naming using verb-noun format)<br>- Gateways (exclusive, parallel, inclusive as appropriate)<br>- Sequence flows<br>- Pools and lanes for each actor/role<br>- Intermediate events where applicable</pre><p>Multi-Format Generation Prompt</p><pre>I need to present the following process to different audiences. Please create:</pre><pre>1. EXECUTIVE SUMMARY: A 5-step high-level overview suitable for leadership (focus on outcomes and value)</pre><pre>2. DETAILED BPMN: Complete BPMN notation with all tasks, gateways, and events</pre><pre>3. TRAINING GUIDE: Step-by-step instructions written for someone new to the process, including what to do and why</pre><pre>4. TECHNICAL REQUIREMENTS: System requirements and integration points that IT needs to implement</pre><pre>5. TEST SCENARIOS: 5 test cases covering the happy path, 2 common exceptions, and 1 edge case</pre><pre>Here is the detailed process description:<br>[PASTE DESCRIPTION HERE]</pre><p><strong>The Value: </strong>A single AI-generated source of truth converts into multiple formats instantly, cutting manual work and eliminating inconsistencies. BAs can deliver the right format for each audience, boosting clarity and buy-in while ensuring all required documents get produced.</p><p><strong>Pro Tip:</strong> Start with the most detailed representation of your process, then use AI to generate simplified views. It’s easier for AI to remove detail than to accurately add it.</p><h3>3. Instantly Generating Acceptance Criteria and User Stories</h3><p><strong>The Traditional Challenge:<br></strong>BAs spend hours converting process models into user stories with acceptance criteria. A single process can require 15–30 stories with 5–10 criteria each — potentially 300+ items to write and review. Missing criteria risks scope creep and defects. The challenge grows with inconsistent formats across teams (Gherkin, checklists, scenarios), making completeness and consistency difficult to maintain.</p><p><strong>How Generative AI Helps?<br></strong>Generative AI transforms technical process models into accessible, audience-appropriate content by:</p><ul><li>Converting process models into conversational step-by-step guides</li><li>Generating FAQs based on process documentation</li><li>Creating role-specific views highlighting relevant tasks</li><li>Producing training scenarios and examples</li><li>Drafting quick reference guides in various formats</li></ul><p><strong>The Prompt:<br></strong>Comprehensive Story with Acceptance Criteria Prompt</p><pre>Generate complete user stories with detailed acceptance criteria for the following process.</pre><pre>For each user story, provide:<br>1. Story title and user story statement (As a... I want... So that...)<br>2. Business value/rationale<br>3. Acceptance criteria in Given-When-Then (Gherkin) format<br>4. Edge cases and exception scenarios<br>5. Non-functional requirements (performance, security, usability)<br>6. Dependencies on other stories<br>7. Suggested story points</pre><pre>Acceptance criteria should:<br>- Cover the happy path completely<br>- Address at least 2-3 exception scenarios per story<br>- Include data validation rules<br>- Specify system behavior for edge cases<br>- Be independently testable<br>- Use concrete examples with specific data</pre><p><strong>The Value: </strong>This saves significant time for backlog refinement sessions. It ensures consistency in documentation standards and helps BAs generate comprehensive, developer-ready requirements that are directly traceable back to the agreed-upon process map.</p><p><strong>Pro Tip: </strong>When asking AI to estimate story points, provide context about your team’s velocity and past stories. Include your Fibonacci scale definitions with time ranges, then paste a few past stories with their actual points as examples. This context improves estimation accuracy.</p><h3>4. Identifying Process Optimization Opportunities Through Pattern Recognition</h3><p><strong>The Traditional Challenge:</strong> <br>Business analysis is not just about drawing maps, it is about finding opportunities for improvement. Experienced BAs spot inefficiencies like redundant steps, handoffs, and bottlenecks, but this expertise takes years to develop. Even seasoned analysts miss patterns in complex or unfamiliar processes.</p><p><strong>How Generative AI Helps?<br></strong>Generative AI models trained on vast amounts of process improvement literature and best practices can analyze process models and suggest optimization opportunities. They can:</p><ul><li>Identify redundant or duplicate steps</li><li>Spot potential bottlenecks based on process structure</li><li>Suggest automation candidates</li><li>Flag compliance or risk issues</li><li>Recommend industry best practices for similar processes</li></ul><p><strong>The Prompt:<br></strong>Efficiency Analysis</p><pre>Analyze the following process for inefficiencies using Lean Six Sigma principles. Specifically identify:</pre><pre>1. WASTE: Any steps that represent the 8 wastes (Defects, Overproduction, Waiting, Non-utilized talent, Transportation, Inventory, Motion, Extra-processing)<br>2. REDUNDANCY: Duplicate steps or approvals that could be consolidated<br>3. BOTTLENECKS: Steps likely to cause delays based on dependencies or complexity<br>4. HANDOFFS: Transitions between roles/departments that could be eliminated or streamlined<br>5. AUTOMATION CANDIDATES: Manual, repetitive tasks suitable for RPA or system automation</pre><pre>For each issue identified, provide:<br>- The specific step(s) affected<br>- Why it&#39;s problematic<br>- A specific recommendation for improvement<br>- Expected impact (time savings, error reduction, etc.)</pre><p><a href="https://medium.com/@preethithakur/effective-user-story-writing-the-business-analysts-step-by-step-guide-to-driving-agile-success-568e81f441c1">“Effective User Story Writing: The Business Analyst’s Step-by-Step Guide to Driving Agile Success”</a></p><p><strong>The Value: </strong>AI reviews every step systematically, reducing the risk of overlooking optimization opportunities. It offers unbiased analysis and generates concrete recommendations that support business cases and executive presentations and reduces analysis time.</p><p><strong>Pro Tip:</strong> Don’t just ask “how can this process be improved?” Be specific: “Analyze this process for redundant steps,” “Identify automation opportunities,” or “Suggest ways to reduce cycle time.” Specific prompts yield more actionable insights.</p><h3>5. Enhancing Process Discovery Through Intelligent Questioning</h3><p><strong>The Traditional Challenge:<br></strong>One of a BA’s most valuable skills is knowing which questions to ask. Incomplete process discovery leads to gaps in requirements, missed edge cases, and expensive rework later. But even experienced BAs can overlook important questions, especially when dealing with complex or unfamiliar processes.</p><p><strong>How Generative AI Helps?<br></strong>Generative AI can serve as an intelligent interview prep tool and a second pair of eyes during process discovery. BAs can:</p><ul><li>Generate comprehensive question lists for specific process types</li><li>Identify missing information in draft process models</li><li>Suggest exception scenarios that should be explored</li><li>Propose additional stakeholders who should be consulted based on process touchpoints</li></ul><p><strong>The Prompt:<br></strong>Interview Preparation Prompt</p><pre>I&#39;m about to interview stakeholders about the [PROCESS NAME] process in a [INDUSTRY] organization.</pre><pre>What I know so far:<br>[BRIEF DESCRIPTION OF WHAT YOU KNOW]</pre><pre>Please generate a comprehensive interview question list organized by:<br>1. Process Flow Questions (to understand the happy path)<br>2. Exception Handling Questions (what can go wrong and how it&#39;s handled)<br>3. Business Rules Questions (decision criteria and policies)<br>4. System &amp; Tool Questions (what technology is used)<br>5. Performance &amp; Metrics Questions (how success is measured)<br>6. Pain Point Questions (current challenges and frustrations)<br>7. Compliance &amp; Risk Questions (regulatory or policy requirements)<br>8. Stakeholder Questions (who else is involved or impacted)</pre><pre>Include follow-up questions for each main question to dig deeper.</pre><p><strong>The Value: </strong>Thorough upfront questioning prevents costly late-stage rework and reduces follow-up meetings. Early edge case identification prevents production issues. Interview prep drops from hours to minutes while producing better questions.</p><p><strong>Pro Tip:</strong> After documenting a process, ask the AI: “What questions should I ask to ensure this process model is complete?” The gaps in your model often reveal themselves through the questions the AI generates.</p><h3>6. Creating Contextual Documentation and Training Materials</h3><p><strong>The Traditional Challenge:<br></strong>Process models are essential tools, but they’re not always accessible to everyone who needs them. New team members struggle to understand complex BPMN diagrams. Process documentation sits in repositories where no one can find it when they need it. Creating user-friendly, contextual documentation takes lot of time that BAs often don’t have.</p><p><strong>How Generative AI Helps?<br></strong>Generative AI can transform technical process models into accessible, audience-appropriate content:</p><ul><li>Convert process models into conversational step-by-step guides</li><li>Generate FAQs based on process documentation</li><li>Create role-specific views highlighting relevant tasks</li><li>Produce training scenarios and examples</li><li>Draft quick reference guides in various formats</li></ul><p><strong>The Prompt:<br></strong>Quick Reference Guide Prompt</p><pre>Create a one-page quick reference guide for the following process that can be:<br>- Printed and kept at someone&#39;s desk<br>- Used during actual work (not training)<br>- Scanned in under 30 seconds to find needed information</pre><pre>Include:<br>- Process overview (2-3 sentences)<br>- Quick checklist of main steps<br>- Key decision points with criteria<br>- Common issues and quick fixes<br>- Important reminders/warnings<br>- Who to contact for help<br>- Links to detailed documentation</pre><pre>Format for visual clarity with sections, bullets, and emphasis.</pre><p><strong>The Value: </strong>User-friendly documentation improves process adherence and speeds up onboarding. Self-service materials reduce training costs and cut support tickets substantially. Documentation creation drops from many hours to under two. Process knowledge becomes accessible to everyone, not just technical readers.</p><p><strong>Pro Tip:</strong> Specify the audience and purpose in your prompts: “Convert this process model into a training guide for new employees with no insurance experience, using simple language and including examples.”</p><h3>Making It Work: Implementation Considerations</h3><p>While these six applications offer tremendous potential, successful implementation requires thoughtfulness.</p><p><strong>Start Small and Focused:<br></strong>Don’t try to AI-ify your entire process modeling practice overnight. Pick one use case, experiment, learn, and expand. Start with the application that addresses your biggest pain point or offers the clearest ROI.</p><p><strong>Validate Everything:<br></strong>Generative AI is a tool, not a replacement for BA expertise. Always review, validate, and refine AI-generated content. The AI provides speed and structure while you provide accuracy, context, and judgment.</p><p><strong>Build Your Prompt Library:<br></strong>The quality of outputs depends heavily on input quality. Develop and refine prompts that work well for your specific needs. Document what works and create templates for common tasks and continuously improve them based on results.</p><p><strong>Address Data Privacy:<br></strong>Be mindful of what information you input into AI tools. Ensure compliance with your organization’s data security policies, especially when working with confidential business processes. Consider using anonymized or sanitized examples for testing prompts before applying them to sensitive data.</p><p><strong>Combine AI with Traditional Methods:<br></strong>Generative AI enhances but doesn’t replace stakeholder collaboration, process observation, data analysis, and critical thinking. Use AI to handle routine aspects of your work, this will free your time for high value activities that require human judgment, relationship building, and strategic thinking.</p><p><strong>Invest in Prompt Engineering Skills:<br></strong>The difference between mediocre and exceptional AI outputs often comes down to prompt quality. Invest time in learning prompt engineering techniques. Read guides, if possible attend workshops and practice iteratively refining your prompts.</p><p><strong>Measure Your Results:<br></strong>Track the time savings, quality improvements, and business outcomes from your AI-assisted work. This data helps justify continued investment and identify which applications provide the most value for your context.</p><h3>The Bottom Line</h3><p>Generative AI isn’t going to replace business analysts. But business analysts who learn to effectively leverage generative AI will be significantly more productive than those who don’t.</p><p>The BAs who are winning with AI aren’t waiting for perfect tools or comprehensive organizational strategies. They’re experimenting, learning, and finding practical ways to use AI to do what they already do — just faster, more thoroughly, and with better results.</p><p>The question isn’t whether to use generative AI in process modeling — it’s how quickly you can start experimenting with the approaches that will transform your daily work.</p><p>What’s your first experiment going to be?</p><p><em>What practical applications of generative AI have you found valuable in your BA work? Share your experiences in the comments below.</em></p><p><a href="https://medium.com/@preethithakur/how-to-run-effective-requirement-gathering-workshops-a-guide-for-business-analysts-and-project-d72030e4a3c8">How to Run Effective Requirement Gathering Workshops: A Guide for Business Analysts and Project…</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ce67a847884" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Run Effective Requirement Gathering Workshops: A Guide for Business Analysts and Project…]]></title>
            <link>https://medium.com/@preethithakur/how-to-run-effective-requirement-gathering-workshops-a-guide-for-business-analysts-and-project-d72030e4a3c8?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d72030e4a3c8</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[requirements]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 05:54:00 GMT</pubDate>
            <atom:updated>2025-04-25T14:55:28.274Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Run Effective Requirement Gathering Workshops: A Guide for Business Analysts and Project Teams</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*IoOFq888oiEyoDMM" /></figure><p>Gathering requirements is one of the most critical phases in any project. When done effectively, it ensures alignment between stakeholders’ expectations and the final products. One of the most powerful techniques to elicit requirements is <strong>Requirement Gathering Workshops, </strong>collaborative sessions that bring stakeholders together to identify, discuss, and agree on what the solution must deliver.</p><p>This article draws from practical frameworks and popular references such as <em>“Mastering the Requirements Process”</em> by Suzanne and James Robertson, <em>“Business Analysis Techniques”</em> by James Cadle, and the <em>BABOK® Guide</em> (Business Analysis Body of Knowledge) from IIBA. It offers a practical, structured approach to running effective workshops, suitable for business analysts, project managers, product owners, and even startups.</p><h3>Phases of a Successful Requirement-Gathering Workshop</h3><h4>1. Pre-Workshop Preparation: Laying the Groundwork</h4><blockquote>“Success depends on prior preparation, and without such preparation there is sure to be failure.” — Confucius</blockquote><p><strong>1.1. Define Objectives and Scope</strong></p><p>Begin by clarifying the workshop’s purpose. <em>What exactly do you want out of the session?</em> Are you defining high-level business needs, validating existing ones, detailing user stories, or resolving conflicting priorities? Align objectives with project goals using SMART criteria (Specific, Measurable, Achievable, Relevant, Time-bound).</p><p><strong><em>Examples:<br> — </em></strong>Identify all functional requirements for the new customer portal.<br> <strong><em>—</em></strong><em> </em>Align stakeholders on MVP scope for the mobile app.</p><p><strong>1.2. Identify and Engage Stakeholders</strong></p><p>Research by the Project Management Institute suggests that stakeholder identification is often incomplete, with up to 40% of relevant stakeholders overlooked during requirements gathering. The effectiveness of your workshop hinges on having the right people in the room:</p><ul><li><strong>Decision Makers</strong>: Those with authority to approve requirements</li><li><strong>Subject Matter Experts</strong>: Those with deep domain knowledge</li><li><strong>End Users</strong>: Those who will ultimately use the solution</li><li><strong>Technical Representatives</strong>: Those who understand implementation constraints</li></ul><p>For each participant, consider:</p><ul><li>What unique perspective do they bring?</li><li>What preparation materials would be beneficial?</li><li>How will their input be specifically solicited?</li></ul><p>Conduct a stakeholder analysis to map influencers, decision-makers, and end-users. Use power-interest grids to prioritize participation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*Ley1fMCAuO_0prc2Aw6oaQ.png" /><figcaption>Power-Interest Grid</figcaption></figure><p><strong>1.3. Design the Workshop Agenda</strong></p><p>Craft a time-boxed agenda that follows a logical progression of topics. Allocate time for:</p><ul><li><strong>Context setting</strong>: Project background, goals, constraints, assumptions (10 mins)</li><li><strong>Discovery</strong>: Current state analysis, pain points, opportunities(15 mins)</li><li><strong>Elicitation</strong>: Detailed requirements using varied techniques(<em>e.g. Edward de Bono’s Six Thinking Hats for structured perspectives</em>) (30 mins)</li><li><strong>Review and Validation</strong>: Testing understanding and capturing feedback (30 mins)</li><li><strong>Prioritization</strong>: Determining importance and implementation sequence (30 mins)</li><li><strong>Next steps</strong>: Documenting actions and responsibilities(15 mins)</li></ul><p><strong>1.4. Set the Stage with Pre-Work Materials</strong></p><p>Send preparation materials beforehandwhich could include:</p><ul><li>Workshop objectives and agenda</li><li>Background information on the project</li><li>Existing documentation to review</li><li>Specific questions to consider before attending</li><li>Templates that will be used during the session</li></ul><p>Roger Burlton, author of “Business Process Management: Profiting From Process,” notes that pre-reading can reduce workshop time by up to 30% when properly assigned and completed.</p><h4>2. Facilitating the Workshop: Techniques for Collaboration</h4><p>The structure of your requirements workshop significantly impacts its productivity and outcomes. Effective workshop design isn’t merely about creating an agenda; it’s about architecting a collaborative experience that systematically builds toward comprehensive requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*7BoF8xrNAtcmSAgf" /></figure><p><strong>2.1. Establish Ground Rules</strong></p><p>Begin with what Karl Wiegers calls the “W<em>orkshop Contract</em>”; establish:</p><ul><li>Ground rules for participation</li><li>Decision-making methods</li><li>How conflicts will be resolved</li><li>Parking lot procedures for off-topic items</li><li>Documentation and follow-up expectations</li></ul><p><strong>2.2. Elicitation Techniques</strong></p><p>Employ a variety of techniques to extract requirements from different perspectives:</p><ul><li><strong>Brainstorming and Mind Mapping</strong>: Encourage creativity using mind mapping to visualize relationships between ideas.</li><li><strong>Journey Mapping</strong>: Outline user interactions to identify pain points and opportunities, as detailed in <em>Business Analysis Techniques</em>.</li><li><strong>Process Mapping</strong>: Visualizing workflows helps identify handoffs, decision points, process inefficiencies and improve requirement accuracy.</li><li><strong>User Stories</strong>: “As a [role], I want [feature] so that [benefit].” Particularly effective framework for user-centric requirements.</li><li><strong>Use Case Scenarios</strong>: Walking through end-to-end scenarios reveals requirements that might be missed in abstract discussions.</li><li><strong>Prototyping</strong>: Creating low-fidelity mock-ups or wireframes (<em>use tools like Figma or Miro</em>) to visualize solutions and gather feedback.</li><li><strong>Affinity Diagrams</strong>: Leverage visual aids like flowcharts, affinity diagrams, or Scrum/Kanban boards for organizing large amounts of information into logical groups.</li></ul><p><strong>2.3. Managing Group Dynamics</strong></p><p>Group dynamics fundamentally influence the success of any requirements workshop. When you have diverse stakeholders with varying levels of authority, technical knowledge, and communication styles, effectively managing these interactions becomes crucial.</p><ul><li><strong>Balance participation</strong>: Use round-robin techniques; go around and give each person a chance to ensure quieter voices are heard.</li><li><strong>Manage dominators</strong>: Tactfully redirect excessive input with phrases like “Thank you for that insight. Let’s hear from someone who hasn’t spoken yet.”</li><li><strong>Address conflicts</strong>: Distinguish between healthy debate and unproductive conflict. Document opposing perspectives rather than forcing premature consensus.</li><li><strong>Maintain energy</strong>: Keep sessions to 90 minutes maximum, with breaks between.</li><li><strong>Use “silent writing” techniques</strong>: Have participants write ideas before sharing to avoid anchoring bias and groupthink.</li></ul><h4>3. Documentation and Validation: Capturing Requirements</h4><p>Documentation during requirements workshops is much more than simply taking notes. It is a critical practice that shapes the quality and usability of the requirements you gather.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/0*5x7hp7GetpdAc67z" /></figure><p><strong>3.1. Real-Time Documentation</strong></p><p>Assign a scribe(<em>a person who is going to write down meeting notes e.t.c.,</em>) to capture decisions, action items, and requirements in a shared space (<em>Use tools like Confluence or Google Docs</em>). Differentiate between:</p><ul><li>Functional Requirements (system behaviors).</li><li>Non-Functional Requirements (performance, security).</li><li>Business Rules (constraints or policies).</li></ul><p><strong>3.2. Traceability and Prioritization</strong></p><p>Link requirements to business objectives using traceability matrices. Prioritize with methods like:</p><p><strong>— MoSCoW Method</strong>: Must-have, Should-have, Could-have, Won’t-have.<br> <strong>—</strong> <strong>Kano Model</strong>: Classify features as basic, performance, or delighters.</p><p>Periodically review what has been documented to ensure accuracy.</p><h4>4. Post-Workshop Actions: Following Through</h4><p>Post-workshop phase transforms raw input into actionable requirements and establishes the foundation for successful implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/0*r_7gbycBYP-fZpGZ" /></figure><p><strong>4.1. Processing and Distributing Results</strong></p><ul><li>Circulate all workshop outputs within 24 hours.</li><li>Develop a communication plan to update stakeholders</li><li>Create a <em>Requirements Document or Product Backlog</em> (for Agile teams), include visuals, diagrams, and examples where possible.</li><li>Distribute documentation to participants for review.</li></ul><p><strong>4.2. Validate and Refine Requirements</strong></p><p>Consider a multi-step validation process such as:</p><ul><li><strong>Self-review</strong>: Check for completeness, clarity, and consistency.</li><li><strong>Peer review</strong>: Have another analyst review for quality.</li><li><strong>Stakeholder review</strong>: Get input from workshop participants.</li><li><strong>Technical feasibility assessment</strong>: Validate implementation viability.</li></ul><p>For complex requirements, consider follow-up sessions focused solely on validation and refinement.</p><p><strong>4.3. Managing Requirement Changes</strong></p><p>Requirements evolve throughout a project’s lifecycle. It is essential to have a systematic change management approach to manage them effectively. Key strategies include:</p><ul><li>Establishing a formal change control process for requirements.</li><li>Documenting the impact of changes on scope, schedule, and resources.</li><li>Creating a requirements baseline after initial approval.</li><li>Tracking versions and maintaining an audit trail.</li></ul><p>Research by the Standish Group indicates that 35% of requirements will change during a project, highlighting the need for robust change management processes.</p><h4>5. Common Challenges/Pitfalls and Solutions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*EH6P6GkotQfcaHus7pbE-w.png" /></figure><p><strong>5.1. Conflicting Stakeholder Priorities<br>Solution</strong>: Apply weighted prioritization techniques from Karl Wiegers’ “First Things First” approach, where business value and implementation cost are scored to create an objective ranking system.</p><p><strong>5.2. Requirements Too Vague or High-Level<br>Solution</strong>: Use the SMART criteria (Specific, Measurable, Achievable, Relevant, Time-bound) and the “Five Whys” technique to drill down to specific, implementable requirements.</p><p><strong>5.3. Workshop Domination by Vocal Participants<br>Solution</strong>: Implement structured participation methods like nominal group technique or brainwriting, which give equal voice to all participants regardless of seniority or assertiveness.</p><p><strong>5.4. Scope Creep During the Workshop<br>Solution</strong>: Create a visual “scope boundary” diagram at the start, and use a parking lot for capturing out-of-scope items for future consideration.</p><h4>6. Advanced Workshop Techniques for Modern Challenges</h4><p><strong>6.1. The Design Studio Approach</strong></p><p>Jeff Gothelf’s “Lean UX” describes the design studio methodology, where cross-functional teams:</p><ul><li>Individually sketch solutions to requirements</li><li>Present ideas to the group</li><li>Critique each solution</li><li>Iterate and refine based on feedback</li><li>Converge on a unified approach</li></ul><p>This technique uncovers hidden requirements and constraints while building consensus around solutions.</p><p><strong>6.2. Jobs-to-be-Done Framework</strong></p><p>Anthony Ulwick’s “Jobs to be Done” framework shifts focus from features to outcomes:</p><ul><li>What job is the customer hiring the product to do?</li><li>Under what circumstances?</li><li>What are the success criteria?</li></ul><p>This approach helps identify requirements that traditional techniques might miss by focusing on the underlying job rather than surface-level features.</p><p><strong>6.3. Event Storming</strong></p><p>Introduced by Alberto Brandolini, Event Storming brings together domain experts to map business processes using sticky notes representing:</p><ul><li>Domain events (orange)</li><li>Commands that trigger events (blue)</li><li>Actors who issue commands (yellow)</li><li>Problems and opportunities (purple)</li></ul><p>This visual technique(<em>use tools such as Miro, Mural, Lucidcharts</em>) is particularly effective for complex domains where traditional requirement gathering might miss critical interactions and dependencies.</p><h4>7. Measuring Workshop Effectiveness</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*AlQFvUj0L4p6A-Gd0v33TQ.jpeg" /></figure><p><em>“What gets measured gets managed”</em><strong> </strong>— and that applies to requirements workshops too.<strong> </strong>To evaluate the effectiveness of your workshop, consider tracking these key metrics:</p><ul><li><strong>Requirement stability</strong>: Percentage of requirements that remain unchanged after approval.</li><li><strong>Implementation accuracy</strong>: Percentage of requirements correctly implemented.</li><li><strong>Stakeholder satisfaction</strong>: Survey participants on workshop effectiveness</li><li><strong>Rework reduction</strong>: Compare rework levels with previous projects</li><li><strong>Time efficiency</strong>: Measure time from requirements approval to implementation</li><li><strong>Stakeholder participation rate:</strong> Check how many right people actively contributed.</li><li><strong>Alignment and consensus:</strong> Was agreement reached on key priorities and scope?</li></ul><h4>Conclusion: The Art and Science of Effective Workshops</h4><p>Effective requirements gathering workshops balance structure with flexibility, technical precision with human dynamics. By thoughtfully preparing, skillfully facilitating, and diligently following through, these workshops can transform project outcomes.</p><p>The techniques outlined here draw from decades of business analysis best practices. While each organization and project will require customization, these fundamentals provide a solid foundation for requirements workshops that deliver clear, complete, and actionable requirements.</p><p>Remember that requirements gathering is not a one-time event but an ongoing process. Even the best workshops should be part of a broader strategy of continuous stakeholder engagement and requirements refinement throughout the project lifecycle.</p><h4>References</h4><ul><li>Carkenord, B. A. (2009). Seven Steps to Mastering Business Analysis. J. Ross Publishing.</li><li>Gottesdiener, E. (2005). The Software Requirements Memory Jogger. GOAL/QPC.</li><li>Wiegers, K. E., &amp; Beatty, J. (2013). Software Requirements (3rd ed.). Microsoft Press.</li><li>Robertson, S., &amp; Robertson, J. (2012). Mastering the Requirements Process: Getting Requirements Right. Addison-Wesley.</li><li>Patton, J. (2014). User Story Mapping: Discover the Whole Story, Build the Right Product. O’Reilly Media.</li><li>Leffingwell, D. (2011). Agile Software Requirements: Lean Requirements Practices for Teams, Programs, and the Enterprise. Addison-Wesley.</li><li>Gothelf, J., &amp; Seiden, J. (2016). Lean UX: Designing Great Products with Agile Teams. O’Reilly Media.</li><li>Ulwick, A. W. (2005). What Customers Want: Using Outcome-Driven Innovation to Create Breakthrough Products and Services. McGraw-Hill.</li><li>International Institute of Business Analysis. (2015). A Guide to the Business Analysis Body of Knowledge (BABOK Guide), Version 3.0.</li><li>Thompson, L. (2013). Creative Conspiracy: The New Rules of Breakthrough Collaboration. Harvard Business Review Press.</li><li>Burlton, R. T. (2001). Business Process Management: Profiting From Process. Sams Publishing.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d72030e4a3c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Effective User Story Writing: The Business Analyst’s Step-by-Step Guide to Driving Agile Success”]]></title>
            <link>https://medium.com/@preethithakur/effective-user-story-writing-the-business-analysts-step-by-step-guide-to-driving-agile-success-568e81f441c1?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/568e81f441c1</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 23:30:07 GMT</pubDate>
            <atom:updated>2025-04-16T23:30:07.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*PXBn0-mAK6-SmBEKkMHKMg.jpeg" /></figure><p>In Agile development, user stories are the heartbeat of product success. They transform vague requirements into actionable insights, align cross-functional teams, and ensure solutions deliver real value to users.</p><p>Poorly written user stories lead to miscommunication, scope creep, and frustrated teams. As a business analyst, your ability to craft clear, actionable user stories can make or break a project.</p><p>This guide cuts through the noise, offering a proven framework to write user stories that align stakeholders, empower developers, and deliver real value.</p><h3>What Makes a User Story Effective?</h3><p>A user story is more than a placeholder for requirements. It’s a <strong>user-centered promise</strong> that answers three questions:</p><ul><li><strong>Who</strong> is the user?</li><li><strong>What</strong> do they need?</li><li><strong>Why</strong> does it matter?</li></ul><p><strong>The Classic Template (And How to Elevate It):</strong><br><em>“As a [role], I want [goal] so that [benefit].”</em><br>While this template is a great starting point, the magic lies in specificity.</p><p><strong>Weak Example:<br></strong><em>“As a user, I want a dashboard to view data.”</em></p><p><strong>Strong Example:</strong><br><em>“As a sales manager, I want to filter dashboard data by region and quarter so I can identify underperforming markets and adjust strategies.”</em></p><p><strong>Why It Works:</strong></p><ul><li>Defines a <strong>specific user</strong> (sales manager).</li><li>Clarifies the <strong>action</strong> (filter by region/quarter).</li><li>Highlights the <strong>business impact</strong> (adjust strategies).</li></ul><p>A good way to begin a user story is to start with <strong><em>Empathy</em></strong><em>. </em>Understand the user before writing a story, <strong><em>know who you’re writing for</em></strong>. Interview stakeholders, create personas, and map user journeys to understand pain points and motivations.</p><p>✅<strong> Pro Tip</strong>: Use empathy maps or storyboards to visualize user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*OJz1qRHXiK_jV_97vpZOSA.png" /><figcaption>Empathy Map</figcaption></figure><h3>The INVEST Framework: Your Blueprint for Success</h3><p>To ensure your stories are Agile-ready, follow the <strong>INVEST</strong> principles:</p><ol><li><strong>Independent</strong>: Avoid dependencies between stories.<br>- <em>Tip:</em> Split large stories (epics) into smaller, self-contained tasks.</li><li><strong>Negotiable</strong>: Leave room for discussion; don’t over-specify upfront.<br>- <em>Pitfall:</em> Writing stories like technical specs kills creativity.</li><li><strong>Valuable</strong>: Every story must deliver user or business value.<br>- Ask: “What happens if we <em>don’t</em> build this?”</li><li><strong>Estimable</strong>: The team must gauge effort.<br>- <em>Red Flag:</em> If developers say, “We need more info,” refine the story.</li><li><strong>Small</strong>: Keep stories small enough to complete in a sprint (1–3 days of work).</li><li><strong>Testable</strong>: Define clear acceptance criteria (more on this below).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*FO0SyAS09wcApfsE_le-ow.jpeg" /></figure><p><strong>Example of an INVEST-Worthy Story:</strong><br><em>“As a frequent traveler, I want to save multiple payment methods in my profile so I can checkout faster when booking flights.”</em></p><h3>Writing Acceptance Criteria: The “Done” Checklist</h3><p>Acceptance criteria (AC) turn user stories into testable outcomes. They answer: <em>“How will we know this story is complete?”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pd8cWfzya_DIV8NNnvZfbQ.png" /></figure><p><strong>Best Practices for Acceptance Criteria:</strong></p><ul><li><strong>Be Specific:</strong> Avoid vague terms like “user-friendly” or “fast.”</li><li><strong>Prioritize Outcomes, Not Solutions:</strong> Focus on “<em>what”</em>, not “<em>how”</em>.</li><li><strong>Use the Given-When-Then Format (BDD):<br> </strong><em>Given</em> a user has items in their cart,<br> <em>When</em> they click “Checkout,”<br> <em>Then</em> the system displays saved payment options.</li></ul><p><strong>Weak Acceptance Criteria:</strong><br><em>“The app should load quickly.”</em></p><p><strong>Strong Acceptance Criteria:</strong><br><em>“The app homepage loads within 2 seconds on a 4G connection, displaying personalized recommendations based on the user’s past purchases.”</em></p><h3>Collaboration: The Secret Sauce for Refinement</h3><p>User stories thrive on teamwork. As a BA, your role is to facilitate conversations between stakeholders, developers, and testers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*r43KLEP7E6IKENzE6246lg.jpeg" /></figure><p><strong>Pro Tips:</strong></p><ul><li><strong>Host Story Refinement Sessions:</strong> Walk through stories to get feedback, clarify assumptions, and align expectations. Break epics into smaller stories with your team.</li><li><strong>Ask “Who, What, Why” Questions: </strong>When refining user stories, asking <strong>“Who, What, Why”</strong> ensures your team stays aligned on <strong>user needs</strong>, <strong>business goals</strong>, and <strong>value delivery</strong>. Here’s how each question drives clarity: <br> <strong><br> — WHO -</strong><em>“Who benefits most from this feature?”<br> &gt; Purpose: </em>Prioritizes stories based on urgency and impact.<br> &gt; <em>Why It Matters: </em>Helps teams avoid wasting time on low-value features. <br> <br><em> — </em><strong>WHAT</strong> -<em> “What’s the risk of delaying this story?” <br> &gt; Purpose</em>: Prioritizes stories based on urgency and impact.<br> &gt; <em>Why It Matters</em>: Helps teams avoid wasting time on low-value features.<br> <br> — <strong>Why -</strong><em> “Why does this story matter to the user or business?”<br> &gt; Purpose</em>: Uncovers the root problem or desired outcome.<br> &gt; <em>Why It Matters</em>: Skipping the “Why” leads to <em>Solutioneering, Misaligned priorities.</em></li><li><strong>Leverage Personas:</strong> Create user personas to keep stories grounded in real needs.</li></ul><blockquote>User personas are fictional profiles based on research that represent your main users. They help Business Analysts make user stories more realistic by focusing on real goals, needs, and challenges instead of guesses.</blockquote><p><strong>Example:</strong><br>A story like <em>“As a user, I want a search feature”</em> becomes:<br><em>“As a busy parent, I want to search for recipes by cooking time (&lt; 30 mins) and dietary restrictions (gluten-free) so I can plan meals quickly.</em></p><h3>Common Pitfalls</h3><ul><li><strong>Vague Goals -</strong> Like “I want a dashboard” — What’s the purpose?</li><li><strong>Stories Too Big</strong> — Makes estimation and testing hard.</li><li><strong>Missing Acceptance Criteria </strong>— Leads to ambiguity.</li><li><strong>Writing Technical Tasks as Stories</strong> — Keep it user-focused.</li><li><strong>Ignoring the ‘Why’ — </strong>Failing to tie stories to user or business value, leading to features that feel disconnected from goals.</li><li><strong>The “Solutioneering” Trap — </strong>The <strong>“Solutioneering” Trap</strong> refers to the common mistake of prescribing a specific technical solution in a user story <em>before</em> understanding the <strong>user’s underlying problem or goal</strong>. Instead of focusing on <em>what the user needs</em>, teams jump straight to <em>how to build it</em>, which often results in solutions that miss the mark. <em>Imagine a doctor prescribing medication without diagnosing the patient’s symptoms.</em><br> <br><strong>—<em> </em>Bad User Story</strong>: <em>“As a user, I want a dropdown menu to filter products.”<br></em> Here the problem is<strong> — </strong>The story dictates the <em>solution</em> (a dropdown) instead of the <em>need</em> (filtering).<br><strong><em>Result</em></strong>: The team might build a dropdown, but users might prefer a slider for price ranges or checkboxes for multiple filters.<br> <br> — <strong>Good User Story</strong>:<em> “As a shopper, I want to filter products by sustainability ratings so I can make eco-friendly purchasing decisions.”<br></em><strong><em>Why It Works</em></strong><em>:</em> It focuses on the user’s goal (finding sustainable products) and leaves the <em>how</em> (dropdown, checkboxes, tags) open for the team to design.</li></ul><p><strong>The Cost of Poor Stories is — </strong>Vague stories lead to scope creep, missed deadlines, and frustrated teams.</p><h3>Tools &amp; Templates to Streamline Your Process</h3><ul><li><strong>Jira/Azure DevOps/ClickUp:</strong> Track stories, acceptance criteria, and progress.</li><li><strong>Confluence / Notion</strong> — To document context and discussions</li><li><strong>Lucidchart / Miro</strong> — For creating process flows, wireframes</li><li><strong>Figma / Balsamiq</strong> — For low-fidelity UI mockups</li><li><strong>Persona Templates:</strong> Define user roles and pain points.</li><li><strong>BDD Frameworks </strong>(<strong>Cucumber/SpecFlow):</strong> Link acceptance criteria to automated tests.</li></ul><h3>From Good to Great</h3><p>Effective user stories are conversation starters, collaboration enablers, and value drivers. By focusing on the user’s voice, embracing the INVEST principles, and refining relentlessly with your team, you’ll transform requirements into solutions that resonate. As a Business Analyst, your stories shape the direction of the product.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=568e81f441c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Missing Data: A Comprehensive Guide to Handling Gaps in Your Dataset]]></title>
            <link>https://medium.com/@preethithakur/mastering-missing-data-a-comprehensive-guide-to-handling-gaps-in-your-dataset-86af800fcbdd?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/86af800fcbdd</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[analysis]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 03:37:11 GMT</pubDate>
            <atom:updated>2025-04-14T03:54:29.166Z</atom:updated>
            <content:encoded><![CDATA[<p>Missing data is a universal challenge in data science. While numerous resources cover this topic, practitioners often struggle to find consolidated, actionable insights in one place. This guide aims to bridge that gap, offering a detailed exploration of missing data handling techniques for data professionals and enthusiasts.</p><p><strong>Understanding Missing Data</strong><br>Missing data refers to values that are absent but would hold meaning if observed. These gaps can stem from incomplete entries, file corruption, human error, or systemic issues during data collection. Real-world datasets are rarely pristine, and addressing missing values is a critical step before analysis or modeling. While some machine learning algorithms handle missing data internally, manual intervention through strategic imputation often yields better results. Success here hinges on domain knowledge and a nuanced understanding of the data’s context.</p><p><strong>The Three Types of Missing Data</strong><br>Missingness falls into three categories, each with distinct implications:</p><ul><li><strong>Missing Completely at Random (MCAR)<br></strong>When we describe data as missing completely at random, it means the missingness is entirely unrelated to the variables being studied — whether it’s the completely observed variable (X) or the partially missing variable (Y). For example, consider a weighing scale that stops working because its batteries run out, a questionnaire that gets lost in the mail, or a blood sample that becomes damaged in the laboratory. MCAR represents an ideal scenario, although it’s typically an unrealistic assumption in most practical situations. Data is generally regarded as MCAR when missingness occurs by design, due to technical equipment failure, samples lost in transit, or samples that are technically unsatisfactory. One key statistical advantage of data that are MCAR is that the analysis remains unbiased, meaning the missingness does not distort the results. In a visual context, MCAR can be represented where the missingness has no relationship with the dataset’s variables X or Y, but is instead associated with an external factor, say Z.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*7KcbJhE9N2HnGLyv.png" /></figure><ul><li><strong>Missing at Random (MAR)</strong><br>Missing at Random refers to situations where the missingness is related to the observed data but not to the missing data itself. In other words, the probability of missing data on variable Y is related to some other observed variable X, but not to the values of Y that are missing. For instance, consider a scenario in a study where younger patients are less likely to report their income details. Here, the missingness in income data is associated with the age variable (which is observed) but not directly with the income variable itself. Although MAR is still an assumption, it is more realistic than MCAR and is widely used in many statistical methods for handling missing data. When data is MAR, with the right statistical techniques and models, we can make reliable imputations that minimize bias in our analysis.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*BnzIVCRSVMgZXR-J.png" /></figure><ul><li><strong>Missing Not at Random (MNAR)</strong><br>MNAR occurs when missingness directly relates to the missing data itself. For example, a drug user skipping a test to avoid detection, a student avoiding an English exam due to poor skills. In a survey about income levels, individuals with higher incomes might deliberately choose not to disclose their earnings. Here, the missingness in the income variable is directly related to the value of the income itself. MNAR introduces significant bias and requires advanced modeling or external data sources to make reasonable assumptions about the missing values. In such cases, standard imputation methods may fall short, and deeper investigation is necessary to mitigate bias.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*Zr0NSph3BUVMbkd0.png" /></figure><p><strong>Strategies for Handling Missing Data</strong></p><p><strong>1. Data Recovery</strong><br>Proactively collect missing data during initial phases if possible (e.g., verifying survey completeness). While ideal, this approach is often impractical post-collection.</p><p><strong>2. Educated Guessing</strong><br>Use context clues (e.g., inferring a missing matrix question response based on adjacent answers). Though subjective, this method can work in structured scenarios.</p><p><strong>3. Data Deletion</strong></p><ul><li><strong>Listwise Deletion</strong>: Remove rows with missing values. Effective for large MCAR datasets but risks bias and reduced sample size.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*PaXqXTx-4nRMDwMx.png" /></figure><ul><li><strong>Pairwise Deletion</strong>: Use only available data points for analysis. Pairwise deletion tends to be less biased, especially when data is <strong>MCAR</strong> or <strong>MAR</strong>. Pairwise deletion preserves more information. However, since each analysis might be based on a different subset of data, comparing results becomes challenging. Moreover, if missingness is widespread, pairwise deletion may still lead to incomplete or unreliable analyses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*VxdhRARgheepAaIb.png" /></figure><ul><li><strong>Dropping Variables</strong>: Eliminate columns with excessive missing data. While there is no strict rule of thumb for deciding when to drop a variable, this option becomes more appealing if the variable(column) is not critical to your analysis and efforts to impute or recover the data are unsuccessful.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/0*1VQel0fombZdP-2L.png" /></figure><p><strong>4. Imputation Techniques</strong></p><ul><li><strong>Mean/Median/Mode Substitution</strong>: Replace missing values with central tendencies. Simple but distorts variance and covariance.<strong><br>a) Mean substitution</strong> uses the average value of a variable to fill in missing entries. This keeps the sample mean unchanged. The idea here is that the mean represents a reasonable estimate for a randomly selected value from a normal distribution. However, if missing values are not entirely random, or if the variables have unequal numbers of missing entries, this method can introduce bias. Key drawbacks include distortion of both the original variance and the covariance with other variables in the dataset.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ZJKbArmlAc_ZrG_t.png" /></figure><ul><li><strong>b) Median substitution</strong> is suitable for skewed distributions. Using the median helps mitigate the impact of outliers and better represents the central tendency in non-normal distributions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*AWGznmyPBG8BIpvs.png" /></figure><ul><li><strong>c) Mode substitution</strong> involves replacing missing values with the most frequently occurring value in the dataset, assuming that the most common value is the most likely substitute.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*NWKZZnlp7CmRd9gK.png" /></figure><ul><li><strong>Last/Next Observation Carried Forward (LOCF/NOCB)</strong>: <br><strong>LOCF </strong>is common in time-series where each missing value is filled with the most recent previous observation. <br><strong>NOCB </strong>is similar to LOCF but in reverse, i.e., it fills missing values by taking the next available observation and carrying it backward to fill gaps. This can be helpful in certain time-dependent datasets.<br>The drawback is these techniques assumes stability over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*oUnVBc_l7GBQTVg9.png" /><figcaption>LOCF</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*P5VGLraKVlk35JU8.png" /><figcaption>NOCB</figcaption></figure><ul><li><strong>Linear Interpolation</strong>: Estimate gaps using neighboring values. Pandas offers advanced methods like spline or polynomial interpolation. While this method works well for linear patterns, more complex trends may require advanced interpolation techniques.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*c0t_49aWsJcWtqbS.png" /></figure><ul><li><strong>Common-Point Imputation</strong>: Use midpoint or mode for ordinal scales. For example consider a 5 point Likert scale, the missing values can be substituted by “3” which is the Midpoint or “4” which is the Mode on a 5-point Likert scale. While similar to using the mean, this approach is better suited for ordinal data.</li></ul><blockquote>We’ve all been asked on a survey how much we agree or disagree with a statement or rate your experience about a survey. That’s a Likert scale.</blockquote><blockquote>It’s a type of rating scale, often found on survey forms, that <strong>measures how strongly people feel about something.</strong></blockquote><blockquote>Asking yourself what a 5-point Likert scale looks like? Check out the Likert scale example below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*Va_QbaYltJ6hKfKq.png" /></figure><ul><li><strong>Adding a “Missing” Category</strong>: One of the most widely adopted methods for handling missing data in categorical variables. Missing data is treated as a separate category often labeled as “Missing”. This method doesn’t make any assumptions about why data is missing and is useful when the amount of missing data is high.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*Er_viRT6vU5dodcD.png" /></figure><ul><li><strong>Frequent Category Imputation</strong>: Replace gaps with the most common category. This is analogous to mean or median imputation but applied to categorical data. It ensures that the most common label fills in the gaps, maintaining consistency in the data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*o7C5Atc8_LmPuA9x.png" /></figure><ul><li><strong>Arbitrary Value Imputation</strong>: Use outliers like -999 or 999 to flag missingness. It’s important to choose a value that doesn’t overlap with the natural distribution of the data. Effective for tree-based models.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*vFsivOu_cEYJxvdb.png" /></figure><ul><li><strong>Missing Indicator Variables</strong>: Create binary flags (0/1) to denote missing data, often paired with mean imputation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ILQ2CZzHfEFd9pSH.png" /></figure><ul><li><strong>Random Sampling</strong>: Fill gaps with random values from the observed distribution, assuming MCAR. This helps preserve the original distribution of the data, making it a good choice when maintaining variance is important.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*kBLuaNdWCRzJ85QNgpvMoA.png" /></figure><p><strong>5. Advanced Methods</strong></p><ul><li><strong>Multiple Imputation (MI)</strong>: This technique involves generating multiple plausible datasets, from the available data, through imputation, analyzing each dataset separately, and then combining the results to account for uncertainty in the imputations. MI operates under the assumption that missing data is either<a href="https://play.google.com/store/books/details?pcampaignid=books_read_action&amp;id=Evq6EAAAQBAJ"> <strong>Missing Completely at Random (MCAR)</strong> or <strong>Missing at Random (MAR)</strong></a>. MI reduces bias.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*YM-CuQkNANrME_4l.png" /></figure><ul><li><strong>Predictive Models:<br>&gt; <em>Linear Regression</em>: </strong>Predict missing values using existing values(observed variables).<br><strong>&gt; <em>Random Forest</em>:</strong> Uses an ensemble of decision trees to estimate missing values and provides out-of-bag (OOB) error estimates for imputation accuracy. Robust for MAR/MNAR data, requires large datasets. Applying it to small datasets can lead to overfitting.<br><strong>&gt; <em>k-NN</em>:</strong> Impute based on nearest neighbors’ attributes. Effective method when there is a strong relationship between features.</li><li><strong>Expectation-Maximization (EM)</strong>: Iteratively estimate parameters and impute values until convergence.</li><li><strong>Maximum Likelihood</strong>: Use observed data(available data) distribution to estimate missing values. The missing data values are estimated based on the parameters which have just been estimated.</li></ul><p><strong>6. Sensitivity Analysis</strong><br>Evaluates how outcomes change under various assumptions about missing data to assess the robustness of results, particularly when the MAR assumption is in doubt.</p><p><strong>Algorithms Robust to Missing Data</strong><br>Some models inherently handle missing values:</p><ul><li><strong>k-Nearest Neighbors</strong>: Ignores missing values in distance calculations.</li><li><strong>Decision Trees</strong>: Treat missingness as a unique split criterion.</li><li><strong>XGBoost</strong>: Automatically manages missing data during training.</li></ul><p><a href="https://medium.com/@tpreethi/dbscan-algorithm-density-based-spatial-clustering-of-application-with-noise-a826538dcb42">DBSCAN Algorithm — Density Based Spatial Clustering of Application with Noise</a></p><p><strong>Best Practices</strong></p><ul><li><strong>Prevent Missing Data</strong>: Optimize data collection processes to minimize gaps.</li><li><strong>Prioritize Advanced Techniques</strong>: Methods like multiple imputation or maximum likelihood outperform traditional approaches for large datasets.</li><li><strong>Validate Assumptions</strong>: Always assess whether MCAR/MAR conditions hold before choosing a strategy.</li><li><strong>Leverage Robust Models</strong>: When imputation fails, use algorithms like XGBoost or Random Forest that tolerate missingness.</li></ul><p><strong>Final Thoughts</strong><br>Missing data isn’t just a hurdle — it’s an opportunity to refine your dataset and enhance model interpretability. While no one-size-fits-all solution exists, combining domain expertise with advanced imputation techniques ensures robust analyses. Always document your handling strategy to maintain transparency and reproducibility in your work.</p><blockquote>Thank you for taking the time to read this blog. Handling missing data is challenging, but with the right approach, we can make our analyses more reliable and insightful.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86af800fcbdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DBSCAN Algorithm — Density Based Spatial Clustering of Application with Noise]]></title>
            <link>https://medium.com/@preethithakur/dbscan-algorithm-density-based-spatial-clustering-of-application-with-noise-a826538dcb42?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a826538dcb42</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dbscan]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 00:09:08 GMT</pubDate>
            <atom:updated>2022-11-08T00:10:44.551Z</atom:updated>
            <content:encoded><![CDATA[<h3>DBSCAN Algorithm — Density Based Spatial Clustering of Application with Noise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*SOUGjZwam-QJdp0Q" /></figure><p>Clustering Analysis is useful for customer segmantation to understand what type of customers are related to each other. There are four different techniques we can use to create clusters:</p><ul><li>Centroid-based Clustering</li><li>Density-based Clustering</li><li>Distribution-based Clustering</li><li>Connectivity-based Clustering</li></ul><p>DBSCAN is a density-based clustering algorithm. In DBSCAN algorithm the data objects or data points are clustererd based on the density. The intuition can be explained in four simple points:</p><ul><li>For each instance, the algorithm counts how many instances are located within a small distance from it. This distance is the radius of the circle formed with data points as center and mathematically it is represented as ε (epsilon). And this region is called the instance’s ε-neighborhood.</li><li>If an instance has at least min_samples instances in its ε-neighborhood (including itself), then it is considered a core instance. In other words, core instances are those that are located in dense regions. And min_samples are the minimum data points that are present within the radius ε.</li><li>All instances in the neighborhood of a core instance belong to the same cluster. This may include other core instances, therefore a long sequence of neighboring core instances forms a single cluster.</li><li>Any instance that is not a core instance and does not have one in its neighborhood is considered an <strong>anomaly</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*md_LxbDDnS9JHoR_.png" /></figure><p>In this image the DBSCAN algorithm has generated two clusters. Data points are categorized into three types of points, which are:</p><ul><li><strong>Core points</strong> (red) — are points that satisfy the cluster criteria, i.e., min_samples instances in its ε-neighborhood. Sometime they are also referred as <em>center data point</em>. Core points can be either inside the circle or just in the centre or on the circle, but not away from circle.</li><li><strong>Border points</strong> (blue) — do not satisfy the cluster criteria but are within a core point’s reach.</li><li><strong>Noise points</strong> (grey) — are the anamolies and these points belong to neither of the two above mentioned types</li></ul><h3>Advantages</h3><ul><li>This algorithm works well if all the clusters are dense enough, and they are well separated by low-density regions.</li><li>Does not require a-priori specification of number of clusters.</li><li>Able to identify noisy data i.e. <em>the outliers</em>, while clustering.</li><li>DBSCAN algorithm is able to find arbitrarily size and arbitrarily shaped clusters.</li></ul><h3>Disadvantages</h3><ul><li>DBSCAN algorithm fails in case of varying density clusters.</li><li>Fails in case of neck type of dataset, like following</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*z-YilXW0wIzPtEQO.png" /></figure><ul><li>Does not work well in case of high dimensional data.</li></ul><h3>DBSCAN Hyperparameters</h3><pre><em>class </em>sklearn.cluster.<strong>DBSCAN</strong>(<em>eps=0.5</em>, <em>*</em>, <em>min_samples=5</em>, <em>metric=&#39;euclidean&#39;</em>, <em>metric_params=None</em>, <em>algorithm=&#39;auto&#39;</em>, <em>leaf_size=30</em>, <em>p=None</em>, <em>n_jobs=None</em>)</pre><p><strong>eps : </strong><em>float, default=0.5</em></p><p>This is the most important DBSCAN parameter to choose appropriately for your data set and distance function. This is the maximum distance between two samples one being the core instance and other is the neighboring core instance .</p><p><strong>min_samples : </strong><em>int, default=5</em></p><p>Another important parameter. This is the number of samples in a neighborhood for a core point. This includes the point itself.</p><p>I have mentioned only few hyperparameters which we will most probably use. You can learn about other hyperparameters related to DBSCAN at <a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html">sklearn documentation</a>.</p><h3>Implementing DBSCAN Clustering in Python</h3><p>Let’s test it on the moons dataset,</p><pre>from sklearn.cluster import DBSCAN<br>from sklearn.datasets import make_moonsX, y = make_moons(n_samples=1000, noise=0.05)<br>dbscan = DBSCAN(eps=0.05, min_samples=5)<br>dbscan.fit(X)</pre><p>The labels of all the instances are now available in the labels_ instance variable:</p><pre>&gt;&gt;&gt; dbscan.labels_array([ 0, 2, -1, -1, 1, 0, 0, 0, …, 3, 2, 3, 3, 4, 2, 6, 3])</pre><p>Some instances have a cluster index as -1, these are anomalies according to DBSCAN algorithm. The indices of the core instances are available in the <strong>core_sample_indices_</strong> instance variable, and the core instances themselves are available in the <strong>components_instance</strong> variable.</p><pre>&gt;&gt;&gt; len(dbscan.core_sample_indices_)<br>808<br>&gt;&gt;&gt; dbscan.core_sample_indices_<br>array([ 0, 4, 5, 6, 7, 8, 10, 11, …, 992, 993, 995, 997, 998, 999])<br>&gt;&gt;&gt; dbscan.components_<br>array([[-0.02137124, 0.40618608],<br>[-0.84192557, 0.53058695],<br>…<br>[-0.94355873, 0.3278936 ],<br>[ 0.79419406, 0.60777171]])</pre><p>This will result into following cluster(left image).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I9bol5YZLB4h8uTN.png" /></figure><p>DBSCAN clustering using two different neighborhood radiuses</p><p>On the left, we can see, it identified quite a lot of anomalies, plus 7 different clusters. If we widen each instance’s neighborhood by increasing eps to 0.2, we get the clustering on the right, which looks perfect. Let’s continue with this model.</p><p>Point to note is, the DBSCAN class does not have a <strong>predict()</strong> method, although it has a <strong>fit_predict()</strong> method. So, it cannot predict which cluster a new instance belongs to. This is understandable, because we already have several classification algorithms and it is easy enough to train one with DBSCAN labels. Let’s see how we can do this!</p><pre>from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=50)<br>knn.fit(dbscan.components_, dbscan.labels_[dbscan.core_sample_indices_])</pre><p>We are using KNN classifier. With this, for given few new instances, we can predict which cluster they most likely belong to, and even estimate a probability for each cluster. Note that we only trained them on the core instances, but we could also have chosen to train them on all the instances, or all but the anomalies: this choice depends on the final task.</p><p><a href="https://medium.com/@tpreethi/introduction-to-k-nearest-neighbors-knn-algorithm-python-implementation-9c387915f31d">Introduction to k-Nearest Neighbors (kNN) — With Python Code</a></p><pre>&gt;&gt;&gt; X = np.array([[-0.5, 0], [0, 0.5], [1, -0.1], [2, 1]]) <br>&gt;&gt;&gt; knn.predict(X)<br>array([1, 0, 1, 0])<br>&gt;&gt;&gt; knn.predict_proba(X)<br>array([[0.18, 0.82],<br>[1. , 0. ],<br>[0.12, 0.88],<br>[1. , 0. ]])</pre><p>This will result into the following clustering with decsion boundary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F5v4xFlNHi00e5M8.png" /></figure><h3>Conclusion</h3><p>DBSCAN is a very simple yet powerful algorithm, capable of identifying any number of clusters, of any shape, it is robust to outliers, and it has just two hyperparameters <strong>eps </strong>and<strong> min_samples</strong>. However, if the density varies significantly across the clusters, it can be impossible for it to capture all the clusters properly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a826538dcb42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Decision Tree?]]></title>
            <link>https://medium.com/@preethithakur/what-is-decision-tree-9793833bd87a?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9793833bd87a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 22:25:43 GMT</pubDate>
            <atom:updated>2022-10-23T21:49:39.520Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a Decision Tree? Classification and Regression Trees | Let’s build Decision Trees | Python Code — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odlebPNCPiS5bEWILGTqbQ.png" /></figure><p><strong>Decision Tree</strong> is one of the most powerful Supervised Learning algorithm used for both Classification and Regression.</p><h4>Intuition</h4><p>This algorithm assumes that the data follows a set of rules and these rules are identified by using various mathematical techniques.</p><p>Decision Trees use hyperplanes, which are parallel to any one of the axes, to cut the coordinate system. Each axis defines a feature. The dotted lines are hyperplanes. o and x are the data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*9YJzaPn_9MY4dCkw.png" /></figure><p>Decision Tree builds classification or regression models in the form of a tree structure.</p><h4>How a Tree Structure is built?</h4><p>Decision Tree uses a <em>binary </em>(each node has two children) or <em>non-binary</em> tree graph (each node has more than two children) to assign a <strong><em>target values</em></strong> for <strong><em>each data sample</em></strong>. The target values are presented in the tree <strong><em>leaf</em></strong><em>(or leaves)</em>. To reach to the leaf, the sample is propagated through <strong><em>nodes</em></strong>, starting at the <strong><em>root node</em></strong>. In each node a decision is made, “<em>to which descendant node it should go?”</em>, these nodes are called as <strong><em>decision nodes</em></strong>. The decision is made based on the selected sample’s feature(<em>feature attribute</em>).</p><blockquote>Decision Tree learning is a process of finding the optimal rules in each decision node according to the selected metric.</blockquote><h4>Tree structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*syqG1somQuIomwRIYZ83NA.png" /></figure><p><em>Let’s say there is this dataset</em>, then the dataset breaks down into smaller branches(subtree) while at the same time an associated decision tree is incrementally developed(<em>look at the right side, the tree is growing</em>). By the way, the Decision tree can handle both categorical and numerical data<em>.</em></p><p><em>Doesn’t it looks like a giant structure of nested if-else conditions?</em></p><h4>Decision Tree Construction Process</h4><p>The Decision Tree construction is a step by step process:</p><ul><li><strong>Feature selection</strong>: Select a feature from the features of the training data as the split standard of the current node. (Different standards generate different decision tree algorithms.)</li><li><strong>Decision tree generation</strong>: Generate internal node upside down based on the selected features and stop until the dataset can no longer be split.</li><li><strong>Pruning</strong>: The decision tree may easily become overfitting unless necessary pruning (including pre-pruning and post-pruning) is performed to reduce the tree size and optimize its node structure.</li></ul><h4>Algorithms to build Decision Tree</h4><p>There are two popular algorithms widely used to construct the Decision trees:</p><ol><li><strong>CART </strong>(Classification and Regression Trees) — uses <strong><em>Gini Index(for Classification)</em></strong>, <strong><em>Standard Deviation Reduction (for Regression) </em></strong>as metrics.</li><li><strong>ID3 </strong>(Iterative Dichotomiser 3) — uses <strong><em>Entropy function </em></strong>and <strong><em>Information gain </em></strong>as metrics.</li></ol><h4>Key Points of Decision Tree Construction</h4><p>Before we begin constructing a Decision Tree, we need to ask the <em>right questions, like,</em></p><ul><li>How to decide which feature should be considered as Root Node?</li><li>How to select Decision Nodes and descendent Decision Nodes?</li><li>How to decide splitting criteria for features?</li></ul><h4>Decision Tree for Classification</h4><p>The key step of constructing a decision tree is to divide data of all attributes(<em>features/columns</em>), compare the result sets in terms of ‘<strong>purity</strong>’, and select the attribute with the <strong>highest ‘purity’</strong> as the data point for dataset division. We have two commonly used splitting criteria metrics to quantify the <strong>purity</strong>.</p><ol><li><strong>Entropy</strong> and <strong>Information Gain</strong></li><li><strong>Gini Index</strong></li></ol><h4><strong>Entropy</strong></h4><p><a href="https://en.wikipedia.org/wiki/Entropy_(information_theory)">Entropy</a> is the measure of disorder. It measures the <strong>unpredictability</strong> or <strong>impurity</strong> in the system. Below we can see when red and green dots are distributed in order then the entropy is low. But when there is randomness in the distribution, the entropy is high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*opnLZSpTnroua6-1jHu74w.png" /></figure><ol><li>For a dataset with only 1 class, the samples are homogeneous(which means all samples are similar, belong to same class), <strong>Entropy </strong>will be <strong>0</strong>.</li><li>For a dataset with 2 classes, when there is<strong> no impurity</strong>(all instances belong to same class) then <strong>Entropy</strong> becomes <strong>0</strong>. When<strong> impurity is high</strong>, which means instances of each class are equally distributed(50% each), the <strong>Entropy </strong>is <strong>1</strong>. Below we have a graph of enthropy for probability of class “+” , where there are 2 classes “+” and “-”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*Wh_RuBieh48nvLi5rNKuig.png" /></figure><p>3. For a dataset with more than 2 classes, the <strong>Entropy</strong> can be <strong>greater than 1 </strong>for <strong>higher impurity</strong>, and <strong>Entropy </strong>is <strong>0 </strong>when <strong>impurity</strong> is <strong>low</strong>.</p><p>The <strong>mathematical equation</strong> to measure Entropy is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*D54yMtA-cPGoFHOD4maWLQ.png" /></figure><p>P<em>i,k</em> is the ratio of class <em>k</em> instances among the training instances in the i<em>th</em> node.</p><h4>Entropy for continuous variables</h4><p><em>If you observe</em>, till now we have discussed Entropy for categorical data. But we said earlier that Decision Tree is also used for Regression tasks. <em>So, how we measure entropy when data is continuous(numericals)? Let’s see!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*20kXRNbGiPflncr6.png" /><figcaption>KDEplot</figcaption></figure><p>Look at this kdeplot. A <strong>wide</strong>, uniform looking <strong>distribution</strong> where we are more equally <strong>unsure</strong> of the <strong>probabilities </strong>of each <strong>outcome</strong> has more uncertainty and hence has <strong>higher</strong> <strong>entropy</strong>. Conversely, a distribution with a <strong>very narrow peak</strong> would indicate that <strong>we know</strong> with high <strong>probability</strong> what our <strong>outcomes</strong> are, or in other words they lie in a narrow range and so we are more certain, thus indicating that this distribution would have <strong>low</strong> <strong>entropy</strong>.</p><blockquote><a href="https://en.wikipedia.org/wiki/Kernel_density_estimation">Kdeplot is a Kernel Distribution Estimation Plot which depicts the probability density function of the continuous or non-parametric data variables</a></blockquote><p>To build a decision tree, we need to calculate two types of entropy using frequency tables as follows:</p><p>Step 1: Entropy using the frequency table of one attribute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*ko9Iu9vDecFyxaC_.png" /></figure><p>Here is the frequency table of one attribute(target variable), on computing we got Entropy = 0.94</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*jT9fOe81VsFVKR3We-R1Lg.png" /></figure><p>Step 2: Entropy using the frequency table of two attributes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*BzUPASpDSAo9q_AgeDtJCQ.png" /></figure><h4>Information gain(IG)</h4><p><a href="https://en.wikipedia.org/wiki/Information_gain_(decision_tree)">Information gain</a> is a metric to train Decision trees. This metric measures the quality of the split. The information gain is based on decrease in entropy after the dataset is split based on an attribute. We need to find out that attribute that returns highest information gain(most homogeneous branches). The Decision Tree algorithm follows various steps to get higest IG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*2VSmGeRHNFHiGtdLeegX_w.png" /><figcaption>Information Gain IG</figcaption></figure><p>Step 1: <strong>Calculate the entropy of the parent before splitting</strong>. From the frequency table of target variable(play golf) entropy is calculated first; Entropy = 0.94</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*jT9fOe81VsFVKR3We-R1Lg.png" /></figure><p>Step 2: <strong>Calculate the entropy of each child</strong>. The dataset is split on the different attributes(Sunny, Overcast, Rain) of a feature(Outlook). Then the entropy of each attribute is calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukbfgpI4xg4EP8WUVDuH2w.png" /></figure><p>Step 3: <strong>Calculate weighted entropy of children. </strong>For feature(Outlook), the product of the entropies( that we calculated in step 2) and probablitity of each child is calculated. Then sum of all the products is calculated. We got weighted entropy of children. <strong>Weighted entropy = 0.693</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*BzUPASpDSAo9q_AgeDtJCQ.png" /></figure><p>Step 4: <strong>Calculate Information Gain. </strong>We have equation of Information gain, all we need to do it substitute the values that we got in previous steps in this equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*Y_ZJQZVj2QhI8Zama3Dxpg.png" /></figure><p>Step 5:<strong> Calculate Information Gain IG for all features</strong>. The algorithm calculates IG for all features and chooses the feature with the largest IG as the <strong>decision node.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*7cJEi02331zVvl2LKNzoxQ.png" /><figcaption>Information Gain for all features</figcaption></figure><p>Look at the pictures, we can see the <strong>highest</strong> <strong>Information Gain</strong> is for <strong>Outlook </strong>feature. Decision Tree chooses Outlook<strong> </strong>feature as the<strong> root node.</strong></p><p>In next step, the Decision tree divides the dataset by its branches and repeats the same process on every branch. <em>Let’s see how!</em></p><p>Step 6: <strong>Find Information Gain recursively</strong>. The Decision Tree then applies a recursive greedy search algorithm in top to bottom fashion to find <strong>IG </strong>at every level of the tree. Splitting stops once we reach to a branch with entropy 0, this branch is the leaf node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otw5qao7l5cN7Vj0lNrHnQ.png" /><figcaption>Demonstration of next splits</figcaption></figure><p>The final decision tree would look like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gDKtMWdwjFA5Bnmr.png" /></figure><h4>Gini Impurity</h4><p>Gini Impurity or <em>Gini Index </em>measures the degree or probability of a particular variable being wrongly classified when it is randomly chosen.<em> </em>It is used to determine how the features of a dataset should split nodes to form the tree. The formula of Gini Impurity is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*ltv4HbplzeHBtro1JcPIlw.png" /></figure><p>The degree of gini index varies from 0 to 1,</p><ul><li>Where 0 depicts that all the elements be allied to a certain class, or only one class exists there.</li><li>The gini index of value as 1 signifies that all the elements are randomly distributed across various classes.</li><li>A value of 0.5 denotes the elements are uniformly distributed into some classes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*pCgRRGEVCj0Ec9TC5GkpJQ.png" /></figure><p>There is not much difference in the Decision trees that we get fromx`x` Entropy and Gini Impurity. But, Gini is computationally <strong>slightly faster</strong> than Entropy. Gini is useful on large datasets. However, when they differ, Gini impurity tends to isolate the most frequent class in its own branch of the tree, while entropy tends to produce slightly more balanced trees.</p><h4>Regularization Hyperparameters</h4><p>In Decision Trees, the tree structure will adapt itself to the training data, which leads the model to overfit on training data and the model fails to generalize on test set/data. To avoid this problem, the Decision Tree’s degree of freedom has to be restrained during training. This process is called as <strong>Regularization. </strong>The regularization hyperparameters depend on the type of algorithm. In Decision trees we can restrain the D<strong>epth</strong> of the tree to prevent the model from overfitting.<strong> </strong><em>Depth</em> of the tree is a measure of how many splits can a Decision Tree make.</p><p>In <em>Scikit-Learn </em><strong>DecisionTreeClassifier </strong>class is used to build the decision tree. Some important hyperparameters that restrict the freedom/shape of the Decision Tree are:</p><ul><li><strong>max_depth</strong> (The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples). The lower max_depth value leads to underfitting and higher value leads to overfitting.</li><li><strong>min_samples_split</strong> (the minimum number of samples a node must have before it can be split)</li><li><strong>min_samples_leaf</strong> (the minimum number of samples a leaf node must have)</li><li><strong>min_weight_fraction_leaf</strong> (same as min_samples_leaf but expressed as a fraction of the total number of weighted instances)</li><li><strong>max_leaf_nodes</strong> (maximum number of leaf nodes)</li><li><strong>max_features</strong> (maximum number of features that are evaluated for splitting at each node).</li></ul><p>Increasing min_* hyperparameters or reducing max_* hyperparameters will regularize the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isn8X6iFcBVzKflMpOeNxA.png" /></figure><p>Here are two Decision Trees trained on the a dataset. On the left, the Decision Tree is trained with the default hyperparameters (without restrictions), and on the right the Decision Tree is trained with <strong>min_sam ples_leaf=4</strong>. We can see that the left model is overfitting, while the right model generalize better.</p><h4><strong>Decision Tree for Regression</strong></h4><p>Decision Trees are also capable of performing regression tasks. Regression tree looks very similar to the classification tree. Contrary to the <em>classification</em> problem the estimation of the target variable in a <em>regression</em> problem is a continuous value and not a categorical value.</p><p>In the following system we can see the decision tree made four splits and divided the data points into five groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*0XlGDxnS0EQQdmS5hQ4cNQ.png" /></figure><p>Now, this algorithm will take the average value of each group and based on that values it will build the decision tree for the dataset. The resultant tree would look like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*8QmAdKxfAt1Jp6bDggBY1Q.png" /></figure><h4>How Does a Decision Tree Work for Regression?</h4><p>The <strong>ID3 algorithm (Iterative Dichotomiser 3)</strong> can be used to construct a Decision tree for <strong>Regression </strong>which replaces the <em>Gini Impurity</em> or <em>Entropy and Information Gain</em> metric with the <strong>Standard Deviation Reduction (SDR)</strong>.</p><p><em>Standard Deviation Reduction</em> is based on the decrease in <strong>Standard Deviation </strong>after a dataset is split on an attribute. The tree will be split by the attribute with the<strong> higher </strong>SDR of the target variable. The standard deviation is used to measure <strong>homogeneity(</strong>similar values<strong>)</strong> of the numerical samples(target variable). The mathematical formula of <em>Standard Deviation Reduction</em> is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*iUQIoWMJuHQZBDQsG7uawg.png" /><figcaption>Standard Deviation Reduction</figcaption></figure><ul><li><em>Y</em> is target variable</li><li><em>X</em> is a specific attribute of the dataset</li><li>SDR(Y,X) is the reduction of the standard deviation of the target variable Y given the information of X</li><li>S(Y) is the standard deviation of the target variable</li><li>S(Y,X) is the standard deviation of the target variable given the information of X</li></ul><p>The node (independent variable) which has more reduction in standard deviation that will be declared as a <strong>Decision node</strong>. In first iteration this node will be called as root node.</p><blockquote>If the numerical sample is completely homogeneous with respect to independent variable (we check for each independent variable separately), then its standard deviation is zero.</blockquote><p>The calculation of <em>S(Y,X)</em> can be broken down with the following formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*vliICTC72Be8AmJ7ti2yPg.png" /></figure><p><strong>S(Y,X)</strong> is the sum of the probability of each of the values of the independent variable multiplied by the standard deviation of the target variable based on those values of the independent variable. Here,</p><ul><li>S(c) is the standard deviation of the target variable based on unique values of the independent variable.</li><li>P(c) is the number of probability of the value of the independent variables over the total values of the independent variable</li></ul><p>The feature with the higher value of <em>S(Y,X)</em> is the feature that has more capability to explain the variations in the target variable, therefore is the feature that the decision tree algorithm will use to split the tree.</p><h4><strong>Reduction in Variance or Standard Deviation Reduction (SDR)</strong></h4><p>Variance tells us the average distance of all data points from the mean point. Standard deviation is the square root of the variance. As variance is calculated in squared unit and hence to come up a value having unit equal to the data points, we take square root of the variance and which is <strong>Standard Deviation</strong>. The mathematical formulas which we need are,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*tUuzsVXoEvvw-tJTit5BEg.png" /></figure><p>Standard Deviation is square root of Mean Square Error (MSE).</p><p>Let’s see the step by step process of building Decision tree for Regression. Here, we have added a new feature as <em>Hours Played, </em>to the weather dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*YlcFqIKcbJ0S47xiOTyCXg.png" /></figure><p><strong>Step 1: </strong>Calculate the total standard deviation with respect to target variable, before split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*S0yaL4zCmEcnlbZXKNg0pw.png" /></figure><p>Coefficient of variation is used as the stopping criteria for further split.</p><p><strong>Step 2:</strong> Calculate SDR with respect to independent variables and decide on root node, decision nodes and leaf nodes.</p><p>SDR for Outlook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8ToVRV9OhgHAwg-tsKoiQ.png" /></figure><p>Similarly, when we calculate SDR for all attributes, we get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*TYQV8mxiQvnPSe1rr_703A.png" /></figure><ol><li>SDR (Hours, Outlook) = 1.66</li><li>SDR (Hours, Temperature) = 0.39</li><li>SDR (Hours, Humidity) = 0.09</li><li>SDR (Hours, Windy) = 0.39</li></ol><p>Step 3: <strong>Deciding the root node</strong></p><p>Outlook has most reduction in standard deviation hence outlook will be the root node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*93DxbJPOWwk4DVN9MgufsA.png" /></figure><p>Step 4: The dataset is divided based on the values of the selected attribute. This process is run recursively on the non-leaf branches, until all data is processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWjdk0Uv9XRMuOOULchrxg.png" /></figure><p>For the next node we need some <strong>termination criteria</strong> like when to stop splitting. Hence, we consider<strong> coefficient of variance CV </strong>as one of the termination criteria and for example can set CV = 10% as a threshold. So, if we have CV &gt; 10% then further splitting is required else will stop there. Or we can also set threshold on number of data points (rows) if less than or equal to 3 then no split required.</p><p>The prediction at leaf node will be the average of that branch. Here Sunny and Rainy nodes need further splitting as both have CV &gt; 10%. However, Overcast does not need splitting as CV for overcast &lt;= 10%.</p><p>Average value of overcast branch = 46.25 will be the prediction at overcast leaf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*uGGdQdlgyccblfVSXMv6Sg.png" /></figure><p>Now we will repeat the same SDR check for data filtered for Sunny and Rainy, to get other decision nodes and subsequent leaf nodes.</p><p><strong>SDR check for Sunny data rows</strong></p><p>Look below, “<em>Sunny</em>” branch CV(22.10%) &gt; 10% threshold, which needs further splitting. We select “<em>Temp</em>” as the best node after “Outlook” because it has the largest SDR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*D-Wz-uM1XiuxbNC6Pu9IMw.png" /></figure><p>Because the number of rows for each Hot, Mild and Cool are &lt; 3, no further split is required.</p><p><strong>SDR check for Rainy Data rows</strong></p><p>The <em>“Rainy” </em>branch has an CV (22%) &gt; 10% threshold. This branch needs further splitting. We select “Temp” as the best node because it has the largest SDR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*flUjVr7750-soJz48DaLgQ.png" /></figure><p>Because the number of data points for both branches (FALSE and TRUE) is equal or less than 3, we stop further branching and assign the average of each branch to the related leaf node.</p><p>The final Decision Tree for Regression is here,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*tv_0lgeZGBa07EmibDcxdA.png" /></figure><p><strong>Decision Tree Interpretation:</strong></p><ol><li>If <strong><em>Outlook</em> </strong>condition is <strong><em>Sunny</em></strong> and <strong><em>Temperature </em></strong>is mild then prediction on number of hours match can be played is <strong>41.5</strong> hours irrespective of other conditions.</li><li>If <strong><em>Outlook</em> </strong>is <strong><em>Overcast</em> </strong>then irrespective of other conditions, prediction is <strong>46.25</strong> hours.</li><li>If <strong><em>Outlook </em></strong>is <strong><em>Rainy</em> </strong>then if it is <strong><em>Windy</em></strong> then prediction is <strong>26.5</strong> hours and if it is not windy then prediction is <strong>47.6 </strong>hours.</li></ol><h4>Advantages and Disadvantages of Decision Trees</h4><p><strong>Advantages</strong></p><ul><li><strong>Less Data Preprocessing</strong> — Unlike other machine learning algorithms, a decision tree does not require well-preprocessed data.</li><li><strong>No Normalization </strong>— Decision tree does not require normalized data.</li><li><strong>No Scaling —</strong> The data doesn’t need to be scaled before feeding it to the decision tree model.</li><li><strong>Not Affected by Missing Value </strong>— Unlike k-Nearest Neighbors or other distance-based algorithms, a decision tree is not affected by missing values.</li><li><strong>Easy and Intuitive</strong> — A decision tree is intuitive and fairly easy to understand and explain the underlying properties.</li></ul><p><strong>Disadvantages</strong></p><ul><li><strong>Highly Sensitive —</strong> A small change in data can cause high instability to a decision tree model.</li><li><strong>Complex Calculation —</strong> A decision tree uses more complex computation compared to other models.</li><li><strong>High Training Time —</strong> It takes higher time to train a decision tree. model.</li><li><strong>Costly — </strong>Decision tree based models require more space and time, so it is computationally expensive.</li><li><strong>Weak —</strong> A single tree can not learn much of the data, therefore, you won’t get a good predictor using a single decision tree. You need to ensemble a higher number of decision trees like <strong><em>Random Forest</em></strong> to get better prediction accuracy.</li></ul><h4>Conclusion</h4><p>Decision trees are most powerful in Machine Learning. For being simple to understand, they are preferered over other approaches to same problems. One can use decision trees to perform basic customer segmentation and build a different predictive model on the segments.</p><p>In next blog let’s see how to implement Decision Tree algorithm for both Classification and Regression tasks using Scikit-Learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9793833bd87a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to k-Nearest Neighbors (kNN) — With Python Code]]></title>
            <link>https://medium.com/@preethithakur/introduction-to-k-nearest-neighbors-knn-algorithm-python-implementation-9c387915f31d?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c387915f31d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[k-nearest-neighbors]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 22:04:15 GMT</pubDate>
            <atom:updated>2022-10-23T21:59:48.356Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to k-Nearest Neighbors (kNN) | Python Code | Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*n9v1xsBi0bek98rqBnWGEg.gif" /></figure><p>The <strong>k-nearest neighbors (kNN) </strong>algorithm, is a non-parametric, supervised learning classifier, which uses proximity to make classifications or predictions about the grouping of an individual data point. While it can be used for either <em>Regression</em> or <em>Classification</em> problems, it is typically used as a classification algorithm, working off the assumption that similar points can be found near one another.</p><p><em>The graphic above shows how a kNN classifier works.</em></p><h4><strong>Intuition</strong></h4><p>The kNN algorithm is different from other machine learning algorithms. Each ML model has its specific formula that needs to be estimated during training. But, the kNN algorithm formula is computed during prediction rather than training. <strong><em>Why?</em></strong> Because of the intuition of the kNN algorithm, which is,</p><blockquote><em>“When a new data point arrives, the kNN algorithm will start by finding the nearest neighbors of this new data point. Then it takes the feature values of these neighbors and uses them as a prediction for the new data point”</em></blockquote><p>From this intuition we can say that, kNN algorithm is,</p><p><strong>Instance-based learning</strong>: The model learns entire training instances then generalizes to new data values by using similarity measure(Euclidean distance) to compare them to the learned instances. <em>In this blog we will learn how this happens.</em></p><p><strong>Lazy Learning</strong>: The model will do nothing in training phase. It just memorizes the training dataset. Only during the time of prediction the model searches nearest neighbors from entire training set, making it expensive.</p><p><strong>Non-parametric </strong>: Meaning, that it does not make any assumptions about the underlying data (For example linear regression assumes data is linearly distributed).</p><h4>kNN for Classification</h4><p>For classification problems, when we want to predict the class of a data point, the algorithm queries the <em>k</em> points that are closest to the data point and returns the class label on the basis of majority voting, that is the most frequently used label of their class will become the predicted label.</p><p>Look below, we took 7 nearest neighbors(k=7) that belong to Class A and Class B. Majority of the neighbors belong to Class B. Therefore the data point class will be labelled as Class B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ky6ofD04Z0axy5OJi4bCoA.png" /></figure><h4>kNN for Regression</h4><p>Regression problems use a similar concept as classification problem, the algorithm queries the <em>k</em> closest points to the data point and returns the average of their values as the predicted value. The main distinction here is that classification is used for discrete values, whereas regression is used with continuous values.</p><p><a href="https://medium.com/@tpreethi19/undesrtand-naive-bayes-algorithm-in-simple-explanation-with-python-code-part-1-bb45c1b0409a">Undesrtand Naive Bayes algorithm in simple explanation with python code — Part 1</a></p><h4>kNN Mathematical Description</h4><p>Now, we know to predict the class label of the given query point we need to identify its nearest neighbors. <em>But, how do we do this? You might have guessed already, we calculate the distance. </em>There are few distance metrics that we can use to calculate the distance between the query point and other data points. These distance metrics help to form decision boundaries, dividing data points on basis of their class labels.</p><ul><li><strong>Euclidean distance</strong>: This is the most commonly used distance measure, and it is limited to real-valued vectors. Using the below formula, it measures a straight line between the query point and the other point being measured.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*G0qOPbhx6iIlRI5TrZSy3Q.png" /></figure><blockquote>Euclidean distance refers to the distance between two points. These points can be in different dimensional space and are represented by different forms of coordinates.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*nxaIbGvmkMRp81ksLExPpg.png" /></figure><p>Here we are computing the euclidean distance between two points (X21,Y21) and (X22,Y22), you take the square root of the sum of the squares of two difference vectors (Y22-Y21) and (X22-X21). Euclidean distance is nothing but the length of the vector and is refered as N<strong>orm </strong>or<strong> Euclidean Norm.</strong></p><ul><li><strong>Manhattan distance</strong>: This is another popular distance metric, which measures the absolute value between two points. The formula is,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/0*JLRFeSG02H_R_4S2.png" /></figure><ul><li><strong>Minkowski distance</strong>: This distance measure is the generalized form of Euclidean and Manhattan distance metrics. The parameter, p, in the formula below, allows for the creation of other distance metrics. Euclidean distance is represented by this formula when p is equal to two, and Manhattan distance is denoted with p equal to one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*2EpAF0Hp5eXAPvMT.png" /></figure><ul><li>p=1: Manhattan Distance (<em>l1</em> norm)</li><li>p=2: Euclidean Distance (<em>l2</em> norm)</li></ul><p><strong>Hamming distance</strong>: This technique is typically used with Boolean or string vectors(<strong>categorical variables</strong>), identifying the points where the vectors do not match. As a result, it has also been referred to as the overlap metric. This can be represented with the following formula,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/0*ZdhSuLfDgYxX3s_3.png" /></figure><h4>Choosing optimal value of k</h4><p>There isn’t a specific way to determine the best <em>k </em>value. You need to experiment with a few values of <em>k </em>before deciding which one to go forward with. Let’s see what all ways we have to choose optimal value of <em>k.</em></p><ul><li>One of the common ways is to choose the value of <em>k</em> by calculating the square root of N samples in the training data set.</li><li>Another way is, by considering that a part of the training samples is “<em>unknown</em>”. Then, we can categorize the unknown data in the test set by using the kNN algorithm and analyze how good the new categorization is by comparing it with the information we already have in the training data.</li><li>When dealing with a binary class problem, try to choose an odd value for <em>k</em>. <em>What will you do if the number of neighbors in each class is the same(50–50)?</em> It will be difficult to predict the class label for our data point. So, choose k as even number in such cases.</li><li><em>k </em>with lower values(<em>k</em>=1 or <em>k</em>=2), can be noisy and subjected to the effects of outliers. The chance for overfitting is also high in such cases.</li><li>While <em>k </em>with larger value, lead to smoother decision boundaries, but <em>k</em> shouldn’t be too large. Otherwise, groups with a fewer number of data points will always be outvoted by other groups. Moreover, larger <em>k </em>will be computationally expensive.</li></ul><h4>Standardization</h4><p>One major drawback in calculating distance measures directly from the training set is in the case where variables have different measurement scales or there is a mixture of numerical and categorical variables. For example, if one variable is based on annual income in dollars, and the other is based on age in years then income will have a much higher influence on the distance calculated. One solution is to standardize the training set as shown below.</p><h4>kNN Advantages and Disadvantages</h4><h4>Advantages</h4><ol><li><strong>Easy to implement</strong>: Given the algorithm’s simplicity and accuracy, this is a great model for many machine learning use cases that don’t require highly complex techniques.</li><li><strong>Adapts easily</strong>: As new training samples are added, the algorithm adjusts to account for any new data since all training data is stored into memory.</li><li><strong>Few hyperparameters</strong>: KNN only requires a<em> k</em> value and a distance metric hence it is very fast to develop.</li></ol><h4>Disadvantages</h4><ol><li><strong>Does not scale well:</strong> Since KNN is a lazy algorithm, it takes up more memory and data storage compared to other classifiers. This can be costly from both a time and money perspective. More memory and storage will drive up business expenses and more data can take longer to compute.</li><li><strong>Curse of dimensionality:</strong> The KNN algorithm tends to fall victim to the curse of dimensionality, which means that it doesn’t perform well with high-dimensional data inputs. This is sometimes also referred to as the <a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.418.6517&amp;rep=rep1&amp;type=pdf">peaking phenomenon</a>, where after the algorithm attains the optimal number of features, additional features increases the amount of classification errors, especially when the sample size is smaller.</li><li><strong>Prone to overfitting:</strong> Due to the “curse of dimensionality”, KNN is also more prone to overfitting. While feature selection and dimensionality reduction techniques are leveraged to prevent this from occurring, the value of k can also impact the model’s behavior. Lower values of k can overfit the data, whereas higher values of k tend to “smooth out” the prediction values since it is averaging the values over a greater area, or neighborhood. However, if the value of k is too high, then it can underfit the data.</li><li><strong>Performance drop:</strong> kNN is less likely to perform well on advanced tasks like <a href="https://en.wikipedia.org/wiki/Computer_vision">Computer Vision</a> and<a href="https://en.wikipedia.org/wiki/Natural_language_processing"> Natural Language Processing NLP</a>. You can try to push the performance of kNN by adding other techniques like called <strong>bagging</strong>, to improve predictive performances. At a certain point of complexity kNN will probably be less effective than other models regardless of the way it was tuned.</li></ol><p><a href="https://medium.com/@tpreethi19/what-is-logistic-regression-4251709634bb">What is Logistic Regression?</a></p><h4>Implementation with python</h4><ol><li>First step is to import necessary python libraries and read dataset.</li></ol><pre>#importing necessary libraries</pre><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.metrics import accuracy_score, confusion_matrix</pre><pre>#read dataset<br>df = pd.read_csv(&quot;../dataset.csv&quot;)</pre><pre>#size<br>df.shape<br>output: (400, 5)</pre><pre>df.head()</pre><p>Our dataset has 400 samples, 5 features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*Ix6qgmAVl6IAQDvXaTxQRQ.png" /></figure><p>2. Now lets split our predictor(input features X) and responce(target y) variables. As predictor X we took columns from Gender, Age, Estimator, and as response y we took Purchased column.</p><pre>X = df.iloc[:,2:-1].values<br>y = df.iloc[:,-1].values</pre><p>Now, with this code X and y will be two arrays. <em>Why did we take arrays?</em> In the mathematical description above, you can notice our data points are actually two vectors. Then calculated the distance between the data points.</p><p>3. Now, we need to split the data into train and test sets. The train set has 80% samples = 320 ; test set has 20% sample = 80</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=43)</pre><pre>X_train.shape<br>#output: (320, 2)<br>y_train.shape<br>#output: (320,)<br>X_test.shape<br>#output: (80, 2)<br>y_test.shape<br>#output: (80,)</pre><h4>Data preprocessing — Feature Scaling</h4><p>4. The values are varying too much, especially Estimated salary column values are really high. The Euclidean Distance will vary too much. This will affect the performance by giving higher weightage to these variables since their norm(magnitude) will be higher. We need to perform feature scaling.</p><p>Let’s scale the values using <strong>StandardScaler()</strong> from<strong> scikit-learn</strong> library.</p><pre>trf = StandardScaler()</pre><pre>X_train_trf = trf.fit_transform(X_train)<br>X_test_trf = trf.transform(X_test)</pre><h4>Finding the k Nearest Neighbors</h4><p>5. Let’s train the kNN classifier and check the accuracy score of the model. Before going ahead we must have an idea of hyperparameter <strong>n_neighbors</strong>. n_neighbors is the value of k, <em>number of neighbors</em>. We need to decide how many nearest neighbors we want to compare with the new data value.</p><pre>knn = KNeighborsClassifier(n_neighbors=20)</pre><pre>knn.fit(X_train_trf, y_train)<br>y_pred = knn.predict(X_test_trf)</pre><pre>print(“Accuracy: “, accuracy_score(y_test, y_pred))<br>print(confusion_matrix(y_test, y_pred))</pre><p>Here, I took only 20 neighbor and checked my model’s accuracy and got 0.83(83%), not bad. But this will not happen in larger datasets, the accuracy score might fall really low. <a href="https://en.wikipedia.org/wiki/Confusion_matrix">Confusion matrix</a> will tell us how many right and predictions our model made. (43 and 24 are right predictions for the 2 classes. 7 and 6 are wrong predictions for the 2 classes)</p><p><em>I took k = 20, But do you know it is not ideal to take k value as even, because there are chances of getting a tie while voting. What if 10 neighbors belong to one class and other 10 belong to other class?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*68BYkEuomnqqwplNYWsFng.png" /></figure><p>But we can improve this score by choosing right k value. <em>Let’s see how we do it.</em></p><pre>error_train=[]<br>error_test=[]</pre><pre>for i in range(1,26):<br>    knn=KNeighborsClassifier(n_neighbors=i)<br>    knn.fit(X_train_trf,y_train)<br>    x=confusion_matrix(y_train,knn.predict(X_train_trf))<br>    y=confusion_matrix(y_test,knn.predict(X_test_trf))<br>    error_train.append((x[0][1]+x[1][0])/x.sum())<br>    error_test.append((y[0][1]+y[1][0])/y.sum())</pre><pre># plot<br>plt.plot(range(1,26),error_train,label=&#39;training error rate&#39;)<br>plt.plot(range(1,26),error_test,label=&#39;test/validation error rate&#39;)<br>plt.xlabel(&#39;K Value&#39;)<br>plt.ylabel(&#39;Error&#39;)<br>plt.legend()</pre><p>Here we have finding out error rate we will get on train and test set for different values of k. On plotting the output we got,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*UQXQr3suzdf_ZgN1DbSeoQ.png" /></figure><p>Looks like we accuracy is high near k =11</p><h4>Prediction</h4><p>6. Now for our final prediction, let’s update n_neighbors value (k=13) in our model and check the accuracy score and confusion matrix once again.</p><pre>knn = KNeighborsClassifier(n_neighbors=11)</pre><pre>knn.fit(X_train_trf, y_train)<br>y_pred = knn.predict(X_test_trf)</pre><pre>print(“Accuracy: “, accuracy_score(y_test, y_pred))<br>print(confusion_matrix(y_test, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*vhOQTFV1Zc9WIzFyFJnFAg.png" /></figure><p>There you go! We could increase accuracy score by 0.02(2% increase). And our model correct predictions have increased too.</p><h4>Conclusion</h4><p>This was a basic approach to kNN model. It takes a few steps to move from a basic kNN model to a fully tuned model, but the performance increase is totally worth it.</p><p><strong>In this tutorial we have learnt:</strong></p><ul><li>Understand the intuition and mathematical foundations behind the <strong>kNN algorithm</strong></li><li>Used <strong>scikit-learn</strong> for data-preprocessing and to fit kNN.</li></ul><p><a href="https://medium.com/@tpreethi19/what-is-linear-regression-15a931de8481">What is Linear Regression? Loss Funtion | Gradient Descent | Polynomial Regression with Python code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c387915f31d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Undesrtand Naive Bayes algorithm in simple explanation with python code — Part 2]]></title>
            <link>https://medium.com/@preethithakur/undesrtand-naive-bayes-algorithm-in-simple-explanation-with-python-code-part-2-a2b91cbbf637?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2b91cbbf637</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 00:24:16 GMT</pubDate>
            <atom:updated>2022-10-23T22:00:25.064Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sentiment Analysis with Naive Bayes Classifier | NLTK | Python Code | Machine Learning</h3><blockquote><em>This article is continuation of “</em><strong><em>Understand Naive Bayes algorithm in simple explanation with python code — Part 1”</em></strong><em>. If you are new to the Naive Bayes algorithm, I encourage you to </em><a href="https://medium.com/@tpreethi19/undesrtand-naive-bayes-algorithm-in-simple-explanation-with-python-code-part-1-bb45c1b0409a"><strong><em>Click here</em></strong></a><em> for Part 1.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fz7M3WgsADvyRF-b.jpg" /></figure><p>In previous blog we have seen intuition of Naive Bayes algorithm and learnt how the alogorithm works.</p><p>We will perform Sentiment Analysis using Naive Bayes Classifier. We are going to implement different technique like <strong>Segmentation, Stopwords, Bag of words model.</strong></p><p>Let’s begin!</p><p>We will import necessary libraries then read the dataset.</p><pre># importing necessary libraries</pre><pre>import pandas as pd<br>import numpy as np<br>import re</pre><pre>df = pd.read_csv(‘Dataset.csv’)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*d7j4l713sCRtH2S0iBzxWQ.png" /></figure><p>Let’s check the size of dataset.</p><pre>df.shape<br>output: (50000, 2)</pre><p>There are 50000 samples(rows). The data is huge. Let’s take a sample for now. This will make our job easy and quicker.</p><pre># Subset<br>df = df.sample(1000)</pre><pre># resetting index<br>df.reset_index(drop=True, inplace=True)</pre><pre># sample dataset size<br>df.shape<br>output: (1000, 2)</pre><p>Let’s update target variables as binary values 0 and 1</p><pre># positive:1 , negative:0<br>df[‘sentiment’].replace({‘positive’:1, ‘negative’:0}, inplace=True)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*QbPc8UTY6j5iLSKmK2wI7A.png" /></figure><h4>Data preprocessing</h4><p>Data preprocessing is important stage in classification.</p><p>We will remove the noise from the dataset such as html tags, brackets, special characters. Let’s change everything to lower case (abcd).</p><pre># functions to remove noise<br># remove html tags<br>def clean_html(text):<br> clean = re.compile(‘&lt;.*?&gt;’)<br> return re.sub(clean, ‘’, text)</pre><pre># remove brackets<br>def remove_brackets(text):<br> return re.sub(‘\[[^]]*\]’, ‘’, text)</pre><pre># lower the cases<br>def lower_cases(text):<br> return text.lower()</pre><pre># remove special characters<br>def remove_char(text):<br> pattern = r’[^a-zA-z0–9\s]’<br> text = re.sub(pattern, ‘’, text)<br> return text</pre><pre># remove noise(combine above functions)<br>def remove_noise(text):<br> text = clean_html(text)<br> text = remove_brackets(text)<br> text = lower_cases(text) <br> text = remove_char(text) <br> return text</pre><pre># call the function on predictors<br>df[&#39;review&#39;]=df[&#39;review&#39;].apply(remove_noise)</pre><p><a href="https://medium.com/@tpreethi19/introduction-to-k-nearest-neighbors-knn-algorithm-python-implementation-9c387915f31d">Introduction to k-Nearest Neighbors (kNN) — With Python Code</a></p><p>Now, we are going to use <a href="https://en.wikipedia.org/wiki/Stemming"><strong><em>Stemming</em></strong></a>, a text normalization technique in <a href="https://en.wikipedia.org/wiki/Natural_language_processing"><strong>Natural Language Processing (NLP</strong></a><strong>). </strong>This technique will reduce the word size ( for example “calling” and “called” words will be reduced to “call”. So we will have 3 words as “call”)</p><blockquote>Stemming is the process of reducing a word to its word stem that affixes to suffixes and prefixes or to the roots of words known as a lemma.</blockquote><pre>from nltk.stem.porter import PorterStemmer</pre><pre>def stem_words(text):<br> ps = PorterStemmer()<br> stem_list = [ps.stem(word) for word in text.split()] <br> text = ‘’.join(ps.stem(word) for word in text)<br> <br> return text</pre><pre>df[‘review’] = df[‘review’].apply(stem_words)</pre><p>Now let’s remove <a href="https://en.wikipedia.org/wiki/Stop_word"><strong>Stopwords</strong></a>. These words do not add much meaning to a sentence. They can safely be ignored without sacrificing the meaning of the sentence in the reviews. <strong><em>“the, is, at, which, and on”</em></strong> are few common stop words we see in English.</p><blockquote><a href="https://en.wikipedia.org/wiki/Stop_word"><strong>Stop words</strong> are the words in a <strong>stop list</strong> (or <strong><em>stoplist</em></strong> or <em>negative dictionary</em>) which are filtered out (i.e. stopped) before or after processing of natural language data (text) because they are insignificant.</a></blockquote><pre># importing from nlptoolkit library<br>import nltk<br>from nltk.corpus import stopwords</pre><pre># creating list of english stopwords<br>stopword_list = stopwords.words(‘english’)</pre><pre># removing the stopwords from review<br>def remove_stopwords(text):<br>    # list to add filtered words from review<br>    filtered_text = []<br>        # verify &amp; append words from the text to filtered_text list<br>        for word in text.split():<br>            if word not in stopword_list:<br>                filtered_text.append(word)<br>        # add content from filtered_text list to new variable<br>        clean_review = filtered_text[:]<br>        # emptying the filtered_text list for new review<br>        filtered_text.clear()<br>        return clean_review</pre><pre>df[&#39;review&#39;]=df[&#39;review&#39;].apply(remove_stopwords)<br>df[&#39;review&#39;]</pre><pre># join back all words as single paragraph<br>def join_back(text):<br>    return &#39; &#39;.join(text)</pre><pre>df[&#39;review&#39;] = df[&#39;review&#39;].apply(join_back)</pre><pre># check if changes are applied<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*tqzVNvJAuwGybfeUKdKclw.png" /></figure><p>Now we are going to perform feature extraction on reviews column to into numerical feature vector. <strong>Feature extraction</strong> is most important sub-tasks in pattern classification. It yields better results than applying machine learning directly to the raw data.</p><blockquote>Feature extracion refers to the process of transforming raw data into numerical features that can be processed while preserving the information in the original data set.</blockquote><p>We will use<strong> Bag of Words Vectorization </strong>technique for conversion<strong>. </strong>This<strong> </strong>is a classic approach of converting input data from its raw format (i.e. text ) into vectors of real numbers which is the format that ML models support.</p><p>Let’s begin converting out input text data.</p><pre>from sklearn.feature_extraction.text import CountVectorizer</pre><pre>cv = CountVectorizer(max_features=800)</pre><pre># vectorizing words and storing in variable X(predictor)<br>X = cv.fit_transform(df[‘review’]).toarray()</pre><pre># predictor<br>X</pre><pre># X size<br>X.shape<br>output: (1000, 800)</pre><pre># target<br>y = df.iloc[:,-1].values</pre><pre># y size<br>y.shape<br>output: (1000, )</pre><p>We will get an array of 0 and 1 as input feature X. And columns have increased from 1 to 800, number of rows(samples) are 1000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*qmlJtiyhRwmZWAvuyZOCCQ.png" /></figure><p>Now we will split the data into test and train sets</p><pre># train set and test set<br>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>Finally, let’s fit the Naive Bayes Classifiers</p><pre>from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB<br>from sklearn.metrics import accuracy_score</pre><pre># Naive Bayes Classifiers<br>gnb = GaussianNB()<br>mnb = MultinomialNB()<br>bnb = BernoulliNB()</pre><pre># fitting and predicting<br>gnb.fit(X_train, y_train)<br>y_pred_gnb = gnb.predict(X_test)</pre><pre>mnb.fit(X_train, y_train)<br>y_pred_mnb = mnb.predict(X_test)</pre><pre>bnb.fit(X_train, y_train)<br>y_pred_bnb = bnb.predict(X_test)</pre><pre># accuracy scores<br>print(&quot;Gaussian&quot;, accuracy_score(y_test, y_pred_gnb))<br>print(&quot;Multinomial&quot;, accuracy_score(y_test, y_pred_mnb))<br>print(&quot;Bernoulli&quot;, accuracy_score(y_test, y_pred_bnb))</pre><p>We got the accuracy scores for the three classifiers and we can see Multinomial Naive Bayes classifier has higher accuracy than the other two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*_UYXWSg_exvwx-g16myhTg.png" /></figure><p>The accuracy score can be improved by <a href="https://scikit-learn.org/stable/modules/classes.html#module-sklearn.naive_bayes">tweaking the hyperparameters</a> for each classifier.</p><p>In this blog we have learnt Naive Bayes model building and evaluating the model in scikit-learn. Naive Bayes is the most straightforward and potent algorithm. In spite of the significant advances in Machine Learning in recent years, it has proved its worth.</p><p><a href="https://medium.com/@tpreethi19/undesrtand-naive-bayes-algorithm-in-simple-explanation-with-python-code-part-1-bb45c1b0409a">Undesrtand Naive Bayes algorithm in simple explanation with python code — Part 1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2b91cbbf637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Undesrtand Naive Bayes algorithm in simple explanation with python code — Part 1]]></title>
            <link>https://medium.com/@preethithakur/undesrtand-naive-bayes-algorithm-in-simple-explanation-with-python-code-part-1-bb45c1b0409a?source=rss-b6c66029ce5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb45c1b0409a</guid>
            <category><![CDATA[naive-bayes-classifier]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Preithi Thakur]]></dc:creator>
            <pubDate>Thu, 13 Oct 2022 18:47:52 GMT</pubDate>
            <atom:updated>2022-10-23T02:51:19.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understand Naive Bayes Algorithm with Python code — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*kaxEwSg6NmXzZeyqyU5Guw.png" /></figure><p>Naive Bayes is a probabilistic machine learning algorithm based on the Bayes Theorem, used in classification tasks. It is used to measure the probability of an event occurring, given that another event has already occurred. <em>Let’s dig further.</em></p><h4>Bayes Theorem</h4><p>Bayes theorem is used to calculate conditional probabilities. <strong>Conditional probability</strong> is defined as the <em>likelihood of an event or outcome occurring, based on the occurrence of a previous event or outcome</em>.<strong> </strong>Mathematically this is written as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*vEVmTNMTTEiolFIWB9fflg.png" /></figure><ul><li><em>P</em>(A<em>|B</em>) is the posterior probability of <em>class</em> (A, <em>target</em>) given <em>predictor</em> (B, <em>attributes</em>).</li><li><em>P</em>(A) is the prior probability of <em>class</em>.</li><li><em>P</em>(B<em>|A</em>) is the likelihood which is the probability of <em>predictor</em> given <em>class</em>.</li><li><em>P</em>(B) is the prior probability of <em>predictor</em>.</li></ul><blockquote>In simpler terms, Bayes’ Theorem is a way of finding a probability when we know certain other probabilities.</blockquote><h4>Assumption</h4><p>Naive Bayes classifier works on basic assumption that each feature(predictor) makes an <strong><em>independent</em></strong> and <strong><em>equal</em></strong> contribution to the outcome.</p><h4>Naive Bayes algorithm working with an Example</h4><p>Here is an example to understand how Naive Bayes works. Let’s consider this weather dataset where we are classifying whether a particular day is suitable for playing golf or not, given the features of the day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*Sc0EFgD8zr_C4X87P8nIDA.png" /></figure><p>The columns represent features and the rows represent individual entries for each day. If we take the first row, we can observe that when the outlook is rainy, temperature is hot, humidity is high and it is not windy, then that day is not suitable for playing golf. So, we can make following two assumptions.</p><ol><li>The temperature being “Hot” has nothing to do with the humidity being “high” or “normal”, the outlook being “Rainy” has no effect on the winds. Hence, the features are assumed to be <strong><em>independent</em></strong>.</li><li>Knowing only temperature and humidity alone we can’t predict the outcome accuratey. None of the attributes is irrelevant and assumed to be contributing <strong><em>equally</em></strong> to the outcome.</li></ol><p><em>Don’t they look similar to Naive Bayes assumptions?</em></p><p>Let’s write the Bayes theorem equation for this weather dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*nvJ_5l6dLm2uhjvY.png" /></figure><ul><li><strong>y</strong> - represents target/class variable (tells, will play golf or not)</li><li><strong>X - </strong>represents the parameters/features (Outlook, temp, humidity, windy) ranging from x1, x2,…..,xn. Here we have 4 features x1,x2,x3,x4</li></ul><p>By substituting x1, x2,…..,xn for <strong>X </strong>and expanding using the chain rule we get posterior probability as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*NbEVUSx_xnHrzdWf.png" /></figure><p>Now, we can obtain the values for each class by looking at the dataset and substitute them into the above equation.</p><p>The posterior probability can be calculated by first constructing a <strong>frequency table</strong> for each attribute against the target. Then, transforming the frequency tables to <strong>likelihood tables</strong> and finally use the Naive Bayesian equation to calculate the posterior probability for each class. The class with the highest posterior probability is the outcome of prediction.</p><h4>Calculating probablities and predicting target variable</h4><p>From our dataset we are constructed a frequency table for the “Outlook” feature, then we derived likelihood table as shown below, then we calculated the posterior probability of the class being “<em>Yes</em>”, given the “Outlook” feature as “<em>Sunny</em>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qK_b9TlqE1YkFkusgVSpHw.png" /></figure><p>Now, we calculate posterior probability of class being “No” given the “Outlook” feauture as “Sunny”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQIcfkc9R0MyzB-nE-rFWg.png" /></figure><p>We got posterior probablity of playing golf higher than that of not playing golf. Hence, we can say that when it is “<em>Sunny</em>” golf will be played; Similarly we can calculate probabilities of “Overcast” and “Rainy”.</p><p>The frequency and likelihood tables for all four predictors is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1b4ym9ROOuPoabZ4Y7iKA.png" /></figure><p>From these tables we can calculate individual probability for each class(Yes, No), for given predictors and find out maximum probability which will be our target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*g-DsbR48HChUTBl3.png" /></figure><p><em>For all entries in the dataset, the denominator does not change, it remain static. Therefore, the denominator has been removed and a proportionality is introduced in above equation.</em></p><p>In our case, the class/target variable(<strong>y</strong>) has only two outcomes, “yes” or “no”. But there can be cases where the classification could be multivariate. Therefore, we need to find the class <strong>y</strong> with <strong>maximum probability</strong>. We use <strong>argmax</strong> since it is an operation that finds the argument that gives the maximum value from a target function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*9CjLgi5AfJKwcgsx.png" /></figure><p>Let’s take an example to implement above equation. <em>From this example you will understand how we use the individual probabilities that we computed above and get the class with maximum probability.</em> So, let’s take a new record of features and find out whether this particular day is a good to play golf or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*f3h4QP5wTdeHFDvlyKdoxA.png" /></figure><p>Below, we calculated individual posterior probabilities for class “Yes” and “No” for given different predictors(features)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*7oUomJVE3QFRsN70Qsv83w.png" /></figure><p>We can see that, for given features/predictors, probability of class being “No” is greater than probability of class being “Yes”. Hence the golf will be “Not played” during this particular day.</p><h4><strong>Types of Naive Bayes Classifier</strong></h4><h4><strong>Multinomial</strong></h4><p>The Multinomial Naive Bayes classifier is used when the data is multinomial distributed. It is primarily used for document classification problems, i.e., a particular document belongs to which category such as Sports, Politics, Education, etc. The classifier uses the frequency of words from this document as the predictors/features.</p><h4><strong>Bernoulli</strong></h4><p>The Bernoulli classifier works similar to the Multinomial classifier, but the predictor variables are the independent Boolean variables. Such as if a particular word is present or not in a document.</p><h4>Gaussian</h4><p>When the predictors take continuous values instead of discrete, then the model assumes that these values are sampled from the Gaussian distribution.</p><p>Since the way the values are present in the dataset changes, the formula for conditional probability changes to,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*VwL41muV2pngufPh.jpg" /></figure><p>Where <em>μ </em>is <em>Mean </em>and <em>σ </em>is <em>Standard Deviation</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*DyyplGf-obFhEgS2Bq2AjQ.png" /></figure><h4>Applications</h4><p>Some​ applications that use Naive Bayes classifiers are:</p><ul><li>Spam Filtering</li><li>Text Analysis</li><li>Recommendation Systems</li></ul><p><a href="https://medium.com/@tpreethi19/what-is-decision-tree-9793833bd87a">What is Decision Tree?</a></p><h4>Naive Bayes advantages and disadvantages</h4><h4>Advantages</h4><ul><li>Naive Bayes is one of the fast and easy ML algorithms to predict a class of datasets.</li><li>It can be used for Binary as well as Multi-class Classifications.</li><li>It performs well in Multi-class predictions as compared to the other Algorithms.</li><li>It is the most popular choice for <strong>text classification problems</strong>.</li></ul><h4>Disadvantages</h4><ul><li>Naive Bayes assumes that all features are independent or unrelated, so it cannot learn the relationship between features.</li><li>If a categorical variable has a category (in the test data set), which was not observed in the training data set, then the model will assign a 0 (zero) probability and will be unable to make a prediction. This is often known as “Zero Frequency”. To solve this, we can use the smoothing technique. One of the simplest smoothing techniques is called Laplace estimation.</li></ul><blockquote>In the part 2 of this blog we will learn implementation of of Naive Bayes Classifier in python</blockquote><p><a href="https://medium.com/@tpreethi19/undesrtand-naive-bayes-algorithm-in-simple-explanation-with-python-code-part-2-a2b91cbbf637">Undesrtand Naive Bayes algorithm in simple explanation with python code — Part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb45c1b0409a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>