<?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 Ayobami Akiode on Medium]]></title>
        <description><![CDATA[Stories by Ayobami Akiode on Medium]]></description>
        <link>https://medium.com/@ayobamiakiode?source=rss-5fd5b621e7fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q_EkJ5a3mr5cAIZWEK1oGQ.jpeg</url>
            <title>Stories by Ayobami Akiode on Medium</title>
            <link>https://medium.com/@ayobamiakiode?source=rss-5fd5b621e7fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:32:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayobamiakiode/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[Defeating Synthetic Data Fraud: 2026 Post-Collection Validation for Human-Verified Surveys]]></title>
            <link>https://ayobamiakiode.medium.com/defeating-synthetic-data-fraud-2026-post-collection-validation-for-human-verified-surveys-25de3b371296?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/25de3b371296</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[market-research-reports]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 18:17:21 GMT</pubDate>
            <atom:updated>2026-01-27T09:17:58.628Z</atom:updated>
            <content:encoded><![CDATA[<h4>In the AI era, the most dangerous data may be the data that looks high quality.</h4><figure><img alt="A detailed illustration contrasting the duality of 2026 data — one side complex, colorful, and organic; the other black-and-white, technical, and structured. This visual highlights the AI versus human data quality audit, branded by Datos-JoieLogicHub." src="https://cdn-images-1.medium.com/max/1024/1*CM4CR56KJWRyA2dBjwmVQw.png" /><figcaption><em>The duality of 2026 data: Which side is your dataset leaning toward?</em></figcaption></figure><p>In 2026, the question is no longer whether artificial intelligence touches survey data.<br> The more uncomfortable question is how much of a dataset was actually produced by humans.</p><p>If you have ever stared at a perfectly clean dataset and felt a quiet, nagging sense of doubt — you are not alone. As AI tools become easier to access, research teams, start-ups, NGOs, academic institutions, and market/social research firms are confronting a new category of data quality risk: datasets that appear complete, consistent, and professionally formatted yet fail to represent real human responses.</p><h4><strong>Quick Post-Collection Reality Check</strong></h4><p>Before diving deeper, here are fast human-credibility signals that analysts use in 2026 audits to assess potential presence of synthetic data:</p><ul><li>Do aggregated totals reconcile with raw exports or logs?</li><li>Are interview durations realistic for questionnaire length?</li><li>Do open-ended responses sound human (variation, slang, imperfections)?</li><li>Do related fields remain logically consistent across records?</li><li>Was cleaning reviewed and documented by a second pair of eyes? Now, If your dataset fails more than two, you may be facing synthetic data fraud or AI-assisted filling, not human variability.</li></ul><h4><strong>The Emerging Risk of “Perfect” Survey Data</strong></h4><p>Prior to the AI-era, traditional data quality checks focused on familiar issues, namely:</p><ul><li>Missing values</li><li>Logical inconsistencies</li><li>Outliers</li><li>Duplicate records</li></ul><p>But in 2026, synthetic survey data clears these checks easily. Instead of obvious errors, fraudulent datasets reveal quieter signals, namely:</p><ul><li>Unusually consistent phrasing</li><li>Implausible completion times</li><li>Over-polished open-ended responses</li><li>Repeated semantic patterns across “independent” respondents</li></ul><p>Though these problems can be tracked with a functional system during data collection, if there an actual data collection system in place; It should be part of the data analyst and handlers’ responsibility to slow down and interrogate the data through post-collection validation after collection.</p><h4><strong>Why We Need Human-Verified Survey Validation</strong></h4><p>Synthetic data fraud undermines:</p><ul><li>Donor reporting</li><li>Policy decisions</li><li>Intervention design</li><li>Academic credibility</li><li>Business intelligence</li></ul><p>In our 2026 audits across market research and M&amp;E portfolios, synthetic responses tended to collapse under cross-variable validation far more than under traditional cleaning workflows.</p><h4><strong>To the Rescue: A Post-Collection Framework for Defeating Synthetic Data Fraud (2026)</strong></h4><p>Having a standard framework, optimized to defeat synthetic data fraud will help to ultimately address this intrinsic problem. The framework below does just that. This framework is designed to complement, not replace, traditional quality control assurance, even during data collection. It draws from post-collection validation practices used in:</p><ul><li>Market research</li><li>Social &amp; academic research</li><li>Monitoring &amp; Evaluation (M&amp;E)</li><li>Public health research</li><li>Data science</li></ul><p>The 10 action-based themes of the framework include:</p><p><strong>1. Reconcile Aggregates with Source Data</strong></p><p>Start by validating that all aggregated totals align with: Source forms; Raw exports, and System logs. Synthetic or manipulated datasets often hold internal coherence but break under reconciliation.</p><p><strong>2. Conduct Outlier &amp; Range Analysis, and Document It</strong></p><p>Outlier detection must move beyond “flag or remove.” Ask whether extreme values make contextual sense. Real-world data typically does not produce the following, but AI-generated datasets do:</p><ul><li>Narrower ranges</li><li>Lower variance</li><li>Fewer contextual extremes</li></ul><p>Documentation becomes crucial when results are challenged later.</p><p><strong>3. Revisit Missingness, Even When It Looks Clean</strong></p><p>AI-assisted datasets often present: No blanks, No default NAs, and No mandatory field violations. That alone should raise suspicion. Look for: Placeholder defaults; illogical filler values, and repetitive entries</p><p>This mean — Completeness ≠ authenticity.</p><p><strong>4. Cross-Validate Logically Related Variables</strong></p><p>This is where many synthetic datasets fail. For this, you can cross-validate logically related variables, such as</p><ul><li>Age vs. date of birth</li><li>Education vs. age</li><li>Gender vs. pregnancy status</li></ul><p>AI generates internally coherent fields but struggles at relational logic at scale.</p><p><strong>5. Examine Timestamps &amp; Metadata Carefully</strong></p><p>Metadata remains one of the strongest fraud indicators. Check for the following:</p><ul><li>Completion speeds</li><li>Clustered timestamps</li><li>Identical device signatures</li><li>Impossible interview durations</li></ul><p>Human behavior has variance; AI does not.</p><p><strong>6. Review by Explicit Supervisor or Quality Assurance Lead</strong></p><p>Post-collection validation should not be informal. Confirm:</p><ul><li>Reviewer identity</li><li>Issues logged</li><li>Corrections documented</li><li>Decisions justified</li></ul><p>Datasets most vulnerable to AI risk often pass “quietly” without validation ownership.</p><p><strong>7. Verify That Data Cleaning Actually Occurred</strong></p><p>“Cleaning” data without evidence is a red flag, verify evidence of:</p><ul><li>Duplicate checks</li><li>Correction logs</li><li>Validation notes</li></ul><p>Real field data is messy; synthetic data skips that mess.</p><p><strong>8. Validate the Final Dataset Against the Instrument</strong></p><p>Confirm alignment with:</p><ul><li>Questionnaire structure</li><li>Skips &amp; filters</li><li>Field constraints</li></ul><p>Synthetic datasets drift when instrument logic is complex.</p><p><strong>9. Confirm Ethical Personal Identification Identifier Handling</strong></p><p>Check for proper:</p><ul><li>Anonymization</li><li>Encryption</li><li>Identifier handling</li></ul><p>Synthetic generation can fabricate or mis-handle PII, creating compliance exposure.</p><p><strong>10. AI-Specific Fraud and Anomaly Detection (Now Essential)</strong></p><p>Modern validation should include:</p><ul><li>Robotic syntax review</li><li>Metadata velocity checks</li><li>Semantic pattern analysis</li></ul><p>Though Human respondents do, AI rarely produces:</p><ul><li>Typos</li><li>Regional or contextual slang</li><li>Style variance</li><li>Timeline realism</li></ul><h4><strong>Why Post-Collection Validation Is Now Non-Optional</strong></h4><p>As AI-generated datasets rarely look “wrong” and look too consistent to be true. Informal validation collapses under:</p><ul><li>Peer review</li><li>Donor audits</li><li>Replication demands</li><li>Policy scrutiny</li></ul><p>And by the time modeling begins, it is already too late.</p><h4><strong>Who This Framework Matters For</strong></h4><p>This framework is especially relevant for:</p><ul><li>Data Scientists &amp; Analysts</li><li>Research Leads &amp; M&amp;E Officers</li><li>Market Research Firms</li><li>NGOs &amp; Academic Institutions</li><li>Data Auditors &amp; QA Teams</li></ul><p>If you are in these roles, you are already operating in an environment where appearance is no longer a reliable signal of truth.</p><h4><strong>Final Thought</strong></h4><p>In 2026, the most dangerous data is not the data that looks messy; it is the data that looks too perfect. As AI continues to blur the line between synthetic and human responses, quality control must move — From the field to the dataset to the metadata. Human-verified surveys now require: Authenticity, Traceability, Defensibility, and not just completeness.</p><h4><strong>Disclosure</strong></h4><p>The validation practices described here reflect structured post-collection checks commonly applied in professional market research, M&amp;E, public health research, and academic audits during 2025–2026 projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25de3b371296" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If Python OOP Confuses You, This Excel Method Will Change Everything]]></title>
            <link>https://ayobamiakiode.medium.com/if-python-oop-confuses-you-this-excel-method-will-change-everything-9b220a1c7512?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b220a1c7512</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 22:34:06 GMT</pubDate>
            <atom:updated>2026-01-12T19:36:19.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiOaK6fJx2bdLAs7C-AUhA.jpeg" /></figure><p>For years, Object-Oriented Programming (OOP) made me feel like I was not “smart enough” for Python. Classes vs. objects. Encapsulation. Inheritance.<br> Methods vs. attributes.</p><p>I jumped from YouTube tutorials to online courses to documentation, but nothing clicked. Every explanation felt abstract — like everyone understood something I did not.</p><p>I understood data. I understood Excel. But OOP? It felt like a different universe.</p><p>Everything changed the day I stopped trying to memorize definitions and started mapping Python OOP to something I already understood: <strong>an Excel sheet. </strong>That single shift made OOP <em>finally</em> make sense.</p><h3>Why Most People Struggle With OOP</h3><p>Everything changed the day I stopped trying to memorize definitions and started mapping Python OOP to something I already understood: <strong>an Excel sheet. </strong>That single shift made OOP <em>finally</em> make sense.</p><h3>Why Most People Struggle With OOP</h3><p>After speaking with other beginners and data professionals, I realized the problem was not me; it was the way OOP is usually taught.</p><p>Most tutorials start with: “Everything in Python is an object.”</p><p>Helpful? Not really. Then they jump to diagrams, complex metaphors, or long definitions that do not connect to real-life experience.</p><p>But when you link OOP to something familiar,<em> </em>like Excel; everything becomes visual and logical. This is exactly what happened to me.</p><h3>My Excel “Aha Moment”</h3><p>One afternoon, while working in Excel, I noticed something: A <strong>Class</strong> is basically your your excel sheet and the column headers in it, that is, a structure. An <strong>Object</strong> is simply a row filled with real values. A <strong>Method</strong> is just an operation you perform on the row. That’s it. It was not magical. It was not abstract. It was simple. Suddenly, OOP felt less like a mystery and more like… spreadsheets.</p><h3>Let Me Show You One Example</h3><p>Imagine this simple Excel table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*fO2ECu-Fy1aTZ_XWpltnBg.png" /></figure><p>This is OOP in disguise:</p><h3>Class (template / column headers)</h3><pre>class Student:<br>    def __init__(self, name, age, score):<br>        self.name = name<br>        self.age = age<br>        self.score = score</pre><h3>Objects (rows in Excel)</h3><pre>s1 = Student(&quot;John&quot;, 14, 89)<br>s2 = Student(&quot;Ada&quot;, 15, 92)</pre><h3>Method (operation performed on the row)</h3><pre>def display(self):<br>    return f&quot;{self.name} scored {self.score}&quot;</pre><p>If you understand Excel, you already understand the logic behind OOP. When I realized this, Python suddenly became less intimidating, and much more enjoyable.</p><h3>Then I Wrote a Book About This</h3><p>After helping a few colleagues and junior analysts understand OOP using Excel analogies, they all said the same thing:</p><blockquote><em>“I wish someone had explained it like this from the beginning.”</em></blockquote><p>So I turned the method into a short, visual, beginner-friendly book: “<strong>Python OOP Made Easy Through Excel”</strong></p><p>It teaches OOP using concepts you already know from Excel, with simple diagrams, projects, and exercises. If this article made OOP feel clearer, then you’ll find the book even more helpful.</p><p>Specifically, this book will help you achieve your goal of understanding python OOP in a more intuitive way through:</p><p>1. Excel-to-Python explanations — understand OOP concepts visually<br>2. Mini-projects &amp; exercises — practice what you learn immediately<br>3. Zero confusion, zero jargon — Python OOP made simple and intuitive</p><p>It’s designed to help people learn Python OOP in <strong>hours</strong>, not weeks.</p><h3>Final Thoughts</h3><p>If you have ever felt like OOP was too abstract or too complicated, please know you are not alone. Many people struggle, not because they can not learn, but because the explanations do not match how they think. If the Excel analogy helped you see OOP differently, feel free to explore the full method in the book.</p><ul><li>Selar (Nigeria): <a href="https://selar.com/97d474776e">https://selar.com/97d474776e</a></li><li>Gumroad: <a href="https://oopmadeeasybyexcel.gumroad.com/l/tecrp">https://oopmadeeasybyexcel.gumroad.com/l/tecrp</a></li></ul><p>Let’s make learning Python easier — one simple explanation at a time. That is a Wrap! You can also connect with me on LinkedIn at <a href="https://www.linkedin.com/in/ayobami-akiode-38528839/"><strong>Ayobami Akiode LinkedIn</strong></a></p><p><strong>Disclosure:</strong> This article includes links to my book on Python OOP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b220a1c7512" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Own Story]]></title>
            <link>https://ayobamiakiode.medium.com/my-own-story-dcb82c840f22?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcb82c840f22</guid>
            <category><![CDATA[poem]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[confidence]]></category>
            <category><![CDATA[poems-on-medium]]></category>
            <category><![CDATA[self-reflection]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 05:53:31 GMT</pubDate>
            <atom:updated>2025-10-26T05:53:31.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owS-7KvqaKpz4csw_cOhvQ.png" /></figure><p>My own story — <br>it is my being in the outer galaxy,<br>the truth of who I am.</p><p>It is my journey,<br>my path toward inner peace and redemption.<br>Only my being knows what my story is, <br>a self-journey walked on a lonely path<br>that only I can tell.</p><p>Only ask M<em>e</em> about my story,<br>for it lives in my truth, through me, in me,<br>and because of me.</p><p>It is the part of me that soared and weathered,<br>the part that fought for my redemption.<br>The outlook of my story is not my truth;<br>so let no man say he knows my story — <br>my own story.</p><p>It is breathing my own breath,<br>carrying the divinity of who I was,<br>who I used to be,<br>who I am,<br>and who I have become.</p><p>It cannot be told by another,<br>for only I walked the path of — my own truth.</p><p>Like a virus,<br>my story lives through me, <br>and dies through someone else.</p><p>The kings and queens may capture and beautify it,<br>and gild it in gold,<br>yet it will never be theirs.<br>They cannot make it <em>not mine,</em><br>for it carries my truth.</p><p>It will no longer breathe<br>outside the words of my mouth,<br>for it is my truth — <br>and my truth alone.</p><p>They may touch the outlook,<br>but not the rough edges,<br>the moments of lost and found,<br>the redefinition of identity<br>that only I can see.</p><p>It is my own story.<br>It is my truth.<br>Let no other man speak it!</p><p>You can connect with me on LinkedIn at <a href="https://www.linkedin.com/in/ayobami-akiode-38528839/"><strong>Ayobami Akiode LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcb82c840f22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From the Ashes I Rise]]></title>
            <link>https://ayobamiakiode.medium.com/from-the-ashes-i-rise-45a24a795ed3?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a24a795ed3</guid>
            <category><![CDATA[poetry-on-medium]]></category>
            <category><![CDATA[poem]]></category>
            <category><![CDATA[deep-thoughts]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[truth]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 06:47:52 GMT</pubDate>
            <atom:updated>2025-10-23T06:47:52.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJ3_EiOe49Ku4EsnEDp-JQ.png" /></figure><p>From the ashes I rise, never to be burned again.<br>From the ashes of grief that consumed my soul<br> and evaporated the core of my certainties, I rise.</p><p>From the ashes I rise,<br>no longer scarred by the holders who once held<br>my fragility and naivety.</p><p>Even in my dust, my hopes and resilience<br>kept me alive. I rise, though the ashes still whisper<br>of the form I was.</p><p>The path narrows my soul toward oblivion,<br>yet the pure truth I carry remains unseen, unbroken.</p><p>The wind once scattered me.<br>But I rise within the storm itself, I have come.</p><p>I rise above the waters that drowned me,<br>that mistook my silence and docility for surrender.<br>I rise, I keep rising, against all odds.</p><p>Not as the shadow that engulfed me,<br>but as the truth that has always called me home.</p><p>Oh, from the ashes I rise, <br>never to be burned again.<br>Oh, I rise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a24a795ed3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Not to Live According to Other People’s Expectations — Live According to Yours]]></title>
            <link>https://ayobamiakiode.medium.com/how-not-to-live-according-to-other-peoples-expectations-live-according-to-yours-60322a0001da?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/60322a0001da</guid>
            <category><![CDATA[mindset]]></category>
            <category><![CDATA[growth-mindset]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[self-growth]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 10:34:40 GMT</pubDate>
            <atom:updated>2025-09-21T10:34:40.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>Live According to Yours: How Not to Live According to Other People’s Expectations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rjHaIkQtEgz0DyjtsU9SA.jpeg" /></figure><p><strong>Not all advice is guidance. Not all pressure is purpose. This is a reminder to listen more closely to your own voice.</strong></p><p>There’s something unsettling about realizing that the world sometimes expects more from you than you expect from yourself.</p><p>Sometimes people’s expectations are rooted in love. Other times, they feel like quiet pressure or loud disappointment. What do you do when the weight of their hope becomes too heavy?</p><p>It is flattering at first. You might hear things like:<br> “You are meant for greatness.”<br> “I know you can do better than this.”</p><p>Sometimes these words are wrapped in love and belief.<br>Other times, they feel like accusations.<br>And when they are thrown in your face — especially when you’re just trying to survive, breathe, or figure things out — they sting.</p><h3>The Compliment and the Burden</h3><p>Here is the truth: when people’s expectations for you are higher than your own, it can be both a <strong>compliment</strong> and a <strong>burden</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Evz8MvbHNvIRTCUsW1NQGg.png" /></figure><p><strong>Should you worry?</strong> Not necessarily.<br><strong>But should you reflect?</strong> Absolutely.</p><p>Here is what it could mean:</p><ul><li><strong>They see potential in you</strong> — sometimes more than you see in yourself. That is not a bad thing.</li><li><strong>They might be projecting</strong> — their own hopes, fears, or values onto you.</li><li><strong>They may lack boundaries</strong> — expecting you to carry more than is fair or realistic.</li></ul><p>But when it is thrown in your face: That is the part to watch.<br>It stops being encouragement and starts to feel like pressure, guilt-tripping, or even emotional manipulation.</p><p>And here is the thing: <strong>You are not obligated to meet expectations that do not align with your reality — your energy, your goals, your timing.</strong></p><p>What to do instead:</p><ul><li><strong>Check in with yourself</strong>: Are you okay with where you are? Are you growing? That’s what matters.</li><li><strong>Set boundaries</strong>: Kindly but firmly remind people that you are charting your own course, not theirs.</li><li><strong>Use their belief as fuel, not fire</strong>: Let it encourage you, but not burn you out.</li></ul><p>If their expectations align with the future you want, maybe it is a gentle nudge. If not, <strong>protect your peace</strong>.<br>You are not a project for others to manage — you are a person with your own pace and path.</p><h3>The Burden of Being Seen</h3><p>People often project their dreams onto those who seem <em>capable</em>. If you have ever shown a spark of brilliance, resilience, or success, some will hold you to a version of yourself they built in their minds.</p><p>That version may not even exist anymore — or yet.</p><p>But here is the quiet truth no one says out loud: <strong>Expectations can become heavy when they are not yours.</strong></p><p>I have been there — wrestling between gratitude and guilt.<br>Grateful that people believe in me.<br>Guilty that I have not lived up to what they see.</p><p>But am I living for them or for me?</p><h3>Navigating the Gap</h3><p>What do you do when the world’s vision of your potential feels bigger than your own?</p><p>You pause.</p><p>You ask yourself:</p><ul><li>What do I want?</li><li>Am I at peace with where I am?</li><li>Is their vision inspiring me, or suffocating me?</li></ul><p>If it is the former, lean into it. Let it be fuel.<br>If it is the latter, step back. Protect your space.</p><h3>You Are Not a Disappointment for Growing at Your Own Pace</h3><p>We do not always grow in public.<br>Sometimes the deepest transformations happen offstage — in silence, in obscurity, in uncertainty.</p><p>The world loves a polished product, but real growth is messy and slow.</p><p>So no — you are not a disappointment because you are not “there yet.”<br>You are not lazy because you are tired.<br>You are not wasting your life because your version of success looks different or is still unfolding.</p><h3>A Quiet Reminder</h3><p>Let people see greatness in you. Let them hope. Let them speak.</p><p>But don’t lose yourself trying to become their vision.<br>Your path is yours. Your timing is sacred.<br>And the expectations that matter most are the ones rooted in your truth — not in their urgency.</p><p>If you are reading this and feeling overwhelmed by what others think you <em>should</em> be doing — breathe. You are allowed to move at your own pace.</p><p>You are allowed to define your own milestones. You are allowed to say, “Not yet,” or even, “Not that.”</p><p>Sometimes the most radical thing you can do is trust yourself more than you trust their image of you.</p><p><strong>That is a Wrap!</strong> Let me know your thoughts in the comments. You can also connect with me on LinkedIn at <a href="https://www.linkedin.com/in/ayobami-akiode-38528839/"><strong>Ayobami Akiode LinkedIn</strong></a><strong> </strong>— I would love to hear how you are handling others expectation of you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60322a0001da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Machine Learning Model Fails in Production: A Deep Dive into Sampling Design]]></title>
            <link>https://medium.datadriveninvestor.com/why-your-machine-learning-model-fails-in-production-a-deep-dive-into-sampling-design-698874ed3dfd?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/698874ed3dfd</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Wed, 14 May 2025 13:13:56 GMT</pubDate>
            <atom:updated>2025-05-15T04:39:29.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B5iH_g_aKOvzhl68" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">CHUTTERSNAP</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Machine learning models live and die by the quality of the data they are trained on. But it is not just the data — it is <em>how</em> you sample it. Poor sampling design is one of the most common and overlooked reasons models that shine in development environments crash in production.</p><h3>What you will learn in this Article</h3><p>In this article, we will explore how sampling design can make or break your machine learning model in production. Specifically, we will cover —</p><h4>1. Why machine learning fails after deployment,</h4><h4>2. The Culprit: Poor Sampling Design,</h4><h4>3. What is Sampling Design in Machine learning,</h4><h4>4. What a good sampling design must do,</h4><h4>5. The core sampling techniques in machine learning,</h4><h4>6. Sampling Gone Wrong: The Common Pitfalls, and</h4><h4>7. Conclusion: Do not Let Sampling Sink Your Model</h4><h3>1. Why machine learning fails after deployment —</h3><h4>The Real Story: A Model with 92% Accuracy That Failed</h4><p>Imagine you trained a model to detect credit card fraud. You achieved 92% accuracy during training and testing. But within weeks of deployment, it was flagged for missing over half of actual fraud cases.</p><h3>2. The Culprit: Poor Sampling Design</h3><p>You might have used random sampling without accounting for <em>temporal drift</em> or <em>class imbalance</em>. Your training data did not reflect how fraud patterns evolve over time — a classic mistake.</p><h3>3. What is Sampling Design in Machine Learning</h3><p>Sampling design refers to the method used to select a representative subset (a <em>sample</em>) of your full dataset (the <em>population</em>) for training, validation, and testing. A well-designed sample must reflect the structure and characteristics of the full dataset, including its distributions, and subgroups. It is not enough to <em>randomly</em> select data; your sample must reflect and represent the real-world conditions your model will face.</p><h3>4. What a good Sampling Design must do</h3><p>A good sampling design must ensure:</p><ul><li><strong>Representativeness: </strong>The sample selected is a complete representative of the target population.</li><li><strong>Fairness: </strong>The sample selected reflect and proportionally represent the subgroups in the target population, accordingly and fairly. If in the target population, the 60% of the data is that of rural cases, and 40% are that of urban, then the sample should also have close to 60% rural cases, and 40% urban cases.</li><li><strong>Consistency</strong> with production conditions: Matches how data behaves in real use.</li><li><strong>Bias reduction</strong>: Prevents overfitting to irrelevant patterns.</li><li><strong>Avoids leakage</strong>: Ensures no future information contaminates the training set.</li></ul><h3>5. The Core Sampling Techniques in Machine Learning?</h3><h4>1. Random Sampling</h4><p>This involves selecting <strong>sample(s)</strong> entirely at random from its larger dataset or target population. Random sampling works best when the dataset is homogeneous — that is, where all records have similar characteristics.</p><p>For example, if you have high consideration for gender in your machine learning modelling and all the cases of the target population are all females or are all males(homogenous), then using a random sampling is adequate. However, if you have a consideration for gender in your machine learning modelling and you have both male and female cases significantly represented(heterogenous), then using random sampling may not be adequate.</p><p>During machine learning process, random sampling is used to split datasets randomly into training and test sets.</p><pre>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br><br># Load example dataset<br>iris = load_iris()<br>X = iris.data<br>y = iris.target<br><br># Random sampling (80% train, 20% test)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br>print(&quot;Train shape:&quot;, X_train.shape)<br>print(&quot;Test shape:&quot;, X_test.shape)</pre><h4>2. Stratified Sampling</h4><p>This method is mainly useful for heterogenous dataset where all the cases of the target population are not uniform. This is especially important in imbalanced classification problems, where rare classes would otherwise be underrepresented.</p><p>For example, if you have high consideration for gender in your machine learning modelling and you have both male and female cases significantly represented(heterogenous), then using a stratified sampling is the most appropriate.</p><blockquote>What is the difference between stratified and cluster sampling —</blockquote><blockquote>The <strong>simple difference</strong> between <strong>stratified</strong> and <strong>cluster sampling</strong> in machine learning lies in <strong>how the groups are used.</strong></blockquote><blockquote><strong>In stratified sampling,</strong> You divide the population into meaningful subgroups (called <strong>strata</strong>) based on a specific feature (e.g., class label, gender, region), <strong>then sample from <em>every</em> subgroup</strong> proportionally. It is deployed to ensure all key subgroups are <strong>fairly represented</strong> in the sample. Use it when you want to <strong>preserve class balance</strong> (e.g., in imbalanced classification tasks).</blockquote><blockquote><strong>In cluster sampling</strong>, You divide the population into groups (called <strong>clusters</strong>) that are <strong>natural groupings</strong> (e.g., schools, regions), and then <strong>randomly select a few clusters</strong> to sample <strong>entirely</strong>. It is deployed to reduce data collection or processing effort by using whole groups. Use it when data is <strong>naturally grouped</strong>, and you want to reduce the effort or cost of sampling.</blockquote><p>During machine learning process, stratified sampling ensures the proportional representation of all the classes of heterogenous groups in the target variable. It is used to preserve the class distribution across train/test sets.</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.datasets import load_iris<br><br>iris = load_iris()<br>X = iris.data<br>y = iris.target<br><br># Stratified sampling<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, stratify=y, random_state=42<br>)<br><br># Check distribution<br>import numpy as np<br>print(&quot;Train class distribution:&quot;, np.bincount(y_train))<br>print(&quot;Test class distribution:&quot;, np.bincount(y_test))</pre><h4>3. Systematic Sampling</h4><p>Systematic Sampling is useful when data or the target variable is ordered. Instead of randomly selecting rows or ensuring class proportions (like in stratified sampling), systematic sampling <strong>selects every k-th record</strong> from your dataset to create a test set — the rest becomes your training set.</p><p><strong><em>How Systematic Sampling Works (Step-by-Step)</em></strong></p><p>Assume you want to split your data into 80% train, 20% test:</p><ol><li><strong>Sort or shuffle your dataset</strong> (if needed).</li><li><strong>Choose a sampling interval </strong><strong>k</strong>:<br> If your dataset has N rows and you want n for test set:<br> → k = N // n</li><li><strong>Select every </strong><strong>k-th row</strong> as the test set.</li><li><strong>All other rows</strong> go into the training set.</li></ol><p>During machine learning process, <strong>Systematic sampling</strong> involves selecting every <em>k-th</em> data point from a sorted dataset. For example, if you have 1,000 samples and want to select 200 for testing, you might pick every 5th record.</p><pre>import pandas as pd<br>import numpy as np<br><br># Sample dataset<br>df = pd.DataFrame({&#39;feature&#39;: range(1, 101), &#39;label&#39;: np.random.choice([0, 1], size=100)})<br><br># Step 1: Shuffle the data (optional but recommended unless already randomized)<br>df = df.sample(frac=1, random_state=42).reset_index(drop=True)<br><br># Step 2: Define sampling interval<br>k = 5  # every 5th record goes to test set<br><br># Step 3: Index-based split<br>test_indices = list(range(0, len(df), k))<br>train_indices = list(set(range(len(df))) - set(test_indices))<br><br># Step 4: Create train and test sets<br>train_df = df.loc[train_indices].reset_index(drop=True)<br>test_df = df.loc[test_indices].reset_index(drop=True)<br>print(&quot;Train size:&quot;, len(train_df))<br>print(&quot;Test size:&quot;, len(test_df))</pre><h4>4. Time-based (Temporal) Sampling</h4><p>Critical for time series and evolving data patterns. It is useful when you want to prevent data leakage from future information.</p><p>During machine learning Process, you can use time-base sampling when You want to <strong>simulate real-world future predictions</strong> from past data, and the Features or targets <strong>depend on time</strong> (e.g., sales, weather, sensor data).</p><pre><br>import pandas as pd<br><br># Simulated time-series data<br>df = pd.DataFrame({<br>    &#39;date&#39;: pd.date_range(start=&#39;2022-01-01&#39;, periods=100),<br>    &#39;feature&#39;: range(100),<br>    &#39;target&#39;: [1 if x &lt; 50 else 0 for x in range(100)]<br>})<br><br># Sort by date<br>df = df.sort_values(&#39;date&#39;)<br><br># Time-based split<br>train = df[df[&#39;date&#39;] &lt; &#39;2022-03-01&#39;]<br>test = df[df[&#39;date&#39;] &gt;= &#39;2022-03-01&#39;]<br><br>print(&quot;Train size:&quot;, train.shape)<br>print(&quot;Test size:&quot;, test.shape)</pre><h4>5. Cluster and Multi-stage Sampling</h4><p>Cluster Sampling is useful for large or naturally grouped datasets (e.g., students within schools). It is usually suitable when data is naturally divided or <strong>hierarchical in nature </strong>(e.g., schools, hospitals) or when it is <strong>geographically</strong> grouped.</p><p>For Multi-stage Sampling, Sampling are usually done in stages — e.g., first you disaggregate the data by region, and then randomly select sample within each region.</p><p>During Machine Learning Process, cluster sampling involves dividing data into <strong>clusters/groups</strong>, then randomly selecting some clusters for training, others for testing.</p><pre>import pandas as pd<br>import numpy as np<br><br># Simulate cluster-like data<br>np.random.seed(42)<br>df = pd.DataFrame({<br>    &#39;region&#39;: np.random.choice([&#39;North&#39;, &#39;South&#39;, &#39;East&#39;, &#39;West&#39;], size=1000),<br>    &#39;feature&#39;: np.random.randn(1000),<br>    &#39;target&#39;: np.random.randint(0, 2, size=1000)<br>})<br><br># Choose 2 clusters randomly<br>clusters = df[&#39;region&#39;].unique()<br>selected_clusters = np.random.choice(clusters, size=2, replace=False)<br>sampled_df = df[df[&#39;region&#39;].isin(selected_clusters)]<br><br>print(&quot;Sampled from clusters:&quot;, selected_clusters)<br>print(&quot;Sample size:&quot;, sampled_df.shape)</pre><h3>6. Sampling Gone Wrong: The Common Pitfalls</h3><h4>1. Data Leakage</h4><p>Example: Using post-diagnosis information to predict a disease. If sampled incorrectly, future information leaks into training.</p><h4>2. Train-Test Distribution Shift</h4><p>When the test data comes from a different distribution (e.g., newer data trends), model performance tanks.</p><h4>3. Ignoring Rare Classes</h4><h3>7. Conclusion: Do not Let Sampling Sink Your Model</h3><p>Sampling design may not sound glamorous, but it’s one of the most important decisions you’ll make when building machine learning models. A flawed sample sabotages even the best algorithms. Get it right, and your model stands a chance in the real world. Invest the time to do it right — your production performance depends on it.</p><p>That is a Wrap! Let me know your thoughts in the comments. You can also connect with me on LinkedIn at <a href="https://www.linkedin.com/in/ayobami-akiode-38528839/"><strong>Ayobami Akiode LinkedIn</strong></a><strong> </strong>— I would love to hear how you’re approaching sampling in your projects.</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=698874ed3dfd" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/why-your-machine-learning-model-fails-in-production-a-deep-dive-into-sampling-design-698874ed3dfd">Why Your Machine Learning Model Fails in Production: A Deep Dive into Sampling Design</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 Non-Negotiable Criteria for Multiple Linear Regression (MLR) Prediction]]></title>
            <link>https://medium.datadriveninvestor.com/7-criteria-that-must-be-met-before-using-a-linear-regression-model-lrm-for-prediction-53d3a906c161?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/53d3a906c161</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 20:58:44 GMT</pubDate>
            <atom:updated>2026-01-09T23:38:16.490Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we would look at the seven criteria that must be met before using Multiple Linear Regression to model a prediction. So, this article will cover the following topics:</p><blockquote><strong>1. Definition of Multiple Linear Regression(MLR),</strong></blockquote><blockquote><strong>2. Difference between Multiple Linear Regression (MLR) and Simple Linear Regression(SLR)</strong></blockquote><blockquote><strong>3. Summary table, and detail of the criteria that must be met before using MLR appropriately for prediction.</strong></blockquote><blockquote><strong>4. Implementation and test of each criteria in python</strong></blockquote><blockquote><strong><em>5. Conclusion</em></strong></blockquote><h3>1. Definition of Multiple Linear Regression(MLR)</h3><p>Multiple Linear Regression is a statistical model that should only be used to model the prediction of a target variable (Y, dependent variable) by the predictor variables (X, features, independent variables).</p><h3>2. Difference between Multiple Linear Regression (MLR) and Simple Linear Regression(SLR)</h3><p>The MLR is a plural version of the Simple Linear Regression (SLR) in terms of the number of feature variables being deployed to predict the target variable. While an MLR would have at least two feature (independents, predictors) variables predicting the target variable, the SLR must only have one feature variable.</p><h3>3. <strong>Summary table, and detail of the criteria that must be met before using MLR appropriately for prediction.</strong></h3><p>In this section, we would present and describe the seven criteria that must be met before using MLR for prediction. The summary table also summarizes both the statistical and graphical tests appropriate for testing if each criteria is met.</p><figure><img alt="Summary table of the 7 criteria for multiple linear regression validation: variable type, linearity, multicollinearity (VIF), homoscedasticity, normal errors, outliers, and autocorrelation." src="https://cdn-images-1.medium.com/max/1024/1*4xqWCRcnfvrGcuznU0Pmzg.jpeg" /><figcaption><strong>This summary figure presents the 7 essential criteria for valid Multiple Linear Regression (MLR) prediction, detailing the necessary statistical tests, such as VIF and Durbin-Watson, and graphical diagnostics required for rigorous 2026 model validation.</strong></figcaption></figure><h4>Criteria 1: The Target Variable (Dependent Variable) must be a Continous or Discrete Variable while each of the Predictor variables (Independent variable) must be either Continuous (Ratio or Interval), Discrete, or Ordinal.</h4><p>The target variable can only be a continuous or discrete variable. While each of the predictor variables can only be continuous, discrete, or ordinal. None should be a nominal or categorical variable.</p><p><strong><em>What are Continous or Discrete variables? </em></strong>Continuous and Discrete variables are those that are intrinsically expressed in numbers E.g Age, height, and weight. In simple terms, a continuous variable can be considered as one with decimal extension E.g Weight — 2.6kg. Discrete can be considered as one that do not have decimal extension E.g Age — It is either you are 2 years old or 3 years old. You can not be 2.5 years old or 2.8 years old.</p><p><strong><em>What are Ordinal Variables? </em></strong>Ordinal variables can be referred to as position-oriented (first position, second position, third position, etc) variables. Referencing is placed on ranking E.g the Grade of a school subject, Position of an athlete in a race. Though an ordinal variable is generally considered a qualitative variable. It must be declared or converted to a numerical variable before use in a multiple regression model.</p><h4>Statistical Test / Diagnostic Check for Assessing Criteria 1</h4><p>Check for the variable type of variables (Target and Predictors). Different applications have different ways of checking this. In python, the “<strong>Info()”</strong> method is used in pandas to check for variables types (Integer, Float, and String). In the STATA application, the “<strong>codebook command”</strong> is used. floats are integers with decimal extensions.</p><h4>Criteria 2: Only Linear relationship exists between each of the Predictor variable (Independent variable) and the Target variable (Dependent Variable)</h4><p>Only a Linear relationship should exist between each predictor (Independent(s)) variable X, and target variable y (dependent). In terms of mathematical representation, the relationship between the Independent variables and the dependent variable can only be represented by the equation of a straight line: Y = MX+C (not by any other type of equations like a quadratic equation or polynomial), where M is the gradient of the line, and C is the intercept.</p><p><strong><em>What is the Gradient of a Straight line?</em></strong> The Gradient of a straight line denoted by M is the increase in Y for every unit increase or decrease in X. It can either be negative or positive. A positive gradient means that Y increases as X increases by a unit. A negative gradient means Y decreases as X decreases by a unit. A zero gradient means that Y is zero no matter the unit change in X.</p><p><strong><em>What is the Intercept of a Straight line? </em></strong>The intercept of a straight line, denoted by C, is the average value of y when X=0.</p><h4>Statistical Test for checking Criteria 2 — Correlation Matrix and corresponding P-value</h4><p>The correlation matrix and the corresponding P-value can be used to check if a statistically significant linear relationship exist between each of the independent variables and the dependent variable. The Correlation matrix indicates the Pearson correlation coefficient, and the corresponding p-value between each of the Predictor Variables, and the Target variable.</p><p>According to the rule of thumb, a p-value &lt; 0.05 indicate a statistically significant linear relationship exist between the specific independent variable and the dependent variable, otherwise none exist.</p><h4>Graphical Diagnostic for checking Criteria 2 — A Scatter Plot between each Independent Variable and the Dependent Variable , with a regression line</h4><p>A scatter Plot for each Independent variable with the Dependent Variable, mapped with a regression line can be used to visually check if only a linear relationship exists between each of the independent variable and the dependent variable. For each scatter plot, each independent variable is on the X-axis, while the dependent variable is on the Y-axis.</p><p>If the regression line is visually shown to be a straight line but not quadratic/polynomial, irrespective of the sloping nature of the line (downward slope, upward slope), then a linear relationship exists between each of the Independent variable and the dependent variable.</p><p><strong><em>What is a regression line? </em></strong>A regression line indicates the connection of the scattered data points with a line on an X-Y graph.</p><p><strong><em>What is a scatter plot?</em></strong> A graph that is use to plot a set of points for two variables that are situated on a vertical (independent variable) and horizontal(dependent variable) axis.</p><h4>Criteria 3: No Multicollinearity must exist between the independent variables.</h4><p>Multicollinearity is a situation where independent variables are strongly correlated. No Multicollinearity exist between a set of independent variables(Xs) if atleast no one pair is strongly correlated. The presence of multicollinearity leads to increased standard errors that leads to wider confidence interval. Wider confidence interval would lead to less precise estimates of slope parameters in regression analysis.</p><h4>Statistical Test for checking Criteria 3 — Variance Inflation Factor (VIF)</h4><p>The Variance Inflation Factor (VIF) can be used to check if a multicollinearity exist between each of the independent variables. It indicates if a correlation exist between an independent variable and the group of other independent variables. In summary, if an independent variable has high VIF, it means they can be predicted by atleast one of other independent variables</p><p>According to the rule of thumb, If an independent variable has high VIF, it means they can be predicted by atleast one of the other independent variables else otherwise.</p><p><em>The general rule of thumb for Multicollinearity: If VIF &lt;= 3, Multicollinearity does not exist. If 4 &gt;= VIF &lt; 9, Multicollinearity might exist, there maybe need to conduct further investigation. If VIF &gt;=10, Multicollinearity significantly exist. The receiprocal of VIF is called Tolelerance.</em></p><h4>Graphical Diagnostic for checking Criteria 3 — Scatter plot to visualize correlation effect among independent variables</h4><p>A pair-wise scatterplot between each possible pair of the independent variable can be used to visually assess if multicollinearity exist between each pair.</p><h4>Criteria 4: There have to be Homoscedasticity in the data</h4><p>To understand the concept of Homoscedasticity, we would can break the word into its smallest unit of meaning (morphemes). Homoscedasticity can be broken into two unit words, namely — <strong>“Homo”, and “Scedasticity”. </strong>That is,<strong> Homoscedasticity → Homo + Scedasticity</strong></p><p><strong><em>What is Homo?</em></strong> It means the same; <strong><em>What about Scedasticity? </em></strong>It means the distribution of error terms.</p><p>Simply put, Homoscedasticity is a situation where error terms are not distributed randomly but distributed in a way that makes them align in an obvious systematic and fixed pattern(same variance or constant variance).</p><p>To understand the concept of homoscedasticity, we need to understand the concept of residual through the X-Y plane. Residual (denoted as Yr ) is the difference between each observed value of the target variable (denoted as Yo), and the estimated/predicted value (denoted as Yp) of the target variable by the prediction model.</p><p>Residual (Yr) = Observed value of the target variable(Yo) — estimated/predicted value of the target variable(Yp): (Yr = Yo-Yp)</p><p>For homoscedasticity to occur, the distribution of Yr on an X-Y plane for each observation of each independent variable X being assessed must be on or along the same horizontal line. That is they must be horizontally distributed. Otherwise, the distribution of Yr on the X-Y plane for each observation of each independent variable X being assessed must show an incremental or decrement line along the Y-axis, that is, it must show a slope (positive or negative). Therefore, Homoscedasticity holds in data when the distance between each residual and the line of best fit is the same throughout all observation points.</p><h4>Statistical Test for checking Criteria 4 — Breusch-Pagan test</h4><p>The Breusch-pagan can be used for checking for the Homoscedasticity of a dataset. The null hypothesis for the Breusch Pagan test is that the error variances are all equal (Homoscedasticity). The alternative hypothesis is that the error variances are not equal(Heteroscedasticity). More specifically, as Y increases, the variances increase (or decrease).</p><h4>Graphical Diagnostic for checking Criteria 4 — The Residual by Fitted Values Scatterplot</h4><p>The Residual by Fitted values scatter plot is a good way to check whether the data are homoscedastic (meaning the residuals are equal across the regression line). In a residual-fitted value scatterplot, if the distance between the regression line and each residual value is the same throughout then Homoscedasticity occurs, otherwise, Heteroscedasticity does.</p><h4>Criteria 5: The error terms are normally distributed</h4><p>To understand the concept of normally distributed error terms, we need to understand the concept of error terms. Error terms are the variation in the value of the dependent variable not explained by the independent variables. So linear regression assumes that the variability in Y, which is unexplained by X, is normally distributed.</p><h4>Statistical Test for checking Criteria 5 — Kolmogorov Smirnov</h4><p>The Kolmogorov-Smirnov can be used to check if error terms distribution follows a normal distribution or have the same pattern of normality. Besides the Kolmogorov-Smirnov test, another common test that be used to statistically check for the normality of error terms is the Shapiro-Wilk test. The Shapiro-Wilk test is preferred for small samples (n is less than or equal to 50). For larger samples, the Kolomogrov-Smirnov test is recommended.</p><h4>Graphical Diagnostic for checking Criteria 5 — The Normal Q-Q Plot</h4><p>A Q-Q plot is a scatterplot formed by plotting two sets of quantiles — one on the X-axis, the other on the Y-axis — against one another. If both are from the same distribution, the plotted points (for each value point(x,y)) roughly form a line that’s straight. If our data comes from a normal distribution, we should see all the points sitting on a straight line and not forming an S or quadratic shape.</p><p><strong><em>What is a quantile? </em></strong><em>is a value that serves as a cut-off point. It divides the set of values of a variable or distribution into equal continuous intervals and equal probabilities. e.g A 0.25 quantile divides a set of points or values into 4 equal sets of values; A 0.20 quantile divides a set of points or values into 5 equal sets of values. Percentiles(1/100 — dividing into 100 equal parts), Deciles(1/10 — dividing into 10 equal parts), Quartiles(1/4 — dividing into 4 equal parts), (1/3 — dividing into 3 equal parts) are examples of quantiles used in research as statistics.</em></p><h4>Criteria 6: There should not be Significant Outliers in the data</h4><p>Outliers are observations of a variable that does not follow the expected trend, pattern, or behavior of the remaining observations of that variable. Outliers stand out from the rest of the observations and can be considered — <strong>rebel observation(s) of the variable</strong>. that is, it does not fit with the rest of the data and be said to be a stand-alone. Outliers in data are observations from each variable in the data that behave totally differently from the rest.</p><p>Within the regression context, they are observations that fall far away from the “cloud” of points. They are extremely important because they can have a strong influence on regression prediction. They are capable of negatively affecting the regression by presenting and over-reporting the regression coefficient of the predictor with the outlier points. It can ultimately reduce the accuracy of the predictive model. It can also affect the statistical significance.</p><h4>Statistical Test for checking Criteria 6 — Cook’s Distance</h4><p>Cook’s Distance is a measure of observation or a variable’s value on linear regression. variable value or observations with a very high and large influence may be outliers.</p><p>To identify values or observations that have a very high influence on a prediction using a cook’s distance, there is a rule of thumb. The rule of thumb is — any point or set of observations with a Cook’s distance value that is greater than over 4/n (where n is the total number of observations or called sample size) should be considered to be an outlier. Therefore should be examined further. Also, any observation or set of values with Cook’s distance value that is more than three times the mean of the variable may possibly be an outlier.</p><h4>Graphical Diagnostic for checking Criteria 6 — Boxplot</h4><p>Boxplot captures the summary of data with only a simple box and whiskers in such a way that it reveals observations that are different from the rest. Boxplots generates 5-number summary statistics, namely — Minimum(Q0, 0th percentile), Lower quartile(Q1, 25th percentile), Median (Q2, 50th percentile), Upper quartile(Q3, 75th percentile), Maximum(Q4, 100th Percentile), and indicate the outliers. One can just get insights(quartiles, median, and outliers) into the dataset by just looking at its boxplot.</p><p>A Box Plot Outliers detector (Box and Whisker Graph) is easy to interpret, even for non-technical audiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*RGDl5oF4cfLQE7Sm.png" /><figcaption>5-number summary of the Boxplot. <a href="https://flowingdata.com/2008/02/15/how-to-read-and-use-a-box-and-whisker-plot/">Image from FlowingData</a></figcaption></figure><p>In a boxplot, an observation or set of values is outliers if they are 1.5 times bigger or smaller than the expected observation. An extreme value is considered to be an outlier if it is at least 1.5 interquartile ranges below the first quartile or at least 1.5 interquartile ranges above the third quartile.</p><p><strong>The interquartile range (IQR) </strong>in a boxplot, is the distance between the upper and lower quartiles (Q3-Q1). IQR is used as a measure of dispersion to indicate how spread out the values of a continuous variable are around the mean. Higher IQR means higher variance, lower IQR means lower variance.</p><h4>Criteria 7: No auto-correlation of the error terms</h4><p>Autocorrelation, within the context of regression, occurs when the error terms are dependent on each other. That is when they strongly influence each other. The existence of autocorrelation can be measured from the level of randomness of error terms. If the clustering of error terms are so random that they do not show any pattern then the error terms can be said to be independent and non-autocorrelated. However, if the clustering of error terms shows clear pattern then the error terms can be said to be dependent on each other, and auto-correlated.</p><h4>Statistical Test for checking Criteria 7 — Durban-Watson Test</h4><p>A Durban-Watson test is used to determine if autocorrelation exist between cluster of errors. If autocorrelation exist, they will determine if they are positively autocorrelated, or negatively autocorrelated.</p><p>The Durbin-Watson test statistic (d) always ranges between 0 and 4. If the value is near 2, it indicates evidence of non-autocorrelation. If the value is towards 0, it indicates evidence of positive autocorrelation. If the value is towards 4, it indicates evidence of negative autocorrelation.</p><p><em>The null hypothesis for the durbin-watson test stastistic — Residuals from the regression are not autocorrelated (autocorrelation coefficient, ρ = 0). The Alternative hypothesis — Residuals from the regression are autocorrelated (autocorrelation coefficient, ρ &gt; 0). The durban-watson statistic is approximately equal to 2*(1-r) where r is the sample autocorrelation of the residuals.</em></p><p>As a general rule of thumb, if the Durbin-Watson test statistic value is between the range of 1.5 and 2.5, then autocorrelation is considered normal. However, values outside of this range could indicate that autocorrelation is a problem.</p><h4>Graphical Diagnostic for checking Criteria 7 — The Residual by Successive Residual Scatter plot (LagPlot of the Residual)</h4><p>A Lagplot of the residual is a type of scatterplot that visually indicate if the residuals are independent and auto-correlated. The lag plot works by plotting each residual value versus the value of the successive residual. That is, the first residual is plotted against the second, the second versus the third, etc.</p><p>As an illustration — if the total number of residuals is n, such that we have — R1, R2, R3,…, Rn. The Lagplot will be an X-Y plane, where for every residual Rn, we would plot an Rn on the Y-axis against an Rn-1 on the X-axis. That is, we would plot an R2 on the Y- axis against an R1 on the X-axis, R3 on the Y-axis against an R2 on the X-axis. The occurrence of lag happens at the X-axis, and at Lag=1 since the gap of comparison for plotting happens between a residual point(say Rn)and the residual point immediately before it(say Rn-1).</p><p>So the maximum number of plots that can be plotted on the lagplot is n-1 since the last lagplot point, P, will be P(Rn-1, Rn). that is, Because of the way the residuals are paired, there will be one less point on this plot than on most other types of residual plots.</p><p>In a Lagplot, If the residual plots are randomly scattered with no apparent structure or pattern, then no autocorrelation exists in the data. Usually, random residual plot distributions do not exhibit any identifiable structure in the lag plot. However, if the residual plots are clustered in a clearly patterned or structured way, such that they provide a linear, quadratic or polynomial plot, then autocorrelation exists in the residual lagplot distribution.</p><h3>4. <strong>Implementation and test of each criteria in python</strong></h3><p>In this section, we would implement the assessment of each criteria in python.</p><p>The data used for this illustration is a free sourced data from the Nigerian Demographic and Health Survey 2018 (NDHS 2018). The DHS is a nationally representative survey that is being conducted in developing countries.</p><p>To request any country-level free sourced data from the DHS program, kindly visit the <a href="https://dhsprogram.com/data/dataset_admin/login_main.cfm?CFID=6656492&amp;CFTOKEN=ce6ca5b288d60002-2AFF6515-C723-702A-D46EDCBB32A8BDBD"><strong>DHS Program</strong></a>, sign-up, and request.</p><h4>1. We will import and load data into python through Jupyter notebook</h4><pre>#import data into python<br>path=r&#39;B:\ndhs2018_respondent_with_child.csv&#39;<br>ndhs2018_respondent_with_child=pd.read_csv(path)</pre><p>The dataset (dataframe) is named — “ndhs2018_respondent_with_child”, as indicated above. Let’s check for the number of observations and variables in the dataset using the shape() method</p><pre>#determine the number of observations and columns<br>ndhs2018_respondent_with_child.shape</pre><pre>(29992, 4)</pre><p>The number of observations is 29992, while the number of variables (columns) is 4.</p><p>Note: We have done some processing to the data to meet our goal before importing into Jupiternote book. The original dataset has thousands of variables (columns) and observations.</p><p><strong><em>Next, we would check for the name, and data type of the 4 variables using the info() method</em></strong></p><pre>#determine the variable type of each variable in the dataset<br>ndhs2018_respondent_with_child.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 29992 entries, 0 to 29991<br>Data columns (total 4 columns):<br> #   Column                 Non-Null Count  Dtype  <br>---  ------                 --------------  -----  <br> 0   v012                   29992 non-null  int64  <br> 1   v106                   29992 non-null  object <br> 2   v190                   29992 non-null  object <br> 3   Percent_children_dead  29992 non-null  float64<br>dtypes: float64(1), int64(1), object(2)<br>memory usage: 937.4+ KB</pre><p>The four variables are — v012, v106, v190, and Percent_children_dead. variables — v012, and Percent_children_dead are integer variables; while variables — v106, and v190 are object variables.</p><p><strong><em>Next, we would conduct an exploratory analysis of the four variables (columns) by running a percentage frequency distribution for each using the count() method.</em></strong></p><p>We also see the option-categories contained in each variable. For example, variable v106 has 4 option-categories namely — no education, secondary, primary, and higher.</p><pre>#list of the response-categories of the educational status(v106)variable<br>ndhs2018_respondent_with_child[&#39;v106&#39;].value_counts(normalize=True)*100</pre><pre>no education    41.527741<br>secondary       31.838490<br>primary         17.841424<br>higher           8.792345<br>Name: v106, dtype: float64</pre><pre>#list of the response-categories of the weatlh index status (v190)variable<br>ndhs2018_respondent_with_child[&#39;v190&#39;].value_counts(normalize=True)*100</pre><pre>poorer     21.399040<br>middle     21.172313<br>poorest    20.992265<br>richer     19.825287<br>richest    16.611096<br>Name: v190, dtype: float64</pre><pre>#percentage distribution of parity variable (Percent_children_dead)<br>ndhs2018_respondent_with_child[&#39;Percent_children_dead&#39;].value_counts(normalize=True)*100</pre><pre>0.00     67.361296<br>33.33     4.527874<br>50.00     3.831022<br>25.00     3.804348<br>20.00     3.214190<br>           ...    <br>90.00     0.003334<br>7.14      0.003334<br>91.67     0.003334<br>61.54     0.003334<br>90.91     0.003334<br>Name: Percent_children_dead, Length: 61, dtype: float64</pre><pre><br>#percentage distribution for variable age (v012)<br>ndhs2018_respondent_with_child[&#39;v012&#39;].value_counts(normalize=True)*100</pre><pre>30    6.948520<br>25    6.658442<br>35    6.255001<br>40    5.128034<br>28    4.154441<br>45    4.134436<br>20    3.907709<br>32    3.587623<br>27    3.584289<br>38    3.440918<br>26    3.217525<br>22    3.204188<br>36    2.817418<br>33    2.807415<br>23    2.774073<br>29    2.747399<br>48    2.717391<br>31    2.564017<br>42    2.557349<br>34    2.550680<br>37    2.534009<br>24    2.510670<br>49    2.310616<br>39    2.140571<br>43    2.060549<br>21    2.007202<br>46    1.800480<br>41    1.767138<br>47    1.613764<br>18    1.513737<br>44    1.507069<br>19    1.373700<br>17    0.816885<br>16    0.230061<br>15    0.056682<br>Name: v012, dtype: float64</pre><h4>2. We will assess the data to see if they meet the 7 criteria.</h4><p><strong><em>2.1. Criteria 1: The Independent variable(s) must be Continous, Ordinal, or Discrete, while the Dependent variable(s) must only be Continuous or Discrete but not Ordinal</em></strong></p><p><strong>Criteria 1 Check — </strong><em>Variable Type Check</em></p><p>In python, we would check for the variables’ type of the 4 columns using the info() method</p><pre>#check the variable types of the four columns(variables)<br>ndhs2018_respondent_with_child.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 29992 entries, 0 to 29991<br>Data columns (total 4 columns):<br> #   Column                 Non-Null Count  Dtype  <br>---  ------                 --------------  -----  <br> 0   v012                   29992 non-null  int64  <br> 1   v106                   29992 non-null  object <br> 2   v190                   29992 non-null  object <br> 3   Percent_children_dead  29992 non-null  float64<br>dtypes: float64(1), int64(1), object(2)<br>memory usage: 937.4+ KB</pre><p>From the result, only variables (column) v012, and percent_children_dead are integers(int64, and float64). the other two (v106, v190) are not (object).</p><p><strong><em>Next, we would convert the two variables (v106, v190)that are not integers to integer variable types, so they can meet criteria 1.</em></strong></p><p>Let’s start with v106:</p><pre>#code the response-categories as numbers<br>Independent_v106 = {<br>                &quot;v106&quot;: {&quot;no education&quot;: 0,  &quot;secondary&quot;: 1,  &quot;primary&quot;: 2,  &quot;higher&quot;:3}<br>                    }<br>ndhs2018_respondent_with_child.replace(Independent_v106, inplace=True)</pre><p>Let’s check if the variable type of variable v106 has changed from object to integer.</p><pre>#check the education variable to see if it has been expressed in numbers<br>ndhs2018_respondent_with_child[&#39;v106&#39;].value_counts(normalize=True) * 100</pre><pre>1    21.399040<br>3    21.172313<br>2    20.992265<br>4    19.825287<br>5    16.611096<br>Name: v190, dtype: float64</pre><p>The variable type of v106 has changed from object to integer</p><p>Let’s convert v190 to integer:</p><pre>#code the response-categories as numbers<br>Independent_v190 = {<br>                &quot;v190&quot;: {&quot;poorer&quot;: 1,  &quot;poorest&quot;: 2,  &quot;middle&quot;: 3,  &quot;richer&quot;:4,  &quot;richest&quot;:5}<br>                    }<br>ndhs2018_respondent_with_child.replace(Independent_v190, inplace=True)</pre><p>The variable type of v190 has changed from object to integer</p><pre>#check the wealth index variable to see if it has been expressed in numbers<br>ndhs2018_respondent_with_child[&#39;v190&#39;].value_counts(normalize=True) * 100</pre><pre>1    21.399040<br>3    21.172313<br>2    20.992265<br>4    19.825287<br>5    16.611096<br>Name: v190, dtype: float64</pre><p><strong><em>Next, let’s check if the four variables or columns are now integers</em></strong></p><pre>#check all the variables to see if they are now integers<br>ndhs2018_respondent_with_child.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 29992 entries, 0 to 29991<br>Data columns (total 4 columns):<br> #   Column                 Non-Null Count  Dtype  <br>---  ------                 --------------  -----  <br> 0   v012                   29992 non-null  int64  <br> 1   v106                   29992 non-null  int64  <br> 2   v190                   29992 non-null  int64  <br> 3   Percent_children_dead  29992 non-null  float64<br>dtypes: float64(1), int64(3)<br>memory usage: 937.4 KB</pre><blockquote><strong><em>Verdict for Criteria 1: All four variables are now integers, so the first criteria was met.</em></strong></blockquote><p><strong><em>2.2. Criteria 2: Only a Linear relationship exists between each of the Predictor variables (Independent variable) and the Target variable (Dependent Variable).</em></strong></p><p>We would use both statistical and graphical diagnostic checks to see if the dataset and its variables meet criteria 2</p><p><strong><em>2.2.1 Statistical Test for checking Criteria 2 — Correlation Matrix and corresponding P-value.</em></strong></p><p>Let’s use a correlation matrix and its p-value to check for Criteria 2</p><pre>#conduct correlation matrix <br>corr_matrix=ndhs2018_respondent_with_child.corr()<br>#round off correlation coefficient to 4 decimal places<br>round(corr_matrix,4)</pre><pre>v012                      v106       v190         Percent_children_dead<br>v012                      1.0000     0.1095      0.1229       0.0771<br>v106                      0.1095     1.0000      0.4389       -0.1516<br>v190                      0.1229     0.4389      1.0000       -0.1841<br>Percent_children_dead     0.0771     -0.1516     -0.1841      1.0000</pre><p>The correlation matrix shows that a linear relationship exist between each of the independent variable (v106, 190, and v190), and the dependent variable (percent children dead). With the relationship was stronger between percent children dead and v190(-0.1841 about -18%), and v106 (-0.1516 about -15%), and less stronger for v012 (0.07 about 7%)</p><p>The Correlation matrix p-value(P-value &lt;0.0)shows that all the pairwise relationships are statistically significant</p><pre>#use custom function to calculate p-values for correlation matrix<br>from scipy.stats import pearsonr<br>r_pvalues(ndhs2018_respondent_with_child)</pre><pre>                       v012 v106 v190  Percent_children_dead<br>v012                   0.0  0.0  0.0   0.0<br>v106                   0.0  0.0  0.0   0.0<br>v190                   0.0  0.0  0.0   0.0<br>Percent_children_dead  0.0  0.0  0.0   0.0</pre><p><strong><em>2.2.2.Graphical Diagnostic for checking Criteria 2 — A Scatter Plot between each Independent Variable and the Dependent Variable, with a regression line</em></strong></p><p>Using scatterplot, let’s visually check if a linear relationship exists between the dependent variable (Percent_children_dead), and each of the Independent variable(v012, v106, and v190).</p><p>Let check that between percent children dead and v012</p><pre># importing libraries<br>import seaborn as sb<br>    <br># use regplot<br>sb.regplot(x = &quot;v012&quot;,<br>            y = &quot;Percent_children_dead&quot;, <br>            ci = None,<br>            data = ndhs2018_respondent_with_child)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*Zr3z1sbEYb8PBmG12aaAZw.png" /></figure><p>The regression line supports the type of linear relationship that exist between the v012 and percent children dead. It shows that it is a positive relationsip (that is “percent children dead” increases as “v012” increases) or decreases as v012 decreases.</p><p>Lets check visually that a linear relationship exist between the dependent variable (Percent_children_dead), and the Independent variable(v106)</p><pre># importing libraries<br>import seaborn as sb<br>    <br># use regplot<br>sb.regplot(x = &quot;v106&quot;,<br>            y = &quot;Percent_children_dead&quot;, <br>            ci = None,<br>            data = ndhs2018_respondent_with_child, color=&#39;yellow&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*OCF55M48FXHMB-zpFNjttQ.png" /></figure><p>The regression line supports the type of linear relationship that exist between the v106 and the percent of children dead variable as indicated statistically. It shows that it is a negative or inverse relationship (that is “percent children dead” decreases as “v106” increases) increases as v106 decreases.</p><p>Lets check if a linear relationship exist between the dependent variable (Percent_children_dead), and the Independent variable(v190), visually</p><pre># importing libraries<br>import seaborn as sb<br>    <br># use regplot<br>sb.regplot(x = &quot;v190&quot;,<br>            y = &quot;Percent_children_dead&quot;, <br>            ci = None,<br>            data = ndhs2018_respondent_with_child, color=&#39;red&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*hwDg3qIYDh3-MTrYK81s0A.png" /></figure><p>The regression line supports the type of linear relationship that exist between the v190 and percent children dead as indicated statistically. It shows that it is a negative or inverse relationsip (that is “percent children dead” decreases as “v190” increases) increases as v190 decreases.</p><blockquote><strong><em>Verdict for Criteria 2: The three independent variables have pairwise linear relationship with the dependent variable. v106, and v190 have inverse or negative relationship with the dependent variable. v012 has direct or positive relationsip with the independent variable. The second criteria was met.</em></strong></blockquote><p><strong><em>2.3.Criteria 3: No Multicollinearity must exist between the independent variables.</em></strong></p><p>We would use both statistical and graphical diagnostic check to see if the dataset and its variables meet criteria 3</p><p><strong><em>2.3.1. Statistical Test for checking Criteria 3 — Variance Inflation Factor (VIF)</em></strong></p><p>Lets use a variance inflation factor (VIF) to statistically check if every possible pair of the independent variables (v012 vs v190, v012 vs v106, etc) have a linear relationship.</p><pre>from statsmodels.stats.outliers_influence import variance_inflation_factor<br>import statsmodels.api as sm</pre><pre># Split the columns into y and X<br>y = ndhs2018_respondent_with_child[&#39;Percent_children_dead&#39;]<br>X = ndhs2018_respondent_with_child[[&#39;v012&#39;, &#39;v106&#39;, &#39;v190&#39;]]</pre><pre># VIF dataframe<br>vif_data = pd.DataFrame()<br>vif_data[&quot;feature&quot;] = X.columns<br>  <br># calculating VIF for each feature<br>vif_data[&quot;VIF&quot;] = [variance_inflation_factor(X.values, i)<br>                          for i in range(len(X.columns))]<br>  <br>print(vif_data)</pre><pre>feature       VIF<br>0    v012  4.670006<br>1    v106  2.403949<br>2    v190  5.822557</pre><p>Based on the rule on the rule of thumb, it appears there is not a significant multicollinearity between the independent variables. especially for v0106 (2.403)</p><p><strong><em>2.3.2.Graphical Diagnostic for checking Criteria 3 — Scatter plot to visualize correlation effect among independent variables</em></strong></p><p>Using scatterplot, let’s visually check if multicollinearity exists between the independent variables using pairwise plotting.</p><pre>import seaborn as sns</pre><pre># Split the columns into y and X<br>y = ndhs2018_respondent_with_child[&#39;Percent_children_dead&#39;]<br>X = ndhs2018_respondent_with_child[[&#39;v012&#39;, &#39;v106&#39;, &#39;v190&#39;]]</pre><pre>sns.pairplot(X);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*_p9yPUCf4GYH_H1LOty6DQ.png" /></figure><p>There appears not to exist a clear linear relationship between each pair of independent variables. Therefore, there is no clear or significant multicollinearity between the independent variables.</p><blockquote><strong><em>Verdict for Criteria 3: No Multicollinearity exist between the independent variables. The third criteria was met.</em></strong></blockquote><p><strong><em>2.4. Criteria 4: There has to be Homoscedasticity in the data</em></strong></p><p>We would use both statistical and graphical diagnostic checks to see if the dataset and its variables meet criteria 3</p><p><strong><em>2.4.1. Statistical Test for checking Criteria 4 — Breusch-Pagan test</em></strong></p><p>Let’s use a Breusch-pagan test to statistically check if there is homoscedasticity in the data. Recall — The null hypothesis for the Breusch Pagan test is that the error variances are all equal (Homoscedasticity).</p><pre># Importing libraries<br>import numpy as np<br>import pandas as pd<br>import statsmodels.formula.api as smf<br>from statsmodels.compat import lzip<br>import statsmodels.stats.api as sms</pre><pre># Conduct the Breusch-Pagan test<br>names = [&#39;Lagrange multiplier statistic&#39;, &#39;p-value&#39;,<br>         &#39;f-value&#39;, &#39;f p-value&#39;]<br> <br># Get the test result<br>test_result = sms.het_breuschpagan(fit_model.resid, fit_model.model.exog)<br> <br>lzip(names, test_result)</pre><pre>[(&#39;Lagrange multiplier statistic&#39;, 2751.761503193194),<br> (&#39;p-value&#39;, 0.0),<br> (&#39;f-value&#39;, 1009.8122027447771),<br> (&#39;f p-value&#39;, 0.0)]</pre><p>Based on the result above, the Lagrange multiplier statistic is 2751.76 and the corresponding p-value is 0.0. Because this p-value is less than 0.05, we reject the null hypothesis that homoscedasticity occurs in the data and accept the alternative hypothesis instead. We conclude that the data did not experience homoscedasticity but heteroscedasticity.</p><p><strong><em>2.4.2. Graphical Diagnostic for checking Criteria 4 — The Residual by Fitted Values Scatterplot.</em></strong></p><p>Using a scatterplot, let’s visually check if heteroscedasticity exists in the data if we plot the residual of the regression with fitted values.</p><pre>import statsmodels.api as sm<br>#Prepare the residual of the dependent variable.<br>residuals = result.resid</pre><pre>plt.scatter(y, residuals)<br>plt.plot(y, [0]*len(y))</pre><pre>plt.xlabel(&quot;Fitted Values(Predicted values of y)&quot;)<br>plt.ylabel(&quot;Residuals(Actual y - Predicted y)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*WbZV1oIp5DEp25Nd-TalNA.png" /></figure><p>Since the residual appears not to be on the same horizontal (constant variance) but spread upwards, it is highly possible that the variance of the residuals are not equal or constant. Therefore, this plot suggests heteroscedasticity exists in the data.</p><blockquote><strong><em>Verdict for Criteria 4: There is no Homoscedasticity in the data. Therefore the fourth criteria was not met.</em></strong></blockquote><p><strong><em>2.5. Criteria 5: The error terms are normally distributed</em></strong></p><p>We would use both statistical and graphical diagnostic checks to see if the dataset and its variables meet criteria 5</p><p><strong><em>2.5.1. Statistical Test for checking Criteria 5 — Kolmogorov Smirnov</em></strong></p><p>We would assess and test the normality status of the error terms of the data using the Kolmogorov-Smirnov statistic. The null hypothesis for the Kolmogorov-Smirnov test is that the error terms are normally distributed or are from a normal distribution</p><pre>#perform Kolmogorov-Smirnov test for normality<br>import math<br>import numpy as np<br>from scipy.stats import kstest<br><br>#perform Kolmogorov-Smirnov test for normality<br>kstest(residuals, &#39;norm&#39;)</pre><pre>KstestResult(statistic=0.6656366230671799, pvalue=0.0)</pre><p>The result of the Kolmogorov-Smirnov test shows that the error terms are not from a normal distribution. Since the p-value = 0.0(&lt;0.05), we would reject the null hypothesis and accept the alternative hypothesis that the error terms are not normally distributed.</p><p><strong><em>2.5.2. Graphical Diagnostic for checking Criteria 5 — The Normal Q-Q Plot</em></strong></p><p>We would visually check if the result of the statistical test makes sense using the normal q-q plot.</p><pre>import statsmodels.api as sm<br>residuals = result.resid<br>sm.qqplot(residuals)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*XZ1nNCwnmFGbNSSW_jZ8fA.png" /></figure><p>Since the plot line takes more of S shape and not close to a straight line, this means the error terms are significantly more likely not to be normally distributed. This supports the statistical findings about the error terms not being normally distributed.</p><blockquote><strong><em>Verdict for Criteria 5: Both the statistical and graphical test show that the error terms are not normally distributed. Therefore, the error terms are not normally distributed. The fifth criteria was not met.</em></strong></blockquote><p><strong><em>2.6.Criteria 6: There should not be Significant Outliers in the data</em></strong></p><p>We would use both statistical and graphical diagnostic checks to see if there are outliers in the dataset.</p><p><strong><em>2.6.1. Statistical Test for checking Criteria 6 — Cook’s Distance</em></strong></p><p>The cook distance would be used to check for outliers. If there exist outliers in the data, an inquiry must be made about the status of the outlier</p><pre>#suppress scientific notation<br><br>import numpy as np<br>np.set_printoptions(suppress=True)<br><br><br>#create instance of influence<br>influence = result.get_influence()<br><br>#obtain Cook&#39;s distance for each observation<br>cooks_distance = influence.cooks_distance<br><br>#display Cook&#39;s distances<br>print(cooks_distance[0])</pre><pre>[0.00000261 0.0000017  0.00000018 ... 0.00000174 0.00000283 0.00049528]</pre><pre>#summary of cooks&#39; distance influence<br>summary_cooks=influence.summary_frame()<br>summary_cooks</pre><pre>#list out identified outliers<br>Cooks_outliers = summary_cooks[summary_cooks[&#39;cooks_d&#39;] &gt; (4/29992) ]<br>Cooks_outliers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*jJCuhPVQ5-owc_rkFew8GA.png" /></figure><p>According to cook&#39;s distance, there are 1446 observations that are outliers out of the total 29992. There may be a need to investigate further on the nature of the outliers. Questions to ask can be: are these systemic, contextual, and acceptable outliers or do they happen by mistake? For this dataset, it is highly less likely that they are actual mistakes. The origin of the dataset (DHS) makes it so. Recall — according to the rule of thumb, outliers have cook distance values that are higher than or equal to 4/n where n is the sample size.</p><p><strong><em>2.6.2. Graphical Diagnostic for checking Criteria 6 — Boxplot</em></strong></p><p>We would visually check if there are outliers in the dataset, as indicated and specified by the cook’s distance</p><pre>#run the boxplots<br>ndhs2018_respondent_with_child.boxplot(figsize = (10, 7))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*_ncHZP7DOfDmlGLli1Q6Qg.png" /></figure><p>As indicated and shown by the boxplot above, there are actually identified outliers in the dataset, and almost all of them are found on the variable “percent children dead”</p><blockquote><strong><em>Verdict for Criteria 6: Though both the statistical test and graphical diagnostic show that there are outliers in the dataset. Remover or none remover of outliers depends on the context and circumstance of the variable (s) concerned, and the goal of analysis. The sixth criteria was not met.</em></strong></blockquote><p><strong><em>2.7.Criteria 7: No auto-correlation of the error terms</em></strong></p><p>We would use both statistical and graphical diagnostic checks to see if the error terms are autocorrelated.</p><p><strong><em>2.7.1.Statistical Test for checking Criteria 7 — Durban-Watson Test</em></strong></p><p>We would use the durban-watson test to check if error terms are autocorrelated</p><pre>#import the durban_watson statistic<br>from statsmodels.stats.stattools import durbin_watson as dwtest</pre><pre>dwtest(residuals)</pre><pre>1.8366305102662541</pre><p>Since the value of the durban-watson statistic is close to 2, one can say that there is no autocorrelation of the error terms. The rule of thumb for the durban-watson statistic states if the value is near 2, it indicates evidence of non-autocorrelation. If the value is towards 0, it indicates evidence of positive autocorrelation. If the value is towards 4, it indicates evidence of negative autocorrelation. Durbin-Watson test statistics (d) always ranges between 0 and 4.</p><p><strong><em>2.7.2. Graphical Diagnostic for checking Criteria 7 — The Residual by Successive Residual Scatter plot (LagPlot of the Residual)</em></strong></p><p>We would visually check if the residuals are autocorrelated or not by conducting a lagplot of the residuals.</p><pre><br>import pandas as pds<br>import matplotlib.pyplot as plt<br><br># Draw a lag plot<br>pd.plotting.lag_plot(residuals, lag=1);<br>plt.title(&quot;residuals Lag plot with lag=1&quot;);<br>plt.show(block=True);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*C7Ka70WISCEBFXlksAFLPw.png" /></figure><p>Based on the result of the graph above, it is apparent that there is no clear pattern or shape (linear, quadratic etc) on about of the scatter suggesting that no autocorrelation exist between residuals.</p><blockquote><strong><em>Verdict for Criteria 7: Both the statistical and graphical test show that autocorrelation does not exist between residuals. Hence the seventh criteria was met.</em></strong></blockquote><h4><strong>5. Conclusion</strong></h4><p>To use linear regression for prediction, the 7 criteria must met first by the variables involve. If any of the 7 criterias are not met, there are ways to fix it, depending on context and specific criteria violated. The fixing may range from removing variables responsible for the violation of the specific criteria, to conducting a transformation using transformation functions like logarithms, to encoding categorical variable to numerical variable.</p><p>For the criteria analysis conducted in python, only four criterias were met out of the 7 assessed. The four criteria that were met are — All variables are integers, Linear relationship exist between each of the independent variable and the dependent variable, No multicollinearity exist between any pair of the independent variables, and the residuals are not autocorrelated. The three that were not met were — There has to be homoscedasticity in the data, the error terms must be normally distributed, and significant outliers must not exist in the data.</p><p>Subscribe to DDIntel <a href="https://ddintel.datadriveninvestor.com/">Here</a>.</p><p>Visit our website here: <a href="https://www.datadriveninvestor.com/">https://www.datadriveninvestor.com</a></p><p>Join our network here: <a href="https://datadriveninvestor.com/collaborate">https://datadriveninvestor.com/collaborate</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53d3a906c161" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/7-criteria-that-must-be-met-before-using-a-linear-regression-model-lrm-for-prediction-53d3a906c161">7 Non-Negotiable Criteria for Multiple Linear Regression (MLR) Prediction</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[23 practical and useful tips to creating compelling data visualization]]></title>
            <link>https://medium.datadriveninvestor.com/23-practical-and-useful-tips-to-creating-compelling-data-visualization-d7a39944c864?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7a39944c864</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 15:22:08 GMT</pubDate>
            <atom:updated>2026-01-10T14:34:20.828Z</atom:updated>
            <content:encoded><![CDATA[<p>Data is a tool; how you use it, is the art</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*JgcUuNYXQUSb4aac" /><figcaption>Photo by RODNAE Productions on <a href="https://www.pexels.com/photo/magnifying-glass-on-white-paper-7948038/">Pexels.com</a></figcaption></figure><p>Data visualization not only deals with expressing your data in visualized formats( infographics, images, clip arts, charts, etc.); it extends to ensuring that these formats aid consumers’ ability to easily internalize the identified patterns and insights in the data, and the stories or realities behind each pattern or insight. Simply put, data visualization holds the key to unraveling the truth embedded in the data through its relatable data stories.</p><h4>Data Storytelling</h4><p>The concept of using stories to relay the realities embedded in your data is called data storytelling. This concept holds the assumption that your data must transform from mere data to visualization, which in turn must transform to patterns and insights, which must then transform to data stories, that will instigate actions, call to action, business decisions, dialogues, etc among data end-users and audience.</p><h4>Data, Data Visualization, Data Storytelling, and Quality</h4><p>The successful transformation of data to the end product of compelling data stories depends solely on the quality of data, then on the quality of data visualizations. This is analogous to the curious case of “garbage-in garbage-out (GIGO)”. This simply means, if the visualization makes sense, the data stories will too; if it does not, the data stories also suffer, simply put, the truth in your data will not be told.</p><p>The conceptual framework below shows the transformation of data to the eventual data use by the final audience.</p><figure><img alt="A flowchart diagram titled ‘Framework: Transforming Data into Action through Visualization’ showing the steps from data and human skills to actions, developed by Datos-JoieLogicHub | Ayobami Akiode" src="https://cdn-images-1.medium.com/max/1024/1*oyzOQkZjeDAb__IMDSt1Bg.png" /><figcaption>Framework illustrating the necessary transformation of data into visualization, patterns, insights, and compelling stories that instigate real-world actions. By Datos-JoieLogicHub | Ayobami Akiode</figcaption></figure><h4>Tips To Generating Compelling Data Visualization</h4><p>So how do you generate compelling data visualizations that will pour out all the realities the data reflect through data stories? In this article, we will state 23 tips to ensuring that your data totally tell the stories embedded in it through the use of visualization.</p><h4>23 Useful Tips To Creating Compelling Data Visualization</h4><p><strong>1.</strong> Know your audience, this is fundamental and core. Consumers determine the type of products producers make, not the other way. You must know who your audience are, what their goals are, what decisions they need to make, what their background is(educational status, experience, age, religion, level of liberality, etc.), what their nuances and norms are, etc.</p><p><strong>2.</strong> Decide on the appropriate chart to use, depending on your goal. If you want to show distributions, use — bar chart, histogram; for comparison, use — bar chart, line chart; for composition, use — pie chart, treemap, stacked bar chart; for relationship, use — scatterplot; for trends, use — line chart; for geospatial distribution, use — chloropleth chart; for an overview, use — table; for ranking, use — bar chart; for illustrations, use — clip arts, images; for cumulative distribution, use — water chart; for popular keyword or figure, use — tag cloud, bold capitalized and increased font size; for human-angle stories, use — photos, photo-series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*mqvQxisBuRd8jYDI" /><figcaption><strong>Source:</strong> <a href="https://www.vectorstock.com/royalty-free-vector/infographic-set-with-colorful-charts-and-diagram-vector-1583653">vectorstock</a></figcaption></figure><p><strong>3.</strong> Use an opaque or not too bright image your audience can relate with it, as the background of your presentation, brief, etc (A transparency value ranging from 86% — 90%, will do). For example, If your data presentation is about adolescents; your presentation’s background can have an image relating to adolescents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*SRklvWKGhAKPpQSj" /></figure><p><strong>4.</strong> You can add small but visible annotations to your graph to tell stories of the changing patterns indicated by the graph. In the figure below, annotations are the circled text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*JMBhPX-ZWNKVIRQH" /></figure><p><strong>5.</strong> You can embed the key message of your slide just on the free space above your graph. In the figure below, the key message is — “ Google searches skyrocked in 2020”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*SVOKxpuf5GaM6Cjc" /></figure><p><strong>6.</strong> Contrast the color of the lines in a line graph. In the figure below, there are two trends line with contrasting colors of blue and orange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*FEpgtZIL-sKybcC9" /></figure><p><strong>7.</strong> The heading/title of your slide can take a question form. You can then use your graph and annotation to answer the question. You can also make the title a call to action, a key message (Imagine the newspapers we read not having headlines)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*kgee12TdadnumS06" /></figure><p><strong>8.</strong> All labels/annotations should be with the part of the graph/chart they are meant to describe. If you can, avoid the use of legends. For E.g. Labels of a pie-chart should be in their appropriate sector, not by a legend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*8d5j8BieNUPSSAbW" /></figure><p><strong>9.</strong> In a bar chart or any visualization chart that requires the use of an axis (X, Y-axis), avoid the distortion of the axis. All axis must start from zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*lKpH16uxajDTBlUb" /></figure><p><strong>10.</strong> Avoid the use of 3D graphs(three-dimensional charts); they are a huge distraction; use 2D, it is better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*VZKCh7z-x4XWIe8D" /></figure><p><strong>11</strong>. Avoid overloading your slide with a lot of information. If you have a lot of information, split it into mini-charts and use coloring, and shapes to emphasize each importance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*2nq4-Zh0w4gaIwpy" /><figcaption><strong>Source:</strong> <a href="https://www.michaelpiperno.com/blog/">michaelpiperno</a></figcaption></figure><p><strong>12.</strong> Conduct a data-ink to non-data-ink ratio analysis. The data-ink ratio should be high. Data-ink refers to the part of your slides that is imperative &amp; indispensable to your message(label, graph). Make things simple and clear; not confusing, heavy, and complex. If a layman can understand your visualization, then the data-ink ratio must be high and appropriate. Non-data-inks from your slide may be legends, gridlines, 3D, axis lines, unimportant or unnecessary bars, colors, clip arts, or images.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*wY0EiJIok05V2JqG" /><figcaption><strong>Source:</strong> <a href="https://www.oreilly.com/library/view/innovative-tableau/9781492075646/ch12.html">Oreilly library</a></figcaption></figure><p><strong>13.</strong> Outline your line of thought (maybe on a notepad) before commencing data visualization. It is imperative you do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/0*aUixJqh2lavPLaDZ" /><figcaption><strong>Source:</strong> NA</figcaption></figure><p><strong>14</strong>. Identify data visualization templates that have themes that correspond to your message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*CiZmSbosXd1xS7cw" /><figcaption><strong>Source:</strong> <a href="https://www.shutterstock.com/search/icon+personen">shutterstock</a></figcaption></figure><p><strong>15.</strong> Relate your data with things your audience can relate with or are familiar with. Compare your concept, message with what they know. If your audience are community leaders, relate your data to what they are very familiar with within their community, if they are policymakers, relate it with relevant and popular policy within their community of practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*wxTnxRbrFB0oi3U9" /><figcaption><strong>Source:</strong> <a href="https://time.com/4110976/empathy-decline/">time.com</a></figcaption></figure><p><strong>16.</strong> For deep emotional connection; you can deploy human-interest stories as the beginning part(story arc) of your presentation, before deploying your charts, and statistics. For example, if your data is on violence against girls seeking education in Pakistan, you can start by telling the compelling story of Malala Yousafzai, and there afterward share the insights and stories in your data. If your data is on the poor economic situation in Ogun State, Nigeria. You can start by telling a story of a struggling household before sharing the data insights or stories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*XHrqjA8bTQBA-cVf" /><figcaption><strong>Source:</strong> <a href="https://slidetodoc.com/human-interest-story-the-art-of-telling-stories/">slidetodoc</a></figcaption></figure><p><strong>17.</strong> You should use arrows, spheres, circles, and other shapes to indicate and emphasize the most important part of your chart or presentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*nhaFtz1ZZGBsvNpW" /></figure><p><strong>18.</strong> The fundamental to a compelling data story is truthfulness and honesty. Ultimately, data generation, processing, and analysis must be of optimum quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*CxED_SQ5QDoZw9WA" /><figcaption><strong>Source:</strong> <a href="https://sites.google.com/site/happinessbusinessbb102/home/week-9">https://sites.google.com/site/happinessbusinessbb102/hom</a></figcaption></figure><p><strong>19.</strong> If you are using PowerPoint to present your data, you can deploy PowerPoint animation when you need the contents of your slides to be ordered, and your thought process organized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*6fV3E4MkLK_gNT6k" /><figcaption><strong>Source:</strong> <a href="https://bagsh.mn/lesson/Powerpoint-Animations">https://bagsh.mn</a></figcaption></figure><p><strong>20.</strong> Consider your presentation slides as movie scenes that come one at a time to make the audience stay glued: Combine animation with numbering to ensure your audience follows you per time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*O-_XT977a4zgacXh" /><figcaption><strong>Source:</strong> <a href="https://www.freeiconspng.com/img/17478">https://www.freeiconspng.com</a></figcaption></figure><p><strong>21</strong>. If possible, only use real-life images, pictures when referencing real-life situations or examples. Use icons/clip arts etc when making statements of facts, or illustrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*GgjxVWXG9cRB-25B" /></figure><p><strong>22.</strong> Colours can be an inhibitor or enabler of your insight, so must be used strategically. The less, the better. Change of colors should be done only on the part you want to emphasize. You can deploy shapes in this regard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*ald1rhPAAjSKqvDU" /><figcaption><strong>Source</strong>: NA</figcaption></figure><p><strong>23.</strong> Relate the data’s patterns and insights, and stories with your audiences’ day-to-day language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*51Gzhnf53NCqGFyWCAc9_Q.png" /><figcaption>This figure illustrates Tip #23 in action: a compelling data visualization must be tailored to its specific audience, transforming raw data on Nigerian debt into relevant, relatable insights. Produced by Datos-JoieLogicHub | Ayobami Akiode</figcaption></figure><h4>In Summary</h4><p>Data visualization is imperative for making sense of data. It helps in delivering the data to the needing audience(decision-makers) in ways they can understand and need. They serve as intermediary that transforms mere data to patterns and insights, then to the realities in the data through data stories.</p><p>Data stories are basically contextualized insights and patterns. They say what the insights and patterns mean within the context of the subject matter. Simply put, they relay the reality implication of the insights and patterns in your data.</p><p><em>Originally published at </em><a href="https://researchdataguy.com/"><em>https://researchdataguy.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7a39944c864" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/23-practical-and-useful-tips-to-creating-compelling-data-visualization-d7a39944c864">23 practical and useful tips to creating compelling data visualization</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Visualization Algorithms (VAT & iVAT) To Assess Cluster Tendency]]></title>
            <link>https://medium.com/analytics-vidhya/using-visualization-algorithms-vat-ivat-to-assess-cluster-tendency-a89251a2400e?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a89251a2400e</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Mon, 17 May 2021 16:22:14 GMT</pubDate>
            <atom:updated>2026-01-10T00:22:09.412Z</atom:updated>
            <content:encoded><![CDATA[<p>Be ‘Visibly&#39; sure there are clusters in that dataset before profiling what the main themes are.</p><figure><img alt="A dark map visually representing clusters of COVID-19 outbreaks in China, Southeast Asia, and Mongolia. This image illustrates real-world data clusters for the VAT and iVAT cluster tendency analysis tutorial." src="https://cdn-images-1.medium.com/max/1024/1*pRaFsHe9u2xIMqkbAgmSlQ.jpeg" /><figcaption>This map highlights natural clusters within a real-world dataset. The VAT and iVAT algorithms help researchers ‘visibly’ confirm that these clusters exist before conducting complex analysis or audience segmentation.<strong> </strong>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Conducting Customer and Audience Segmentation etc are cost-effective ways of making evidence-based decisions, by finding themes from unsupervised data. However, conducting Cluster Analysis on a dataset and making decisions with it without verifying, first, if clusters indeed exist; can be far more damaging, expensive, and costly.</p><p>In this article, we will explain how you can use two visualization algorithms (VAT and iVAT), to assess the Clustering Tendency of an unsupervised data set in python before commencing any relevant Cluster analysis.</p><p>To look at the different areas of VAT and iVAT, we would cover the following sections:</p><blockquote><strong><em>1. The Concept of Cluster Tendency</em></strong></blockquote><blockquote><strong><em>2.Cluster Tendency Algorithms</em></strong></blockquote><blockquote><strong><em>3.The VAT, and iVAT Algorithms</em></strong></blockquote><blockquote><strong><em>4. How to Evaluate the Cluster Tendency of a Dataset using VAT, and iVAT test in Python</em></strong></blockquote><blockquote><strong><em>5. Conclusions</em></strong></blockquote><blockquote><strong><em>6. Summary</em></strong></blockquote><h3>1. The Concept of Cluster Tendency</h3><p>Cluster Tendency is the process of assessing a dataset for the possible existence of clusters. It is meant to help us answer this critical question — ‘Are there clusters in this dataset based on our research question?’</p><p>It is essential to answer this question; because it will determine if going ahead to conduct cluster analysis (K-means, hierarchical, etc) on the dataset, is necessary or not.</p><p>So, how do we answer this question, or what do we do to answer it?</p><p><em>The simple answer — We deploy ‘Cluster Tendency Assessment Algorithms’</em></p><h3>2. Cluster Tendency Assessment Algorithms</h3><p>Cluster tendency assessment algorithms are machine learning methods that assess datasets for the possible existence of cluster patterns. There are two main methods for conducting these assessments; which are — Statistical and Visual methods. An example of the Statistical method is the Hopkins test, while examples of the Visual methods are — Visual Assessment of Tendency (VAT), and Improved Visual Assessment of Tendency (iVAT) test.</p><h3>3. The VAT, and iVAT Algorithms</h3><h4>3.1. VAT (Visual Assessment for Tendency)</h4><p>VAT is a visual method of assessing the clustering tendency of a dataset. The algorithm specifies the numbers of clusters that can be found in a dataset, and also shows if there are existing clusters within clusters( cluster hierarchies) by creating densely black square along the left diagonal of a squared-size Map. The algorithm works by creating a minimum spanning tree of observations, the pairwise distance between those observations is displayed as the black squares of the map.</p><p>Please note — While the VAT/iVAT image is always square (because it represents an <em>n × n</em> dissimilarity matrix), the <strong>dark shapes</strong> representing clusters may not be perfect squares — they can appear <strong>rectangular or irregular</strong>, especially when clusters are imbalanced.</p><p>Also, the use of VAT and iVAT should not be seen as a substitute for metrics (E.g Elbow, and Silhouette methods) specifically designed in determining the number of clusters that can be found in a dataset. Majorly, the sole function of the VAT and iVAT algorithms is to visually suggest if clusters exist in a dataset or not, so as to avoid the expensive cost of conducting cluster analysis on datasets that have none. That is, the VAT and iVAT Maps can be used to validate and reinforce the main algorithms that estimate number of clusters, they should not be used as substitutes.</p><p>In general, the way to calculate the number of clusters for a given VAT/iVAT algorithm is to calculate the number of densely black squares within the printed map.</p><p><strong>Example of VAT Maps</strong>: The figure below shows 4 main Maps (3a — 3d) with differing numbers of black squares representing clusters. As illustrations, the first Map with the 3a-tag has three visibly black squares, therefore it has three clusters. Also, the last figure with 3d-tag has two black squares, so it has two clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*EJXrqfw2_kTmEDfQbPqKlg.png" /><figcaption>Figure 3.1:Set of VAT Maps. Image from a Publication by Bezdek et al(2007) at <a href="https://www.researchgate.net/publication/3336491_Visual_Assessment_of_Clustering_Tendency_for_Rectangular_Dissimilarity_Matrices">Researchgate</a></figcaption></figure><h4><strong>3.2. iVAT (Improved Visual Assessment for Tendency)</strong></h4><p>iVAT is a visual method of assessing the clustering tendency of a dataset. It is an improved variant of VAT. It is different from VAT, by providing more precise and clearer densely black squares/rectangles in its printed map. However, it has more computing time cost.</p><p>Just as it is with the VAT algorithm, the black square images, which represents the number of clusters, will in rare situations not be on the left diagonal and may not be squares.</p><p><strong>Example of iVAT Maps</strong>: The figure below shows 3 Maps (referencing from the left) with differing numbers of black squares, representing clusters. As illustrations, the first square (from the left) has three clusters (though there exist clusters within clusters too), the second has three black squares, therefore it has three clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*jZpdCOh_wzM15ynASJ6nwg.png" /><figcaption>Figure 3.2:Set of iVAT Maps. Image from a Publication by Bezdek et al(2010) at <a href="https://www.researchgate.net/publication/224177086_Clustering_elliptical_anomalies_in_sensor_networks">Researchgate</a></figcaption></figure><h3>4. How to Evaluate The Cluster Tendency of a Dataset Using VAT and iVAT Test in Python</h3><p>In Python, the VAT and iVAT assess the Cluster Tendency of a dataset, visually, using a Dissimilarity matrix. The matrix works for both numerical and categorical data types, as it has specific functions for all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_L7vZoZPFw36iu8x9VTRg.png" /><figcaption>Figure 4.1: Dissimilarity &amp; Similarity Functions For Categorical Features. Image from <a href="https://www.youtube.com/channel/UCzL_0nIe8B4-7ShhVPfJkgw">Data Science Dojo</a></figcaption></figure><p>Now, let’s talk briefly about Dissimilarity (and Similarity) for the sake of those that are keenly interested in knowing what it is.</p><h4>4.1. The Basic Concept Of Dissimilarity and Similarity</h4><p><strong>Dissimilarity</strong> is the numerical measure of how different two data objects/points are. The farther away two data points are, the higher their dissimilarity, vice versa. It is worthy of mention that <strong>‘Similarity’</strong>, which is the numerical measure of how alike two data objects/points are, is the direct opposite of Dissimilarity. The closer two data objects are, the higher their similarity, vice versa.</p><p>Therefore, if two data points have a high similarity value, they will have a low dissimilarity value; If they have a high dissimilarity value, they will have a low similarity value. This simply means that dissimilarity and similarity have an inverse relationship.</p><h4>4.2. Dissimilarity and Clustering</h4><p>Within the context of VAT and iVAT algorithms in python, a very low dissimilarity between two data points indicates highly dense black squares/rectangle, indicating the existence of clustering. while a very high dissimilarity simply means they are far apart to be clustered or be in a cluster.</p><h4><strong>4.3. VAT and iVAT Algorithms (VAT) in Python</strong></h4><p>To implement the VAT (&amp; iVAT) algorithms in python, we would carry out the following, sequentially, in our anaconda environment :</p><ol><li>Import the dataset into the anaconda working environment as dataframe through Pandas;</li><li>Import the VAT and iVAT algorithms into our working environment from the <strong>pyclustertend</strong> module;</li><li>Convert any categorical feature in the dataset into a numerical feature using either OneHot Encoding (Dummy Coding, if the feature is Nominal) or LabelEncoding (if the feature is Ordinal);</li><li>Convert the dataframe into NumPy array;</li><li>Feed the algorithms with the Numpy array dataset; and</li><li>Get the result of algorithms as Maps.</li></ol><p>The output of running the algorithms on our dataset will produce <strong>an ordered dissimilarity square-shaped Map </strong>containing the black squares (or rectangles).</p><h4><strong>4.4. Practical Session: Implementing the Algorithms</strong></h4><p>4.4a. <strong>Import the Packages</strong></p><pre>#import the packages<br>import pandas as pd # working with data<br>import numpy as np # working with arrays<br>from pyclustertend import vat<br>from pyclustertend import ivat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*E8OyCuUbTwSkunVesl3NHg.png" /></figure><p>4.4b. <strong>Import the Dataset</strong></p><pre>#import dataset into anaconda through pandas<br># Specify the path directory to the stata dataset on your computer so as to import it into pandas<br>path=r&quot;B:\Current_Contraceptive_Users_Modified_NDHS2018_15_19.dta&quot;</pre><pre># Read the stata dataset into pandas (as its dataframe) and name the dataframe as DHS <br>Young_Contraceptive_Users=pd.read_stata(path)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*CgFmC5XgUofVrZKbda_MCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVF-7BrZY6VnGjGxAx-CqQ.png" /><figcaption>There are 109 observations and 6 features</figcaption></figure><p>4.4c. <strong>Convert Categorical Features to Numerical Features</strong></p><p>There are 5 nominal(not ordinal) features in our dataset, we would convert them to numerical features using One hot encoding ( dummy coding)</p><pre># convert the categorical features in the dataset to numerical <br>Young_Contraceptive_Users=pd.get_dummies(Young_Contraceptive_Users, columns = [&#39;v025&#39;,&#39;v106&#39;,&#39;v130&#39;,&#39;MaritalStatus&#39;,&#39;SES&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTTSICdOTvtkKrtEyiuBqw.png" /><figcaption>There are 109 observations and 15 features after One Hot Encoding (OHE)</figcaption></figure><p>4.4d. <strong>Convert Pandas Dataframe to Numpy Array</strong></p><pre># convert the categorical features in the dataset to numerical <br>Young_Contraceptive_Users=pd.get_dummies(Young_Contraceptive_Users, columns = [&#39;v025&#39;,&#39;v106&#39;,&#39;v130&#39;,&#39;MaritalStatus&#39;,&#39;SES&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NsHSco8fn0MifAAZWX0yg.png" /></figure><p>4.4e. <strong>Feed the Array Data to the VAT Algorithm</strong></p><pre>#feed the array data to the VAT (Visual Assessment Tendency) algorithm <br>vat(Young_Contraceptive_Users_array)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tliNki2gZahkWaagCrKcLQ.png" /></figure><p>4.4f. <strong>Feed the Array Data to the iVAT Algorithm</strong></p><pre>#feed the array data to the improved VAT (Visual Assessment Tendency) algorithm <br>ivat(Never_Use_Contraceptive_array)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrrPvAoHp_YgF1w9PIzpjg.png" /></figure><h3>5. Conclusion</h3><p>From the result of implementing the Algorithms (both VAT and iVAT), it is observed from the maps produced that the Young Contraceptive Users’ dataset has clusters, and therefore should be explored and profiled with Cluster analysis. It is convenient to conduct the K-Prototype Cluster Analysis on the dataset since it has both numerical and categorical features(Mixed data type). Also, the iVAT map appears clearer and more precise than that of the VAT as expected. At minimum, there are about seven clusters in the dataset, as shown by the maps.</p><p>Remember, there are specific algorithms, designed to help you identify the numbers of statistically significant clusters. The VAT and iVAT Algorithms are just meant to help us decide if we should go ahead with the cluster analysis or not. Though VAT and iVAT maps can be used to validate and reinforce the main algorithms that estimate number of clusters, they should not be used as substitutes.</p><h3><strong>6. Summary</strong></h3><p>1.The use of Visual Assessment Tendency(VAT) and its iVAT variant is to, visually, suggest if there is a need to conduct Cluster analysis or not on your dataset.</p><p>2.The use of Visual Assessment Tendency (VAT) and its variant should not be used for determining the number of clusters that can be found in a dataset.Though they can be used to validate and reinforce the main algorithms that estimate number of clusters, they should not be used as substitutes. There are specific metrics — Elbow method and Silhouette method, available to help you do that.</p><p>3. The Improved Visual Assessment Tendency (iVAT) is the improved version of VAT because it has more precise and clearer images. However, it has more computing time cost. That is, it takes more time converging than the VAT.</p><p><strong>Now that’s it</strong>. Hope you find this useful? Please drop your comments and follow me on LinkedIn at <a href="https://www.linkedin.com/in/ayobami-akiode-38528839/">Ayobami Akiode LinkedIn</a></p><p>The Jupyter notebook used for this analysis is available<strong> </strong><a href="https://github.com/ayobamiakiode/My-projects/blob/master/Using%20Visualization%20Algorithms%20(VAT%20and%20iVAT)%20To%20Assess%20Cluster%20Tendency-%20Copy.ipynb"><strong>here</strong></a></p><h4>Data source:</h4><p>The data used in this article is a free sourced secondary data of the demographic and health survey (DHS) for Nigeria collected in 2018, called NDHS 2018. The DHS is a nationally representative survey that is being conducted in developing countries. In Nigeria, the survey is routinely conducted every 5 years; and covers all the states of Nigeria, including the capital.</p><p>To request any country-level free sourced data from the DHS program, kindly visit the <a href="https://dhsprogram.com/data/dataset_admin/login_main.cfm?CFID=6656492&amp;CFTOKEN=ce6ca5b288d60002-2AFF6515-C723-702A-D46EDCBB32A8BDBD"><strong>DHS Program</strong></a>, sign-up, and request.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a89251a2400e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/using-visualization-algorithms-vat-ivat-to-assess-cluster-tendency-a89251a2400e">Using Visualization Algorithms (VAT &amp; iVAT) To Assess Cluster Tendency</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualization Only! Not Enough. How to Carry Out Bivariate Statistical Test in Python]]></title>
            <link>https://medium.com/geekculture/visualization-only-not-enough-how-to-carry-out-bivariate-statistical-test-in-python-fc8238b896c?source=rss-5fd5b621e7fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc8238b896c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Ayobami Akiode]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 15:02:40 GMT</pubDate>
            <atom:updated>2021-03-18T15:02:40.252Z</atom:updated>
            <content:encoded><![CDATA[<h4>Test the predictor feature statistically at bivariate, before including it in the model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V5xbi9dwzDGWsDZa" /><figcaption>Photo by <a href="https://unsplash.com/@battlecreekcoffeeroasters?utm_source=medium&amp;utm_medium=referral">Battlecreek Coffee Roasters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Do you know? Using boxplots, scatterplots, and other visualization tool is awesome but never enough in confirming that a relationship exists between two variables (The target feature (Y)and each of the predictor features(X))?</p><p>I know you may ask, why?</p><p>Well, because a statistician may argue that the visual pattern you are seeing in your sample is not what truly obtains in the population your sample represents. Specifically, she/he may say — “What you are seeing actually happened by chance, so it is highly probable that when a sample of similar characteristics is drawn, severally, from the same population, you may not see the relationship indicated by this visualization again”</p><p><strong>What then is the best practice to overcome the huddle created by statistics or statisticians in this instance…?</strong></p><blockquote><strong><em>The gold standard </em></strong><em>— “</em>Use data visualization tools(charts/two-way table) to visualize possible existence of relationships or association between the two features, then conduct a statistical test to statistically confirm if what the visual pattern suggests is true or not”</blockquote><p>In this article, we would — state the appropriate criteria for using the different bivariate statistical tests in confirming the existence of a relationship/association between the target feature (Y) and each of the predictor variables (X); and demonstrate how to implement that in python.</p><p>This article will cover the following sections:</p><blockquote><strong><em>1.A Quick Overview Of Inferential Bivariate Analysis Concepts and Framework</em></strong></blockquote><blockquote><strong><em>2.Overview Of Data Source</em></strong></blockquote><blockquote><strong><em>3. Rules For applying the different inferential bivariate statistical test</em></strong></blockquote><blockquote><strong><em>4. How To carry out bivariate inferential analysis in Python</em></strong></blockquote><h3><strong>1 . A Quick Overview Of Inferential bivariate analysis concepts and framework</strong></h3><p>Bivariate analysis is the empirical analysis of two variables to ascertain if a relationship or association exists between them. It has two components, the descriptive, and the inferential components. The descriptive component is concerned with the visualization of the relationship using graphs like the scatterplot, boxplots, and numerical tabulations (cross-tabulation, etc). The inferential component is concerned with the use of statistical methods in testing and determining the relationship. The figure below highlights the hierarchical system of the components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWQZ7fH5a52LL9Arf5jNtw.png" /><figcaption><strong>Conceptual framework of Bivariate Analysis. Image by Akiode Ayobami</strong></figcaption></figure><p>In this study, we would only be looking at the inferential component of the bivariate framework. An extensive description of the descriptive component can be found in my related earlier article — <a href="https://medium.com/analytics-vidhya/visualization-not-enough-to-assess-relationship-between-2-variables-combine-with-statistical-test-2a32a2c99153"><strong>Visualization, not enough to suggest a relationship; Confirm it with a Statistical test</strong></a></p><h4><strong>1.1. Inferential Bivariate Analysis</strong></h4><p>This is the application of statistical methods in determining if a relationship, association, or difference exists between two variables/features. There are two types, namely — Parametric and Non-parametric.</p><p><strong>1.1.1 Parametric Bivariate Analysis: </strong>is used when the distribution of the population from which the two variables are from are normally distributed or bell-shaped. Though according to the central limit theorem, parametric methods can still be used when the sample size of the sample is at least 30 or more. Though, there are statistical methods that can be used to test for normality, E.g — the Shapiro-Wilk test, D’agostino’s k-squared test, Anderson-darling test, lilliefors test, Jarque–beta test, Kolmogorov-Smirnov test, and Chi-square Test.</p><p><strong>1.1.2 Non-Parametric Bivariate Analysis: </strong>is used when the distribution of the population from which the two variables are from, are unknown or not normally distributed. Though it is mostly also considered for small sampled datasets that are not parametric. There are statistical tests that fall within the non-parametric rule. This statistical test can be seen in the bivariate analysis framework figure above. Just like the parametric statistical test, the non-parametric statistical test to use at any instance depends on the type of variables/features.</p><h3><strong>2.Overview Of Data Source</strong></h3><p>The data used in this article is a free sourced secondary data of the demographic and health survey (DHS) for Nigeria collected in 2013, called NDHS 2013. The DHS is a nationally representative survey that is being conducted in developing countries. In Nigeria, the survey is routinely conducted every 5 years; and covers all the states of Nigeria, including the capital. The strata of respondents data for this analysis is that of Ogun State.</p><p>To request any country-level free sourced data from the DHS program, kindly visit the <a href="https://dhsprogram.com/data/dataset_admin/login_main.cfm?CFID=6656492&amp;CFTOKEN=ce6ca5b288d60002-2AFF6515-C723-702A-D46EDCBB32A8BDBD"><strong>DHS Program</strong></a>, sign-up, and request.</p><h3><strong>3. Rules for applying the different inferential bivariate statistical test</strong></h3><p>Selecting the appropriate statistical test that would go with a bivariate visualization is determined by two things: the parametric status of the sample and the types of variables involved.</p><p>The table below indicates, in brief, the two parametric status and variable type criteria that must be met for each bivariate inferential statistic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSy99Rvs7XlQLd9z8sGeYQ.png" /><figcaption><strong>Table 3.1: Statistical test Parametric and type of variable compatibility Table. Image by Akiode Ayobami</strong></figcaption></figure><h3><strong>4. How To carry out bivariate inferential analysis in Python</strong></h3><p>In this section, we would show how to carry out bivariate analysis in python starting with parametric methods, then non-parametric methods.</p><p>First, we will import and load data into python through the Jupyter notebook</p><pre>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qviZajn7t4Qk4h4PGOYrgQ.png" /></figure><p>Though there are 4617 features (variables) and 630 rows (observations) in this data frame, we would only require 9 in our analysis. As a consequence, we would only keep the 9 in the dataframe.</p><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]<br>Ogun_ndhs2013.shape<br>Ogun_ndhs2013.head(9)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8du1lgW__b2DzwO6asANTw.png" /></figure><h4>4.1. Parametric Inferential Bivariate Analysis in python</h4><p><strong>4.1.1 Chi-square Test of Independence: </strong>This is a bivariate parametric method that is used for testing the association between a nominal target feature (independent variable) and a predictor feature(dependent variable). None of the cells of the contingency must be 5 or less than it. In cases where such exist(cell(s) value ≤5), then Fisher’s exact test should be used. <br> <br>In this instance of our analysis, our Nominal target feature will be — current contraceptive method (v313), while our Nominal predictor feature will be — the type of place of residence (v025)</p><p>We will import all required libraries and modules</p><pre>import numpy as np<br>from scipy.stats import chi2_contingency<br>from scipy.stats import chi2</pre><p>We would run frequency distributions of the predictor and target features and recode the v313 from 4-response-category to 3-response-category feature.</p><pre>Ogun_ndhs2013 [&#39;v025&#39;].value_counts()<br>Ogun_ndhs2013 [&#39;v313&#39;].value_counts()</pre><pre>#We will v313 recode into: No method, Modern Method, and Others<br>v313_recode =  { &quot;v313&quot;: <br>                             {&quot;No method&quot;: &#39;No method&#39;,  <br>                              &quot;Modern method&quot;: &#39;Modern method&#39;,  <br>                              &quot;Traditional method&quot;: &#39;Others&#39;,  <br>                              &quot;Folkloric method&quot;: &#39;Others&#39;}<br>             }</pre><pre>Ogun_ndhs2013.replace(v313_recode, inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hiEH4zKXkHVrrdeEKDZ3_w.png" /></figure><p>Make the crosstabulation (two-way table) of the predictor feature (v025), and the target feature (v313), and compute the chi-square statistic and its related p_value</p><pre>#Develop crosstabulation needed for chi-square statistic and p_value computation<br>tab0=pd.crosstab(index=Ogun_ndhs2013.v313, columns=Ogun_ndhs2013.v025)<br>print(tab0)</pre><pre>#compute the chis-quare statistic and p_value<br>chi2, p, dof, expected=chi2_contingency(tab0.values)<br>print(&#39;Chi-square statistic is %0.3f,  p_value is %0.3f&#39; %(chi2,p))</pre><p>The chi-square statistic value is 0.001, p_value=0.9. Since p_value&gt;0.05; there is no association between the two features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwclaVhgQhUUEg8l7dJVQw.png" /></figure><p><strong>4.1.2 T-test of mean difference: </strong>This is a bivariate parametric method that is used to test if there is a significant difference in the mean value of the numerical target feature (dependent variable) between the two response-categories of the binary predictor feature(independent variable).</p><p>There are majorly three types of T-test, namely: <br>a. One sample t-test <br>b. Two independent sample t-test<br>c. Paired Sample t-test</p><p>In this instance, the numerical target feature will be — Age (v012), while the binary predictor feature will be — Type of place of residence (v025)</p><p><strong>4.1.2.1 One-sample T-test of mean difference</strong>: This is a bivariate parametric method that is used to test if there is a significant difference between the mean value of a numerical target feature and a hypothetical value. The hypothetical value usually represents what the population or known value is. As an example, if the Nigerian National census shows that the average age of a Nigerian is 30, this may be considered the hypothetical value. You may collect a data sample from a state in Nigeria, and use a one-sample t-test to see if the average age of people in that state is significantly different from the National value(30).</p><p>For our analysis, using our Ogun 2013 NDHS data, we would take the overall mean age of women of reproductive in Ogun state as the hypothetical value. With the one-sample t-test, we would test if the mean age of women of reproductive age in rural areas of Ogun is significantly different from the hypothetical overall mean age of women in the state.</p><p>In most contexts, the hypothetical value would have been known beforehand. In fact, it would have been documented in literature or from the community of practice.</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import ttest_1samp</pre><p>Calculate the mean age of women of reproductive age in Ogun state, and in rural areas of Ogun state only.</p><pre>#Overall Mean age of women in Ogun state </pre><pre>Ogun_state_mean_age=Ogun_ndhs2013[&#39;v012&#39;]<br>Ogun_state_mean_age.mean(), Ogun_state_mean_age.std()</pre><pre><br>#Mean age of women in rural areas of Ogun state</pre><pre>age_rural=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v012&#39;]&gt;=15) &amp; (Ogun_ndhs2013[&#39;v025&#39;]== &quot;Rural&quot;)]<br>age_rural=age_rural[&#39;v012&#39;]<br>age_rural.mean(), age_rural.std()</pre><p>Compute the one-sample t-test statistic and its associated p_value</p><pre>stats.ttest_1samp(rural_age,31)</pre><p>The one-sample t-test statistic value is 2.06, p_value=0.03. Since p_value&lt;0.05; there is a significant mean difference between the mean age of rural respondents and the hypothetic value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPk9oOaZl7OlRuqtGOQzzw.png" /></figure><p><strong>4.1.2.2 Two independent sample t-test of mean difference</strong>: This is a bivariate parametric method that is used to test if there is a significant difference in the mean value of the numerical target feature (dependent variable) between the two response-categories of a binary predictor feature that are independent.</p><p>Note, it called an independent sample because it is expected that the observations of the two response-categories should be mutually exclusive. For example, the response-categories of the variable — Type of place of residence is mutually exclusive, because respondents can either be rural or urban, but not both.</p><p>In this instance, the numerical target feature will be — Age (v012), while the binary predictor feature will be — Type of place of residence (v025)</p><p>We would take the mean age of women of reproductive in rural and urban areas of Ogun state. Using the two independent sample t-test, we would test if the mean age of women of reproductive age in rural areas and urban areas of Ogun is significantly different.</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import ttest_ind</pre><p>Calculate the mean age of women of reproductive age in rural and urban areas of Ogun state.</p><pre>#Overall Mean age of women in urban areas  Ogun state</pre><pre>age_urban=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v012&#39;]&gt;=15) &amp; (Ogun_ndhs2013[&#39;v025&#39;]== &quot;Urban&quot;)]<br>age_urban=age_urban[&#39;v012&#39;]<br>age_urban.mean(), age_urban.std()</pre><pre>#Mean age of women in rural areas of Ogun state</pre><pre>age_rural=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v012&#39;]&gt;=15) &amp; (Ogun_ndhs2013[&#39;v025&#39;]== &quot;Rural&quot;)]<br>age_rural=age_rural[&#39;v012&#39;]<br>age_rural.mean(), age_rural.std()</pre><p>Compute the independent sample t-test statistic and p_value</p><pre>stats.ttest_ind(age_rural,age_urban)</pre><p>The two independent sample t-test statistic values between the mean age of rural and urban respondents are 2.82, p_value=0.004. Since p_value&lt;0.05; there is a significant mean difference between the mean age of rural and urban respondents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18wpocx5zTJ0nc6m3oqO5w.png" /></figure><p><strong>4.1.2.3 Paired-sample t-test test of mean difference</strong>: This is a bivariate parametric method that is used to test if there is a significant mean difference of the same variable collected at two different times from the same set of respondents or observations.</p><p>Let&#39;s give two scenario examples —</p><p>First scenario: You may want to test if the mean score of a set of students in Biochemistry in the first year of college is different from their mean score in Biochemistry in the second year.</p><p>Second scenario: You may want to test if the mean score of a set of children in writing is different from the mean score of the same set of children in reading.</p><p>We would use two similar features in our analysis, to reflect how to use paired sample t-test. The number of respondent’s daughters not living with respondents (v203); and the number of respondent’s daughters living with respondents(v205). we would test if the mean number of respondent’s daughter living with her is different from the mean of those not living with her.</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import ttest_rel</pre><p>Take out v205 and v203 from the Ogun NDHS 2013 data as series</p><pre>daughter_home=Ogun_ndhs2013[&#39;v205&#39;]<br>daughter_away=Ogun_ndhs2013[&#39;v203&#39;]</pre><p>Compute the paired sample t-test statistic and p_value</p><pre>ttest_rel(daughter_home,daughter_away, nan_policy=&#39;omit&#39;)</pre><pre># The omit means that ignore pairs with missing values in the #analysis. <br>#Other options are: propagate (the default argument). With this, if #there are missing pairs or one part of a pair, the program will #return &quot;nan&quot;)</pre><p>The paired sample t-test statistic value is 9.84 , p_value=0.00. Since p_value&lt;0.05; there is a significant mean difference between the mean number of respondents’ daughters that live at home and those that are living away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7V4pe_kFW6IQ0ZMhh2QCg.png" /></figure><p><strong>4.1.3 Pearson Correlation test of relationship: </strong>This is a bivariate parametric method that is used to test if a linear relationship exists between two numerical variables, a predictor and target feature. Correlation values range from -1 to 0(zero)to +1. If the value of the correlation statistics is between 1 and 0, then the relationship between the two variables is positive, contextually, it means that as one variable is increasing, the other is increasing, also if one variable is decreasing, the other is decreasing. if the value of the correlation statistic is negative, that is if it has a value between 0 and -1, then the two variables have a negative relationship. Contextually, it means that as one variable is increasing, the other is decreasing vice versa. If the value of the correlation statistic is zero, that is if it has a value of 0 then the two variables have no relationship(linear). Contextually, it means an increase or decrease in one does not correlate to an increase or decrease in the other.</p><p>Note, correlation statistic is widely known as correlation coefficient and it is denoted by r. Let give two scenario examples, where the use of correlation statistic is suitable.</p><p>In this instance, the numerical predictor feature will be — Age (v012), while the numerical target feature will be — Number of living children(v218)</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import pearsonr</pre><p>Take out v012 and v218 from the Ogun NDHS 2013 data as series</p><pre>Age_X=Ogun_ndhs2013[&#39;v012&#39;]<br>No_Living_Chid_Y=Ogun_ndhs2013[&#39;v218&#39;]</pre><p>Compute the Pearson correlation statistic and its associated p_value</p><pre>stats.pearsonr(Age_X, No_Living_Chid_Y)</pre><p>The Pearson correlation statistic value is 0.7 , p_value=0.00. Since p_value&lt;0.05; there is a significant strong positive relationship between the age of respondents and the number of their living children.</p><p><strong>4.1.4 Regression test of Linear relationship: </strong>This is a bivariate parametric method that is used to compute and estimate the linear regression line that exists between two numerical features (Target feature(Y); Predictor feature (X) ), that has been found to be correlated. <br>A regression line is denoted by — Y=<strong>M</strong>X+<strong>C</strong>. It is used for computing the two essential parameters, namely: <br>1. <strong>M</strong>, called <strong>gradient or slope</strong> of the regression line. It is defined as the increase in the value of Y for every unit increase in X (change in Y/change in X)<br>2. <strong>C</strong>, called <strong>intercept</strong> of the regression line. It is defined as the value of Y when X=0.</p><p>In this instance, the numerical predictor feature will be — Age (v012), while the numerical target feature will be — Number of living children(v218)</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import linregress</pre><p>Take out v012 and v218 from the Ogun NDHS 2013 data as series</p><pre>Age_X=Ogun_ndhs2013[&#39;v012&#39;]<br>No_Living_Chid_Y=Ogun_ndhs2013[&#39;v218&#39;]</pre><p>Compute regression statistic and p_value</p><pre>slope, intercept, r_value, p_value, std_err = stats.linregress(Age_X, No_Living_Chid_Y)</pre><pre># r squared is the coefficient of determination, and tells stands between 0 and 1<br>print (&quot;r-squared:&quot;, r_value**2)</pre><p>The regression coefficient is 0.155, p_value=0.00. Since p_value&lt;0.05; the change in the number of children living with respondents for every unit increase in the age of respondents is significant. Also, R-squared=0.49 means, 49% of the variance observed in the Target feature(number of children living with respondents) is explained by the variance of the Predictor feature(age of respondents)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBZO2Kqsfyaphl4uQBeZFw.png" /></figure><p><strong>4.1.4 One-way Analysis of Variance(ANOVA): </strong>This is a bivariate parametric method that is used to test if there is a significant difference in the mean value of the numerical target feature (independent variable) across the response-categories of a nominal predictor feature/variable (with more than two response-categories). The difference between the T-test and the ANOVA is that the predictor feature in a T-test is a two response-categories categorical feature, while the predictor feature in an ANOVA has more than two response-categories.</p><p>In this instance, the numerical predictor feature will be — Age (v012), while the numerical target feature will be — the educational status of respondents (v106)</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import f_oneway</pre><p>Calculate the age distribution of respondents by their educational status</p><pre>#Age distribution of respondents that have no education</pre><pre>Only_NoEducation=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;No education&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>NoEducation_educ_age=Only_NoEducation[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have primary education</pre><pre>Only_primary_education=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Primary&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>primary_educ_age=Only_primary_education[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have secondary education</pre><pre>Only_secondary_education=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Secondary&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>secondary_educ_age=Only_secondary_education[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have higher education</pre><pre>Only_Higher=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Higher&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>Higher_educ_age=Only_Higher[&#39;v012&#39;]</pre><p>Compute one way ANOVA statistic and p_value</p><pre>f_oneway(secondary_educ_age,primary_educ_age, NoEducation_educ_age, Higher_educ_age)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pPwLUHmo5VoTK65vP90Xw.png" /></figure><p>The ANOVA statistic value is 16.4, p_value=0.00. Since p_value&lt;0.05, there is a mean age difference, at least between two respondents by educational status.</p><h4>4.2. Non-parametric Inferential Bivariate Analysis</h4><p><strong>4.2.1 Man-Whitney U test: </strong>This is a non-parametric method, that is analogous to the two-sample independent sample t-test, except it is used when the data are ordinal or ranked. It can be used as a replacement for the independent sample t-test when there is no assumption that the (interval or ordinal) predictor feature is normally distributed or when the distribution is unknown. The Mann-Whitney U test can still be used when the number of observations is just 8. Though the Mann-Whitney U test has less statistical power than the t-test; it is stronger with more skewed data, including those with high outliers. Whitney-Manny assumes equal variance (homoscedasticity) of the two samples being compared else might not be a fit for use even if the data is ordinal.</p><p>The null hypothesis for Mann-Whitney is: The probability that a randomly drawn observation from one of the samples is greater than a randomly drawn observation from the other sample is 0.5. In simple terms, the null hypothesis proposes that the median of the two samples is equal or the same.</p><p>In this instance of our analysis, the target feature will be — Age (v012), while the binary predictor feature will be — Type of place of residence (v025).</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import mannwhitneyu</pre><p>Get the age distribution of respondents by type of place of residence from the Ogun NDHS 2013 data, as series</p><pre>#Rural respondents&#39; age data as series</pre><pre>age_urban=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v012&#39;]&gt;=15) &amp; (Ogun_ndhs2013[&#39;v025&#39;]== &quot;Urban&quot;)]<br>age_urban=age_urban[&#39;v012&#39;]<br> age_urban.std()</pre><pre>#Urban respondents&#39; age data as series</pre><pre>age_rural=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v012&#39;]&gt;=15) &amp; (Ogun_ndhs2013[&#39;v025&#39;]== &quot;Rural&quot;)]<br>age_rural=age_rural[&#39;v012&#39;]<br> age_rural.std()</pre><p>Compute the Mann_whitney U test statistic and its associated p_value</p><pre>stats.mannwhitneyu(age_rural,age_urban)</pre><p>The Mann-Whitney statistic value is 42368, p_value=0.002. Since p_value&lt;0.05; so there is a significant age difference between women in urban and rural areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_2eNeaWdV6uhaZcfe2JKA.png" /></figure><p><strong>4.2.2 Spearman Rank Correlation</strong>: This is a non-parametric method, that is analogous to a Pearson correlation statistic. The statistic is called the Spearman rank coefficient and measures the strength and direction of the relationship between the two variables (A predictor feature(X), and a Target feature(Y)). To be implemented, it requires that either of the two variables have ordinal properties so they could either be ordinal, or continuous (interval, ratio). Similarly ranked features will have a high Spearman rank correlation coefficient, vice versa.</p><p>The statistical power of the Pearson correlation is stronger than that of the spearman rank correlation, however, it is suitable for use when the distributions of the two variables are not normal or are skewed.</p><p>Also, a spearman rank correlation measures the monotonic relationship between the two variables, while the Pearson statistic measures the linear relationship between the two variables. The measure of a monotonic relationship is measured using the -1 to +1 range like a spearman correlation coefficient. The p-value of the spearman is more reliable for the sample size of 500 or more. The statistical reliability of Spearman rank correlation in testing the null hypothesis is accepted, at minimum, when the sample size is 8. Though you can still carry out spearman rank correlation for data with less than 8 sample sizes, it will have close to zero statistical power.</p><p>The null hypothesis for Spearman rank correlation is: There is no monotonic association between the two features. A monotonic relationship is one in which the two variables move in the same direction or opposite direction at a constant rate.</p><p>We would use — Age(v012) as the predictor feature, and — Number of living children (v218), as the target feature, with the assumption that their distribution is skewed or unknown, but not normal.</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import spearmanr</pre><p>Pull out v012 and v218 from the Ogun NDHS 2013 data as series</p><pre>Age_X=Ogun_ndhs2013[&#39;v012&#39;]<br>No_Living_Chid_Y=Ogun_ndhs2013[&#39;v218&#39;]</pre><p>Compute the Spearman rank correlation statistic and its associated p_value</p><pre>stats.spearmanr(Age_X, No_Living_Chid_Y)</pre><p>The spearman rank correlation statistic value is 0.72, p_value=0.00. Since p_value&lt;0.05; there is a significant positive monotonic relationship between the age of women and their number of living children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rY9rNdNfy_NeCWLzsTPEuQ.png" /></figure><p><strong>4.2.3 Kruskal Wallis</strong>: This is a non-parametric method, that is analogous to an Analysis of Variance (ANOVA), and a substitute for the Mann-Whitney test when the Predictor feature(X) has more than two response-categories. The Kruskal follows a chi-square distribution when each response-category has at least 5 observations. It computes the median of the target feature (Y) on each response-category of the predictor feature then compares to see if they are the same. It is important to note that Kruskal Wallis is also used for scale parameters comparison.</p><p>Note, the Kruskal Wallis assumes the variance of the response-categories is the same. In instances where this variance assumption does not hold, the mood statistic should be used.</p><p>The null hypothesis for Kruskal-Wallis is: The median value of the predictor feature by the response-categories of the target feature is the same or equal.</p><p>We would use the two variables used in computing the one-way analysis of variance (one-way ANOVA), with the assumption that their distribution is skewed, unknown, but not normal.</p><p>In this instance, the numerical predictor feature will be — Age (v012), while the numerical target feature will be — the educational status of respondents (v106)</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import kruskal</pre><p>Get the age distribution of respondents by their educational status from the Ogun NDHS 2013 data, as series</p><pre>#Age distribution of respondents that have no education<br>Only_NoEducation=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;No education&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>NoEducation_educ_age=Only_NoEducation[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have primary education<br>Only_primary_education=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Primary&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>primary_educ_age=Only_primary_education[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have secondary education<br>Only_secondary_education=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Secondary&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>secondary_educ_age=Only_secondary_education[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have higher education<br>Only_Higher=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Higher&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>Higher_educ_age=Only_Higher[&#39;v012&#39;]</pre><p>Compute Kruskal Wallis statistic and p_value</p><pre>stats.kruskal(secondary_educ_age,primary_educ_age, NoEducation_educ_age, Higher_educ_age)</pre><p>The Kruskal Wallis statistic value is 46.33, p_value=0.00. Since p_value&lt;0.05; there is a significant difference in median age among, at least, two women educational groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rY9rNdNfy_NeCWLzsTPEuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xS50qrKkPQ18vKB_NWN_fw.png" /></figure><p><strong>4.2.4. Mood Median test</strong>: This is a non-parametric method, that is used to test if an ordinal Target feature (Y) has the same median across the two or more response-categories of the nominal/binary predictor feature(X). That is, it test if the median of the response-category of the target feature (Y) is the same across the different response-categories of the nominal/binary predictor feature(X).</p><p>Computing the mood median test requires that the overall median of the target feature is calculated. The median values of the target feature are also then calculated by the response-categories of the predictor features. The value of the median for each response-category is then compared with the overall median. A contingency table is formed based on the comparison outcome between the grand median and the median value of each response-category. <br>The value of the contingency table is used to compute the mood median test statistic and its p-value. This computation method makes the mood median test different from the Mann-Whitney and Kruskal-Wallis median tests.</p><p>Mood median is stronger than both Whitney-Manny and Kruskal-Wallis with data that has outliers. Both Kruskal-Wallis and Mann-Whitney have stronger statistical power than the mood median test for moderate to larger sample size data, vice versa. Mood median is also suitable for use in situations where homoscedasticity does not hold, as Kruskal-Wallis assumes homoscedasticity</p><p>The null hypothesis for mood median is: The median value of the predictor feature by the response-categories of the target feature, in relative to the overall mean, is the same or equal</p><p>In this instance, we would assume age to be an ordinal feature, since, in some real-life contexts, it is considered ordinal.</p><p>In this instance, the predictor feature will be — Age (v012), while the target feature will be — the educational status of respondents (v106)</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import median_test</pre><p>Get the age distribution of respondents by their educational status from the Ogun NDHS 2013 data, as series</p><pre>#Age distribution of respondents that have no education<br>Only_NoEducation=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;No education&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>NoEducation_educ_age=Only_NoEducation[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have primary education<br>Only_primary_education=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Primary&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>primary_educ_age=Only_primary_education[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have secondary education<br>Only_secondary_education=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Secondary&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>secondary_educ_age=Only_secondary_education[&#39;v012&#39;]</pre><pre>#Age distribution of respondents that have higher education<br>Only_Higher=Ogun_ndhs2013[(Ogun_ndhs2013[&#39;v106&#39;]==&#39;Higher&#39;) &amp; (Ogun_ndhs2013[&#39;v012&#39;]&gt;=15)]<br>Higher_educ_age=Only_Higher[&#39;v012&#39;]</pre><p>Compute mood median statistic and p_value</p><pre>stat, p, med, tbl = median_test(secondary_educ_age,primary_educ_age, NoEducation_educ_age, Higher_educ_age)</pre><p>The mood median statistic value is 29.72, p_value=0.00. Since p_value&lt;0.05; there is a significant difference in the median age, at least, among two women educational groups or samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgQ6vzL9x3crJf-T8WzrKg.png" /></figure><p><strong>4.2.5. Goodman and Kruska’s gamma: </strong>This is a non-parametric method that measures the association between two ranked variables, it simply assesses the rank correlation between two ranked variables.</p><p>For a Goodman and Kruskal gamma statistic to be used, two assumptions must be met, namely: The two variables must be ordinal, and the relationship between the two variables must be monotonic. A monotonic relationship is one in which the two variables move in the same direction or opposite direction at a constant rate. It is typically impossible to estimate a monotonic relationship statistically, but a graph can roughly visually show it. In contrast, for a linear relationship; the two variables move in the same or opposite direction but not at a constant rate.</p><p>Goodman and Kruska’s gamma can be used as a substitute for Spearman rank correlation, Wilcoxon two-sample test, and the sign test when the observation of the two variables has tied rank value. Tied rank is when the observations of two distinct samples have the same rank value.</p><p>A value of -1 for the Goodman and Kruska’s gamma statistic indicates a negative association; while a value of +1 for the Goodman and Kruska’s gamma statistic indicates a positive association. A zero value means there is no relationship.</p><p>It is important to note that currently, there is no package or library in python for calculating Goodman and Kruska’s gamma statistic. We would use the function developed by P.Stikker to resolve this problem. Stikker’s method was compared with STATA Goodman and Kruskal method output and was found to be the same. Please note, P.Stikker’s original has been modified here to suit our needs.</p><p>In this instance, the ordinal predictor feature will be — categorized age (v013), while the ordinal target feature will be — wealth index of respondents (v190)</p><p>Import required libraries from python and add the function developed by P.Stikker</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import norm</pre><p>Add P.Stikker’s Gamma and Kruskals developed python function</p><pre>def goodmanKruskalgamma(data, row_feature, column_feature):<br>    myCrosstable = pd.crosstab(data[row_feature], data[column_feature])<br>    <br>    nRows = myCrosstable.shape[0]<br>    nCols = myCrosstable.shape[1]<br>    <br>    <br>    C = [[0 for x in range(nCols)] for y in range(nRows)]</pre><pre># top left part<br>    for i in range(nRows):<br>        for j in range(nCols):<br>            h = i-1<br>            k = j-1        <br>            if h&gt;=0 and k&gt;=0:            <br>                for p in range(h+1):<br>                    for q in range(k+1):<br>                        C[i][j] = C[i][j] + list(myCrosstable.iloc[p])[q]</pre><pre># bottom right part                    <br>    for i in range(nRows):<br>        for j in range(nCols):<br>            h = i+1<br>            k = j+1        <br>            if h&lt;nRows and k&lt;nCols:            <br>                for p in range(h, nRows):<br>                    for q in range(k, nCols):<br>                        C[i][j] = C[i][j] + list(myCrosstable.iloc[p])[q]<br>                        <br>    D = [[0 for x in range(nCols)] for y in range(nRows)]</pre><pre># bottom left part<br>    for i in range(nRows):<br>        for j in range(nCols):<br>            h = i+1<br>            k = j-1        <br>            if h&lt;nRows and k&gt;=0:            <br>                for p in range(h, nRows):<br>                    for q in range(k+1):<br>                        D[i][j] = D[i][j] + list(myCrosstable.iloc[p])[q]</pre><pre># top right part                    <br>    for i in range(nRows):<br>        for j in range(nCols):<br>            h = i-1<br>            k = j+1        <br>            if h&gt;=0 and k&lt;nCols:            <br>                for p in range(h+1):<br>                    for q in range(k, nCols):<br>                        D[i][j] = D[i][j] + list(myCrosstable.iloc[p])[q]</pre><pre>P = 0<br>    Q = 0<br>    for i in range(nRows):<br>        for j in range(nCols):<br>            P = P + C[i][j] * list(myCrosstable.iloc[i])[j]<br>            Q = Q + D[i][j] * list(myCrosstable.iloc[i])[j]<br>               <br>    GKgamma = (P - Q) / (P + Q)<br>    <br>    n = myCrosstable.sum().sum()<br>    <br>    Z1 = GKgamma * ((P + Q) / (n * (1 - GKgamma**2)))**0.5<br>    <br>    forASE_R = 0<br>    forASE_SPSS = 0<br>    for i in range(nRows):<br>        for j in range(nCols):<br>            forASE_R = forASE_R + list(myCrosstable.iloc[i])[j] * (Q * C[i][j] - P * D[i][j])**2<br>            forASE_SPSS = forASE_SPSS + list(myCrosstable.iloc[i])[j] * (C[i][j] - D[i][j])**2</pre><pre>ASE_R = 4 * (forASE_R)**0.5 / (P + Q)**2<br>    ASE_SPSS = 2 * (forASE_SPSS - (P - Q)**2 / n)**0.5 / (P + Q)        <br>    Z_R = GKgamma / ASE_R<br>    Z_SPSS = GKgamma / ASE_SPSS<br>    <br>    from scipy.stats import norm<br>    <br>    p1 = norm.sf(Z1)<br>    p2_R = norm.sf(Z_R)<br>    p3_SPSS = norm.sf(Z_SPSS)<br>            <br>    return print(&#39;gamma statistic is %0.3f, p_value for R is %0.3f, ASE for R is %0.3f, p_value for spss is %0.3f, ASE for spss is %0.3f&#39; %(GKgamma,p2_R,Z_R,p3_SPSS,Z_SPSS))</pre><p>Assess the two features to see if there is a need for pre-processing</p><pre>Ogun_ndhs2013[&#39;v013&#39;].value_counts()</pre><pre>Out[4]:</pre><pre>25-29    122<br>30-34    108<br>35-39     88<br>15-19     88<br>20-24     82<br>40-44     80<br>45-49     62<br>Name: v013, dtype: int64</pre><pre>Ogun_ndhs2013[&#39;v190&#39;].value_counts()</pre><pre>Richest    237<br>Richer     237<br>Middle     114<br>Poorer      40<br>Poorest      2<br>Name: v190, dtype: int64</pre><p>Pre-process wealth index(v190) by recoding into three response-categories (rich, middle, poor), it currently has five response-categories (richest, richer, middle, poorer, and poorest)</p><pre>#We will recode into: Rich, Middle, and Poor<br>recode_v190 =  { &quot;v190&quot;: <br>                             {&quot;Richest&quot;: &#39;Rich&#39;,  <br>                              &quot;Richer&quot;: &#39;Rich&#39;,  <br>                              &quot;Middle&quot;: &#39;Middle&#39;,  <br>                              &quot;Poorer&quot;: &#39;Poor&#39; ,<br>                              &quot;Poorest&quot;: &#39;Poor&#39;}<br>             }</pre><pre>Ogun_ndhs2013.replace(recode_v190, inplace=True)</pre><pre>#v190 was recoded into same feature, that&#39;s into v190<br>#New v190 after pre-processing</pre><pre>Ogun_ndhs2013[&#39;v190&#39;].value_counts()<br>Rich      474<br>Middle    114<br>Poor       42<br>Name: v190, dtype: int64</pre><p>Compute the crosstab needed for computing the Gammas and Kruskal’s statistic</p><pre>myCrosstable = pd.crosstab(Ogun_ndhs2013[&#39;v013&#39;], Ogun_ndhs2013[&#39;v190&#39;])<br>myCrosstable</pre><p>Compute Gamma and Kruskal statistic and p_value</p><pre>goodmanKruskalgamma(Ogun_ndhs2013, &#39;v013&#39;, &#39;v190&#39;)</pre><p>The Gamma and Kruskal statistic value is -0.122, p_value=0.98. Since p_value&gt;0.05; there is no association between the two features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*bPVR1H9r0Gy9WFI2GPd7hA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*PRNZru5ygv2DUM0-I7yjFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*cCpOJwoJ4IV1GIR5oviVyQ.png" /></figure><p><strong>4.2.6 Chi-square Goodness of fit test: </strong>This is a non-parametric method that tests if the observed proportion or frequency of the response-category of a categorical variable is totally different from their expected value. That is, it test if the distribution of the observed value fits any of the theoretical distribution (binomial, multinomial). It is analogous to how we test if a feature’s mean is the same as a hypothetical mean in a one-sample T-test. Note, the frequency value of each response-category should be at least 5.</p><p>In general, The set-up of the chi-square goodness of fit test command in python is — chi-square(f_obs, f_exp=None, ddof=0, axis=0), where f_obs is the observed observation in each response-category, f_exp is the expected observation in each response-category. by default, they are assumed as uniform and the mean of the expected values. axis: The axis of the broadcast result of f_obs and f_exp along which to apply the test. If the axis is None, all values in f_obs are treated as a single data set. Default is 0.</p><p>In this instance, we would use — v313 (currently using a method ), as our Target categorical feature, while the predictor feature will be — v025 (a type of place of residence)</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>X_y=Ogun_ndhs2013[[&#39;v313&#39;,&#39;v025&#39;]]</pre><pre>import sklearn as svm<br>from sklearn.feature_selection import chi2</pre><p>Indicate the frequency of the two features (v313, v025)</p><pre># None of the value is less than 5<br>Ogun_ndhs2013 [&#39;v313&#39;].value_counts()<br>No method             489<br>Modern method         118<br>Traditional method     16<br>Folkloric method        7<br>Name: v313, dtype: int64</pre><pre>X_y[&#39;v025&#39;].value_counts()<br>Urban    358<br>Rural    272<br>Name: v025, dtype: int64</pre><p>Conduct feature engineering on the two features — convert their response-categories into numerical values and also merge some response-categories</p><pre>#We will recode v313 into 2-response-category designated as 1 and 0</pre><pre>v313_recode =  { &quot;v313&quot;: <br>                             {&quot;No method&quot;: 0,  <br>                              &quot;Modern method&quot;: 1,  <br>                              &quot;Traditional method&quot;: 0,  <br>                              &quot;Folkloric method&quot;: 0}<br>             }</pre><pre>X_y.replace(v313_recode, inplace=True)</pre><pre>#frequency distribution of v313 after feature engineering</pre><pre>X_y[&#39;v313&#39;].value_counts()<br>0    512<br>1    118<br>Name: v313, dtype: int64</pre><pre>#We will recode v025 into 2-response-category designated as 1 and 2<br>v025_recode =  { &quot;v025&quot;: <br>                             {&quot;Urban&quot;: 1,  <br>                              &quot;Rural&quot;: 2}<br>             }</pre><pre>X_y.replace(v025_recode, inplace=True)</pre><pre>#frequency distribution of v025 after feature engineering<br>X_y[&#39;v025&#39;].value_counts()<br>1    358<br>2    272<br>Name: v025, dtype: int64</pre><p>Compute the chi-square goodness of the fit test statistic and p_value</p><pre># state X and y</pre><pre>X = X_y.drop(&#39;v313&#39;,axis=1)<br>y = X_y[&#39;v313&#39;]</pre><pre>#compute the statistic and p_value<br>chi_scores = chi2(X,y)<br>print(&#39;statistic=%.3f, p-value=%.3f&#39; % (chi_scores[0], chi_scores[1]))</pre><p>The Goodness of fit test statistic value is 0.00002121, and p_value=0.99632516. Since p_value&gt;0.05; the observed values do not fit the expected value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZCiDejW0ioE274fKpg4sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XsHb3ZvHc9TvTTNn7xmPA.png" /></figure><p><strong>4.2.7 Mcnemar test</strong>: This is a non-parametric method that is used to test if two proportions of the same binary variable and from the population are the same. it is also called the test of homogeneity or consistency because it helps to check if the same binary variable has changed after an intervention. Basically, it answers the question — is there a change in a phenomenon after something was done concerning it? Essentially, It is used in evaluating the effect or impact of an intervention on a population. it is used in pretest-posttest research design,case-control studies, and matched pairs. <br>It is analogous to a paired sample t-test but for a target binary feature measure, not a target continuous feature.</p><p>For example, you may test if there is an increase in the proportion of those that passed an exam after a tutorial was institutionalized. Also, you may want to test if the proportion of women using contraceptive methods increases after a family planning radio jingo was aired.</p><p>For a Mcnemar test, you must have a target binary feature and a predictor binary feature. Also, the sample data should be randomly selected from the population. The Mcnemar test requires a 2X2 contingency table to check the marginal homogeneity of the binary variable. The minimum sample size required for the Mcnemar test is 10.</p><p>Cochran’s Q test is a broader variant of the Mcnemar test. it is used to determine if there are differences in a dichotomous dependent variable between three or more related groups.</p><p>Note: if the contingency table is not 2x2. Then exact will be false. A binomial distribution is used for the estimation if the contingency table is 2*2 or square contingency table. If the contingency table is not 2*2, it uses chi-square distribution. Chi-square is the approximation to the distribution of the test statistic for large sample sizes. Therefore, the test statistic is a chi-square statistic if exact is false, else it is a binomial statistic.</p><p>Since for the Mcnemar test, we are majorly interested in assessing the change in the same binary (dichotomous)feature/variable assessed at different times; and the NDHS 2013 is cross-sectional. We would use a single variable and modify it to achieve our analysis and illustration goal.</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>import statsmodels as sm<br>import statsmodels.stats as sms<br>from statsmodels.stats.contingency_tables import mcnemar</pre><p>For this analysis, we would pre-process the v313 variable and create two variables out of it. One will serve as a pre-test, the other as a post-test</p><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import norm</pre><p>Create the pre-test feature from v313</p><pre>#We would use variable - v313</pre><pre>Ogun_ndhs2013 [&#39;v313&#39;].value_counts(normalize=True) * 100</pre><pre>No method             77.619048<br>Modern method         18.730159<br>Traditional method     2.539683<br>Folkloric method       1.111111<br>Name: v313, dtype: float64</pre><pre>#create a pretest feature Ogun_ndhs2013[&#39;pre_test_using_modern_method&#39;]=Ogun_ndhs2013[&#39;v313&#39;]</pre><pre>#We will recode into: Yes, No. Only Modern method is yes<br>pre_recode =  { &quot;pre_test_using_modern_method&quot;: <br>                             {&quot;No method&quot;: &#39;No&#39;,  <br>                              &quot;Modern method&quot;: &#39;Yes&#39;,  <br>                              &quot;Traditional method&quot;: &#39;No&#39;,  <br>                              &quot;Folkloric method&quot;: &#39;No&#39;}<br>             }</pre><pre>Ogun_ndhs2013.replace(pre_recode, inplace=True)</pre><pre># check the created the pretest feature again<br>Ogun_ndhs2013[&#39;pre_test_using_modern_method&#39;].value_counts(normalize=True) * 100</pre><pre>No     81.269841<br>Yes    18.730159<br>Name: pre_test_using_modern_method, dtype: float64</pre><p>Create the post-test feature from v313</p><pre>Ogun_ndhs2013[&#39;post_test_using_modern_method&#39;]=Ogun_ndhs2013[&#39;v313&#39;]</pre><pre>Ogun_ndhs2013[&#39;post_test_using_modern_method&#39;].value_counts(normalize=True) * 100<br>No method             77.619048<br>Modern method         18.730159<br>Traditional method     2.539683<br>Folkloric method       1.111111<br>Name: post_test_using_modern_method, dtype: float64</pre><pre>#We will recode into: Yes, No. Modern and Tradtional methods are yes</pre><pre>post_recode =  { &quot;post_test_using_modern_method&quot;: <br>                             {&quot;No method&quot;: &#39;No&#39;,  <br>                              &quot;Modern method&quot;: &#39;Yes&#39;,  <br>                              &quot;Traditional method&quot;: &#39;Yes&#39;,  <br>                              &quot;Folkloric method&quot;: &#39;Yes&#39;}<br>             }</pre><pre>Ogun_ndhs2013.replace(post_recode, inplace=True)</pre><pre># check the created post-test feature again</pre><pre>Ogun_ndhs2013[&#39;post_test_using_modern_method&#39;].value_counts(normalize=True) * 100</pre><pre>No     77.619048<br>Yes    22.380952<br>Name: post_test_using_modern_method, dtype: float64</pre><p>Create the contingency table of the pre-test and post-test feature</p><pre>post_test_using_modern_method   No  Yes<br>pre_test_using_modern_method           <br>No                             489   23<br>Yes                              0  118</pre><p>Compute Mcnemar statistic and p_value</p><pre>result=mcnemar(tab0, exact=True)</pre><pre># summarize the finding<br>print(&#39;statistic=%.3f, p-value=%.3f&#39; % (result.statistic, result.pvalue))</pre><p>The Mcnemar statistic value is 0.0000, and p_value=0.00000. Since p_value&lt;0.05; There is a significant increase in the proportion of women using modern contraceptives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfM3dYKouFdM6PVbfV5X-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LYqFUKmsocjoNVnTLaTaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyTkP1uxsawyqlY4pMgw6A.png" /></figure><p><strong>4.2.8 Kendall Tau Correlation</strong>: This is a non-parametric method that measures how two ordinal variables correspond. It is an alternative to spearman rank correlation when the sample is small and the tied ranks are many. The features involve must be ordinal or continuous. Though not a strict requirement, a monotonic relationship between the two features makes the Kendall tau correlation a suitable fit for use. Just like Pearson and spearman rank correlation, correlation values range from -1 to 0(zero)to +1. If the value of the correlation statistics is between 1 and 0, then the relationship between the two variables is positive, contextually, it means that as one variable is increasing, the other is increasing, also if one variable is decreasing, the other is decreasing. if the value of the correlation statistic is negative, that is if it has a value between 0 and -1, then the two variables have a negative relationship. Contextually, it means that as one variable is increasing, the other is decreasing vice versa. If the value of the correlation statistic is zero, that is if it has a value of 0 then the two variables have no relationship.</p><p>There are three types of Kendall Tau correlation: Kendall Tau-a, Kendall Tau-b, and Kendall Tau-c, also known as Stuart’s tau-c. Though their values are close, the standardization of their values on the -1 to +1 scale makes them a bit different. Kendall Tau-a is approximate Kendall Tau-b and Kendall-c when their ranks are not tied(tied rank). The Mann-Whitney U test is the same as Kendall’s tau when the predictor feature is binary.</p><p>We would use the two variables used in computing the spearman rank correlation coefficient, with the assumption that their distribution is skewed or unknown, have a smaller small size than that of the spearman rank, and monotonic.</p><p>In this instance, the numerical predictor feature will be — Age (v012), while the numerical target feature will be — Number of living children(v218)</p><p>Import required libraries and dataset</p><pre>#import Ogun NDHS 2013 dataset into pandas<br>import pandas as pd<br>path=r&#39;B:\..\..\Ogun_NDHS_2013.dta&#39;<br>Ogun_ndhs2013=pd.read_stata(path)</pre><pre>Variables_needed=[&#39;v313&#39;,&#39;v025&#39;, &#39;v012&#39;, &#39;v013&#39;, &#39;v203&#39;, &#39;v205&#39;, &#39;v218&#39;, &#39;v106&#39;, &#39;v190&#39;] # These are the only variables needed</pre><pre>Ogun_ndhs2013=Ogun_ndhs2013[Variables_needed]</pre><pre>import numpy as np<br>from scipy import stats<br>from scipy.stats import kendalltau</pre><p>Take out v012 and v218 from the Ogun NDHS 2013 data as series</p><pre>Age_X=Ogun_ndhs2013[&#39;v012&#39;]<br>No_Living_Chid_Y=Ogun_ndhs2013[&#39;v218&#39;]</pre><p>Compute the Kendall Tau correlation statistic and its associated p_value</p><pre>stats.kendalltau(Age_X, No_Living_Chid_Y)</pre><pre>tau, p_value = kendalltau(Age_X, No_Living_Chid_Y)<br>tau, p_value</pre><p>The Kendall Tau correlation statistic value is 0.57, and p_value=0.00000. Since p_value&lt;0.05; There exists a significant relationship between the age of respondents and the number of living children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZfaa7tqe6WpQtPxLS-qXw.png" /></figure><p>The Jupyter notebook used for this analysis is available<strong> </strong><a href="https://github.com/ayobamiakiode/My-projects/blob/master/Bivariate%20Statistical%20Methods%20Analysis%20%20in%20Python%20.ipynb"><strong>here</strong></a></p><h4>Key take-aways:</h4><ol><li>Carrying out bivariate visualization as the only way to confirm a relationship exists between two features, is statistically not enough.</li><li>Using a bivariate statistical test address the possibility that the relationship shown by the visualization happens by chance.</li><li>The type of bivariate statistical test depends on the type of the target and predictor features (categorical, numerical), the sample size, and the parametric nature (parametric, non-parametric) of the features.</li><li>For a statistical test between a predictor and target feature where the p_values is less than or equal to 0.05 (p_value≤0.05), then the predictor feature can be included in the modeling, else (p_value&gt;0.05), the predictor feature should not be included in the modeling of the target feature.</li><li>The central limit theorem supports using a parametric method for features that have a sample size ≥ of 30.</li></ol><p><strong>Now that’s it. </strong>Hope you find this useful? Please drop your comments and follow me on LinkedIn at <a href="https://www.linkedin.com/in/ayobami-akiode-38528839/">Ayobami Akiode LinkedIn</a></p><p><strong>References</strong></p><p><a href="https://www.real-statistics.com/">https://www.real-statistics.com</a></p><ul><li><a href="https://statistics.laerd.com/features-tests.php">Features - A list of our statistical guides | Laerd Statistics</a></li><li><a href="https://www.statisticshowto.com/">Statistics How To: Elementary Statistics for the rest of us!</a></li><li><a href="https://docs.scipy.org/">Numpy and Scipy Documentation - Numpy and Scipy documentation</a></li><li><a href="https://scikit-learn.org/">scikit-learn</a></li><li><a href="https://www.youtube.com/stikpet">stikpet</a></li><li><a href="https://www.wikipedia.org/">Wikipedia, the free encyclopedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc8238b896c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/visualization-only-not-enough-how-to-carry-out-bivariate-statistical-test-in-python-fc8238b896c">Visualization Only! Not Enough. How to Carry Out Bivariate Statistical Test in Python</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>