<?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 Aryo Atha Rizaldi on Medium]]></title>
        <description><![CDATA[Stories by Aryo Atha Rizaldi on Medium]]></description>
        <link>https://medium.com/@aryoatha?source=rss-423aa313321------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*i98L1Uvf0T5UUkx3</url>
            <title>Stories by Aryo Atha Rizaldi on Medium</title>
            <link>https://medium.com/@aryoatha?source=rss-423aa313321------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:46:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aryoatha/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[I Built an AI System That Resolves Jira Tickets Automatically — And It Won 1st Place]]></title>
            <link>https://medium.com/@aryoatha/i-built-an-ai-system-that-resolves-jira-tickets-automatically-and-it-won-1st-place-1c6d43d6ff11?source=rss-423aa313321------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c6d43d6ff11</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[n8n]]></category>
            <dc:creator><![CDATA[Aryo Atha Rizaldi]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 06:10:00 GMT</pubDate>
            <atom:updated>2026-03-02T06:10:00.776Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>I Built an Agentic AI System That Resolves Jira Tickets Automatically — And It Won 1st Place</strong></h3><p><em>How a stray idea and a friend’s frustration built a multi-agent pipeline that cut ticket resolution time by 90%</em></p><p>It started from two separate moments that somehow pointed to the same idea.</p><p>The first was a casual conversation. A friend, <strong>Andri</strong>,<strong> </strong>came to me one day with a question out of nowhere: <em>”What if there was a ticket resolution system that was fully end-to-end and agentic AI?”</em> No context, no build-up. Just an idea, thrown into the air.</p><p>I didn’t have an answer then. But the question stuck.</p><p>The second moment came at the office. A different friend, different day — I happened to overhear him venting about his Jira backlog. In a single day, he’d get hit with a flood of tickets. And it wasn’t just the volume that drained him. It was the repetition. The same kinds of issues, the same manual back-and-forth, the same human errors creeping in when he was tired. One ticket would take hours. By the time he finished, three more had appeared.</p><p>Two moments. Two different places. One was a question without an answer. The other was a problem without a solution. But together, they pointed to the same thing:</p><p><em>What if the repetitive parts didn’t have to be done by a human at all?</em></p><p>That question led me down a two-month rabbit hole — solo, on my personal laptop, running AI models locally — that eventually became <strong>an end-to-end agentic AI pipeline for automated Jira ticket resolution</strong>. A system that could read a ticket, analyze the problem, write a technical spec, generate code, review it, loop until it’s good enough, and only then hand it off to a human for final approval.</p><p>And earlier this year, that project won <strong>1st Place at iFuntastic 2025</strong>— an internal competition across all of Astra Graphia Information Technology (AGIT) — in the <strong>Suggestion System (SS)</strong> category.</p><p>This is the story of how it was built, what broke along the way, and what it taught me about building AI systems that actually work.</p><h3><strong>The Problem With Manual Ticket Resolution</strong></h3><p>Before I built anything, I mapped out what the existing process actually looked like.</p><p>An engineer receives a Jira ticket. They read it, try to understand the problem, figure out a root cause, write a solution, code it, review it, test it, and push it. Simple on paper. But in reality:</p><ol><li><strong>1 to 2 full days</strong> per ticket (around 18 calendar hours)</li><li><strong>25% rework rate</strong> — meaning one in four tickets had to be revisited</li><li><strong>No standard format</strong> for how solutions were documented</li><li><strong>Sprint backlog growing 10–15% </strong>during high-load periods,</li><li>And completely <strong>human-dependent</strong> at every single step</li></ol><p>The problem wasn’t just speed. It was the structural fragility of a process that breaks down the moment your engineers are overloaded. There was no consistency, no telemetry, no way to know how long things actually took or why they failed.</p><p>I didn’t want to just build something faster. I wanted to build something <em>structurally better</em>.</p><h3><strong>The Architecture: A Software Team Made of AI Agents</strong></h3><p>The core idea was role simulation. Instead of one AI doing everything, I designed a system where each agent plays a specific role — just like a real software team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*havgNOzzST_l2cqkmaMsyw.png" /></figure><p>Every model runs locally via <strong>Ollama</strong>. The whole pipeline is orchestrated through <strong>n8n</strong>, containerized with <strong>Docker</strong>, and integrated with both the <strong>Jira API </strong>and <strong>Telegram Bot API</strong>. No cloud LLM. No vendor lock-in. No ongoing API cost. Everything self-hosted.</p><p>The reason I split the models wasn’t arbitrary. These are two very different types of cognitive work.</p><p><strong>Qwen 2.5 7B</strong> excels at structured reasoning and producing clean, consistent output — which is exactly what you need for analysis and specification work. It’s lighter on resources too, which mattered given my hardware constraints.</p><p><strong>CodeLlama 13B Instruct</strong> is purpose-built for code. It was trained specifically on programming tasks and instruction-following in a coding context, which makes it more stable and accurate for both generating implementations and evaluating them.</p><p><strong>Model-role alignment matters.</strong> One model trying to do everything — read requirements, write specs, generate code, and review it — tends to do none of those things particularly well. Splitting by role mirrors how real software teams work: different people with different strengths, each owning their part of the process.</p><h3><strong>How the Pipeline Actually Works</strong></h3><p>Here’s the full flow, from trigger to resolution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*XIbF5C07wp6BD8t7HkCX7Q.png" /><figcaption>The full pipeline in n8n — every node, every handoff, every decision point. What looks intimidating is really just four agents passing work to each other, the same way a team would.</figcaption></figure><ol><li><strong>Jira Trigger</strong>— A ticket comes in and kicks off the pipeline.</li><li><strong>AI Reader</strong>— Parses the ticket. Identifies the issue, root cause, constraints, required components, ambiguities, assumptions, and edge cases. Outputs strict JSON. No markdown, no freeform text — just a clean, parseable schema.</li><li><strong>AI Technical Writer</strong>— Takes the Reader’s output and converts it into a full technical blueprint: architecture decisions, file structure, API contracts, database schema, validation rules, test cases, error handling strategy, security considerations. Also strict JSON.</li><li><strong>AI Coder — </strong>Works from the blueprint. Generates a complete implementation — not just snippets, but helper functions, config setup, error handling, validation, test logic, and deployment notes.</li><li><strong>AI Reviewer — </strong>Compares the implementation against the original spec. Checks for completeness, logic correctness, security handling, and alignment with the design. Produces qualitative feedback and a confidence-based score. Returns either <strong>APPROVED</strong> or <strong>REJECTED</strong>.</li><li><strong>Self-Correcting Loop</strong> — If rejected, the feedback goes back to the AI Coder. It revises. Goes back to the Reviewer. Loops until approved. There’s an important safeguard here: the loop is capped at <strong>3 iterations</strong>. If the AI Reviewer rejects the output three times in a row, the system stops, escalates to a human engineer, and flags that the ticket requires human intervention. Without this cap, a tricky ticket could have the pipeline spinning indefinitely — burning compute and going nowhere. Three strikes and it asks for help. That’s not a failure mode; that’s good system design.</li><li><strong>Human Validation via Telegram</strong> — Once the AI Reviewer approves, a structured message hits Telegram. The human engineer sees the ticket info, problem analysis, generated fix, changes made, AI review result, and confidence level. They click <strong>APPROVED</strong> or <strong>DECLINED. </strong>Here’s what that message actually looks like:</li></ol><pre>🤖 AI Code Fix Ready for Review<br><br>━━━━━━━━━━━━━━━━━━━━━<br>📋 TICKET INFORMATION<br>━━━━━━━━━━━━━━━━━━━━━<br><br>Ticket: AJ-9<br>Summary: Bug: Missing closing parenthesis in app.js<br>Priority: Highest<br><br>━━━━━━━━━━━━━━━━━━━━━<br>🔍 PROBLEM ANALYSIS<br>━━━━━━━━━━━━━━━━━━━━━<br><br>Issue: A SyntaxError is thrown because of a missing closing parenthesis in the JavaScript code within the startApp function.<br><br>Root Cause: A SyntaxError is thrown because of a missing closing parenthesis in the JavaScript code within the startApp function.<br><br>━━━━━━━━━━━━━━━━━━━━━<br>✨ AI GENERATED FIX<br>━━━━━━━━━━━━━━━━━━━━━<br><br>Fixed Code:<br>function startApp() { console.log(&#39;App started&#39;); }<br><br><br>Changes Made:<br>1. Fixed missing closing parenthesis<br><br>Explanation: The root cause was a missing closing parenthesis in the console.log statement, which caused a SyntaxError to be thrown. To fix this, I simply added the missing closing parenthesis and the code now runs without errors.<br><br>━━━━━━━━━━━━━━━━━━━━━<br>✅ AI REVIEW RESULT<br>━━━━━━━━━━━━━━━━━━━━━<br><br>Status: ✅ APPROVED<br>Assessment: Fix correctly adds the missing closing parenthesis<br>Confidence: HIGH%<br><br>━━━━━━━━━━━━━━━━━━━━━<br>⏰ WAITING FOR YOUR DECISION<br>━━━━━━━━━━━━━━━━━━━━━<br><br>Please reply with one of these:<br>• APPROVED - to resolve this ticket<br>• DECLINED - to reject this fix<br><br>This message was sent automatically with n8n</pre><p><strong>8. Jira Resolved</strong> — If approved, the ticket gets closed out automatically on Jira.</p><h3><strong>The Struggles Nobody Talks About</strong></h3><p>Building this was not clean. Let me be honest about what actually broke.</p><ol><li><strong>Getting the Agents to “Behave”</strong></li></ol><p>Prompt engineering for agentic systems is a different beast. Each agent needed to be constrained enough to produce consistent, structured output — but not so rigid that it would fail on edge cases or unusual ticket formats.</p><p>There’s a sweet spot. Too strict, and the agent breaks or halts on anything unexpected. Too loose, and it starts hallucinating, going off-script, or producing output that’s technically text but structurally useless.</p><p>Finding that balance per agent, per model, took a significant chunk of those two months. It’s less about clever prompting and more about understanding how each model interprets instructions under pressure.</p><p><strong>2. JSON Was a Constant Battle</strong></p><p>The entire pipeline depends on structured JSON passing between agents. Which sounds clean in theory. In practice, models — especially running locally on constrained hardware — would produce JSON that was <em>almost</em> valid. Missing brackets. Stray newlines. Markdown code fences wrapping the output. Escaped characters in the wrong places.</p><p>I had to build a dedicated JSON cleanup and validation layer just to make the pipeline reliable. This isn’t glamorous work, but it’s what separates a demo from a system that actually runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gS1dkgIDKMp323pEKkgJ_w.jpeg" /><figcaption>Example of what prompt engineering for agentic systems actually looks like — every variable, every instruction, every edge case accounted for.</figcaption></figure><p><strong>3. Running on a Personal Laptop</strong></p><p>I’ll say it plainly: I built this on my own personal laptop. Not a workstation, not a cloud GPU instance — a regular laptop. That meant I was limited to models that could run locally without melting the hardware.</p><p>Qwen 2.5 7B and CodeLlama 13B Instruct were what I could realistically run. And they worked. But I’ll be equally plain about this: if this pipeline were running on something like Claude or GPT-4, the output quality would be significantly higher. The architecture is sound — the ceiling is in the model, not the design.</p><p>The hardware constraint was frustrating. But it also forced me to build something that works within real-world limits, not just ideal conditions.</p><h3><strong>The Results</strong></h3><p>After running benchmark simulations against the previous manual process, the numbers were stark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*9UrMZo2ePhYHUZuMMzpWpw.png" /></figure><p>That’s roughly:</p><p><strong>~90% reduction in time per ticket</strong></p><p><strong>−84% rework</strong></p><p><strong>~3× sprint throughput</strong></p><p><strong>−80% manual effort</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l69QAmOja7WScAk2yamI0g.png" /><figcaption>This is what the pipeline looks like under the hood — every agent timed, every handoff logged. No black boxes.</figcaption></figure><p>Target KPIs I set going in were: ticket duration ≤ 2 hours, rework ≤ 5%, and workflow success rate ≥ 95%. The system hit all of them.</p><h3><strong>What Happened at iFuntastic 2025</strong></h3><p>When I presented this at iFuntastic — AGIT’s internal innovation competition spanning the entire organization — I felt ready. I knew the system well, I’d lived with it for two months, and I believed in what it could do.</p><p>What I wasn’t prepared for was how the room reacted.</p><p>The judges noted that mine was the only project in the competition that <em>genuinely</em> leveraged AI — not as a feature, not as a layer on top of something else, but as the core mechanism. They said it aligned directly with AGIT’s forward-looking vision for AI adoption across the organization.</p><p>And then came something I genuinely didn’t see coming: the pipeline was proposed for real deployment. There are internal projects at AGIT handling enormous ticket volumes daily, and the judges saw this as a direct solution.</p><p>Winning 1st place in the Suggestion System category felt good. Knowing the work might actually get used — that felt better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0Bjh-H3STXbG8QjBjOnuA.jpeg" /><figcaption>I never really thought about what winning would look like. I was too busy trying to make the thing work. And then this happened.</figcaption></figure><h3><strong>What This Is Really About</strong></h3><p>I keep thinking back to those two moments.</p><p>Andri, casually throwing out a question like it was nothing. A friend at the office, exhausted by a backlog that never seemed to shrink. Neither of them knew they were describing the same problem from different angles — one from curiosity, one from frustration.</p><p>Two months later, I had a pipeline that could take a Jira ticket, analyze it, write a spec, generate code, review it, and escalate to a human only when it truly needed to. Not because I was trying to build something impressive. But because the problem was real, the frustration was real, and it felt wrong that the solution didn’t exist yet.</p><p>The architecture — multi-agent orchestration, role specialization, self-correcting loops, human-in-the-loop governance — is reusable beyond Jira. The same pattern applies to DevOps, data pipelines, ETL workflows. But that’s secondary.</p><p>What matters more to me is simpler: somewhere out there, an engineer won’t have to spend two days on a ticket that a well-designed system could handle in two hours. They’ll get that time back. They can use it for work that actually needs a human.</p><p>That’s what this was always about.</p><h3><strong>Tech Stack Summary</strong></h3><ul><li><strong>Orchestration:</strong> n8n</li><li><strong>Runtime:</strong> Docker</li><li><strong>LLM Runtime:</strong> Ollama (local)</li><li><strong>Models: </strong>Qwen 2.5 7B, CodeLlama 13B Instruct</li><li><strong>Integrations:</strong> Jira API, Telegram Bot API</li><li><strong>Monitoring: </strong>n8n telemetry nodes, Grafana</li></ul><p><em>Built solo over 2 months. Deployed locally. Won 1st place at iFuntastic 2025, Suggestion System category — Astra Graphia Information Technology.</em></p><blockquote><em>I’m Atha, a Data Analyst at AGIT who apparently also builds agentic AI pipelines in my spare time. If you’re building agentic AI systems or thinking about internal automation, I’d love to connect.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c6d43d6ff11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Banking Strategies: Unleashing the Power of Predictive Modeling for Deposit…]]></title>
            <link>https://python.plainenglish.io/revolutionizing-banking-strategies-unleashing-the-power-of-predictive-modeling-for-deposit-bc2c7a3d64be?source=rss-423aa313321------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc2c7a3d64be</guid>
            <category><![CDATA[machine-learning-python]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[banking-technology]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aryo Atha Rizaldi]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 08:35:43 GMT</pubDate>
            <atom:updated>2023-12-06T01:49:41.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revolutionizing Banking Strategies: Unleashing the Power of Predictive Modeling for Deposit Acquisition (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*mJ6RywFIqRHo3oQX19FyGA.jpeg" /><figcaption>Image by <a href="https://www.appletechsoft.com/how-ai-machine-learning-are-transforming-the-banking-industry/">Appletechsoft</a></figcaption></figure><p>In the fast-paced world of banking, where every moment and resource counts, the effectiveness of marketing campaigns can make a pivotal difference. Imagine being able to predict with high accuracy which potential customers are likely to invest in fixed-term deposits. This foresight could revolutionize how a bank allocates its resources, ensuring that valuable time and finances are invested where they truly matter.</p><p><strong>Decoding the Challenge</strong></p><p>Our journey begins with a critical challenge faced by the marketing, sales, and customer service teams in the banking sector. The process of reaching out to customers for fixed-term deposit campaigns involves significant time and financial investment. <strong>Without a pre-screening mechanism, there’s a risk of squandering resources by approaching customers indiscriminately. </strong>Enter <strong>Machine Learning, a game-changer in optimizing this process.</strong></p><p><strong>Machine Learning offers the ability to analyze and model complex patterns in historical data</strong>, unveiling the most influential factors in a potential customer’s decision-making. This approach empowers the bank to <strong>enhance marketing campaign efficiency, optimize resource utilization, and precisely target candidates with the highest likelihood of investing in fixed-term deposits.</strong> The aim is clear: to sift through potential customers diligently, targeting those with the highest potential and optimizing both time and cost.</p><p><strong>Goals of the Game</strong></p><p>The bank aspires to develop predictive capabilities to forecast whether a prospective customer is willing to deposit funds. The <strong>objective is to precisely target marketing campaigns towards candidates with the highest potential to invest in fixed-term deposits.</strong> With the assistance of Machine Learning, the bank aims to improve the efficiency and effectiveness of its marketing strategies, focusing efforts on customer segments most likely to respond positively to fixed-term deposit offers. This approach not only saves resources but also prevents the need to contact every potential customer, reducing material and time losses.</p><p><strong>The Analytical Approach</strong></p><p>Our plan involves a deep dive into the data, aiming to identify patterns that differentiate between potential customers willing to deposit and those who are not. We will construct a classification model, a predictive tool for the bank, estimating the probability that a prospective customer will or will not deposit.</p><p>The analytical approach includes comprehensive data exploration to uncover relationships and trends among related variables. Feature selection and data adjustments will follow to prepare them as inputs for the classification model. The goal is to <strong>enhance prediction accuracy and identify key factors influencing customer decisions.</strong></p><p>For building the classification model, appropriate Machine Learning techniques such as Logistic Regression or Decision Trees and so on, will be employed. The model will undergo testing and evaluation using unseen holdout data to ensure reliability and good performance in predicting customer behavior.</p><p><strong>Metric Evaluation: Balancing Act</strong></p><p>In this journey, we will be mindful of two types of errors:</p><p>- <strong>False Positive (Type 1 error):</strong> Predicting a customer can deposit, but they don’t.<br> — Consequence: Wasting campaign time and costs on customers with deposit potential.</p><p>- <strong>False Negative (Type 2 error):</strong> Predicting a customer can’t deposit, but they actually have the potential. <br> — Consequence: Losing potential customer candidates.</p><p>Below is the estimated cost that the bank will incur for each false positive and false negative:</p><ul><li><strong>False Positive</strong><br>The cost incurred by the bank for each false positive is the campaign cost spent on that customer. This campaign cost includes labor, media, and other expenses. According to McKinsey &amp; Company’s research, the marketing campaign cost for banking products in Indonesia is estimated to be Rp500,000 per customer. Therefore, the cost incurred by the bank for each false positive is Rp500,000.</li><li><strong>False Negative</strong><br>The cost incurred by the bank for each false negative is the potential income lost from that customer. This potential income could be in the form of the customer’s deposit. According to OJK Indonesia, the minimum bank deposit is Rp8,000,000. Hence, the potential income lost from each false negative is Rp8,000,000 per customer.</li><li><strong>Comparison with Loss of Potential Customer Candidates<br></strong>Losing potential customer candidates can negatively impact the bank’s long-term revenue. This is because the bank will miss the opportunity to offer its products and services to these customers. Based on the research conducted by Frederick F. Reichheld &amp; W. Earl Sasser, Jr., a bank losing one customer could potentially lose up to Rp50 million per year.</li></ul><p>If we calculate False Positives without machine learning and without the possibility of losing customers (because all customers are contacted):</p><blockquote><em>Assuming the cost incurred is in line with the statement above, which is Rp500,000 per customer. <br>The number of customers (total test and holdout data without prior filtering): 2813 customers. <br>If without filtering, the bank will contact all customers without consideration/guidance, the bank will incur a cost of: <br>2813 customers x Rp500,000/customer = ± Rp1,406,500,000 (± 1.4 billion) without any certainty that these customers will make a deposit.</em></blockquote><p>This doesn’t make sense to proceed with because, in rough terms, the bank would have to spend approximately <strong>1.4 billion IDR</strong> just for the campaign, and this cost doesn’t justify the potential income from these customers. It would also consume a significant amount of time to contact all these customers without filtering. Therefore, considering the consequences, the primary focus is to develop this model to <strong>reduce False Negatives</strong> and <strong>increase False Positives</strong>, as the bank would experience a <strong>greater loss if it misses potential customer candidates</strong> compared to the cost of the campaign and time spent. The main goal is to increase <strong>Recall</strong>, maximizing the identification of actual potential customers willing to make a deposit, even with an acceptable increase in false positives. This approach aims to achieve an optimal balance between campaign cost efficiency and the retention of sought-after customer potential.</p><p><strong>Embarking on the Data Journey</strong></p><p>The dataset presents a <strong>balance between the number of customers depositing and not depositing.</strong> Most features in the dataset are categorical, either nominal or ordinal, with some exhibiting high cardinality. Each entry reflects information about a customer who has made a deposit withdrawal in the preceding period.</p><p>In the forthcoming articles, we will unravel the layers of data exploration, feature engineering, and model development. Our goal is not just to build a predictive model but to empower the bank with actionable insights, fostering a data-driven approach to marketing campaigns. Join us on this journey as we harness the potential of Machine Learning to transform banking campaigns into strategic and targeted endeavors.</p><p>Before we dove into the nitty-gritty, lets get familiar first with our dataset:</p><p><strong>Customer profile</strong></p><ul><li><strong>age: </strong>Customer’s age</li><li><strong>job: </strong>Customer’s job</li><li><strong>balance:</strong> Customer’s bank balance</li><li><strong>housing:</strong> Customer’s housing loan</li><li><strong>loan:</strong> Customer’s other loans</li></ul><p><strong>Marketing data</strong></p><ul><li><strong>contact:</strong> Contact communication type.</li><li><strong>month:</strong> Last contact month of the year.</li><li><strong>campaign:</strong> Number of contacts performed during this campaign and for this client.</li><li><strong>pdays:</strong> Number of days after the client was contacted from the previous campaign.</li><li><strong>poutcome: </strong>Outcome of the previous marketing campaign.</li><li><strong>deposit:</strong> Whether the customer deposits or not.</li></ul><p>Before we dive into the exciting parts, let’s import the libraries that we’re going to use</p><pre># Data Manipulation<br>import pandas as pd<br>import numpy as np<br><br># Model Preprocessing<br>from sklearn.compose import ColumnTransformer<br>from sklearn.preprocessing import OneHotEncoder<br>import category_encoders as ce<br>from category_encoders import OrdinalEncoder<br><br># Model Selection<br>from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold<br><br># Pipeline<br>from sklearn.pipeline import Pipeline<br><br># Model<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.svm import SVC<br><br># Ensemble<br>from sklearn.ensemble import StackingClassifier, VotingClassifier, RandomForestClassifier, BaggingClassifier<br>from sklearn.ensemble import GradientBoostingClassifier, AdaBoostClassifier<br>from xgboost.sklearn import XGBClassifier<br>from lightgbm.sklearn import LGBMClassifier<br><br># Metric<br>from sklearn.metrics import classification_report, make_scorer, recall_score, precision_score<br><br># Data Vizualisation<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p>And then the dataset</p><pre>df = pd.read_csv(&#39;data_bank_marketing_campaign.csv&#39;)</pre><h3><strong>Data Cleaning</strong></h3><p>We’re on a quest to unravel the dataset mysteries first. Our toolkit includes checking data types, counting unique values, and deciphering the unique values’ secret codes.</p><pre>pd.set_option(&#39;display.max_colwidth&#39;, None)<br><br>uniqueItem = []<br>for column in df.columns:<br>    uniqueItem.append([column, df[column].nunique(), df[column].unique(), df[column].dtype])<br><br>unique = pd.DataFrame(columns=[&#39;Column&#39;, &#39;Unique Count&#39;, &#39;Unique Value&#39;, &#39;Data Type&#39;], data=uniqueItem)<br>unique</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFJ6tT4Xl1-MS6OHBOt0lw.png" /><figcaption>Picture 1: Data unique count, unique values and datatype</figcaption></figure><p>After taking a peek at the results, it turns out our data types are on point — no need for a makeover there! Now, let’s embark on a thrilling adventure to uncover the mysterious realm of Missing Values.</p><pre>df.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*6Yj6vCyqKgmxKRj1Idsy3w.png" /><figcaption>Picture 2: Missing values</figcaption></figure><p>phew *Thank god there’s no missing values in our dataset. Let’s now move into the more tricky part, checking for duplicate values</p><pre>df[df.duplicated(keep=False)].sort_values(by=[&#39;job&#39;, &#39;balance&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*p3BwB-HIB9GjaILE_7E47Q.png" /><figcaption>Picture 3: Duplicate values</figcaption></figure><p>Uh-Oh! Turns out, there’s a doppelgangers in our dataset! But fear not, because duplicate data in the dataset is none of our concern and doesn’t need any special attention. This is because the columns in the dataset <strong>allow for entries that are similar or the same,</strong> without having unique identifiers like a National Identity Card number. This is totally normal and doesn’t require any fancy tricks to fix the duplicate data.</p><p>After that, we’ll check for outliers in our dataset</p><pre># # Checking every numerical columns using IQR<br><br>def checkOutlier(df):<br>    Q1 = df.quantile(0.25)<br>    Q3 = df.quantile(0.75)<br>    IQR = Q3 - Q1<br>    return (df &lt; (Q1 - 1.5 * IQR)) | (df &gt; (Q3 + 1.5 * IQR))<br><br>dataChecking = checkOutlier(<br>                        df[[&#39;age&#39;, &#39;balance&#39;, &#39;campaign&#39;, &#39;pdays&#39;]]<br>)<br><br>dataOutlier = pd.DataFrame(dataChecking[dataChecking.any(axis=1)])<br><br><br><br>dataOutlier[&#39;outlierColumn&#39;] = dataChecking[dataChecking.any(axis=1)].apply(lambda x: &#39;,&#39;.join(x.index[x]), axis=1)<br><br># Used looping to show how many outliers are there<br><br>for col in dataOutlier.columns:<br>    if col != &#39;outlierColumn&#39;:<br>        print(f&quot;Outlier Count of {col} column : {len(dataOutlier[dataOutlier[col] == True])}({len(dataOutlier[dataOutlier[col] == True])/len(df)*100:.1f}%)&quot;)<br><br>plt.figure(figsize=(15, 10))<br><br>plt.subplot(2, 2, 1)<br>box_plot1 = sns.boxplot(data=df[&#39;age&#39;])<br>box_plot1.set_title(&#39;Age Outliers&#39;)<br>plt.grid()<br><br>plt.subplot(2, 2, 2)<br>box_plot2 = sns.boxplot(data=df[&#39;balance&#39;])<br>box_plot2.set_title(&#39;Balance Outliers&#39;)<br>plt.grid()<br><br>plt.subplot(2, 2, 3)<br>box_plot3 = sns.boxplot(data=df[&#39;campaign&#39;])<br>box_plot3.set_title(&#39;Campaign Outliers&#39;)<br>plt.grid()<br><br>plt.subplot(2, 2, 4)<br>box_plot4 = sns.boxplot(data=df[&#39;pdays&#39;])<br>box_plot4.set_title(&#39;Pdays Outliers&#39;)<br>plt.grid()<br><br>plt.suptitle(&#39;Outliers Count&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*mTiwM427Sr2WgTCwBI9RhA.png" /><figcaption>Picture 4: Outliers count</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SGApTSLTOfPo3N3nCBF7Tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zTezevATNwaG-RTrWflI2Q.png" /><figcaption>Fig 1: Outliers boxplot</figcaption></figure><p>So like we always know, outliers are like weird data points that don’t fit in with the rest of the crowd. They can happen for all sorts of reasons, like mistakes when measuring stuff, rare events, or just plain weirdness.</p><p>In this case, we found some outliers in the numbers part of the dataset. But I decided not to mess with them. There are a few reasons for this:</p><ul><li>Outliers might actually be real. For example, a big balance in a bank account might not be an outlier if the person really has a lot of money.</li><li>Outliers might show how people behave differently sometimes. If we don’t know enough about the business or the data, getting rid of outliers might mean losing important information.</li><li>No outliers at all can make models act weird, especially if they show something important about how people behave. If we take them out, the models might not work as well.</li></ul><p>In these cases, <strong>getting rid of outliers might mean losing important information about customers or products.</strong> So, instead of messing with these outliers, I decided to leave them alone. This way, we keep all the information we have and don’t risk messing anything up.</p><p>Okay after we get acquainted and checked our dataset, and we feel happy about it, let’s dive into the more exciting part, <strong>Data Preprocessing</strong> and <strong>Feature Engineering.</strong></p><h3>Data Preprocessing and Feature Engineering</h3><p>Before we start processing our data, let’s check if our dataset is balanced or not.</p><pre>plt.title(&quot;Targets (deposit) Count&quot;, size=18, weight=&#39;bold&#39;)<br>sns.countplot(x=df[&#39;deposit&#39;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*AkZzCIyWYJ2FKcLk9qUIkg.png" /><figcaption>Fig 2: Barplot between Yes and No in target columns</figcaption></figure><pre>plt.figure(figsize=(7,7))<br>plt.title(&quot;Target (deposit) Proportion on Dataset&quot;, size=18, weight=&#39;bold&#39;)<br>plt.pie(df[&#39;deposit&#39;].value_counts(), explode=(0,0.1), labels=[&#39;No&#39;, &#39;Yes&#39;], colors=[&quot;orange&quot;,&quot;green&quot;], autopct=&#39;%1.1f%%&#39;, shadow=True, <br>        startangle=90, textprops={&quot;fontsize&quot;:20})<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*ihGDVdXUyN3NJuNo2NgfVQ.png" /><figcaption>Fig 3: Proportion of Yes and No in target column</figcaption></figure><p>The “deposit” column is considered <strong>balanced</strong> because the difference between the proportions of “Yes” and “No” is only about <strong>4.4%</strong>. That’s pretty small, so the column is considered balanced based on a general rule of thumb that you can check <a href="https://datascience.stackexchange.com/questions/122571/determining-whether-a-dataset-is-imbalanced-or-not"><strong>here!</strong></a></p><h4>Splitting the Data</h4><p>Let’s split the data into two parts. First, we’ll set aside 20% of the data as a holdout dataset. We’ll split this holdout dataset into two parts: one with all the columns except deposit, and one with only the deposit column. This is to make sure the model doesn’t learn about the target variable from the test data. We’ll use the holdout dataset to see how well the model performs.</p><p>Second, we’ll split the rest of the data into two parts: one with all the columns except deposit, and one with only the deposit column. Then, we’ll split these two parts into four parts: x_train, x_test, y_train, and y_test. We’ll use x_train and y_train to train the model, and x_test and y_test to see how well the model performs.</p><pre># Making holdout from 20% of the dataset<br>holdout = df.sample(frac=0.2, random_state=2)<br><br># Drop holdout sample from dataset<br>df.drop(holdout.index, inplace=True)<br><br># Membagi holdout menjadi feature dan target<br>holdout_feature = holdout.drop(columns=[&#39;deposit&#39;])<br>holdout_target = np.where(holdout[&#39;deposit&#39;] == &#39;yes&#39;, 1, 0)</pre><pre># Splitting dataset that&#39;s left into feature and target<br>feature = df.drop(columns=[&#39;deposit&#39;])<br>target = np.where(df[&#39;deposit&#39;] == &#39;yes&#39;, 1, 0)<br><br># Splitting feature and target into training and testing sets<br>x_train, x_test, y_train, y_test = train_test_split(feature, target, test_size=0.2, random_state=2, stratify=target)# Membagi dataframe yang tersisa menjadi feature dan target<br>feature = df.drop(columns=[&#39;deposit&#39;])<br>target = np.where(df[&#39;deposit&#39;] == &#39;yes&#39;, 1, 0)<br><br># Splitting feature and target into training dan testing sets<br>x_train, x_test, y_train, y_test = train_test_split(feature, target, test_size=0.2, random_state=2, stratify=target)</pre><p>After splitting the data, we’ll give it a makeover (feature engineering) so the machine can understand it better. This will help the machine make more accurate predictions.</p><h4>Feature Engineering</h4><p>Alright, let’s encode the categorical features in the dataset. We’re gonna do the following:</p><ol><li>Use One Hot Encoding for the job, housing, loan, contact, and poutcome columns, because these features don&#39;t have an order and have a small number of unique values.</li><li>Use Ordinal Encoding for the month column, because this feature has an order.</li></ol><p>We’re not gonna do any feature engineering for the balance and campaign columns for the following reasons:</p><ol><li>The balance column already provides clear information about the customer’s balance, so we don’t need to manipulate it. Leaving it unchanged makes it easier to understand and ensures that the actual balance information is not lost.</li><li>The campaign column provides direct information about the number of contacts made during the marketing campaign. Manipulating this feature can reduce clarity about how often the campaign was conducted, which can be important information.</li><li>Feature engineering can affect the performance of the model, especially if the changes are not in line with the natural nature of the data.</li></ol><pre># Mapping for month column<br>ordinal_mapping = [<br>    {&#39;col&#39;:&#39;month&#39;,<br>    &#39;mapping&#39;:{<br>        &#39;jan&#39;       :    1,<br>        &#39;feb&#39;       :    2, <br>        &#39;mar&#39;       :    3, <br>        &#39;apr&#39;       :    4, <br>        &#39;may&#39;       :    5, <br>        &#39;jun&#39;       :    6,<br>        &#39;jul&#39;       :    7,<br>        &#39;aug&#39;       :    8,<br>        &#39;sep&#39;       :    9, <br>        &#39;oct&#39;       :    10, <br>        &#39;nov&#39;       :    11, <br>        &#39;dec&#39;       :    12,<br>    }}<br>]</pre><pre>transformer = ColumnTransformer([<br>    (&#39;onehot&#39;, OneHotEncoder(drop = &#39;first&#39;), [&#39;job&#39;, &#39;housing&#39;, &#39;loan&#39;, &#39;contact&#39;, &#39;poutcome&#39;]),<br>    (&#39;ordinal&#39;, ce.OrdinalEncoder(mapping = ordinal_mapping), [&#39;month&#39;])<br>], remainder = &#39;passthrough&#39;)</pre><pre># Fitting x_train<br>transformer.fit(x_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*n5J_kZg91vfS9EafhvoGPg.png" /><figcaption>Picture 5: ColumnTransformer result</figcaption></figure><p>As we conclude this chapter of exploration and understanding, I’m thrilled by the anticipation of what lies ahead. If you’ve enjoyed the journey so far, the real excitement awaits you in part 2.</p><p>A heartfelt thank you for joining us on this insightful journey in Part 1! Join me in unraveling the intricacies of Machine Learning, where we’ll delve into the nuances of model benchmarking and the art of crafting the model itself. So, without further ado, let’s turn the page and venture into the heart of the machine learning journey in part 2. Your data adventure in part 2, continues <a href="https://medium.com/@aryoatha/revolutionizing-banking-strategies-unleashing-the-power-of-predictive-modeling-for-deposit-700d033d8574"><strong>here!</strong></a></p><p><strong>Sources</strong>:</p><ul><li>McKinsey &amp; Company, <a href="https://www.mckinsey.com/capabilities/quantumblack/our-insights/the-data-driven-enterprise-of-2025">The Data-Driven Organization: How Analytics and Machine Learning Are Transforming Business</a></li><li>OJK Indonesia, <a href="https://sikapiuangmu.ojk.go.id/FrontEnd/CMS/Article/252">Berinvestasi Melalui Deposito</a></li><li>Frederick F. Reichheld and W. Earl Sasser, Jr., <a href="https://hbr.org/1990/09/zero-defections-quality-comes-to-services">The Cost of Losing a Customer</a></li></ul><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc2c7a3d64be" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/revolutionizing-banking-strategies-unleashing-the-power-of-predictive-modeling-for-deposit-bc2c7a3d64be">Revolutionizing Banking Strategies: Unleashing the Power of Predictive Modeling for Deposit…</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Banking Strategies: Unleashing the Power of Predictive Modeling for Deposit…]]></title>
            <link>https://python.plainenglish.io/revolutionizing-banking-strategies-unleashing-the-power-of-predictive-modeling-for-deposit-700d033d8574?source=rss-423aa313321------2</link>
            <guid isPermaLink="false">https://medium.com/p/700d033d8574</guid>
            <category><![CDATA[banking-technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-tools]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Aryo Atha Rizaldi]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 08:34:21 GMT</pubDate>
            <atom:updated>2023-12-06T01:49:27.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revolutionizing Banking Strategies: Unleashing the Power of Predictive Modeling for Deposit Acquisition (Part 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*mJ6RywFIqRHo3oQX19FyGA.jpeg" /><figcaption>Image by <a href="https://www.appletechsoft.com/how-ai-machine-learning-are-transforming-the-banking-industry/">Appletechsoft</a></figcaption></figure><p>A warm welcome and heartfelt gratitude to all readers who have journeyed through Part 1 of my story! Your enthusiasm is truly appreciated. Now, I sense your eagerness to dive into the next chapter, so let’s cut to the chase and explore the exciting world of Machine Learning together!</p><h3>Model Benchmarking</h3><p>Since our dataset is <strong>balanced</strong>, we don’t need to do any balancing. Here, I’ll use the models and ensemble models that I’ve learned about before to compare them and see which one works best.</p><pre>models = None<br>knn = KNeighborsClassifier()<br>logreg = LogisticRegression(random_state = 2)<br>dt = DecisionTreeClassifier(random_state = 2)<br>svm = SVC(random_state = 2)<br>xgb = XGBClassifier(random_state=2)<br>ada = AdaBoostClassifier(random_state=2)<br>gds = GradientBoostingClassifier(random_state=2)<br>lgbm = LGBMClassifier(random_state=2)<br>stacking = StackingClassifier(estimators=models)<br>bagging = BaggingClassifier(random_state=2)<br>voting = VotingClassifier(estimators=models)<br>rf = RandomForestClassifier(random_state=2)</pre><pre>model = None<br>pipe = Pipeline([<br>    (&#39;prepocessing&#39;, transformer),<br>    (&#39;clf&#39;, model)<br>])</pre><pre>model_search = {<br>    &#39;clf&#39; : [knn, logreg, dt, svm, xgb, ada, gds, lgbm, stacking, bagging, voting, rf]<br>} <br>grid_search = GridSearchCV(<br>    estimator = pipe,<br>    param_grid = model_search,<br>    scoring = &#39;recall&#39;, # because my evaluation metric is recall score, so im going to focus only on recall score<br>    verbose=1, <br>    return_train_score=True,<br>    cv = StratifiedKFold(shuffle=True, random_state=2),<br>    n_jobs=-1<br>)<br>grid_search.fit(x_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*WpkwZsj4PeOFLivP3dHhBA.png" /><figcaption>Picture 6: Model benchmarking</figcaption></figure><p>Now let’s check the result after benchmarking</p><pre>before_tuning = pd.DataFrame(grid_search.cv_results_).sort_values(&#39;mean_test_score&#39;, ascending=False).head(3)<br>before_tuning[[&#39;param_clf&#39;, &#39;mean_test_score&#39;, &#39;mean_train_score&#39;, &#39;std_test_score&#39;, &#39;std_train_score&#39;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nDNmK695zhNSLrrxO2CLA.png" /><figcaption>Picture 7: Model benchmarking results</figcaption></figure><p>The top three best models with the highest mean_test_score recall are:</p><ul><li>RandomForestClassifier: <strong>0.633586</strong></li><li>LogisticRegression: <strong>0.630666</strong></li><li>XGB: <strong>0.621502</strong></li></ul><p>Of the three best models with the highest mean_test_score recall, Random Forest Classifier has the highest recall score of <strong>0.633586</strong>. However, Logistic Regression is the second-best model with a recall score of <strong>0.630666</strong>, only about <strong>0.00292</strong> or less than 1% off the best model score.</p><p>When compared to Random Forest, <strong>Logistic Regression shows consistent results between mean test and train scores. </strong>With a mean test score of <strong>0.630666</strong> and a mean train score of <strong>0.630576</strong>, the difference is relatively small. This suggests that the Logistic Regression model is not <strong>prone to overfitting.</strong> In addition, although the std score of Logistic Regression is higher than Random Forest, Logistic Regression is still a good choice because it does not experience overfitting.</p><p>In addition, based on the book <strong>The Elements of Statistical Learning</strong> by Hastie, T., Tibshirani, R., &amp; Friedman, J. (2009), it states that</p><blockquote>“Logistic regression is a very general and powerful model for binary classification. It is relatively easy to understand and interpret, and it can be extended to handle a wide variety of problems.”</blockquote><p>The book also states that Logistic Regression has several advantages, such as:</p><ul><li>Can handle binary classification problems with high accuracy</li><li>Can handle categorical features well</li><li>Can be implemented efficiently</li></ul><p>Based on the above quote and considerations, I decided to use Logistic Regression as my main model, which I will do <strong>hyperparameter tuning</strong> on.</p><h3>Logistic Regression Hyperparameter Tuning</h3><p>First, let’s check logistic regression parameters using get_params</p><pre># Getting Logistic Regression parameters<br>logreg_params = logreg.get_params()<br><br># Print the parameters<br>for param, value in logreg_params.items():<br>    print(f&quot;{param}: {value}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*TnhZnv0UhaictmXlkxUo8g.png" /><figcaption>Picture 8: Logistic Regression default parameters</figcaption></figure><p>Based on my considerations with the help of the documentation of Logistic Regression which can be found <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html"><strong>here</strong></a>, I decided to tune the parameters only on:</p><ol><li><strong>C</strong>: This parameter controls the strength of regularization in the model. The smaller the C value, the less regularization is applied to the model.</li><li><strong>penalty</strong>: Determines the type of regularization to be used. ‘l1’ uses L1 regularization (Lasso), while ‘l2’ uses L2 regularization (Ridge), and ‘elasticnet’ uses both regularization.</li><li><strong>solver</strong>: The solver that is used in solving the optimization problem that arises in logistic regression. ‘liblinear’ is used for small datasets, while ‘sag’ and ‘saga’ are suitable for large datasets.</li><li><strong>max_iter</strong>: The maximum number of iterations that the solver will perform to find a solution. The number of iterations is necessary for the model to converge to an optimal solution.</li><li><strong>dual</strong>: Determines whether the primal or dual formulation of the optimization problem will be used. If ‘dual’ is set to True, the solver will solve the dual problem.</li></ol><p>I decided to tune these parameters because they are the most important ones that can affect the performance of the model.</p><p>I will use a GridSearch to tune these parameters. I will use a range of values for each parameter and evaluate the performance of the model on the holdout dataset.</p><p>First we will make a pipeline that contains ColumnTransformer and the model that we’re going to use, Logistic Regression.</p><pre>pipe_logreg = Pipeline([<br>    (&#39;Preprocessing&#39;, transformer),<br>    (&#39;model&#39;, logreg)<br>])</pre><p>Now, we’re going to make a parameter space that contain values that i want to try.</p><pre># Making object for parameter search<br>parameter_space = {<br>    &#39;model__C&#39; : [0.01, 0.1, 1, 10, 100],<br>    &#39;model__penalty&#39; : [&#39;l1&#39;, &#39;l2&#39;, &#39;elasticnet&#39;],<br>    &#39;model__solver&#39; : [&#39;liblinear&#39;, &#39;sag&#39;, &#39;saga&#39;],<br>    &#39;model__max_iter&#39; :[10, 100],<br>    &#39;model__dual&#39; :[True, False],<br>    }</pre><p>Making GridSearch object to perform iteration based on parameter space above.</p><pre># Making GridSearch object<br>gridsearch_logreg = GridSearchCV(<br>    estimator=pipe_logreg,<br>    param_grid=parameter_space,<br>    scoring=&#39;recall&#39;,<br>    cv=StratifiedKFold(shuffle=True, random_state=2), # KFold -&gt; n_split default = 5<br>    verbose=1,<br>    return_train_score=True<br>)<br>gridsearch_logreg.fit(x_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*uuS-5l59RywuoYqhi8QuUQ.png" /><figcaption>Picture 9: Hyperparameter Tuning</figcaption></figure><p>Now let’s check the <strong>Hyperparameter Tuning </strong>score</p><pre>print(&#39;Best Parameter: &#39;, gridsearch_logreg.best_params_)<br>print(&#39;Best Score: &#39;, gridsearch_logreg.best_score_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkMc134nGnVPIsd4mg_DYw.png" /><figcaption>Picture 10: Hyperparameter tuning result</figcaption></figure><p>Based on the results of the hyperparameter tuning above, we got the best parameters:</p><p>{‘model__C’: 0.01, ‘model__dual’: False, ‘model__max_iter’: 10, ‘model__penalty’: ‘l1’, ‘model__solver’: ‘saga’}</p><p>with the best score: <strong>0.910799</strong></p><p>Those parameters seem pretty good. The mean train score of <strong>0.912776</strong> suggests that the model is <strong>not overfitting</strong>, and the small std test and train scores suggest that the model is <strong>balanced and consistent</strong>.</p><p>Here’s the comparison between before and after tuning the model</p><pre>pd.DataFrame(before_tuning.iloc[1][[&#39;param_clf&#39;, &#39;mean_test_score&#39;, &#39;mean_train_score&#39;, &#39;std_test_score&#39;, &#39;std_train_score&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*CA3OLH2OX13K4OACirO_xw.png" /><figcaption>Picture 11: Logistic Regression score before tuning</figcaption></figure><pre>pd.DataFrame(after_tuning.iloc[0][[&#39;params&#39;,&#39;mean_test_score&#39;, &#39;mean_train_score&#39;, &#39;std_test_score&#39;, &#39;std_train_score&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*kjlO0ihFomEGpEs-3_D8dg.png" /><figcaption>Picture 12: Logistic Regression score after tuning</figcaption></figure><p>Before the model was tuned, the recall score of the model was <strong>0.630666</strong> on test and <strong>0.630576</strong> on train with std test score <strong>0.01745</strong> and std train score <strong>0.018881</strong>. This suggests that the model has a small tendency to overfit and still has a slightly lower level of stability and consistency when compared to the three models above.</p><p>After tuning, the model’s recall score increased significantly to <strong>0.910799</strong> on test and <strong>0.912776</strong> on train. Additionally, the std test score decreased significantly to <strong>0.008749</strong> and std train score to <strong>0.005947</strong>. These improvements indicate that the model is now less prone to overfitting and has a higher level of stability and consistency.</p><p>The improved <strong>recall score </strong>suggests that the model is now better at identifying customers who will deposit. The lower std test and train scores indicate that the model is more stable and consistent in its predictions.</p><p>In conclusion, the model after hyperparameter tuning is significantly better than before. The model is now more accurate at predicting whether a customer will deposit and is less prone to overfitting.</p><p>Next, we’ll use those parameters to predict on the test and holdout data to see how well the model performs.</p><h3>Predicting</h3><h4>Predicting x_test</h4><p>Now, we’re going to try predicting x_test using our model with the best parameter from our <strong>Hyperparameter Tuning</strong> result above</p><pre>pipepredict_logreg = Pipeline([<br>    (&#39;prepocessing&#39;, transformer),<br>    (&#39;model&#39;, LogisticRegression(C= 0.01, dual= False, max_iter= 10, penalty=&#39;l2&#39;, solver=&#39;saga&#39;))<br>])</pre><pre>pipepredict_logreg.fit(x_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*EVuQYSKhbaZ1XjQiKY2iAA.png" /><figcaption>Picture 13: Pipeline for predicting x_test</figcaption></figure><pre>y_pred_logreg = pipepredict_logreg.predict(x_test)<br>print(classification_report(y_test, y_pred_logreg))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*1zGWe4SKYImGZ8nHV92tvg.png" /><figcaption>Picture 14: Classification report for x_test prediction</figcaption></figure><p>Based on the classification report above, the recall score for predicted class 1 is <strong>0.90</strong> and the recall score for predicted class 0 is <strong>0.22</strong>. This means that the model we are using is better at predicting class 1, than class 0.</p><h4>Predicting Holdout</h4><pre>y_pred_holdout = pipepredict_logreg.predict(holdout_feature)<br>print(classification_report(holdout_target, y_pred_holdout))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*UNvGZtIX5j47PSxssJqwtw.png" /><figcaption>Picture 15: Classification report for holdout prediction</figcaption></figure><p>Based on the classification report for the holdout data above, the recall score for predicting 1 is <strong>0.92</strong>, while the recall score for predicting 0 is <strong>0.20</strong>. This indicates that the model we are using is already quite <strong>generalized</strong> and <strong>robust</strong> to previously unseen data, as the difference in values between the test and holdout classification reports is not significant. Additionally, we have effectively anticipated and avoided undesirable outcomes, such as data leakage.</p><p>The model also tends to perform better in predicting the positive class than the negative class, aligning with the business task of increasing False Positives and decreasing False Negatives. Now, let’s examine the Confusion Matrix for easier interpretation.</p><h3>Confusion Matrix</h3><p>Confusion Matrix is a table that summarizes the performance of a classification model. It shows how many instances of each class were correctly classified and how many were misclassified.</p><pre>from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix<br><br>cm = confusion_matrix(y_test, y_pred_logreg)<br>cmd = ConfusionMatrixDisplay(cm)<br>cmd.plot()<br>plt.title(&#39;Test Confusion Matrix\n&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*rX2BB65YOp7lbD2mw6EsZg.png" /><figcaption>Fig 4: Test set confusion matrix</figcaption></figure><pre>cm = confusion_matrix(holdout_target, y_pred_holdout)<br>cmd = ConfusionMatrixDisplay(cm)<br>cmd.plot()<br>plt.title(&#39;Holdout Confusion Matrix\n&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*2R8cmwjudvkOgoXm0mvQ-Q.png" /><figcaption>Fig 5: Test set confusion matrix</figcaption></figure><p>Based on the results of the <strong>confusion matrix</strong> for the test and holdout data above, we can observe that the model has <strong>responded in line with the business objective</strong> and demonstrated better performance compared to the test, specifically in <strong>increasing</strong> the number of <strong>False Positives</strong>. In this context, the increase in False Positive is considered more <strong>advantageous</strong> because the impact of the losses incurred by the bank when contacting customers predicted to make a deposit but, in reality, do not deposit is <strong>relatively smaller than the risk of missed opportunities</strong> if the model produces <strong>False Negatives</strong>.</p><p>By increasing False Positive, the bank can <strong>optimize its marketing strategy</strong> by reaching out to more potential customers, even if some of them turn out not to make a deposit. Although this may result in some loss of time and cost, the potential gains from attracting more new customers who actually have the potential to make a deposit can <strong>compensate</strong> for it.</p><p>On the other hand, the <strong>main risk to be avoided is the occurrence of False Negatives</strong>, where the model predicts that a customer is not likely to make a deposit, but in reality, they have a significant potential. This can <strong>lead to a greater loss of opportunities, and customers who should have been offered a deposit might be overlooked.</strong></p><p>With this approach, the bank can be more <strong>aggressive in marketing and customer acquisition efforts</strong>, increasing the chances of attracting potential customers who genuinely intend to make a deposit. However, it’s essential to note that the increase in FP should be balanced with <strong>continuous evaluation to minimize negative impacts and ensure that the benefits of this strategy outweigh any potential losses.</strong></p><p>Okay, let’s look at the comparison of scores from the evaluation metrics that are most affected by high recall scores, precision.</p><pre>from sklearn import metrics<br>def print_evaluate(true, predicted):<br>    recall = metrics.recall_score(true, predicted)<br>    precision = metrics.precision_score(true, predicted)<br>    print(&#39;Precision:&#39;, precision)<br>    print(&#39;Recall:&#39;, recall)</pre><pre>print(&#39;Test set evaluation:\n_____________________________________&#39;)<br>print_evaluate(y_test, y_pred_logreg)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*OU_W2stvEHXlNBfLEqBvhA.png" /><figcaption>Picture 16: Test set evaluation</figcaption></figure><pre>print(&#39;Holdout set evaluation:\n_____________________________________&#39;)<br>print_evaluate(holdout_target, y_pred_holdout)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*6mJySpia1XlnCaCV75NO2Q.png" /><figcaption>Picture 17: Holdout set evaluation</figcaption></figure><p>Based on the results, we can see that a high recall score can lead to a low precision score. This is because the model is more likely to predict true positives, even if it also predicts some false positives.</p><p>In my case, I am okay with this trade-off because I am more concerned with <strong>avoiding false negatives.</strong> In my business task, it is more important to reach out to as many potential customers as possible, even if some of them turn out not to be interested.</p><p>The evaluation results also show that the model is <strong>generalizable and robust.</strong> This means that it is not too dependent on the specific characteristics of the training data and can perform well on new data. This is important because I will be using the model to make predictions about new customers.</p><h3>Feature Importance</h3><pre>feature_imp = pd.DataFrame()<br>feature_imp[&#39;feature&#39;] = gridsearch_logreg.best_estimator_.named_steps[&#39;Preprocessing&#39;].get_feature_names_out()<br>feature_imp[&#39;score&#39;] = gridsearch_logreg.best_estimator_.named_steps[&#39;model&#39;].coef_.reshape(-1, 1)<br>feature_imp = feature_imp.set_index(&#39;feature&#39;)<br>feature_imp.sort_values(&#39;score&#39;, ascending=True).tail(5).plot(kind=&#39;barh&#39;, figsize=(10, 7))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlUQFWgZ-kRTjAdRIqKJGQ.png" /><figcaption>Fig 6: Feature importance result</figcaption></figure><p>Based on the results, we can see that ‘p_days’, ‘balance’, and ‘p_outcome_success’ are the features that the model uses the most to make predictions. These features are likely to be important because they can reflect the following:</p><ul><li><strong>How recently the customer was contacted by the bank.</strong> If a customer has been contacted recently, they may be more likely to be interested in making a deposit.</li><li><strong>The customer’s financial situation.</strong> Customers with higher balances may be more likely to have the money to make a deposit.</li><li><strong>The customer’s history of responding to marketing campaigns.</strong> Customers who have responded positively to previous campaigns may be more likely to respond positively to future campaigns.</li></ul><p>It is also possible that these features interact with each other in a way that makes them even more important. For example, customers who have been contacted recently and have a high balance may be even more likely to make a deposit than customers who have only one of these factors.</p><p>Overall, these features are likely to be important for the bank because they can help the bank to identify customers who are most likely to make a deposit.</p><h3>SHAP Values</h3><pre>transformerSHAP = gridsearch_logreg.best_estimator_.named_steps[&#39;Preprocessing&#39;]<br>transformerSHAPNames = pd.Series(transformerSHAP.get_feature_names_out()).str.replace(pat=r&#39;[A-Za-z]*__&#39;, repl=&#39;&#39;, regex=True)<br>modelSHAP = gridsearch_logreg.best_estimator_.named_steps[&#39;model&#39;]</pre><pre>import shap<br>transformerSHAP.fit(x_train)<br>x_train_pp = transformerSHAP.transform(x_train)<br>x_train_pp = pd.DataFrame(x_train_pp, columns=transformerSHAP.get_feature_names_out())<br>x_test_pp = transformerSHAP.transform(x_test)<br>modelSHAP.fit(x_train_pp, y_train)<br>explainer = shap.LinearExplainer(<br>    modelSHAP, x_train_pp, feature_names=transformerSHAPNames<br>)<br>shap_values = explainer(x_test_pp)<br>shap.plots.beeswarm(shap_values)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngkCaBWvOR2nFU3Ct9ajVA.png" /><figcaption>Fig 7: SHAP Value</figcaption></figure><p>Based on the above SHAP Value results, <strong>balance and pdays</strong> are the features with the most significant impact on model predictions. A more detailed look at the SHAP value for the <strong>balance</strong> feature suggests that <strong>the higher the balance a customer has, the more likely they are to make a deposit.</strong> This aligns with the Feature Importance we created earlier, where balance is the second most contributing feature to the model’s predictions, meaning that the higher the balance, the more likely a customer is to make a deposit.</p><p>Additionally, <strong>pdays</strong> also has a significant impact on the model, indicating that the longer it has been since a customer was last contacted, the more likely they are to make a deposit. This is because<strong> customers who haven’t been contacted by the bank for a long time tend to be more open to new offers. </strong>This shows that my assumption about pdays, that the more frequent the customer is contacted, the higher the likelihood of a deposit, is not accurate. According to the SHAP Value above, the longer the time since a customer was last contacted by the bank, the higher the likelihood of that customer making a deposit.</p><h3>Conclusion and Recommendation</h3><h4>Analysis Conclusion</h4><p><strong>Without Machine Learning:</strong><br>Without Machine Learning, the bank might <strong>incur significant losses.</strong> Indiscriminately contacting all customers without filtering could result in substantial resource wastage, such as phone call costs, agent time, and untargeted promotions. Lack of intelligent predictions could lead to missed opportunities in attracting genuinely potential depositors, potentially resulting in losses ranging from thousands to millions of dollars, depending on the campaign scale and operational costs.</p><p><strong>With Machine Learning:</strong><br>Machine Learning enables the bank to <strong>optimize resources and marketing strategies.</strong> Although the model may generate some <strong>False Positives,</strong> the benefits of reaching actual potential customers can outweigh these losses. By contacting 2384 customers, approximately 50% of whom are predicted to deposit (based on the confusion matrix), the bank can save costs and still attract profitable customers.</p><p>Calculating the scenario, assuming a campaign cost of Rp. 500,000 per customer, and a minimum deposit of Rp. 8,000,000, the bank would spend Rp. 1.1 billion but gain Rp. 9.7 billion. The net profit for the bank would be Rp. 8.5 billion. In this scenario, investing in Machine Learning is deemed a valuable step, optimizing resource use and potentially avoiding significant losses compared to a less intelligent approach.</p><h4>Model Conclusion</h4><p>1. <strong>Model Choice:</strong><br> — <strong>Logistic Regression</strong> is selected as the <strong>main model</strong> due to its balanced performance and avoidance of overfitting.<br> — Despite <strong>Random Forest</strong> having the highest recall, <strong>Logistic Regression</strong> is chosen for its balanced class performance.</p><p>2. <strong>Model Evaluation:</strong><br> — The model excels in <strong>identifying positive cases (high recall for class 1).</strong><br> — Consistent performance between test and holdout data demonstrates good generalization and robustness.</p><p>3. <strong>Model Limitations and Recommendations:</strong><br> — The model’s strong bias towards predicting positive cases is a trade-off, leading to lower performance in predicting negative cases.<br> — Recommendation to improve class 0 recall or evaluate business strategies to <strong>address potential prediction errors in negative cases.</strong></p><p>4. <strong>Model Reliability:</strong><br> — The model is considered <strong>sufficiently general and robust</strong> for handling new or unseen data previously<br> — Overall, the model is <strong>reliable for predicting fixed-term deposits</strong> in the provided dataset.</p><p>5. <strong>Additional Considerations:</strong><br> — Further evaluation metrics like <strong>precision </strong>and<strong> f1-score</strong> may be considered based on specific business needs.<br> — Continuous model improvement or adjustment is advisable based on evolving data characteristics or business policy changes.</p><p>6. <strong>Feature Importance:</strong><br> — <strong>p_days</strong> is the most influential feature, reflecting the time since the last contact made by the bank to potential customers.</p><p>In conclusion, the adjusted <strong>Logistic Regression</strong> model performs well in predicting fixed-term deposits in the given dataset. Continuous evaluation and model adjustments are recommended for sustained optimal performance over time.</p><h4>Recommendations</h4><p><strong>For the Bank:</strong></p><p>1. <strong>Utilize Model Insights:</strong><br> — Use the Machine Learning model to target customers with deposit potential who haven’t received previous offers, enhancing the effectiveness of marketing efforts.</p><p>2. <strong>Strategic Targeting:</strong><br> — Target campaigns towards high-balance customers who haven’t been contacted recently, as they show a higher likelihood of making deposits.</p><p>3. <strong>Personalized Marketing:</strong><br> — Implement Machine Learning to create personalized marketing content based on individual customer profiles, increasing engagement.</p><p>4. <strong>Campaign Evaluation:</strong><br> — Employ Machine Learning to measure campaign effectiveness, allowing for continuous improvement in attracting fixed-term deposits.</p><h4>For Real-Life Implementation:</h4><p><strong>Improvements and Future Considerations:</strong></p><p>1. <strong>Threshold Adjustment:</strong><br> — Explore adjusting prediction thresholds for a balanced approach between precision and recall.</p><p>2. <strong>Model Ensemble:</strong><br> — Consider combining models, like Logistic Regression with Random Forest, to enhance overall performance.</p><p><strong>Data Enhancement:</strong></p><p>1. <strong>Feature Engineering:</strong><br> — Explore advanced feature engineering for deeper insights.</p><p>2. <strong>Outlier Handling:</strong><br> — Address or remove outliers in numerical features if identified.</p><h4>General Recommendations:</h4><p>1. <strong>Stakeholder Involvement:</strong> Engage marketing and business teams in interpreting model results.</p><p>2. <strong>Education for Stakeholders:</strong> Provide stakeholders with a clear understanding of the model’s strengths and limitations.</p><p>3. <strong>Continuous Monitoring:</strong> Implement continuous monitoring systems for ongoing performance and data changes.</p><h4>Conclusion:</h4><p>The current model is a good start, but there are some areas that could be improved to make it more effective in real-world applications. By following the recommendations above, you can make sure that the model is a valuable tool for your business.</p><p>Thank you for joining this journey into the realm of Machine Learning and predictive analytics for fixed-term deposit marketing. You can check my <a href="https://github.com/athwbx/Bank-Campaign-Machine-Learning-Prediction"><strong>GitHub</strong></a> to be fully immersed with my project.</p><p>The insights gained and recommendations provided are aimed at empowering the bank in making informed decisions and optimizing its outreach efforts.</p><p>In the dynamic landscape of banking and finance, leveraging data-driven approaches becomes pivotal. The possibilities are vast, and by embracing the power of Machine Learning, the bank stands poised to not only enhance its marketing strategies but also to navigate the ever-evolving landscape of customer engagement.</p><p>Your interest and engagement in this narrative are appreciated. Here’s to the exciting possibilities that lie ahead, where data meets strategy, and innovation fuels success. Until our next exploration, thank you for reading this story of predictive analytics and Machine Learning in the banking domain🍻</p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=700d033d8574" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/revolutionizing-banking-strategies-unleashing-the-power-of-predictive-modeling-for-deposit-700d033d8574">Revolutionizing Banking Strategies: Unleashing the Power of Predictive Modeling for Deposit…</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Examining Customer Behavior in Supermarket X: A Comprehensive Analysis (Part 1)]]></title>
            <link>https://python.plainenglish.io/examining-customer-behavior-in-supermarket-x-a-comprehensive-analysis-part-1-d2295e53b651?source=rss-423aa313321------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2295e53b651</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[marketing-strategies]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[tableau]]></category>
            <dc:creator><![CDATA[Aryo Atha Rizaldi]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 15:53:47 GMT</pubDate>
            <atom:updated>2023-11-20T04:57:05.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*iElGskZRwfKBw1R7MLX-Cw.jpeg" /><figcaption><a href="https://flashbak.com/pile-it-high-sell-it-low-the-saga-of-the-supermarket-406316/">Image by Flashbak</a></figcaption></figure><p>Hey there, folks! A little while back, I dove into the world of Supermarket Customer analysis. Today, I’m excited to take you through the nitty-gritty details, from tidying up the data to uncovering insights and wrapping it all up with some solid conclusions and recommendations.</p><p>But first, let’s understand about our main character: <strong>The Supermarket’s Dataset</strong>, affectionately known as Supermarket X. This treasure trove of information spills the beans on the customers of Supermarket X. We’re talking <strong>demographics</strong>, <strong>product purchases</strong>, the <strong>lowdown on promotions</strong>, and <strong>how the customers felt</strong> about them. Plus, we’ve got the details on <strong>buying behavior </strong>and the <strong>online antics</strong> of these shoppers on the supermarket’s website back in 2014.</p><p>On this part 1 of the story, i will be only covering the data understanding and the EDA. If you want to get straight to the analysis, you can go to part 2 <a href="https://medium.com/@aryoatha/examining-customer-behavior-in-supermarket-x-a-comprehensive-analysis-part-2-adf4f9c21fa5"><strong>here</strong></a>. Intrigued? Before we dive into the nitty-gritty stuff, let’s cozy up and get to know our dataset first, shall we?</p><p>Alright, let’s spill the tea on what this dataset vibrant cast of characters! Here’s the lowdown:</p><p><strong>People</strong>:<br>- ID: Unique ID for each customer.<br>- Year_Birth: The birth year of our customers.<br>- Education: How fancy their education level is.<br>- Marital_Status: Are they single or married?<br>- Income: The annual cash flow of their household<br>- Kidhome: Count of kids in the house.<br>- Teenhome: Number teens strutting around.<br>- Dt_Customer: The date they officially joined the Supermarket X fan club.<br>- Recency: Days since their last shopping spree.<br>- Complain: 1 if they voiced concerns in the last 2 years, 0 if they’re all good.</p><p><strong>Product</strong>:<br>- MntWines: Money spent on that classy grape nectar in the last 2 years.<br>- MntFruits: Cash splash on fruity delights in the past 2 years.<br>- MntMeatProducts: Bucks dropped on meaty treats in recent times.<br>- MntFishProducts: Funds dedicated to underwater delicacies.<br>- MntSweetProducts: Sweet tooth expenses over the last 2 years.<br>- MntGoldProds: Bling-bling budget for gold-themed goodies.</p><p><strong>Promotion</strong>:<br>- NumDealsPurchases: Count of discounted shopping sprees. AcceptedCmp1–5: Did they say “Count me in!”? (1 for yes, 0 for not this time).<br>- Response: 1 if they said “Yes, please!” to the last campaign, 0 if they were feeling a bit shy.</p><p><strong>Place</strong>:<br>- NumWebPurchases: Online shopping scorecard.<br>- NumCatalogPurchases: Old-school catalog shopping count.<br>- NumStorePurchases: Direct in-store purchase tally.<br>- NumWebVisitsMonth: Monthly website visit count.</p><p>And there you have it, the Supermarket X data universe decoded for your reading pleasure! 🛒✨</p><h3>Business Task</h3><h4><strong>Background Problem</strong></h4><p>So, Supermarket X had a bit of a hiccup in the past with campaigns that didn’t quite spark joy among its members. It could be the lack of oomph in the campaigns, a shortage of personal touches in the offers, or maybe just not fully understanding what the members fancy. But hey, the latest campaign did manage to bring in more customers! Still, the management is wise to the fact that they need to keep the momentum going by cooking up more <strong>engaging campaign strategies</strong> to keep their existing members excited. They’ve also noticed a dip in new member sign-ups, and they reckon a better understanding of their <strong>diverse customer</strong> base is the key. Supermarket X aims to spot groups of customers with similar vibes and craft super <strong>effective </strong>campaign strategies. This way, they’re gearing up to tackle any future drops in customer interest like pros!</p><h4>Main Challenge</h4><p>The management is on a quest to spice up their campaign game, aiming to prevent a drop in customer interest in joining the membership program. They’re not just looking for any solution; they want to make the campaigns <strong>more effective</strong> and <strong>tailored to customer preferences.</strong> The goal? Keep existing members happily swiping their cards and reel in new members who’ve been on the fence. It’s all about turning those transactions into a win-win dance of benefits and, of course, welcoming new faces into the membership! 🎉</p><h4>Problem Statement</h4><p>Let’s unveil the roadmap for our analysis:</p><ol><li>Unveil the mysteries of different market segments based on relevant categories<br>- Is there a relationship between Customer Recency and Shopping Interest?<br>- How does income influence the shopping patterns of supermarket customers?<br>- Can differences in educational backgrounds affect preferences and shopping interests?<br>- Is there a correlation between age and shopping preferences?<br>- Do married customers tend to make larger purchases compared to unmarried customers?<br>- Does having children influence shopping patterns among customers?</li></ol><p>2. Evaluating the Most Efficient Marketing Channels</p><p>3. Conclusions &amp; Marketing Strategies Recommendation</p><p>Before we dive into the exciting parts, let’s import the libraries that we’re going to use</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import missingno as msno<br>import  warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p>and then the dataset</p><pre>df = pd.read_csv(&#39;Supermarket_Customers.csv&#39;, sep=&#39;\t&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4Soc97UaKUP54EQT3gtOA.png" /><figcaption>Picture 1: The dataset head</figcaption></figure><p>Let’s check the dataset’s each columns, unique values, and data types</p><pre>pd.set_option(&#39;display.max_colwidth&#39;, None)<br><br>uniqueItem = []<br>for column in df.columns:<br>    uniqueItem.append([column, df[column].nunique(), df[column].unique(), df[column].dtype])<br><br>unique = pd.DataFrame(columns=[&#39;Column&#39;, &#39;Unique Count&#39;, <br>                              &#39;Unique Value&#39;, &#39;Data Type&#39;], data=uniqueItem)<br>unique</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rdkKDbHIk7kNLEuvVoCxsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-JYxhW-nmkxS4lxTAbw2rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMowkRr-q6XbfUuSpQjspA.png" /><figcaption>Picture 2–4: Column names, Unique Values and Data Types</figcaption></figure><h3>Data Cleaning</h3><h4>Standardizing the Data</h4><p>Because the column names in this dataset are kind of mixed up, I’ve decided to bring some order to the chaos. Time to standardize those column names using the <strong>camelCase</strong> method! 🐫</p><pre>df.rename(columns={&#39;Year_Birth&#39; : &#39;yearBirth&#39;, &#39;Marital_Status&#39; : &#39;maritalStatus&#39;, <br>                   &#39;Kidhome&#39; : &#39;kidHome&#39;, &#39;Teenhome&#39; : &#39;teenHome&#39;, <br>                   &#39;Dt_Customer&#39; : &#39;dtCustomer&#39;, &#39;MntWines&#39; : &#39;mntWines&#39;,<br>                   &#39;MntFruits&#39; : &#39;mntFruits&#39;,&#39;MntMeatProducts&#39; : &#39;mntMeatProducts&#39;, <br>                   &#39;MntFishProducts&#39; : &#39;mntFishProducts&#39;, &#39;MntSweetProducts&#39;: &#39;mntSweetProducts&#39;,<br>                   &#39;MntGoldProds&#39; : &#39;mntGoldProducts&#39;, &#39;NumDealsPurchases&#39; : &#39;numDealsPurchases&#39;, <br>                   &#39;NumWebPurchases&#39; : &#39;numWebPurchases&#39;, &#39;NumCatalogPurchases&#39; : &#39;numCatalogPurchases&#39;, <br>                   &#39;NumStorePurchases&#39; : &#39;numStorePurchases&#39;, &#39;NumWebVisitsMonth&#39; : &#39;numWebVisitsMonth&#39;,<br>                   &#39;AcceptedCmp3&#39; : &#39;acceptedCmp3&#39;, &#39;AcceptedCmp4&#39; : &#39;acceptedCmp4&#39;, <br>                   &#39;AcceptedCmp5&#39; : &#39;acceptedCmp5&#39;, &#39;AcceptedCmp1&#39; : &#39;acceptedCmp1&#39;,&#39;AcceptedCmp2&#39; : &#39;acceptedCmp2&#39;,<br>                   &#39;Z_CostContact&#39; : &#39;ZCostContact&#39;, &#39;Z_Revenue&#39; : &#39;ZRevenue&#39;}, inplace=True)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wKuzSeKnMG5hdTglZElxA.png" /><figcaption>Picture 5: Renamed Columns</figcaption></figure><h4>Changing data types</h4><p>So, our <strong>dtCustomer </strong>column is currently having a bit of an identity crisis — it thinks it’s an “Object.” Well, time to transform it into datetime!</p><pre>df[&#39;dtCustomer&#39;] = pd.to_datetime(df[&#39;dtCustomer&#39;], format=&#39;%d-%m-%Y&#39;)<br>df[&#39;yearBirth&#39;] = df[&#39;yearBirth&#39;].astype(&#39;int&#39;)<br>print(f&quot;The data type for dtCustomer: {df.dtCustomer.dtype}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*Yg9MtnxT_8M4xIxQWL86fw.png" /><figcaption>Picture 6: Data type of dtCustomer</figcaption></figure><h4>Replacing 2n Cycle to Master Degree</h4><p>We noticed some values like Master and 2n Cycle on the column. But according to the wise folks at Università di Bologna <a href="https://www.unibo.it/en/teaching/enrolment-transfer-and-final-examination/the-university-system/what-is-a-second-cycle-degree-programme">here</a>, it turns out 2n Cycle is just another way of saying Master Degree. Time for a transformation! I’m turning 2n Cycle into “Master”!</p><pre>df[&#39;Education&#39;] = df[&#39;Education&#39;].replace(&#39;2n Cycle&#39;,&#39;Master&#39;)<br>df[&#39;Education&#39;].unique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*VF6lVOdefrEyhwdl94y9iA.png" /><figcaption>Picture 7: Unique values of Education column</figcaption></figure><h4>Replacing and dropping irrelevant Marital Status</h4><p>In the <strong>maritalStatus </strong>column, we’ve got a lineup — Single, Together, Married, Divorced, Widow, Alone, Absurd, and YOLO. Here’s the catch: Together is the same as Married, Divorced doubles as Widow, and Alone takes the stage for Single.</p><p>Time for some relationship order! I’m standardizing these values for a smoother vibe. As for the irrelevant status, Absurd and YOLO, we’re going to drop them. Less than 1% of the data, and they’re not vibing with the rest. Adiós!</p><pre>df[&#39;maritalStatus&#39;] = df[&#39;maritalStatus&#39;].replace({&#39;Alone&#39; : &#39;Single&#39;, &#39;Together&#39; : &#39;Married&#39;, &#39;Widow&#39; : &#39;Divorced&#39;})<br>df = df[(df[&#39;maritalStatus&#39;] != &#39;Absurd&#39;) &amp; (df[&#39;maritalStatus&#39;] != &#39;YOLO&#39;)]<br>df[&#39;maritalStatus&#39;].unique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*pIwgWkMx-2H4ypZ5HtlIXg.png" /><figcaption>Picture 8: Unique values from maritalStatus column</figcaption></figure><h4>Adding Age column</h4><p>Introducing the <strong>Age </strong>column! We’re creating a brand new column, <strong>Age</strong>, by subtracting the birth years from the assumed data capture year, which is 2014. Time to unveil the ages!</p><pre>df[&#39;Age&#39;] = 2014 - df[&#39;yearBirth&#39;]<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*BX5DiCVRphsahSBgdu-_Lg.png" /><figcaption>Picture 9: Showing Age column</figcaption></figure><h4>Adding haveChild and childCount column</h4><p>Adding the columns based on the values in the <strong>kidHome </strong>and <strong>teenHome </strong>columns to streamline our analysis. The <strong>haveChild </strong>column is determined by checking if either <strong>kidHome</strong> or <strong>teenHome </strong>is not equal to 0, with the output being ‘Yes’ or ‘No’.</p><p>Meanwhile, the <strong>childCount </strong>column is derived by summing the values in the <strong>kidHome </strong>and <strong>teenHome </strong>columns.</p><pre>df[&#39;haveChild&#39;] = df.apply(lambda row: &#39;Yes&#39; if row[&#39;kidHome&#39;] != 0 or row[&#39;teenHome&#39;] != 0 else &#39;No&#39;, <br>                  axis=1)<br>df[&#39;childCount&#39;] = df[&#39;kidHome&#39;] + df[&#39;teenHome&#39;]<br>df.head()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*Vv1VIUAMkAtnKQyR-gCCAQ.png" /><figcaption>Picture 10: Showing haveChild and childCount column</figcaption></figure><h4>Handling Missing Values</h4><p>Time to investigate the dataset for any missing values. We’ve called in the missingno<strong> </strong>library to help us out!</p><p>Ready, set, let the missing values reveal themselves!</p><pre>msno.matrix(df);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6f9mqyBaoW3E_-eHnCakmw.png" /><figcaption>Picture 11: Checking for NaN values using missingno</figcaption></figure><p>Uh oh! Turns out there’s a missing values on the <strong>Income </strong>column! Let’s have a more detailed look</p><pre>df[df[&#39;Income&#39;] != df[&#39;Income&#39;].values]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueHG6CFjDeKtAlZFgtZaDA.png" /><figcaption>Picture 12: Detailed look on the missing values on Income column</figcaption></figure><p>As you can see, the <strong>Income </strong>column is in the spotlight, and we’re unleashing the magic of visualization to guess the missing digits based on <strong>Education Level</strong> and <strong>Marital Status</strong>. The theory? <strong>Education </strong>and <strong>marital status</strong> might hold the secret to predicting <strong>income</strong>. High education might mean high income, and marital status could play a role too, especially if it’s a joint income situation.</p><p>Before we dive deeper, let’s light up the scene with a heatmap. Why? To make sure our <strong>assumptions are on point</strong>. After this visual treat, we’ll decide whether to fill the gaps with the Mean or Median.</p><pre>heatmapData = df.groupby([&#39;Education&#39;, &#39;maritalStatus&#39;])[&#39;Income&#39;].median().unstack()<br><br>plt.figure(figsize=(12, 6))<br>sns.heatmap(heatmapData, annot=True, fmt=&#39;.0f&#39;, cmap=&#39;YlGnBu&#39;, cbar=True, linewidths=0.5)<br>plt.title(&#39;The Relationship Between Educational Background and Marital Status with Income\n&#39;, fontsize=13, fontweight=&#39;bold&#39;)<br>plt.xlabel(&#39;Marital Status&#39;, fontsize=11.5, fontweight=&#39;bold&#39;)<br>plt.ylabel(&#39;Educational Background&#39;, fontsize=11.5, fontweight=&#39;bold&#39;)<br>plt.xticks(fontsize=9.5)<br>plt.yticks(fontsize=9.5)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZClbfxXqSVC3VMudXUPZww.png" /><figcaption>Figure 1: Correlation between Educational Background and Marital Status with Income</figcaption></figure><p>Our heatmap unveils a <strong>strong bond between Education and Marital Status </strong>— except for “basic” Education category. But fear not! because the majority is in sync, and we’re using this combo to patch up the missing pieces in the <strong>Income </strong>column.</p><p>But, before we dive into the imputation, let’s check the <strong>income distribution </strong>first. We’re on a quest to decide whether to call in the Mean or the Median — for imputing those <strong>missing income</strong> values.</p><pre>sns.histplot(df, x=&#39;Income&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*WXp9uk1jJ8bRj_F62bbVuQ.png" /><figcaption>Figure 2: The data distribution of Income Column</figcaption></figure><p>Whoops! Turns out we found an outlier on <strong>Income </strong>columns. Let’s have a detailed look</p><pre>df.loc[df[&#39;Income&#39;] &gt; 150000, [&#39;Education&#39;, &#39;maritalStatus&#39;, &#39;Income&#39;]].sort_values(by=&#39;Income&#39;, ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*A5Rr_HFtzBSiaG7-YzT22w.png" /><figcaption>Picture 13: Alleged outliers</figcaption></figure><pre>round(df[&#39;Income&#39;].loc[df[&#39;Income&#39;] != 666666.0].mean())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*txaab1qegOiNtYqb8daK3A.png" /><figcaption>Picture 14: Mean for Income column without the outlier</figcaption></figure><p>The average income from the <strong>Income </strong>column (without the outlier) is <strong>$51,970</strong>. But, there’s a <strong>outlier </strong>lurking at <strong>$666,666</strong>! Time to bid that outlier farewell because we’re all about data harmony.</p><p>Now, here’s the plot twist: Incomes ranging from <strong>$162,397 to $153,924 get to stay</strong>. Why? Well, these high rollers seem legit based on their stellar Education and Marital Status. We’re letting them shine in the <strong>income</strong> column!</p><h4>Dropping Outlier on Income Column</h4><pre>df = df[df[&#39;Income&#39;] != 666666.0]<br>df[&#39;Income&#39;].sort_values(ascending=False).head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*P-UlVP540dtcgHorZ_DNEQ.png" /><figcaption>Picture 15: Income column after dropping outlier</figcaption></figure><p>After the outlier has been dropped, let’s see the data distribution on <strong>Income</strong> column</p><pre>sns.histplot(df, x=&#39;Income&#39;)<br>plt.title(&#39;Distribusi Data pada Kolom Income\n&#39;)<br>plt.tight_layout();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Hvzfk-QzVxhWH-shZEdtMA.png" /><figcaption>Figure 3: The data distribution of Income Column after dropping outlier</figcaption></figure><p>Let’s check if the column has a normal distribution or not using common tests used for data <strong>normality test</strong></p><pre>from scipy.stats import kstest<br><br># Using kstest to check if the data is normally distributed or not<br><br>stats, pvalue = kstest(&#39;norm&#39;, df[&#39;Income&#39;])<br>print(&#39;\nKolmogorov-Smirnov Test:&#39;)<br>print(f&#39;Statistic: {stats}&#39;)<br>print(f&#39;p-value: {pvalue}&#39;)<br>alpha = 0.05<br>if pvalue &gt; alpha:<br>    print(&#39;Sample Normal&#39;)<br>else:<br>    print(&#39;Sample Not Normal&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*ii8vx905xwwdZvsTuAkQ_A.png" /><figcaption>Picture 16: Result of Kolmogorov-Smirnov Test</figcaption></figure><p>Turns out the <strong>Income </strong>data <strong>is not normally distributed</strong>. No worries, though because our plan is to <strong>fill in those missing values </strong>in the <strong>Income </strong>column using the <strong>median</strong>. But here’s the kicker: we’re tailoring it with <strong>Education </strong>and <strong>MaritalStatus</strong>. Precision in every step for our data!</p><pre>df[df[&#39;Income&#39;].isna()][[&#39;ID&#39;,&#39;Education&#39;, &#39;maritalStatus&#39;, &#39;Income&#39;]].merge(df.groupby([&#39;Education&#39;, &#39;maritalStatus&#39;])[&#39;Income&#39;].median(), <br>                                                                      on=[&#39;Education&#39;, &#39;maritalStatus&#39;], suffixes=(&#39;_original&#39;, &#39;_median&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*C89hMyOwYNWhFamV20PiAg.png" /><figcaption>Picture 17: Median income based on Education and Marital Status</figcaption></figure><p>Okay let’s fill in the NaN values with the corresponding median values</p><pre>df[&#39;Income&#39;] = df[&#39;Income&#39;].fillna(df.groupby([&#39;Education&#39;, &#39;maritalStatus&#39;])[&#39;Income&#39;].transform(&#39;median&#39;))<br>msno.matrix(df);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALKXe14Id6Gjtj37Kf0gJg.png" /><figcaption>Picture 18: Checking the dataset after imputation</figcaption></figure><p>Time for a data health check! After our <strong>imputation </strong>mission, we’re peeking into the data distribution. Why? We want to make sure our <strong>imputation </strong>didn’t mess with the data and accidentally creating <strong>bias</strong>.</p><pre>sns.histplot(df, x=&#39;Income&#39;)<br>plt.title(&#39;Distribusi Data pada Kolom Income\n&#39;)<br>plt.tight_layout();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*jm9U4SBEXpZlAUZKlR2UeA.png" /><figcaption>Figure 4: The data distribution of Income Column after imputation</figcaption></figure><p>Behold the post-imputation visual feast! The data <strong>remains unchanged </strong>from the imputation. The <strong>Income </strong>column’s vibe is <strong>still on point!</strong><br>High-fives all around because those empty spots in Income got filled with some slick, appropriate values.</p><h4>Handling Duplicate Values</h4><p>Since our dataset is a vibrant mosaic of <strong>diverse customer traits</strong>, we’re going to be <strong>focusing on the IDs</strong> only to check for the duplicates on our dataset.</p><pre>df[&#39;ID&#39;].duplicated().sum()</pre><p>Since there’s no duplicate values on our dataset, let’s move onto the next phase, the more thrilling one, handling outliers!</p><h4>Handling Outliers</h4><p>Time to wrangle those outliers, but we’re narrowing the spotlight to these columns:</p><p>- yearBirth<br>- dtCustomer<br>- recency<br>- mntWines<br>- mntFruits<br>- mntMeatProducts<br>- mntFishProducts<br>- mntSweetProducts<br>- mntGoldProducts<br>- numDealsPurchases<br>- numWebPurchases<br>- numCatalogPurchases<br>- numStorePurchases<br>- numWebVisitsMonth</p><p>Because <strong>Income </strong>column got its outlier dropped already, so it’s sitting this one out. Let the outlier check commence!</p><pre># Checking for outliers on each columns using IQR<br><br>def checkOutlier(df):<br>    Q1 = df.quantile(0.25)<br>    Q3 = df.quantile(0.75)<br>    IQR = Q3 - Q1<br>    return (df &lt; (Q1 - 1.5 * IQR)) | (df &gt; (Q3 + 1.5 * IQR))<br><br>dataChecking = checkOutlier(<br>                        df[[&#39;yearBirth&#39;,&#39;Recency&#39;, &#39;mntWines&#39;, &#39;mntFruits&#39;,<br>                        &#39;mntMeatProducts&#39;, &#39;mntFishProducts&#39;, &#39;mntSweetProducts&#39;,<br>                        &#39;mntGoldProducts&#39;, &#39;numDealsPurchases&#39;, &#39;numWebPurchases&#39;,<br>                        &#39;numCatalogPurchases&#39;, &#39;numStorePurchases&#39;, &#39;numWebVisitsMonth&#39;]]<br>)<br><br>dataOutlier = pd.DataFrame(dataChecking[dataChecking.any(axis=1)])<br><br># Adding new column to show if there&#39;s any outlier <br><br>dataOutlier[&#39;outlierColumn&#39;] = dataChecking[dataChecking.any(axis=1)].apply(lambda x: &#39;,&#39;.join(x.index[x]), axis=1)<br><br># Using for loop to show how much outliers is inside the columns<br><br>for col in dataOutlier.columns:<br>    if col != &#39;outlierColumn&#39;:<br>        print(f&quot;Outlier Count of {col} column : {len(dataOutlier[dataOutlier[col] == True])}({len(dataOutlier[dataOutlier[col] == True])/len(df)*100:.1f}%)&quot;)<br><br><br>data_presentation = df[[&#39;yearBirth&#39;,&#39;Recency&#39;, &#39;mntWines&#39;, &#39;mntFruits&#39;,<br>                        &#39;mntMeatProducts&#39;, &#39;mntFishProducts&#39;, &#39;mntSweetProducts&#39;,<br>                        &#39;mntGoldProducts&#39;, &#39;numDealsPurchases&#39;, &#39;numWebPurchases&#39;,<br>                        &#39;numCatalogPurchases&#39;, &#39;numStorePurchases&#39;, &#39;numWebVisitsMonth&#39;]]<br><br>plt.figure(figsize=(15, 6))<br><br>plt.subplot(1, 3, 1)<br>box_plot2 = sns.boxplot(data=data_presentation[[&#39;yearBirth&#39;]])<br>box_plot2.set_xticklabels(box_plot2.get_xticklabels(), fontsize=8) <br>plt.grid()<br><br>plt.subplot(1, 3, 2)<br>box_plot3 = sns.boxplot(data=data_presentation[[&#39;mntWines&#39;, &#39;mntFruits&#39;,<br>                        &#39;mntMeatProducts&#39;, &#39;mntFishProducts&#39;, &#39;mntSweetProducts&#39;,<br>                        &#39;mntGoldProducts&#39;]])<br>box_plot3.set_xticklabels(box_plot3.get_xticklabels(), fontsize=7, rotation=45)<br>plt.grid()<br><br>plt.subplot(1, 3, 3)<br>box_plot4 = sns.boxplot(data=data_presentation[[&#39;numDealsPurchases&#39;, &#39;numWebPurchases&#39;,<br>                        &#39;numCatalogPurchases&#39;, &#39;numStorePurchases&#39;, &#39;numWebVisitsMonth&#39;]])<br>box_plot4.set_xticklabels(box_plot4.get_xticklabels(), fontsize=7, rotation=45)<br>plt.grid()<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*faRMgsTtANN11XruR_BT4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHNm4ODXb5W6tDGzTtSPXw.png" /><figcaption>Figure 5: Outliers depicted with boxplots</figcaption></figure><p>We’ve spotted a wild <strong>anomaly </strong>in the <strong>yearBirth </strong>column — customers claiming to be born before 1940. Let’s have a more detailed look</p><pre>yearBirthOutliers = df[df[&#39;yearBirth&#39;] &lt; 1940]<br>yearBirthOutliers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*7yXT7IYlRJHQODz6kG2ozg.png" /><figcaption>Picture 19: Customer’s with yearBirth below 1940</figcaption></figure><p>Now, let’s be real, these birthdates <strong>don’t quite sync</strong> up with the last data update in 2014. Time to bid farewell to the <strong>yearBirth </strong>oddities and <strong>drop the data entries </strong>from 1899–1900.</p><h4>Handling yearBirth Outliers</h4><pre># Dropping the outliers<br>df = df[df[&#39;yearBirth&#39;] &gt; 1940] <br><br># Checks if there&#39;s still customer&#39;s yearBirth below 1940<br>df[df[&#39;yearBirth&#39;] &lt; 1940]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*9GrTEESLX1u4gWnFMfaI5A.png" /><figcaption>Picture 20: Checks if there’s still customer with yearBirth below 1940</figcaption></figure><h4>Handling mnt Category and numPurchases Outliers</h4><p>The <strong>mnt </strong>categories and <strong>numPurchases </strong>columns have a lot of outliers, and we’re on a mission to decode the data mysteries. It’s time to unravel the quirks behind these rebellious data points!</p><pre># Checks if there&#39;s an outliers in each columns<br>def findNonOutlier(df, col):<br>    Q1 = df[col].quantile(0.25)<br>    Q3 = df[col].quantile(0.75)<br>    IQR = Q3 - Q1<br>    nonOutlier = df[(df[col] &gt;= (Q1 - 1.5 * IQR)) &amp; (df[col] &lt;= (Q3 + 1.5 * IQR))]<br>    return nonOutlier<br><br>wines = len(findNonOutlier(df, &#39;mntWines&#39;))<br>fruits = len(findNonOutlier(df, &#39;mntFruits&#39;))<br>meatproducts = len(findNonOutlier(df, &#39;mntMeatProducts&#39;))<br>fishproducts = len(findNonOutlier(df, &#39;mntFishProducts&#39;))<br>sweetproducts = len(findNonOutlier(df, &#39;mntSweetProducts&#39;))<br>goldproducts = len(findNonOutlier(df, &#39;mntGoldProducts&#39;))<br>webPurchases = len(findNonOutlier(df, &#39;numWebPurchases&#39;))<br>storePurchases = len(findNonOutlier(df, &#39;numStorePurchases&#39;))<br>catalogPurchases = len(findNonOutlier(df, &#39;numCatalogPurchases&#39;))<br><br>print(f&#39;Outliers count on Wines column: {len(df) - wines}&#39;)<br>print(f&#39;Outliers count on Fruits column: {len(df) - fruits}&#39;)<br>print(f&#39;Outliers count on Meat column: {len(df) - meatproducts}&#39;)<br>print(f&#39;Outliers count on Fish column: {len(df) - fishproducts}&#39;)<br>print(f&#39;Outliers count on Sweets column: {len(df) - sweetproducts}&#39;)<br>print(f&#39;Outliers count on Gold column: {len(df) - goldproducts}&#39;)<br>print(f&#39;Outliers count on Web Purchases column: {len(df) - webPurchases}&#39;)<br>print(f&#39;Outliers count on Store Purchases column: {len(df) - storePurchases}&#39;)<br>print(f&#39;Outliers count on Catalog Purchases column: {len(df) - catalogPurchases}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*MuPrjqszweg4MpLR-O5tcQ.png" /><figcaption>Picture 21: Outliers count for each column in <strong>mnt</strong></figcaption></figure><p>After second thought, i think it’s best to let the outliers in the <strong>mnt</strong> and <strong>numPurchases</strong> columns to stay. Why? Well, we believe these bold customers, defying the data norms, have some serious personal preference and strong reasons to spend on those specific product categories. With <strong>high incomes, fancy marital statuses, and top-notch education</strong>, they’ve got the financial firepower to back their unique shopping choices. Additionally, these outliers can provide insights into customer preferences, aiding in analysis and showcasing customer trends.</p><p>In this retail adventure, it’s all about <strong>individual preferences</strong> and pe<strong>rsonal reasons</strong>. As long as the customers are living their best financial lives and their <strong>incomes cover their spending</strong> spree, these outliers get the green light!</p><p>With no <strong>NaN values</strong>, no <strong>duplicate values</strong>, and the <strong>outliers </strong>are on their best behavior. It’s time to unleash this squeaky-clean data for some analysis using <strong>Tableau</strong>. Let the insights begin!</p><p>As we conclude this chapter of <strong>exploration</strong> and <strong>understanding</strong>, I’m thrilled by the anticipation of what lies ahead. If you’ve enjoyed the journey so far, the real excitement awaits you in part 2.</p><p>Join me in unraveling the <strong>analysis</strong>, where we’ll uncover <strong>meaningful patterns</strong> and <strong>insights</strong> from the data we’ve delved into. So, without further ado, let’s turn the page and venture into the heart of the <strong>analysis</strong> in part 2. Your data adventure in part 2, continues <a href="https://medium.com/@aryoatha/examining-customer-behavior-in-supermarket-x-a-comprehensive-analysis-part-2-adf4f9c21fa5"><strong>here</strong></a>!</p><blockquote>Feel free to explore the inner workings of the analysis by checking out my <a href="https://github.com/athwbx/Capstone_Project2-Supermarket_Analysis"><strong>GitHub repository</strong></a>. For a visual feast of interactive insights, take a stroll through the <a href="https://public.tableau.com/app/profile/aryo.atha.rizaldi/viz/ProjectCapstone2SupermarketXAnalysis/SupermarketStory"><strong>Tableau dashboards</strong></a>. Your curiosity is the key to unlocking the full depth of this data narrative.</blockquote><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2295e53b651" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/examining-customer-behavior-in-supermarket-x-a-comprehensive-analysis-part-1-d2295e53b651">Examining Customer Behavior in Supermarket X: A Comprehensive Analysis (Part 1)</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Examining Customer Behavior in Supermarket X: A Comprehensive Analysis (Part 2)]]></title>
            <link>https://python.plainenglish.io/examining-customer-behavior-in-supermarket-x-a-comprehensive-analysis-part-2-adf4f9c21fa5?source=rss-423aa313321------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf4f9c21fa5</guid>
            <category><![CDATA[marketing-strategies]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Aryo Atha Rizaldi]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 15:29:27 GMT</pubDate>
            <atom:updated>2023-11-20T04:57:10.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*iElGskZRwfKBw1R7MLX-Cw.jpeg" /><figcaption><a href="https://flashbak.com/pile-it-high-sell-it-low-the-saga-of-the-supermarket-406316/">Image by Flashbak</a></figcaption></figure><p>Welcome back, avid reader! If you’ve journeyed through the insights of part 1, your curiosity has led you here to the beginning of part 2. Get ready for a deeper dive into the <strong>analysis</strong>, as we’ll <strong>uncover hidden patterns </strong>and<strong> unravel intricate relationships.</strong> Join me as we <strong>unveil the secrets concealed</strong> within our data!</p><h3>1. Unveiling the mysteries of different market segments based on relevant categories</h3><h4>Customer Membership Growth Overtime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxOWIvpv3XBVLEd61CeGBA.png" /><figcaption>Figure 6: Customer Membership Growth</figcaption></figure><p>The visual journey unveils a sign-ups <strong>up and down</strong> at Supermarket X. <strong>August 2012</strong> takes the crown for the ultimate membership surge, <strong>welcoming 118 eager shoppers</strong> into the club. <strong>October 2013 and May 2014 follow suit with 117 and 112 registrations</strong>, respectively.</p><p>But wait, there’s a plot twist. <strong>December 2012</strong> took a dip from <strong>97 to 82 new members,</strong> <strong>defying the high season vibes</strong>. Fast forward to December the following year, and the drop continued, adding just 2 new members. <strong>June 2014</strong> witnessing a <strong>plunge from 112 to 74 new members.</strong></p><p>These membership dips makes me wonder. Why the dips in what should be high season months? Time for some market detective work to uncover the mysteries and find the right market moves to keep the membership magic alive!</p><h4>Segmentation for Last Campaign by Education Background, Customer Recency, Marital Status, Age Group, Income Group and Having Child</h4><p>Before we dive into the visualization of last campaign for each customer segmentation, first, we need to bin the <strong>Customer Recency, Age and Income </strong>column into groups so it’s easier to analyze.</p><pre>recencyBins = [0, 10, 25, 50, 75, 100]<br>recencyLabels = [&#39;Within 10 days&#39;, &#39;11-25 days&#39;, &#39;26-50 days&#39;, &#39;51-75 days&#39;, &#39;76-100 days&#39;]<br>df[&#39;recencyCategory&#39;] = pd.cut(df[&#39;Recency&#39;], bins=recencyBins, labels=recencyLabels, right=False)</pre><pre>ageBins = [20, 30, 40, 50, 60, 70, 100]<br>ageLabels = [&#39;20-29&#39;, &#39;30-39&#39;, &#39;40-49&#39;, &#39;50-59&#39;, &#39;60-69&#39;, &#39;70+&#39;]<br>df[&#39;ageGroup&#39;] = pd.cut(df[&#39;Age&#39;], bins=ageBins, labels=ageLabels, right=False)</pre><p>But, for the income category, since we’re going to group it to <strong>High or Low Income</strong> Customer, we need to know what divides them first. According to the <a href="https://aspe.hhs.gov/2014-poverty-guidelines">2014 U.S. Department of Health and Services data</a>, the <strong>low-income threshold</strong> is between <strong>$11,670 and $40,090</strong> per year.</p><p>Now, we’re going to check if the data is normally distributed, so then we can use the result to determine which are we going to use, the Mean or Median to be the threshold between Income Categories. Brace yourselves for the magic number, marking the boundary between the low-income crew and the high rollers!</p><pre># Checks if the income threshold is normally distributed or not</pre><pre>lowIncomeThreshold = [11670, 15730, 19790, 23850, 27910, 31970, 36030, 40090]<br>kstest(&#39;norm&#39;, lowIncomeThreshold)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*grCjsJdsWR03cmN81C8FnA.png" /><figcaption>Picture 22: Normality Test Result</figcaption></figure><p>It turns out, the data is not normally distributed. So we’re going to use the median value of the data to use it as the threshold between <strong>High and Low Income</strong> category</p><pre>medianLowIncome = np.median(lowIncomeThreshold)<br>df[&#39;incomeCategory&#39;] = pd.cut(df[&#39;Income&#39;], bins=[0, medianLowIncome, float(&#39;inf&#39;)], labels=[&#39;Low Income&#39;, &#39;High Income&#39;])</pre><p>It’s time to unveil the customer segmentation, starring those who either <strong>aced </strong>or <strong>fumbled </strong>the <strong>last campaign</strong>. Picture this: charts, graphs, and a plot of customer responses — some cheering, some not so much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOlAbG190PYJjxiZ6fzWWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wQx_dZdb6I4SxEx-iGI-g.png" /><figcaption>Figure 7: Each Segmentation Respond for Last Campaign</figcaption></figure><p>Let’s unwrap the visual insights:</p><ol><li><strong>Recency Group(Graph 1):</strong> The “Rarely” folks lead the response parade, with “Very Often” taking a chill in the backseat.</li><li><strong>Educational Background (Graph 2):</strong> Graduates steal the spotlight with the highest response in the last campaign, while the “Basic” crew gives it a bit of a pass.</li><li><strong>Age Group(Graph 3):</strong> The golden age group “40–49” shines as the top responders, while the “70+” squad keeps it low-key.</li><li><strong>Marital Status (Graph 4): </strong>Married life champions the response game, with “Single” status playing it cool.</li><li><strong>Income Group (Graph 5):</strong> High rollers in the “High Income” category steal the show, while “Low Income” response takes a modest bow.</li><li><strong>Parental Status (Graph 6):</strong> No-kid warriors take the lead in response, while parents take a step back.</li></ol><p>In a nutshell, <strong>education</strong>, <strong>recency</strong>, <strong>age</strong>, <strong>marital status</strong>, <strong>income</strong>, and <strong>parental status </strong>hold the keys to the <strong>last campaign’s responses</strong>. With this insights, the company can tweak their campaigns to hit the bullseye, targeting groups more likely to give them positive responses.</p><p>Now, let’s validate if this response-heavy segment is a <strong>true representation for all customers,</strong> and see if their shopping habits, including transaction frequency and amounts, reveal any intriguing tales!</p><h4>Is there a relationship between Customer Recency and Shopping Interest?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifhQGIq2EvanzQxNtuvb4w.png" /><figcaption>Figure 8: Shopping Interest on Customer Recency</figcaption></figure><p>Taking a peek at Supermarket X’s recency data:</p><p>1. <strong>Popular Period:</strong> The <strong>51–75 days</strong> is showing that most customers like to shop within this timeframe.</p><p>2. <strong>Noteworthy Ranges:</strong> The <strong>26–50 days</strong> is also throwing in a significant number, indicating a sweet spot for purchases.</p><p>3. <strong>Fast Shoppers: </strong>We’ve got a bunch (231 to be precise) who likes to make purchases within 10 days.</p><p>4. <strong>Purchasing Intervals: </strong>The <strong>76–100 days</strong> and <strong>11–25 days</strong> squads are hanging out with similar customer counts, hinting at longer purchase intervals.</p><p>5.<strong>Marketing Moments: </strong>Crafting specific strategies for each recency group could spice up customer engagement and loyalty.</p><p>In summary, understanding customer recency patterns helps the supermarket strategize marketing initiatives to tailor marketing moves for different shopper vibes.</p><h4>How does income influence the shopping patterns of supermarket customers?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6NGqnJ_v6noK0wBimIlO6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bzPDEbSS4-N2IYO0IOERxw.png" /><figcaption>Figure 9: Average Total Spending by Income Category</figcaption></figure><p>Breaking down the shopping scene:</p><p>1. <strong>Big Spenders:</strong> High income customers take the spotlight by spending on both expensive items and everyday goodies. Some are even outpacing the average shopping spree.</p><p>2. <strong>Low-Key Shoppers:</strong> Low income customers are in the mix too, doing some transactions, though not as hefty as the high income customers.</p><p>3. <strong>Buying Preferences:</strong> The high income customers leans towards indulging in wine and meaty delights. On the flip side, the low income customers is into budget-friendly choices like meat and a surprising amount of gold. Maybe gold holds a special place in their hearts or as a form of investment strategy?</p><p>In summary, the <strong>high income customers rules the purchase game</strong>, showcasing a diverse shopping appetite. This hints that income levels could play a role in market segmentation.</p><h4>Can differences in educational backgrounds affect preferences and shopping interests?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWyL2GJxQj-qbx13CbghXQ.png" /><figcaption>Figure 10: Customer Education Background Proportion</figcaption></figure><p>Based on the customer’s proportion for education background, <strong>Graduation </strong>steal the show! Here comes the real question. Are different education backgrounds vibing with high spending averages and spending in various categories?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*6l6jbXe-1PWjyZZOa4dkKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*dWGA2IhwPFa5Y4J4IvbxCA.png" /><figcaption>Figure 11: Average Total Spending by Education</figcaption></figure><p>Breaking down the education scene:</p><p>1. <strong>Average Spending Rundown:</strong> Those PhD are the big spenders, showing higher averages spending than their lower-educated counterparts.</p><p>2. <strong>Product Spending Peek:</strong> In the product preference spotlight, Wines and Meat Products is the favorite category for all education background, except for basic education, where they tend to spend on gold and fish, maybe viewing gold as an investment.</p><p>3. <strong>Spending Symphony:</strong> There’s a shopping rhythm among education groups for certain products. This could be used for targeted marketing strategies!</p><p>4. <strong>Elite Shoppers:</strong> The academically elite, with PhDs and Graduation degrees, tend spend higher than the averages. Unraveling their purchasing behaviors could refine marketing strategies.</p><p>So, does educational background influence on spending? It’s about income levels and lifestyle preferences.</p><h4>Is there a correlation between age and shopping preferences?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F43seFQmki3j2vKcV50DDw.png" /><figcaption>Figure 12: Customers Age Distribution</figcaption></figure><p>If we take closer look at the figure above, it looks like the majority of customers is under 50 years old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cMM1mlDYv1C53UgezVIzpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*hxHEtkoI3jDsJyN7swvWSQ.png" /><figcaption>Figure 13: Average Total Spending by Age Group</figcaption></figure><p>In the shopping showdown of <strong>age groups</strong>, the fabulous <strong>70+</strong> <strong>customers</strong> takes the crown for the highest shopping enthusiasm and product love. Their favorite is <strong>wine</strong> and <strong>meat</strong> products, while fish, fruit, and sweets play a bit hard to get. Surprise, surprise, gold is still a hot pick, probably because it’s not just for accessories — it’s an investment thing.</p><p>Now, comparing this with the age group’s response to campaigns, the 40–49 age customers initially responded more on the last campaign. But hold up, in the total spend, they’re not keeping up with the <strong>70+ age group</strong>. Even though the <strong>70+ customers</strong> seemed unimpressed by the last campaign, overall, they’re the real shopping MVPs. It’s like a shopping paradox, right?</p><p>Why might the 70+ squad be big spenders but low-key about campaigns?</p><p>1. <strong>Old-School Shopping Vibes:</strong> Maybe the older customers prefers the traditional in-store experience over the online shopping. Nothing beats seeing the goods in person.</p><p>2. <strong>Awareness Woes:</strong> They might not really understand or fully informed about the supermarket’s hype campaigns. Someone needs to make an extra effort to spill the shopping tea to them.</p><p>3. <strong>Not Hooked on Campaigns:</strong> Even though they’re big spenders, specific campaigns might not tickle their shopping fancy. They prefers to the beat of their own product preferences.</p><p>4. <strong>Basic Needs Rule:</strong> They’re all about fulfilling basic needs and everyday essentials, less about diving into optional campaign options.</p><p>5. <strong>Physical Hurdles:</strong> Limited mobility or other physical constraints could be playing a role in their low interest in campaigns involving travel or physical activities.</p><h4>Do married customers tend to make larger purchases compared to unmarried customers?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_rOYOib9pkuRCt4hvtMa_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NKQSTrOr-V3Flc64yHfidA.png" /><figcaption>Figure 14: Average Total Spending by Marital Status</figcaption></figure><p>From the chart above, let’s unravel the customer’s shopping vibes. Overall, there’s <strong>no wild shopping showdown</strong> between the married and unmarried customers. But, hold your cart — there’s a cool trend alert!</p><p>Customers who are <strong>married</strong> or <strong>divorced</strong> exhibit a <strong>robust shopping presence</strong>, engaging in larger-scale purchases in comparison to their single counterparts.</p><p>On the flip side, the <strong>singles</strong> still rocking some serious shopping, maybe with a dash of roommate influence or family ties nudging their cart choices.</p><p>Oh, and every marital status has favorite preference, which is wines, meats and gold. Consistency is the name of the game, folks!</p><p>In the intricate world of retail, there is no significant drama in product preference — everyone follows the same shopping rhythm. Recognizing these subtleties could be the key element in devising precise marketing strategies for each marital status group.</p><h4>Does having children influence shopping patterns among customers?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Kd5hsfvtfHHntTQicj-cUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ZsnrhLFBGOWIM7UA5lHtwg.png" /><figcaption>Figure 15: Average Total Spending by Having Child</figcaption></figure><p>In the visualization above, customers with kids are spending more cash compared to the child-free customers. But hold up, when we zoom in, the child-free customers are actually spending more. Plot twist! Why’s that?</p><p>1. <strong>Spending Priorities</strong>: Customers without child, rocking a bigger vibe in the wine and meat aisles compared to the customers with child. As the kid count goes up, the spending vibe goes down. Seems like the child-free customers are living the high life, spending on things that spark joy without the whole family bugging.</p><p>2. <strong>Lifestyle:</strong> Parents are tuning into health vibes, loading up on fish and fruits for the fam’s well-being. Plus, there’s a mission to cut down on sugar, giving sweet treats the side-eye and promoting a healthier menu for the kids.</p><p>3. <strong>Financial Up and Downs:</strong> Having child at home shakes up the family budget . School fees, daycare bills, and daily expenses goes up. Parents play it smart, saving the gold for a secure future while balancing the family budget.</p><h3>2. Evaluating the Most Efficient Marketing Channels</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SCUOdClDLIyq0HQdsPMJA.png" /><figcaption>Figure 16: Total Purchases for Each Channel</figcaption></figure><p>Peeking at the bar plot, it seems the web and catalogs purchases were in a neck-and-neck race from 2012 to 2014 — no clear winner.</p><p>But hold up — the real star of the show? It’s the good old stores purchase! Here’s the lowdown:<br>1. <strong>Touching-and-Feeling:</strong> Customers can touch, try, and <strong>test products live and direct, building trust and satisfaction</strong>. It’s a whole different story from online or catalog purchases, where you’re just staring at images.</p><p>2. <strong>Live Interaction with the Store MVPs:</strong> Walk into a store, and if you need, you can <strong>always chat it up with the sales inside the supermarket</strong> who would be gladly spill the tea on products. No offense to online support, but waiting for their replies is like waiting for a text from the pretty girl at school.</p><p>3. <strong>No Waiting Involved:</strong> In-store buys are the real preference for customers who likes something instant. <strong>No waiting for delivery trucks — you grab your treasure and dash</strong>. Perfect for folks who need stuff ASAP or are not familiar with online shopping yet.</p><p>Based on the analysis above, <strong>the most suitable customer segments</strong> to target are:<br>1. Customers with a bachelor’s degree<br>2. Customers aged 40–49 years<br>3. Married customers<br>4. High-income customers<br>5. Customers who made their last purchase 26–50 days ago<br>6. Customers without children</p><h3>3. Conclusions &amp; Marketing Strategies Recommendation</h3><h4>Conclusions</h4><p>After plunging into the analysis of the data, here’s the conclusion:</p><p>1. <strong>Membership Madness:</strong> The membership growth had its ups and downs, hitting its peak in August 2012 and taking a dip in June 2014.</p><p>2. <strong>Last Campaign Lovers:</strong> Meet the Graduates, aged 40–49, happily married, has high income, shopping in the last 11–25 days, and kid-free!</p><p>3. <strong>High Education Levels: </strong>The educated customers like bachelors, masters, and PhD shows consistent purchasing power. Smart choices and savvy spending are the names of the game.</p><p>4. <strong>Financial Stability:</strong> Age 40–49 means financial stability and a sweet spot in life. They’re not just spending; they’re investing in quality goods.</p><p>5. <strong>Marriage Status:</strong> Married customers dominate. Married life equals more financial responsibilities, combining family income for a bigger purchasing potential.</p><p>6. <strong>High Income Category:</strong> The high-income customers is dominating the shopping scene. Big spenders alert!</p><p>7. <strong>Loyal Shoppers:</strong> Returning for more in 26–50 days? You’re in the loyalty club!</p><p>8. <strong>Child-Free Customers:</strong> Those without the childs are making waves with their freer spending and no parental responsibilities.</p><p>9. <strong>Channel Showdown:</strong> The battle of the shopping channels! Web and catalog versus the classic in-store experience. Direct shopping still takes the crown.</p><p>10. <strong>Target Market:</strong> Aligning with the most responsive segment, the ideal target market includes highly educated, 40–49 years old, married, high-income customers who shopped in the last 26–50 days and have no children.</p><p>With this targeted approach, marketing strategies can be more effective, tailored to customer preferences, strengthening relationships with this specific audience.</p><h4>Recommendation</h4><p>Here are some suggestions to <strong>amp up</strong> the <strong>supermarket campaign program</strong>, keep the membership alive, and make campaigns more effective and relevant:</p><p>1. <strong>Tailored Campaign:</strong> Use customer data to create personalized campaigns that feel like they were brewed just for them.</p><p>2. <strong>Members-Only Magic:</strong> Gift members with exclusive perks — extra discounts, buy-one-get-one-free goodies, or sneak peeks at the newest arrivals. Make them feel like VIPs on a shopping spree!</p><p>3. <strong>Reward Program:</strong> Turn up the excitement in the rewards program! Picture members cashing in points for cool stuff — from trendy products to quirky gifts. The bigger the total spend, the bigger the rewards!</p><p>4. <strong>Keep the Membership Alive:</strong> Don’t forget to retain the long-time members! Launch campaigns that celebrate their loyalty so they will feel like accepted and taken care of.</p><p>5. <strong>Data-Driven Shopping Campaigns: </strong>Craft campaigns that connect the dots between what members bought before and what they might fancy next. With this insight, we can create campaigns that just pierce through their heart.</p><p>6. <strong>Referral Programs:</strong> Let members bring their pals to the shopping party and joining membership, and give reward to them for bringing the ultimate shopping squad.</p><p>7.<strong> Communication Charm: </strong>Keep the conversation going! Provide members with regular updates through emails, texts, or app messages.</p><p>8. <strong>Evaluation and Feedback:</strong> Let the customers share their thoughts regularly — it’s like getting tips from the ultimate shopping critics.</p><p>9. <strong>Targeted Campaigns:</strong> Aim your campaigns like arrows at the bullseye — the most likely responsive groups. This ensures effective use of marketing resources and maximizes campaign results!</p><p>10. <strong>Marketing Channel:</strong> While in-store are preferred, we need to spice things up online and in catalog. Enhance the online experience with online-specific promotions and interactive catalogs.</p><p>11. <strong>Performance Measurement:</strong> Regularly monitor campaign performance. Track those numbers — new memberships, frequent shopping sprees, and record-breaking transactions. Identify what works and areas needing improvement.</p><p>12. <strong>Customer Feedback:</strong> Collect customers voices through regular feedback to tune into their shopping preferences, needs and concerns.</p><p>13. <strong>Campaign Scoreboard:</strong> Measure the wins and misses, and cheer for every campaign touchdown, allowing for continuous improvement in future campaigns.</p><p>14. <strong>Continues Data Analysis:</strong> Supermarkets need to continue periodic data analysis to monitor changes in customer behavior. With a deeper understanding of how customers shop, supermarkets can adjust their strategies.</p><p>By implementing these recommendations, the supermarket’s membership program will be more effective, existing members will stay engaged, and new customers will be enticed to join. This leads to greater profits and sustainable growth for the supermarket.</p><p>A heartfelt thank you to the dedicated reader who has journeyed through the entirety of this story. Your curiosity and engagement mean the world. If you’ve found the insights valuable, consider checking out the code on <a href="https://github.com/athwbx/Capstone_Project2-Supermarket_Analysis"><strong>GitHub</strong></a> for a behind-the-scenes look at the data magic. Additionally, explore the interactive visualizations on <a href="https://public.tableau.com/app/profile/aryo.atha.rizaldi/viz/ProjectCapstone2SupermarketXAnalysis/SupermarketStory"><strong>Tableau</strong></a> to truly immerse yourself in the data’s narrative. Your exploration doesn’t have to end here; it’s a continuous journey. Until our next data adventure, happy exploring!</p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf4f9c21fa5" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/examining-customer-behavior-in-supermarket-x-a-comprehensive-analysis-part-2-adf4f9c21fa5">Examining Customer Behavior in Supermarket X: A Comprehensive Analysis (Part 2)</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exception Handling In Python]]></title>
            <link>https://python.plainenglish.io/exception-handling-in-python-a-tutorial-on-how-to-use-it-and-when-to-use-it-the-fun-way-57afbcae6081?source=rss-423aa313321------2</link>
            <guid isPermaLink="false">https://medium.com/p/57afbcae6081</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-analyst]]></category>
            <category><![CDATA[exception-handling-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[purwadhika]]></category>
            <dc:creator><![CDATA[Aryo Atha Rizaldi]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 14:08:04 GMT</pubDate>
            <atom:updated>2023-11-07T01:00:28.636Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Tutorial On How To Use It And When To Use It (The Fun Way!)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDeyvxai5xKJc4Wugh-gTQ.png" /></figure><p>Usually, when our code decides to go on an adventure of its own and doesn’t quite stick to the rules of Python, we end up with a pair of Python’s very own mischievous troublemakers. Let’s meet them:</p><ol><li>Syntax error</li><li>Runtime error</li></ol><p>If your Python script decides throw a tantrum with a <strong>runtime error</strong> or <strong>syntax</strong> hiccup and we don’t catch it, the program goes “Bye-bye!” But hey, to keep the party going and stay in control, we’ve got this nifty thing called <strong>exception handling</strong>🎉</p><h3>Alrighty, let’s dive into the exciting stuff! When and why would we want to sprinkle some “exception handling” magic in our code, and, of course, how do we pull off this wizardry? 🪄</h3><p><strong>Why:</strong></p><p>When your Python script goes all “Oopsie-daisy!” and throws an <strong>exception</strong>, it’s like a game of hot potato — you’ve got to <strong>handle it</strong> pronto, or else it might just pack its bags and leave the party!</p><p><strong>When:</strong></p><p>Got some code that’s got the potential to be a real party pooper by throwing an <strong>exception </strong>that could crash the whole shindig? No worries! We’ve got your back with a cool trick called <strong>“exception handling”</strong> to keep the good times rolling and prevent the program from doing a dramatic <strong>exit</strong>.</p><p>But hey, before we delve into the really fun stuff, let’s lay the groundwork and grasp the basic flow of <strong>Exception Handling</strong> in Python. 🎉🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jjgKJLGVo6WC9innmi9fNw.png" /></figure><p>Picture it like this: the try block is your code’s adventure playground, and it keeps having fun until it stumbles upon an <strong>exception</strong>. When that happens, it’s like a secret signal — the control gets passed to the except block, or if there’s no <strong>exception</strong>, it takes a detour to the else → finally zone.</p><p>Inside the except zone, we’re like the superheroes of <strong>error </strong>land. We’re ready for any kind of <strong>exception </strong>— the special ones and the regular ones. It’s all part of the plan because we’re smart like that. We’re like Sherlock Holmes, but for code mysteries!</p><p>And then there’s the finally block, the ever-dependable buddy who shows up no matter what. It’s like that loyal friend who never lets you down, even when things get crazy. This block is here to tidy up after the party, whether it was smooth sailing or a wild ride.</p><p>So, if a pesky error tries to crash your coding party, don’t fret! Your program’s got your back, all set to <strong>catch those errors</strong> and make your coding life a breeze! 🚀🔍</p><h4>In this awesome article, we’re going to dive into the nitty-gritty with the help of this code block right here:</h4><pre>try:<br>    numerator = 10<br>    denominator = 0<br><br>    result = numerator/denominator<br><br>    print(result)<br>except:<br>    print(&quot;Error: Denominator cannot be 0.&quot;)<br><br># Output: Error: Denominator cannot be 0. <br></pre><p>In our little example, we’re gonna roll with the <strong>try…except</strong> duo. What’s the deal? Well, we’re attempting to do the impossible: divide a number by <strong>zero</strong>! Brace yourselves because this code is about to throw us a curveball in the form of an exception!</p><p>To catch those curveballs, we’ve wrapped our code, where we do the division (you know, result = numerator/denominator), inside a try block. So, when an exception decides to crash our party, the rest of the try block just takes a coffee break and chills out, and it’s time for the except block to be the superhero🦸‍♂️</p><p>Think of the except block as your trusty safety net. It’s always ready to catch an <strong>exception </strong>if one dares to misbehave in your code.</p><p>And here’s the cool part — if your try block behaves itself and doesn’t cause any trouble, the except block takes a vacation and lets your code party on without any interruptions! 🏖️</p><h4>handling specific exception</h4><p>And guess what? You can even get super <strong>specific </strong>with your <strong>exception handling</strong>! It’s like having a secret weapon for a particular kind of trouble. Here’s the scoop:</p><pre>try:<br>    <br>    evenNumbers = [2,4,6,8]<br>    print(evenNumbers[5])<br><br>except ZeroDivisionError:<br>    print(&quot;Denominator cannot be 0.&quot;)<br>    <br>except IndexError:<br>    print(&quot;Index Out of Bound.&quot;)<br><br># Output: Index Out of Bound</pre><p>Get this: for every try block you throw into the mix, you can bring in as many except blocks as you want. It’s like having a whole team of problem-solvers on standby! 🛠️</p><p>And the best part? Each except block has its own unique superpower to handle <strong>exceptions </strong>in its own special way. It’s like having a whole bunch of superheroes with different abilities! 💥</p><p>Each except block is like a superhero with its own special powers, and the argument type tells us which kind of trouble they’re equipped to handle.</p><p>Hang tight, I’ve got something for you! Imagine we’ve got this fantastic <strong>list </strong>called evenNumbers— it’s like a lineup of your favorite characters, but all in the language of code. And, because <strong>lists </strong>kick off their counting from <strong>0</strong>, our final character hangs out at index <strong>3</strong>.</p><p>Now, get ready for the real fun because here’s where the action unfolds — watch out for this <strong>statement</strong>:</p><pre>print(evenNumbers[5])</pre><p>Picture this: we’re on a mission to grab something from the index <strong>5</strong>. But wait for it — here comes the plot twist. There’s no index <strong>5 </strong>on the list! So IndexError exception decided to <strong>crashes </strong>our party like an unexpected guest.</p><p>Here’s where it gets interesting: when our uninvited IndexError <strong>exception </strong>shows up in the try block, it’s like the star of the show. It takes the spotlight, and guess what? The ZeroDivisionError <strong>exception </strong>doesn’t even get a chance to audition because it get skipped. The set of code inside the IndexError <strong>exception</strong> takes center stage and steals the scene! 🎭</p><h3>try.. else clause</h3><p>Sometimes, we want to throw a little celebration when our try block behaves perfectly, with no <strong>errors </strong>in sight. 🥳</p><p>To make that happen, we’ve got this cool trick up our sleeves — it’s the optional else keyword, and it goes hand in hand with the try statement. Now, let’s dive into an <strong>example </strong>and see this party in action! 🕺🎈</p><pre># program to print the reciprocal of even numbers<br><br>try:<br>    num = int(input(&quot;Enter a number: &quot;))<br>    assert num % 2 == 0<br>except:<br>    print(&quot;Not an even number!&quot;)<br>else:<br>    reciprocal = 1/num<br>    print(reciprocal)</pre><p>When we feed an <strong>odd </strong>number into the mix, brace yourselves for some epic <strong>output</strong>:</p><pre>Enter a number: 1<br>Not an even number!</pre><p>Now, if we decide to toss in an <strong>even </strong>number, get ready for a real treat — we crank up the math machine, calculate the reciprocal, and show you the results! 🎩</p><pre>Enter a number: 4<br>0.25</pre><p>However, if we toss a <strong>zero </strong>into the mix, things get wild! We’re talking about a ZeroDivisionError here, because our trusty except block from earlier doesn’t know how to handle the shenanigans happening inside the else block. 🙅‍♂️</p><pre>Enter a number: 0<br>Traceback (most recent call last):<br>  File &quot;&lt;string&gt;&quot;, line 7, in &lt;module&gt;<br>    reciprocal = 1/num<br>ZeroDivisionError: division by zero</pre><blockquote><strong>Here’s a friendly reminder:</strong> when it comes to exceptions in the <strong>else </strong>clause, the preceding <strong>except </strong>clauses don’t have your back. It’s like they’re off on their own adventure, leaving the <strong>else </strong>clause to deal with its own surprises! 🌟🗺️</blockquote><h4>try.. finally</h4><p>Now, let’s talk about the always dependable finally block in <strong>Python</strong>. It’s your trusty sidekick, and it’s got your back no matter what; whether there’s an <strong>exception </strong>or not!</p><p>Keep this in mind: the finally block is your choice — you can invite it to the coding bash or leave it out. But here’s the twist, for each try block, there’s only room for <strong>one </strong>finally block. No party crashers allowed!</p><p>Ready for some hands-on fun? Let’s dive into an example! 🚀🔍</p><pre>try:<br>    numerator = 10<br>    denominator = 0<br><br>    result = numerator/denominator<br><br>    print(result)<br>except:<br>    print(&quot;Error: Denominator cannot be 0.&quot;)<br>    <br>finally:<br>    print(&quot;This is finally block.&quot;)</pre><p><strong>Output:</strong></p><pre>Error: Denominator cannot be 0.<br>This is finally block.</pre><p>Now, in the example we just peeked at, we decided to be a bit mischievous and tried to divide a number by <strong>zero </strong>right inside the try block. And guess what? It’s like we rang the bell for trouble, and an exception came knocking at our door!</p><p>But fear not, our trusty except block stepped in like a superhero and saved the day! 🦸‍♂️ And after all the excitement, the finally block, our reliable sidekick, made sure to do its thing as well. It’s all in a day’s work for this coding crew! 🚀</p><h3>I’m crossing my fingers that you had a blast reading this article, and that it left you with some cool insights! Thanks a million for being a part of this coding adventure with us!</h3><blockquote>coding is like a fun puzzle, and the more you practice, the more mesmerizing it becomes. I guarantee it’ll turn into a beautiful masterpiece as you keep on coding! 🧩💻🌟</blockquote><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57afbcae6081" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/exception-handling-in-python-a-tutorial-on-how-to-use-it-and-when-to-use-it-the-fun-way-57afbcae6081">Exception Handling In Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>