<?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 Hadia Butt on Medium]]></title>
        <description><![CDATA[Stories by Hadia Butt on Medium]]></description>
        <link>https://medium.com/@hadia.rbutt?source=rss-6603b31526c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Xe_8qEFz4CmU-U9M</url>
            <title>Stories by Hadia Butt on Medium</title>
            <link>https://medium.com/@hadia.rbutt?source=rss-6603b31526c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:45:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hadia.rbutt/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[No Code, No Problem: 3 Ways Power Query Transformed My Retail Analytics Work at Levi’s]]></title>
            <link>https://medium.com/@hadia.rbutt/no-code-no-problem-3-ways-power-query-transformed-my-retail-analytics-work-at-levis-cc2f2c37b2de?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc2f2c37b2de</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[retail-analytics]]></category>
            <category><![CDATA[power-query]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 01:40:11 GMT</pubDate>
            <atom:updated>2026-01-09T01:40:11.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRioMqaS7ATmZy0SyIPBqg.png" /></figure><p>Data integration and analysis form the backbone of effective business intelligence. However, delivering actionable insights doesn’t always require complex programming in Python or SQL. While these languages are undeniably powerful and widely adopted in the data community, they aren’t the only path to meaningful analytics. For many business intelligence needs, accessible tools like Excel — specifically Power Query — can provide sophisticated analytical capabilities without the steep learning curve of traditional programming languages. The key is matching the tool to the business need, rather than assuming that more technical complexity automatically yields better results.</p><p>During my time at Levi’s, Power Query became an essential tool for delivering timely, high-quality insights to stakeholders across the organization. This article outlines three specific applications of Power Query that significantly improved both the efficiency and quality of my analytical work.</p><p><strong>1. Centralizing Data Sources to Build Custom Dashboards</strong></p><p>As a business analyst at Levi’s, an integral part of my role was performance reporting at a daily, monthly, quarterly and yearly basis. Sales reporting was rarely restricted to communicating a single sales number and almost always entailed measuring it against last year, last month and monthly financial targets to track under or over delivery. It did not just stop there. Next came investigating further into the levers responsible for the performance. These levers were either store focused or product focused. Did a store have a significantly high footfall or were sales driven by new inventory of seasonal assortments? The answer to these questions lay in the data and part of my role was to bring data in one place to facilitate such deep dives.</p><p>The challenge, however, was that all the data required to answer these analytical questions and measure business performance was never available in one neat sheet. The sales revenue and units sold data had to be extracted from the ERP system. Footfall and transactions data came separately. Data on sales targets came from district managers in excel files (which hardly followed a standard and often times varied from the financial plan submitted at year start). Then came the product master sheet— table containing details on product SKUs, brand, categories, sub categories, gender, size sets, planning group, product status. Similar to a product master existed a store master which contained information on store location, city, region, distribution channel etc. The data was scattered and there was a dire need to synthesize it all into a comprehensive dashboard view to get immediate answers.</p><p>Power Query enabled seamless integration of data from multiple disparate sources through its merge and append functionality, consolidating various data tables into a unified data model. The transformation capabilities facilitated efficient data preparation, including column manipulation, standardization of data formats, and the creation of conditional columns based on business logic. The automatic documentation of all transformation steps provided full transparency and auditability, allowing for easy modification and troubleshooting of the data pipeline when requirements changed.</p><p>Once the data model was established, creating pivot tables with dynamic filters became straightforward, enabling flexible data analysis across multiple dimensions. These pivot tables served as the foundation for custom dashboards directly within Excel, providing stakeholders with visual, interactive reporting capabilities.</p><p>The most significant efficiency gain came from Power Query’s refresh functionality. With daily sales data updates, the manual repetition of transformation steps was eliminated. A single refresh command automatically re-executed all queries and updated the entire data model with current data, transforming a previously time-intensive daily process into an automated workflow.</p><p><strong>2. Enabling Rapid Ad Hoc Sales Analysis</strong></p><p>Once the data model was in place, it became much easier and quicker to conduct ad hoc sales analysis. Business stakeholders frequently needed quick analysis based on specific filters or conditions: “How did our seasonal denim line perform in the South region during the holiday promotion?” or “Which distribution channels showed the strongest growth in core product categories last quarter?”</p><p>These ad hoc requests were common and urgent. Traditional approaches — extracting data, building pivot tables, creating visualizations — were too slow. By the time analysis was ready, the business context had often shifted. Consequently, there was a need for a more responsive analytical capability.</p><p>Ad hoc analyses that previously required 2–4 hours could now be completed in 15–30 minutes using Power Query. The key was building flexible, parameterized queries that could be quickly adjusted for different filters and conditions. When a stakeholder requested analysis of a specific product line’s performance, I simply updated the relevant parameters, refreshed the query, and had clean, filtered data ready for analysis.</p><p>The cumulative impact was significant. With approximately 8–10 such requests per week, Power Query saved roughly 20–30 hours of analytical work weekly across my responsibilities. This allowed me to respond to business questions the same day they were asked, rather than adding them to a backlog.</p><p>Power Query delivered on both: speed and accuracy. The quality improvements in ad hoc analysis came from several factors:</p><p>First, using pre-built, tested queries eliminated the introduction of errors common in rushed manual analysis. Each time I filtered data for a new request, I knew the underlying transformations and calculations were correct because they’d been validated previously.</p><p>Second, the consistency of data preparation meant insights were comparable across different analyses. When comparing Q3 performance to Q3 last year, both datasets underwent identical cleaning and standardization processes, ensuring apples-to-apples comparisons.</p><p>Third, the speed of analysis allowed for iterative exploration. Rather than delivering one static answer to a business question, I could quickly explore multiple angles. If initial analysis of regional performance raised questions about specific store clusters, I could drill down immediately. This iterative approach often uncovered deeper insights than the original question anticipated.</p><p>A specific example: When asked about declining sales in a particular product category, quick Power Query analysis revealed the decline was concentrated in a single region. Further iteration showed it was specific to stores in that region. Final analysis identified that road renovations, civil work and route closures impacted footfall in those locations. This progression from initial question to actionable competitive intelligence took under an hour with Power Query; it would have required days with manual methods.</p><p><strong>3. Leveraging No-Code Analysis for Accessibility and Collaboration</strong></p><p>As the analytics function evolved, there was growing recognition that data skills needed to be distributed more broadly across the organization. Category managers, regional managers, and merchandising analysts all needed analytical capabilities, but most lacked programming backgrounds. Traditional analytics tools required SQL or Python knowledge, creating a skill barrier that limited organizational data literacy.</p><p>Power Query’s visual, no-code interface offered a solution. I could build sophisticated data transformation workflows that colleagues without technical backgrounds could understand, modify, and replicate.</p><p>The no-code nature of Power Query created time savings in two ways: for me as an analyst, and for the broader team.</p><p>For my work, building queries through Power Query’s interface was faster than writing equivalent SQL scripts or Python code. The point-and-click approach for common transformations — removing duplicates, splitting columns, changing data types, merging tables — was efficient and intuitive. Complex operations that might require researching syntax or debugging code were accomplished in seconds through menu selections.</p><p>For the team, Power Query enabled self-service analytics. Rather than every data request flowing through the analytics team, I trained category managers and regional analysts to build their own queries for routine analyses. This distributed analytical capability and reduced bottlenecks significantly.</p><p>The “Applied Steps” feature in Power Query proved particularly valuable for knowledge transfer. When a colleague needed to understand how data was being processed, they could review the step-by-step transformations in plain language rather than deciphering code. This transparency accelerated learning and reduced dependency on the central analytics team. The no-code approach improved insight quality by democratizing analytical capabilities across the organization.</p><p><strong>Key Takeaways</strong></p><p>Power Query proved valuable not as a replacement for more advanced analytical tools, but as a practical solution for common business intelligence challenges. Its strength lay in making sophisticated data operations accessible and efficient. The three applications described here — centralized dashboard development, rapid ad hoc analysis, and accessible no-code transformation — addressed different but complementary needs.</p><p>For business analysts in retail or similar industries, Power Query offers immediate practical value and serves as a great starting point. The tool’s learning curve is manageable, its applications are diverse, and its integration with the broader Microsoft ecosystem creates a pathway to more advanced analytics platforms.</p><p>The return on investment is clear: significant time savings, higher quality insights, and broader organizational analytical capabilities. In an environment where data-driven decision-making is increasingly critical, Power Query provides accessible tools to meet that demand.</p><p><em>Thanks for reading! If you enjoyed this article, feel free to follow me to receive new posts and support my work, or check out my other articles for hands-on projects and tips.</em></p><ul><li><a href="https://medium.com/@hadia.rbutt/time-series-forecasting-made-simple-a-practical-introduction-214614768fe0">Time-Series Forecasting Made Simple: A Practical Introduction</a></li><li><a href="https://medium.com/@hadia.rbutt/from-theory-to-practice-implementing-multilinear-regression-in-python-a-step-by-step-guide-for-91f74af6fa44">From Theory to Practice: Implementing Multilinear Regression in Python — A step by step guide for…</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc2f2c37b2de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Book Review: ‘Designing Machine Learning Systems’ for Academic ML Students]]></title>
            <link>https://medium.com/@hadia.rbutt/book-review-designing-machine-learning-systems-for-academic-ml-students-692af343226a?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/692af343226a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 17:52:44 GMT</pubDate>
            <atom:updated>2025-12-30T17:52:44.407Z</atom:updated>
            <content:encoded><![CDATA[<p>As a graduate student in analytics, I’ve spent countless hours perfecting model architectures, tuning hyperparameters, and celebrating when my validation accuracy crosses that magical 95% threshold. I recently had the opportunity to read Chip Huyen’s “Designing Machine Learning Systems,” and quickly realized I had been living in a beautifully controlled bubble that bore little resemblance to the messy reality of production ML. Here is a brief summary of the book and the key insights I gained about the gap between academic and production ML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*4VcUWTPp-HrSVYP877RBww.png" /></figure><h3>The Wake-Up Call</h3><p>In academic settings, we work with clean datasets that fit comfortably in memory. We have clearly defined problem statements, labeled data handed to us on a silver platter, and the luxury of running experiments until we get publishable results. Huyen’s book was my wake-up call that real-world ML is a completely different beast.</p><p>The book opens by distinguishing between ML in research and ML in production, and this distinction hit home immediately. In production, your model isn’t the product — it’s one component in a larger system that needs to create business value. That 95% accuracy I was so proud of? It might be worthless if the model takes too long to make predictions, costs too much to run, or fails catastrophically on edge cases that never appeared in my training data.</p><h3>It’s Not Just About the Model</h3><p>Perhaps the biggest paradigm shift for me was understanding that the model itself represents only a tiny fraction of an ML system. There’s significant attention to data engineering, feature stores, model deployment, monitoring, and maintenance. Moreover, the requirements of a model to be reliable, scalable, maintainable and adaptable provide an additional perspective of the real world. In my coursework, I’ve barely touched these topics beyond a cursory mention.</p><p>The chapter on data engineering was particularly eye-opening. I learned about data lineage, the importance of tracking data provenance, and how data distribution shifts can silently degrade model performance over time. In class, we assume our test set represents future data. In production, that assumption can cost companies millions when it proves false.</p><p>Feature engineering, which I’d always treated as a creative preprocessing step, becomes exponentially more complex in production. Huyen discusses feature stores, the challenge of training-serving skew, and the critical difference between batch features and real-time features. I’d never considered that a feature I can easily compute offline might be impossible to calculate with the millisecond latency requirements of a production system.</p><h3>The Operational Reality</h3><p>The middle sections of the book dive into model deployment and serving, areas I’d given almost no thought to. How do you actually get a model from your laptop into a system serving millions of requests? While I partially understood the iterative process of model development, deployment into a full blown ML system was something I hadn’t thought of. Huyen walks through different deployment patterns, from batch prediction to online prediction, and discusses the trade-offs between each approach.</p><p>I was particularly fascinated by the discussion of different serving patterns: batch processing for scenarios where you can precompute predictions, online prediction for real-time requests, and streaming for continuous data. In my academic work, I’ve only ever done batch processing because that’s all I’ve needed. The idea of optimizing a model to make predictions in under 100 milliseconds while handling thousands of concurrent requests was completely foreign to me.</p><p>The book also covers model compression techniques like quantization, pruning, and knowledge distillation, not as academic curiosities but as practical necessities when you need to deploy on edge devices or reduce infrastructure costs.</p><h3>Monitoring and Maintenance: The Never-Ending Story</h3><p>Perhaps the most sobering realization was that deploying a model isn’t the end of the journey — it’s the beginning. Huyen dedicates extensive coverage to monitoring, debugging, and maintaining ML systems over time. In academia, once I submit my assignment, I’m done. In production, you need to continuously monitor for data drift, concept drift, model staleness, and operational issues.</p><p>The chapter on continual learning and test in production was fascinating. Huyen discusses strategies like A/B testing, multi-armed bandits, and canary deployments. These aren’t just nice-to-haves; they’re essential practices for safely updating models in production without breaking things for users. I’d never considered that updating a model could be risky or that you might need sophisticated rollout strategies.</p><h3>The Human Element</h3><p>What surprised me most was how much of the book focuses on team dynamics, organizational challenges, and responsible AI. Huyen discusses the importance of cross-functional collaboration between data scientists, engineers, and product managers. She addresses bias, fairness, and the ethical implications of ML systems in a way that feels practical rather than purely theoretical.</p><p>In my academic bubble, I work alone or with a small team of fellow students who all speak the same technical language. Huyen makes it clear that in industry, successful ML practitioners need to communicate with stakeholders who don’t understand gradient descent but do understand business metrics. You need to translate model performance into business value and make trade-offs between model complexity and maintainability.</p><h3>Practical Wisdom for Aspiring Practitioners</h3><p>Throughout the book, Huyen offers practical advice grounded in real-world experience. She discusses when to use simpler models versus complex deep learning, how to prioritize which models to build first, and how to think about the full lifecycle of an ML system. This type of wisdom simply doesn’t exist in academic curricula focused on algorithmic innovation.</p><p>One chapter that particularly resonated was on debugging ML systems. In class, when my model doesn’t work, it’s usually a coding bug or a hyperparameter issue. Huyen catalogs the myriad ways production ML systems can fail: infrastructure issues, data pipeline problems, training-serving skew, feedback loops, and more. Debugging becomes a much more complex detective process.</p><h3>Bridging the Gap</h3><p>Reading “Designing Machine Learning Systems” has fundamentally changed how I think about my career trajectory. I now understand that the transition from academia to industry will require learning an entirely new set of skills that complement my theoretical foundation. The book has shown me the questions I should be asking about ML systems: What are the latency requirements? How will we handle model updates? What happens when the data distribution changes? How do we measure success beyond model metrics? How do we frame business problems as ML problems?</p><p>For any graduate student or academic who plans to work with ML in industry, this book is essential reading. It doesn’t just teach you how to build ML systems; it teaches you how to think about them holistically. It’s the bridge between the controlled environment of academic ML and the chaotic, dynamic reality of production systems where models need to create value while remaining reliable, maintainable, and fair.</p><p><em>Have you made the transition from academic ML to production systems? What surprised you most? I’d love to hear your experiences in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=692af343226a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data to insights — a step by step Guide to Mastering SQL Queries in Python]]></title>
            <link>https://medium.com/@hadia.rbutt/data-to-insights-a-step-by-step-guide-to-mastering-sql-queries-in-python-14a66dc684d1?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a66dc684d1</guid>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[sakila-database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[relational-databases]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 02:41:12 GMT</pubDate>
            <atom:updated>2025-12-25T02:41:12.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data to insights — a step by step Guide to Mastering SQL Queries in Python</h3><p>SQL is often taught as a standalone skill — you open a database client, write queries, and inspect results. In real-world analytics work, however, SQL rarely lives alone. It is frequently embedded inside Python workflows, where querying, analysis, and visualization happen together.</p><p>In this article, I walk through a hands-on project where I use SQL inside Python (via Jupyter Notebook) to analyze the Sakila video rental database. This is a beginner friendly guide for someone just starting their journey with SQL. If you’re curious about how SQL and Python complement each other and want a hands-on experience writing SQL queries, this guide will walk you through the entire process, from connecting to the database to analyzing and interpreting the results.</p><p><strong>Why Combine SQL and Python?<br></strong>SQL is excellent for extracting data, joining tables and aggregating large datasets. Python, on the other hand, excels at automation, reproducibility, analysis, modeling, visualization and reporting. By combining both, we get a workflow that mirrors how analysts and data scientists work in practice.</p><p><strong>An overview of the Sakila Database</strong></p><p>The Sakila database used for this project represents a fictional video rental business. It includes tables for customers, films, categories, rentals, payments, stores and staff. From a business perspective, it allows us to answer questions like:</p><ol><li>Which movies generate the most revenue?</li><li>Which categories are most popular?</li><li>Which customers rent the most?</li></ol><p>This makes Sakila a great dataset for practicing relational SQL in a realistic setting. Following is the entity relationship diagram (ERD) that summarizes the tables, fields and the relationships between the tables including details such as primary and foreign keys as part of the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJyy9_HYahx3EXpua96b1g.png" /></figure><p>You can find the database file along with the Jupyter notebook for this project <a href="https://github.com/HadiaRButt/python-x-sql">here</a>. Make sure you download it in the same directory as your Jupyter notebook.</p><p><strong>Connecting Python to the Database</strong></p><p>The first step is creating a connection between Python and the database file:</p><pre>import sqlite3<br>import pandas as pd<br><br>conn = sqlite3.connect(&#39;sqlite-sakila.db&#39;)</pre><p>Here the connection (conn) opens a communication channel to the database. SQLite handles all reads and writes through this connection. Once connected, SQL queries can be executed directly from Python. We will be reading the results of SQL queries into pandas using the following syntax:</p><pre>pd.read_sql_query(query, conn)</pre><p>This approach executes the SQL query, automatically converts the result into a pandas DataFrame and hence makes downstream analysis easier. This is especially useful when SQL is just one step in a larger analytics pipeline.</p><p>Before writing complex queries, it is also important to understand the schema. Although an ERD for this database is available, a simple query like:</p><pre>pd.read_sql_query(&quot;&quot;&quot;SELECT name<br>FROM sqlite_master<br>WHERE type = &#39;table&#39;&quot;&quot;&quot;, conn)</pre><p>helps identify available tables and how they might relate to each other.</p><p>Now with the database connected, we will run some preliminary SQL queries to explore the database to understand what data is available to us.</p><p><strong>Data Exploration</strong></p><p>As a first step, we will write a simple query to see how many video rental stores this business has. The following query helps us count the store IDs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMZ2SLmHcAWuETL3lYtfCQ.png" /></figure><p>The query above finds out the number of stores that exist in the database and bring that result into Python for further analysis. The SQL statement counts the number of store_id values in the store table and labels the result as count, making the output easy to interpret. By using pd.read_sql, the query is executed directly from the Jupyter Notebook, and the result is returned as a pandas DataFrame rather than raw SQL output. This allows the count to be viewed, stored, and reused seamlessly within a Python-based analytics workflow.</p><p>Next, we will see how much inventory each store carries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Y_NmaFeNiMcTJXGpdoqJQ.png" /></figure><p>This query calculates how many inventory items each store holds. It groups the inventory data by store_id and counts the number of inventory_id values for each store, allowing us to see how inventory is distributed across stores. Again, the results are loaded directly into a pandas DataFrame, making them easy to inspect and use for further analysis in Python.</p><p>Now we will see what the top 10 films are with the highest inventory count:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvpfjWc6vpQGc8uxJlZnNA.png" /></figure><p>This query shows how many copies of each film are available in the inventory and ranks them from most to least. It connects the film and inventory tables using the shared film_id, then groups the data by film title so that each row represents a single movie. For each title, it counts how many times the film appears in the inventory, which corresponds to the number of copies available. The results are ordered in descending order by this count, and films.head(10) displays the top ten films with the highest number of inventory copies.</p><p>Next, we will see the number of films in each category and then create a plot to visualize the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UZamCZEvojdjkp-Q3Iwbw.png" /></figure><p>The code above first runs a SQL query to calculate how many films belong to each category by joining the category, film, and film_category tables. The query groups the data by category name and orders the results by the number of films in descending order, making it easy to see which categories contain the most films. The result is stored as a pandas DataFrame. The following Python code then uses Matplotlib to visualize this information as a bar chart, with each bar representing a film category and its corresponding film count.</p><p><strong>Using SQL Joins</strong></p><p>Joins are at the heart of SQL. Joins are essentially used to combine data from multiple tables based on related columns, allowing information that is stored separately to be analyzed together. They are useful for working with relational databases, where data is normalized across different tables to avoid duplication. By using joins, we can answer more meaningful business questions that require context from multiple parts of the database.</p><p>We will now use join in SQL to answer a few business questions regarding our video rental database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pw3YsoGj33SR6jwaSXsoA.png" /></figure><p>This query calculates the <strong>total revenue generated by each film category</strong> and ranks the categories from highest to lowest revenue. It starts from the payment table, since revenue is recorded at the payment level, and then progressively joins related tables to understand <em>what</em> each payment was made for. Each payment is linked to a rental, each rental to a specific inventory item, and each inventory item to a film. The film is then connected to its category through the film_category table, and finally to the category table to retrieve the category name.</p><p>Once all the relevant tables are joined, the query groups the data by category name and sums the payment amounts to calculate total revenue per category. The results are ordered in descending order of revenue so the highest-earning categories appear first. The output is returned as a pandas DataFrame, and .head(5) displays the top five revenue-generating categories, making it easy to identify which types of films contribute the most to overall sales.</p><p>This is a great business question to practice working with joins, especially since information is spread across multiple tables. While it can feel overwhelming at first, it becomes much easier as you start thinking in terms of the data structure and understanding where each piece of information is coming from.</p><p>We will now look at another example of how joins can be used to help answer a question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETNJLw1GjpCCbCXqd-gOMw.png" /></figure><p>This query identifies the top ten films by total revenue generated. It starts from the payment table and joins it to rentals, inventory, and films to determine which movie each payment corresponds to. The query then sums the payment amounts for each film, groups the results by film title, and orders them from highest to lowest revenue, returning only the top ten films.</p><p>Finally, we will now look at top 10 highest paying customers for this video rental business:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJY7h6ThGju79eRyY6eO2w.png" /></figure><p>The query above identifies the top-paying customers in the database. It joins the payment table with the customer table using customer_id to link each payment to the corresponding customer. For each customer, it sums all their payment amounts, groups the results by customer first name, and orders them from highest to lowest total payment. Using .head(10) displays the top ten most loyal (highest-paying) customers as a pandas DataFrame.</p><p>From a business standpoint, the insights generated above could support promotional campaigns, pricing strategies or inventory stocking decisions for this business. With just a few queries, you can quickly get a sense of how the business is performing and what could be the potential pain points. This is how combining SQL and Python becomes so impactful: you can extract meaningful insights directly from the database and immediately analyze or visualize them in a flexible, reproducible way. By using SQL to retrieve and aggregate data and Python to explore and present it, even complex business questions become approachable.</p><p><strong>A quick note on using multi-line SQL strings in Python</strong></p><p>You may notice that longer SQL queries are written using triple quotes:</p><pre>query = &quot;&quot;&quot;<br>SELECT ...<br>FROM ...<br>JOIN ...<br>&quot;&quot;&quot;</pre><p>This is a Python formatting choice, not a SQL requirement. Triple quotes improve readability and preserve SQL’s natural formatting which makes complex queries easier to debug and maintain. Short, one-line queries can still use single quotes without issue.</p><p><strong>Conclusion</strong></p><p>Learning SQL is essential, but learning how to <strong>use SQL inside Python</strong> is what makes it practical. Projects like these help move from writing isolated queries to building end-to-end analytics workflows — the kind that are actually used in analytics, consulting, and data-focused roles.</p><p>If you’re learning SQL for analytics, practicing with realistic datasets like Sakila and embedding queries inside Python is a powerful way to build job-ready skills.</p><p><em>Thanks for reading! If you enjoyed this guide, feel free to follow me to receive new posts and support my work, or check out my other articles for hands-on projects and tips.</em></p><ul><li><a href="https://medium.com/@hadia.rbutt/data-detox-how-to-streamline-your-dataset-for-a-successful-analysis-c04fb9cb13ec">Data Detox: How to Streamline Your Dataset for a Successful Analysis</a></li><li><a href="https://medium.com/@hadia.rbutt/from-theory-to-practice-implementing-multilinear-regression-in-python-a-step-by-step-guide-for-91f74af6fa44">From Theory to Practice: Implementing Multilinear Regression in Python — A step by step guide for…</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14a66dc684d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting with Holt-Winters Multiplicative Seasonality in Excel: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@hadia.rbutt/forecasting-with-holt-winters-multiplicative-seasonality-in-excel-a-step-by-step-guide-db960dc035d2?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/db960dc035d2</guid>
            <category><![CDATA[seasonality]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[holt-winters]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 18:54:20 GMT</pubDate>
            <atom:updated>2025-12-25T18:28:53.123Z</atom:updated>
            <content:encoded><![CDATA[<p>Time series forecasting is a critical skill for anyone working with data that changes over time — whether you’re predicting sales, website traffic, inventory needs, or financial metrics. One of the most powerful and widely-used forecasting methods is the Holt-Winters model, particularly when your data exhibits both trend and seasonality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*lsoYCnngItCJu2yrM8IJdA.png" /></figure><p>In this article, I’ll walk you through building a Holt-Winters multiplicative seasonality forecasting model in Excel from scratch. We’ll work with quarterly data spanning 5 years (20 periods), optimize the model parameters using Excel Solver, and generate forecasts for the next 4 quarters.</p><h3><strong>What is Holt-Winters?</strong></h3><p>The Holt-Winters method, also known as Triple Exponential Smoothing, is a forecasting technique that captures three components of time series data:</p><p><strong>Level (E):</strong> The baseline value of the series, excluding trend and seasonality<br><strong>Trend (T):</strong> The rate at which the series is increasing or decreasing over time <br><strong>Seasonality (S):</strong> Regular patterns that repeat at fixed intervals (quarterly, monthly, etc.)</p><p>The “multiplicative” version of Holt-Winters is particularly useful when the seasonal variations increase or decrease proportionally with the level of the series — for example, when a business experiences larger seasonal swings as it grows.</p><h3><strong>The Holt-Winters Equations</strong></h3><p>The method uses three smoothing parameters (α, β, γ) that control how much weight is given to recent observations versus historical patterns:</p><ul><li><strong>Alpha (α):</strong> Smoothing parameter for the level (0 ≤ α ≤ 1)</li><li><strong>Beta (β):</strong> Smoothing parameter for the trend (0 ≤ β ≤ 1)</li><li><strong>Gamma (γ):</strong> Smoothing parameter for seasonality (0 ≤ γ ≤ 1)</li></ul><p>The multiplicative model equations are:</p><p><strong>Level:</strong> E_t = α(Y_t / S_{t-s}) + (1 — α)(E_{t-1} + T_{t-1})<br><strong>Trend:</strong> T_t = β(E_t — E_{t-1}) + (1 — β)T_{t-1}<br><strong>Seasonality:</strong> S_t = γ(Y_t / E_t) + (1 — γ)S_{t-s}<br><strong>Forecast:</strong> F_t = (E_{t-1} + n*T_{t-1}) × S_{t-s}</p><p>Where s is the seasonal period (4 for quarterly data), Y_t is the actual value at time t, and F_t is the forecast.</p><h3><strong>Our Forecasting Project</strong></h3><p>We’ll be working with quarterly sales data for 5 years (20 periods). Our goal is to:</p><ol><li>Initialize the model using the first 4 periods (one complete seasonal cycle)</li><li>Calculate level, trend, and seasonal factors for all remaining periods</li><li>Generate in-sample forecasts and calculate forecast accuracy</li><li>Optimize α, β, and γ parameters to minimize Mean Squared Error (MSE)</li><li>Forecast the next 4 quarters using the optimized model</li></ol><p>Let’s dive in.</p><h3>Step 1: Setting Up Your Excel Spreadsheet</h3><p>Start by creating a table with the following columns:</p><ul><li>Year (1 to 5)</li><li>Quarter (Q1, Q2, Q3, Q4 repeating)</li><li>Period (1 to 20)</li><li>Actual Sales (Y_t)</li><li>Base Level (E_t)</li><li>Trend (T_t)</li><li>Seasonal Factor (S_t)</li><li>Forecast (F_t)</li></ul><p>Next, create cells for your smoothing parameters α, β, and γ and set these to 0.3, 0.1, and 0.3 as starting values. We will later change these to get optimal values that minimize the Mean Squared Error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*a43wuBy2Di8-RW6hAsnlBA.png" /></figure><h3>Step 2: Initialize the First Seasonal Cycle</h3><p>For Holt-Winters, we need to establish initial values for level, trend, and seasonal factors using the first complete seasonal cycle (periods 1–4).</p><p><strong>Initial Level (E_4):</strong><br>Calculate the average of the first 4 periods:<br> L_1 = (Y_1 + Y_2 + Y_3 + Y_4) / 4</p><p>Copy the formula for the first 4 periods to get L_1, L_2, L_3 and L_4</p><p><strong>Initial Trend (T_4):</strong><br>We will assume the initial trend to be 0.</p><p><strong>Initial Seasonal Factors (S_1 to S_4):</strong><br> Divide each actual value by the initial level:<br> S_1 = Y_1 / L_4<br> S_2 = Y_2 / L_4<br> S_3 = Y_3 / L_4<br> S_4 = Y_4 / L_4</p><p>These initial seasonal factors should ideally sum to approximately 4 (the number of seasons). If they don’t, normalize them by dividing each by their average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*_1m6Dqd_wG4-D4UQv9PF6Q.png" /></figure><h3>Step 3: Calculate Components for Remaining Periods</h3><p>Starting from period 5, apply the Holt-Winters equations recursively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*Ib85qV0B9RS7d3wh2y39LA.png" /></figure><p><strong>For period 5:</strong></p><p>Level: E_5 = α × (Y_5 / S_1) + (1 - α) × (E_4 + T_4)</p><p>Trend: T_5 = β × (E_5 - E_4) + (1 - β) × T_4</p><p>Seasonal Factor: S_5 = γ × (Y_5 / E_5) + (1 - γ) × S_1</p><p>Continue this process for periods 6 through 20, remembering that:</p><ul><li>When calculating level for period t, use the seasonal factor from period t-4</li><li>When calculating the new seasonal factor for period t, update the factor from period t-4</li><li>Make sure to fix the parameter cells α, β, and γ when dragging the formula down for each period</li></ul><h3>Step 4: Generate Forecasts</h3><p>The forecast for each period is calculated using the previous period’s level and trend, multiplied by the appropriate seasonal factor from 4 periods ago.</p><p><strong>For period 5:</strong><br> F_5 = (L_4 + T_4) × S_1</p><p><strong>For period 6:</strong><br> F_6 = (L_5 + T_5) × S_2</p><p>And so on. Note that for periods 1–4, you won’t have forecasts since these are used for initialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*txTVuZHyG0EeVMleXBJyMg.png" /></figure><h3>Step 5: Calculate Forecast Errors</h3><p><strong>Mean Squared Error (MSE):</strong></p><p>We will now calculate the MSE. Create a clearly labeled cell for MSE and use the formula to calculate the error term:</p><p>=SUMXMY2(H7:H22,D7:D22)/COUNT(H7:H22)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rrIoN0qZh2VCgKPE3--Pw.png" /></figure><p>Place this MSE calculation in a clearly labeled cell — this is what we’ll minimize next.</p><h3>Step 6: Optimize Parameters with Excel Solver</h3><p>Now comes the powerful part. We’ll use Excel Solver to find the optimal values of α, β, and γ that minimize our MSE.</p><p><strong>To set up Solver:</strong></p><ol><li>Go to Data tab → Solver (if you don’t see it, enable it in Excel Add-ins)</li><li>Set Objective: Select your MSE cell</li><li>To: Min (minimize)</li><li>By Changing Variable Cells: Select the cells containing α, β, and γ</li><li>Add Constraints:</li></ol><ul><li>β ≥ 0, β ≤ 1</li><li>γ ≥ 0, γ ≤ 1</li></ul><ol><li>Select solving method: GRG Nonlinear</li><li>Click Solve</li></ol><ul><li>α ≥ 0, α ≤ 1</li><li>β ≥ 0, β ≤ 1</li><li>γ ≥ 0, γ ≤ 1</li></ul><p>6. Select solving method: GRG Nonlinear<br>7. Click Solve</p><p>Solver will iteratively adjust α, β, and γ until it finds the combination that produces the lowest MSE. This typically takes just a few seconds.</p><h3>Step 7: Forecast Future Periods</h3><p>With optimized parameters, we can now forecast periods 21–24 (the next 4 quarters).</p><p><strong>For period 21 (Q1):</strong></p><p>Level: L_21 = L_20 + T_20 (no new actual data, so level continues with trend)</p><p>Trend: T_21 = T_20 (trend remains constant)</p><p>Forecast: F_21 = (L_20 + T_20) × S_17 (use seasonal factor from 4 periods ago)</p><p><strong>For periods 22–24:</strong></p><p>Continue extending the level and trend while rotating through the seasonal factors:</p><ul><li>Period 22 uses S_18</li><li>Period 23 uses S_19</li><li>Period 24 uses S_20</li></ul><p>These forecasts represent your best prediction for the next year of quarterly sales based on the historical patterns captured by the model.</p><h3>Interpreting Your Results</h3><p>Once your model is built and optimized, look at:</p><p><strong>Optimal smoothing parameters:</strong> High α values mean the model reacts quickly to changes in level. High β values mean rapid adjustment to trend changes. High γ values indicate quickly adapting to seasonal pattern shifts.</p><p><strong>MSE value:</strong> Lower is better. Compare this to other forecasting methods to assess relative performance.</p><p><strong>Forecast plots:</strong> Graph your actual values alongside forecasts. The forecasts should track the actual values reasonably well, capturing both the trend and seasonal patterns.</p><p><strong>Future forecasts:</strong> These extend your learned patterns forward. Remember, they assume the future will behave like the past — a key limitation of all statistical forecasting methods.</p><h3>Tips and Best Practices</h3><p><strong>Check your initial values:</strong> Poor initialization can lead to suboptimal results. Ensure your initial seasonal factors are reasonable and sum to approximately s (the number of seasons).</p><p><strong>Validate your model:</strong> Consider holding out the last few periods as a test set, building the model on the remaining data, and checking forecast accuracy on the holdout set.</p><p><strong>Watch for overfitting:</strong> If your optimized parameters are at the extreme boundaries (0 or 1), your model may be overfitting to noise.</p><p><strong>Consider additive seasonality:</strong> If seasonal variations remain constant in absolute terms (rather than growing with the level), try the additive version of Holt-Winters instead.</p><p><strong>Combine with judgment:</strong> Statistical forecasts should inform, not replace, human judgment. Consider external factors, market changes, and business knowledge when making final predictions.</p><h3>Conclusion</h3><p>The Holt-Winters multiplicative seasonality model is a robust and practical forecasting tool that balances simplicity with sophistication. By building it from scratch in Excel, you gain deep insight into how exponential smoothing methods work and can customize the approach to your specific needs.</p><p>The combination of Excel’s formula capabilities and Solver’s optimization power makes this a practical solution for real-world forecasting problems — no specialized software required. Whether you’re forecasting revenue, demand, web traffic, or any other metric with trend and seasonality, this method provides a solid foundation for data-driven decision making.</p><p>Now it’s your turn. Grab some time series data, fire up Excel, and start forecasting!</p><p>You can access the complete excel file here:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db960dc035d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time-Series Forecasting Made Simple: A Practical Introduction]]></title>
            <link>https://medium.com/@hadia.rbutt/time-series-forecasting-made-simple-a-practical-introduction-214614768fe0?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/214614768fe0</guid>
            <category><![CDATA[holt-winters]]></category>
            <category><![CDATA[moving-average]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[exponential-smoothing]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 17:23:18 GMT</pubDate>
            <atom:updated>2025-12-23T17:23:18.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gQbozE7Uk6eYaO-EyHnuA.png" /></figure><p>Forecasting is a technique to make an estimate of what will happen tomorrow, next quarter or next year. From a business point of you, knowing how the market will be can be crucial for planning</p><p>There are generally two approaches to forecasting: qualitative and quantitative. Qualitative forecasting methods involve subjective inputs coming from consumer surveys, retail staff, managers or experts and are based on what’s called <em>soft </em>information (personal opinions, hunches etc). Quantitative methods to forecasting, on the other hand, are all based on <em>hard</em> data including (but not limited to) historical sales, pricing information, amount spent on advertising etc. While there are multiple forecasting techniques, my focus for this piece was on the quantitative forecasting methods, particularly time-series forecasting.</p><p>Time-series data is a special type of data collected in regular time intervals including hourly, daily, weekly or monthly. Hourly temperature, daily gold prices, weekly stock prices and monthly sales are all examples of time-series data. Each time-series is unique depending on features like trend, seasonality or cyclical patterns. Some series have an upward trend, while others have quarterly seasonality. The choice of an algorithm then depends on the type of time-series on hand.</p><p>While there are multiple forecasting techniques, the focus of this article is on the quantitative forecasting methods, particularly the time-series forecasting. The objective is to explain the basic concepts and give a gentle introduction of different time-series forecasting models so that you are prepared to run your first forecasting model.</p><p><strong>Stationary vs Non Stationary</strong></p><p>A time series is called stationary if its statistical properties — such as mean, variance, and autocorrelation — remain constant over time. In simple terms, the data fluctuates around a stable level without long-term upward or downward movement. Non-stationary time series, on the other hand, show trends, changing variance, or evolving patterns over time. Most real-world business data (like sales or revenue) is non-stationary, which is why identifying and handling non-stationarity is a critical first step in forecasting.</p><p>Before diving into stationary models, it is important to understand two fundamental components of time-series data: <strong>trend</strong> and <strong>seasonality</strong>. A <strong>trend</strong> represents the long-term direction of a series, showing whether values are generally increasing, decreasing, or remaining stable over time — such as steadily rising sales as a business grows. <strong>Seasonality</strong>, on the other hand, refers to repeating patterns that occur at regular intervals, like higher retail sales every December or increased electricity usage during summer months. Identifying trend and seasonality early helps determine which forecasting models are appropriate and how the data should be modeled.</p><p>Now let’s look at some of the common forecasting models for stationary data:</p><p><strong>1. Simple Moving Average</strong></p><p>The Simple Moving Average method forecasts future values by taking the average of a fixed number of the most recent observations. Each data point in the window is given equal importance. This method helps smooth out short-term fluctuations and highlight the underlying level of the series, making it useful when the data has no clear trend or seasonality.</p><p><strong>2. Weighted Moving Average</strong></p><p>A Weighted Moving Average is similar to the simple moving average, but it assigns different weights to past observations. Typically, more recent data points are given higher weights because they are assumed to be more relevant for predicting the future. This approach allows the model to respond more quickly to recent changes while still smoothing out noise.</p><p><strong>3. Exponential Smoothing</strong></p><p>Exponential Smoothing improves upon moving averages by applying exponentially decreasing weights to older observations. This means recent data has a much stronger influence on the forecast, while older data still contributes but at a diminishing rate. It is simple, efficient, and widely used in practice when the time series has no trend or seasonality.</p><p><strong>4. Seasonality: Additive vs Multiplicative</strong></p><p>Seasonality refers to repeating patterns at fixed intervals, such as monthly or quarterly effects. In additive seasonality, the seasonal effect remains constant in size over time (for example, sales increase by a fixed amount every December). In multiplicative seasonality, the seasonal effect grows or shrinks with the level of the series (for example, December sales are always 20% higher than average). Choosing the correct form is important for building accurate models.</p><p>Next, we will dive into some of the forecasting models for non-stationary data:</p><p><strong>1. Holt’s Double Exponential Smoothing</strong></p><p>Holt’s method, also known as Double Exponential Smoothing, extends simple exponential smoothing by explicitly modeling both the level and the trend of a time series. This makes it suitable for data that shows a consistent upward or downward movement over time but does not exhibit seasonality.</p><p><strong>2. Holt Winters Additive Seasonality</strong></p><p>The Holt-Winters Additive model further extends Holt’s method by incorporating seasonality, assuming the seasonal effect remains constant over time. It models three components: level, trend, and additive seasonality. This approach works well for series where seasonal fluctuations do not increase as the overall level of the data grows.</p><p><strong>3. Holt Winters Multiplicative Seasonality</strong></p><p>The Holt-Winters Multiplicative model is designed for time series where seasonal patterns change proportionally with the level of the data. Instead of adding a fixed seasonal effect, the model multiplies the level by a seasonal factor. This is especially useful for business data like sales, where seasonal spikes tend to grow as the business scales.</p><p><strong>Measuring Forecasting Accuracy</strong></p><p>To evaluate how well a forecasting model performs, we commonly use <strong>Mean Squared Error (MSE)</strong> as a measure of accuracy. MSE calculates the average of the squared differences between the actual values and the forecasted values, penalizing larger errors more heavily. In simple terms, it tells us how far our predictions are from reality, on average. A lower MSE indicates a better-fitting model, making it useful for comparing multiple forecasting approaches on the same dataset. Because it is easy to compute and interpret, MSE is often one of the first metrics used to assess and refine forecasting models.</p><p><strong>Conclusion</strong></p><p>Forecasting is as much about understanding your data as it is about choosing the right model. Before jumping into complex algorithms, it is crucial to identify whether your time series has a trend, seasonality, or both. Simple models like moving averages and exponential smoothing often perform surprisingly well and serve as excellent baselines.</p><p>Time-series forecasting does not require advanced mathematics to get started. By breaking a series into level, trend, and seasonal components, we can build intuitive models that are easy to interpret and implement. As your data becomes more complex, these foundational methods prepare you to explore more advanced techniques such as ARIMA, SARIMA, or modern tools like Facebook Prophet.</p><p>If you are new to forecasting, the best way to learn is by experimenting. Start small, visualize your data, try multiple models, and compare their performance. Forecasting is an iterative process — and every model you run brings you one step closer to understanding what the future might hold.</p><p>If you’d like to learn more, check out my other articles on Forecasting:</p><ul><li><a href="https://medium.com/@hadia.rbutt/forecasting-101-a-beginners-guide-into-time-series-forecasting-in-r-bc094ff97fb1">Forecasting 101 — A beginner’s guide into time-series forecasting in R</a></li><li><a href="https://medium.com/@hadia.rbutt/heres-how-you-can-forecast-for-multiple-products-an-r-introduction-7a606a4d5b00">Here’s how you can forecast for multiple products — An R introduction</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=214614768fe0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Theory to Practice: Implementing Multilinear Regression in Python — A step by step guide for…]]></title>
            <link>https://medium.com/@hadia.rbutt/from-theory-to-practice-implementing-multilinear-regression-in-python-a-step-by-step-guide-for-91f74af6fa44?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/91f74af6fa44</guid>
            <category><![CDATA[multilinear-regression]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 19:41:02 GMT</pubDate>
            <atom:updated>2025-10-26T20:46:46.889Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Theory to Practice: Implementing Multilinear Regression in Python — A step by step guide for beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pbv-DlpzDu-6f2a5" /><figcaption>Photo by <a href="https://unsplash.com/@davfts?utm_source=medium&amp;utm_medium=referral">David Pupăză</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Regression is one of the most popular predictive modelling machine learning algorithms used to predict future outcomes based on varying relationships between dependent and independent variables. This article aims to illustrate the step by step process used to conduct a simple multilinear regression analysis in Python.</p><p>The article assumes basic familiarity with python, jupyter notebooks and the fundamental regression concepts. In case you are not familiar with these preliminaries, you can refer to the links at the bottom of this article to bring yourself up to speed with the basics.</p><p>This analysis has been conducted on <strong>Ford Cars</strong> dataset that can be accessed <a href="https://www.kaggle.com/datasets/hadiabutt98/ford-used-cars">here</a>. The dataset consists of approximately 18,000 observations/rows and 9 columns containing a mix of categorical and numerical data regarding features of different Ford cars. Overall, the core objective of the analysis was to determine if there existed a statistically significant relationship between the independent variables such as fuel type, transmission, engine size, mileage etc. and the dependent variable price and subsequently to quantify the impact of such features/explanatory variables on the response variable price.</p><p><strong>Step 1: Loading the required libraries</strong></p><p>As the first step, a jupyter notebook was created and the essential python libraries were loaded. At this point, only the libraries relevant for data exploration were imported including pandas, numpy and matplotlib. The read_excel function was used to read the Ford dataset in the notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnnaxTn0paeJaW39PP30rg.png" /></figure><p><strong>Step 2: Exploratory Data Analysis (EDA)</strong></p><p>As the next step of the analysis, data exploration was done to understand the data with regards to its statistical properties. However, before performing EDA, some structure based pre-processing and cleaning was done. This included removal of white spaces, conversion of data into correct data types, removal of duplicate entries, filling missing data and treating outliers.</p><p><a href="https://medium.com/@hadia.rbutt/data-detox-how-to-streamline-your-dataset-for-a-successful-analysis-c04fb9cb13ec">You can find the detailed article on how to perform these exact steps involved in data preparation here.</a></p><p>Once the data was appropriately cleaned, the next step was to get a basic summary of <strong>descriptive statistics </strong>to understand the patterns in the data. The summary table was built to view the descriptive statistics such as mean, standard deviation, median, minimum, and maximum values. These are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*qeLcWuxvQDEFYh5KrpVBsw.png" /></figure><p>Following insights were drawn from the summary table:</p><ol><li>engineSize had a mean value of 1.35 and a low standard deviation of 0.39 indicating that the data was mostly centered around the mean. As the median was less than the mean value, it meant that our data was right-skewed. Moreover, initially, there was a large difference between the 75th percentile and the max value indicating presence of outliers which was fixed.</li><li>The mean price of used cars in the dataset was $12,197 while the standard deviation was $4459 indicating that once again, data was centered around the mean. Median value of price was slightly less than the mean which meant data on price was right skewed as well.</li><li>The mean mileage of cars was 22454 while the standard deviation was quite high at 16421 meaning that the data was spread out and there was some variation.</li><li>Tax column had an average of 135 and a low standard deviation of 21.09 which meant the data was mostly spread around the mean.</li><li>Mpg column had a mean of 57.9 and low standard deviation of 9.7 which meant most of the data was spread around the mean value. The mean and median values were close to each other implying that the data was symmetrical.</li></ol><p>After an assessment of the numerical variables, the <strong>3 categorical variables</strong> were analyzed: transmission type, fuel type and model type. Following insights were gathered from the charts:</p><ol><li>Fiesta was the most frequently occurring model followed by Focus, Kuga and EcoSport.</li></ol><pre>#Frequency of model<br>plt.figure(figsize=(15,5))<br>#sns.color_palette(&quot;Set2&quot;)<br>sns.countplot(x = &#39;model&#39;, data = df, order = df[&#39;model&#39;].value_counts().index, palette= &quot;husl&quot;, edgecolor=&#39;black&#39;)<br>plt.xticks(rotation=60,fontsize=12)<br>plt.xlabel(&quot;Car Model&quot;,fontsize=15)<br>plt.ylabel(&quot;Frequency&quot;,fontsize=15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkS7nJGK6ezy5Edoe0vdAg.png" /></figure><p>2. Approximately 15,000 cars had a manual transmission, 1300 cars had an automatic transmission while 1000 cars had a semi-auto transmission.</p><pre>#bar plot for transmission<br>plt.figure(figsize=(10,5))<br>sns.countplot(x=&#39;transmission&#39;, data=df, order = df[&#39;transmission&#39;].value_counts().index, palette=&#39;husl&#39;,edgecolor=&#39;black&#39;)<br>plt.xticks(rotation=0,fontsize=12)<br>plt.xlabel(&quot;Transmission Type&quot;,fontsize=15)<br>plt.ylabel(&quot;Frequency&quot;,fontsize=15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*r_EXOh5XUAcHiLNMulPe_w.png" /></figure><p>3. About 12,000 cars had petrol as their fuel type while 6,000 had diesel as their fuel type. Cars with hybrid and electric fuel type were very less. Therefore, these were combined into one variable “other” such that we only had 3 fuel types: petrol, diesel and others.</p><pre>#combine electric and hybrid cars as &quot;other&quot;<br>df[&#39;fuelType&#39;] = df[&#39;fuelType&#39;].replace([&#39;Hybrid&#39;, &#39;Electric&#39;,&#39;Other&#39;], &#39;Other&#39;)<br><br>#bar plot for Fuel Type<br>plt.figure(figsize=(10,5))<br>sns.countplot(x=&#39;fuelType&#39;, data=df,palette=&quot;husl&quot;, edgecolor=&#39;black&#39;)<br>plt.xticks(rotation=0,fontsize=12)<br>plt.xlabel(&quot;Fuel Type&quot;,fontsize=15)<br>plt.ylabel(&quot;Frequency&quot;,fontsize=15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*YHvE6_oqBSwSANGz3P4Usg.png" /></figure><p>Next,<strong> bivariate analysis</strong> was conducted and correlation matrix was built to understand the relationship between the numerical variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*_64SwmhvlbsWb87NzgEmjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*jpx5dUuS837plKhbvntICA.png" /></figure><p>The following insights were drawn from the heat map above:</p><ol><li>Price had positive correlation with engineSize and a lower positive correlation with tax whereas it had a higher negative correlation with Mileage and lower negative correlation with mpg.</li><li>engineSize had a lower positive correlation with mileage and tax and a lower negative correlation with mpg.</li><li>Fuel type had an impact on price. Cars with fuelType as Diesel were slightly more expensive than petrol.</li><li>Transmission type also affected the car price. Automatic cars were the most expensive while cars with Semi-Auto and Manual transmissions were less expensive.</li></ol><p><strong>Step 3: Building the Regression Model</strong></p><p>Once the exploratory data analysis was done, the next step was to build a regression model. A multilinear regression model was built as number of independent variables was more than 1. The dependent variable was price while variables including engineSize, mileage, mpg, fuelType and transmission were used as our independent variables. Dummy variables were also created for categorical data such as fuel type and transmission. Additionally, the data was divided in training and test sets with test size as 30%.</p><p>At this point, relevant libraries required to run a regression analysis in python were loaded. Essentially, the sklearn and the statsmodel libraries were used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*g_7-ulV-EfyoWL7MncUQqQ.png" /></figure><p>Additionally, in order to include categorical variables in our regression model, they were converted into dummy variables using the pandas get_dummies function. As fuelType and transmission were the categorical variables that had to be encoded, these were used in the get_dummies function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LwlY9KxCb7UmTcXSlyumzQ.png" /></figure><p>It is important to note that one of the dummy variables for each category was dropped before including the variables in the regression model to avoid multicollinearity amongst these variables. This was because keeping all three levels for both categories (petrol, diesel and others for fuelType and automatic, manual and semi-auto for transmission) would have provided no extra information to us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtlFykUwJXfUQvyGXDUJjw.png" /></figure><h4><strong>Model 1:</strong></h4><p>The first model, <strong>linear_model1, </strong>was built using both our numerical and categorical variables. The <strong>statsmodels library</strong> with the <strong>Ordinary Least Squares</strong> module was used. The data was also split into training and test sets to measure prediction accuracy later on. The model was built on the training set and tested on the test set. Training set included 70% of the data and the test set included 30% of the data.</p><pre>#Train-Test Split<br>x_train, x_test, y_train, y_test = train_test_split(regression_data1, regression_data1[&#39;price&#39;],test_size=0.3, random_state=0)</pre><pre>#building the multilinear regression model<br>linear_model1 = smf.ols(formula=&#39;price ~ engineSize + mileage + mpg + tax + fuelType_Petrol + fuelType_Diesel + transmission_Automatic + transmission_Manual&#39;, <br>                    data = x_train).fit()<br>print(linear_model1.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*n8aD2XOslmBtX-T9En5dzw.png" /></figure><h4>Interpretation:</h4><p>Our first regression model indicated a <strong>high adjusted R-squared value of 0.625</strong>. This meant that our model explained approximately 63% of variance in the prices. The value of our <strong>F-statistic was high at 2594</strong> and it was statistically significant with <strong>p-value &lt; 0.05</strong> indicating that our model was able to fit the data well.</p><p>The coefficients of intercept and our independent variables also appeared statistically significant as their p-values were &lt; 0.05 except for the variable transmission_Automatic which had a p-value of 1.62.</p><p>As we dropped the variables <strong>fuelType_Other</strong> and <strong>transmission_Semi-auto</strong>, their combined impact on price was captured in the intercept which meant that the <strong>estimated mean price of a car with fuelType as other and transmission as semi-auto was 23130</strong>. This estimate was significant as the p-value was &lt; 0.05.</p><h4>Model coefficients:</h4><ol><li>The coefficient of <strong>engineSize</strong> was 2215 which indicated that with every unit increase in engine size the price of car would go up by 2215.</li><li>The coefficient of a car with <strong>fuelType_Diesel</strong> was <strong>-4040</strong> indicating that the estimated mean price of cars with diesel fuel type was 4040 less than the estimated mean price of cars with fuel type as other. Thus, the estimated mean price of <strong>Diesel car was 23130–4040 = 19,090</strong>. This made intuitive sense as the ‘other’ category included electric and hybrid cars which are generally more expensive.</li><li>Similarly, the coefficient of a car with transmission as <strong>Manual</strong> was <strong>-302</strong> indicating that the estimated mean price of cars with transmission as Manual was 302 less than the mean price of cars with transmission as semi-auto. Thus, the estimated mean <strong>price of a manual cars was 23130–302 = 22828</strong>. This also made intuitive sense as cars with manual transmission are less expensive than cars with automatic or semi-auto transmissions.</li></ol><h4>Regression Equation:</h4><p>Our regression model’s equation was as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*dyUTjAlr0r3iBUqArKqaOg.png" /></figure><h4>Prediction Accuracy:</h4><p>One of the major uses of regression analysis are their ability to predict</p><p>Next, the prediction accuracy of the model was calculated using metrics such as Root Mean Squared Error (RMSE), Mean Absolute Error (MAE) and Mean Squared Error (MSE).</p><p>We will calculate the accuracy for both training and test sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFGbrrHM_jvQUX4TmeH5YA.png" /></figure><p>The training set had a Mean Absolute Error of 2158 and a Mean squared Error of 7575629. The Root Mean Squared Error was 2752 which meant that on average, the model predictions of price are off by $2752.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoOgcC0RaRl9NRb_vuBKZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYTr-BOnN1Zlg_zwgSTU0Q.png" /></figure><p>The test set had a Mean Absolute Error of 2121 and a Mean squared Error of 7273331. The Root Mean Squared Error was 2696 which meant that on average, the model predictions of price in the unseen test data are off by $2696. As this is close to the metrics for training set, it’s a good model.</p><p>Next, the variable <strong>transmission_Automatic</strong> was dropped as it wasn’t statistically significant to see if the value of our adjusted R-squared improves.</p><h4>Model 2:</h4><pre>#building the multilinear regression model<br>linear_model2 = smf.ols(formula=&#39;price ~ engineSize + mileage + mpg + tax + fuelType_Diesel + fuelType_Petrol + transmission_Manual&#39;, <br>                    data = x_train).fit()<br>print(linear_model2.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*sWkhwjS3V1BQt8LNLyWMLg.png" /></figure><h4>Interpretation:</h4><p>The 2nd regression model indicated that our adjusted R-squared did not improve when we removed the variable transmission_Automatic from our model. This meant that our model still explained approximately 63% of variance in the prices. However, the value of our <strong>F-statistic has improved to 2963</strong> and it was statistically significant with <strong>p-value &lt; 0.05</strong> indicating that our model was able to fit the data better as compared to model 1.</p><p>The coefficients of intercept and all our independent variables also appeared statistically significant as their p-values were &lt; 0.05.</p><p>The intercept or the estimated mean price of a car with fuelType as other and transmission as semi-auto was now <strong>23310</strong>. This estimate was significant as the p-value was &lt;0 .05.</p><h4>Model coefficients:</h4><ol><li>The coefficient of <strong>engineSize </strong>was 2217 which indicated that with every unit increase in engine size the price of car would go up by 2217.</li><li>The coefficient of a car with <strong>fuelType_Diesel </strong>was <strong>-4107.3</strong> indicating that the estimated mean price of cars with diesel fuel type was 4107.3 less than the estimated mean price of cars with fuel type as other. Thus, the estimated mean price of <strong>Diesel car was 23310–4107.3 = 19,202</strong>. This made intuitive sense as ‘other’ category included electric and hybrid cars which are generally more expensive.</li><li>Similarly, the coefficient of a car with transmission as <strong>Manual</strong> was now <strong>-422.6</strong> indicating that the estimated mean price of cars with transmission as Manual was 422 less than the mean price of cars with transmission as semi-auto. Thus, the estimated mean <strong>price of a manual cars was 23310–422.6 = 22887.4</strong>.</li></ol><h4>Regression Equation:</h4><p>Our regression model’s new equation was as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*0MzocZ-BCg6hMZr2J4yWaw.png" /></figure><h4>Prediction Accuracy:</h4><p>Similarly, the error metrics were used once again to check the prediction accuracy of this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0-t2DSAWb0_C40ayBmO1g.png" /></figure><p>The training set with model 2 had a Mean Absolute Error of 2158 and a Mean squared Error of 7577242. The Root Mean Squared Error is also 2752 which means that on average, the model predictions of price were off by $2752. These were also close to the metircs for model 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ATyevGUWWOzylQmeo7i3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDMVAo49_muDRXlBY2IVEA.png" /></figure><p>The test set had a Mean Absolute Error of 2121 and a Mean squared Error of 7273331. The Root Mean Squared Error was 2696 which meant that on average, the model predictions of price in the unseen test data were off by $2696. As this was close to the metrics for training set, it’s a good model. The values are also similar to those of Model 1 which means both models had similar accuracy.</p><p>At this point, we stopped the iterations of models considered Model 2 as our final model.</p><p><strong>Limitations and Recommendations</strong></p><p>One key limitation of the models created was that even when statistically non-significant variable was removed, the value for adjusted R-squared did not improve. While F-statistic improved slightly, the overall adjusted R-sqaured of 0.63 is not a sufficiently large given that a good adjusted R-squared lies between 0.8–0.9.</p><p>Additional data points such as the age of the car or customer purchase decision could have been used to predict the probability of a customer purchasing a used car.</p><p>Nonetheless, such a regression model can be used by stakeholders like car dealerships to appropriately price used cars such that cars with bigger engine sizes could be priced higher than those with smaller engine sizes. The quantified impact of other variables can also be used to take pricing decision.</p><p>To further assist business managers, additional machine learning technique of K-means clustering could be used to create segments of customers based on car prices so that targeted campaigns could be run highlighting the right product features for the right customer group.</p><p>Regression Basics: <a href="https://www.analyticsvidhya.com/blog/2021/05/all-you-need-to-know-about-your-first-machine-learning-model-linear-regression/">https://www.analyticsvidhya.com/blog/2021/05/all-you-need-to-know-about-your-first-machine-learning-model-linear-regression/</a></p><p>Jupyter Notebooks Basics: <a href="https://www.audiolabs-erlangen.de/resources/MIR/FMP/B/B_Jupyter.html">https://www.audiolabs-erlangen.de/resources/MIR/FMP/B/B_Jupyter.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91f74af6fa44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Detox: How to Streamline Your Dataset for a Successful Analysis]]></title>
            <link>https://medium.com/@hadia.rbutt/data-detox-how-to-streamline-your-dataset-for-a-successful-analysis-c04fb9cb13ec?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c04fb9cb13ec</guid>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 19:36:53 GMT</pubDate>
            <atom:updated>2024-02-17T19:43:38.906Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Detox: How to Clean Your Dataset for a Successful Analysis</h3><p>There’s a fundamental principle in the field of data science: Garbage in, garbage out. If the input data is inaccurate, incomplete, or inconsistent (i.e., “garbage”), then the output produced by any analysis or model based on that data will also be unreliable or flawed (“garbage”).</p><p>In practical terms, this means that even the most sophisticated algorithms and analytical techniques will yield incorrect or misleading results if they are fed with poor-quality data. Data cleaning, preprocessing, and validation are essential steps to mitigate the risks associated with garbage in, garbage out and to ensure the integrity and reliability of the results produced by data-driven processes. Therefore, it is crucial for data scientists and analysts to ensure that the first steps that they perform when analyzing data are around the cleanliness, accuracy, and relevance of the data they use for analysis.</p><p>In this article I will be going over 5 data cleaning steps in python that are essential to streamline any dataset for analysis. While these steps are fairly simple, they will go a long way in ensuring reliable and accurate results.</p><p>I will be using Ford Cars dataset that can be accessed <a href="https://www.kaggle.com/datasets/hadiabutt98/ford-used-cars">here</a>.</p><p><strong>Load the libraries</strong></p><p>As the first step, we will load the required libraries and import the raw data in our jupyter notebook:</p><pre>#loading the relevant libraries<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from matplotlib import pyplot<br><br>#importing raw data<br>df = pd.read_excel(&quot;ford.xlsx&quot;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*pfYkRyV5ef1DQQtk6OqUJA.png" /></figure><p>Our dataset contains 17,966 observations (rows) and 9 columns that can be seen above. The data is a mixture of numerical and categorical data points.</p><p><strong>Number 1: Check the data type and null values</strong></p><p>Next, we will use the <strong>df.info ()</strong> function to inspect the data type of our variables. Ensuring the correct data type allows for easier data manipulation. For examples, calculations such as mean/median/ standard deviation can not be performed on string data and so any numerical variable stored as a string will first have to be converted to an appropriate data type. Following are the key data types with examples:</p><ol><li>Integer: 3,4,5</li><li>Float: 3.4, 5.6</li><li>Object/String: “Hello”, “Text”</li><li>Date/time: dates and time</li></ol><pre>#check data types<br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*Ssi6DNGNvvSg9IHWXNpQQg.png" /></figure><p>The above result shows the following:</p><ol><li>The class of the data is dataframe.</li><li>2 columns are of the type float (engine size, mpg).</li><li>4 columns are of type integer (year, price, mileage and tax).</li><li>3 columns are of type object/string (model, transmission, fuelType).</li><li>There are no missing/null values.</li></ol><p>As the year column is stored as an integer, we will convert it into a date/time object as appropriate.</p><pre>#Convert data type of year from integer to date<br>df[&#39;year&#39;] = pd.to_datetime(df[&#39;year&#39;], format=&#39;%Y&#39;)</pre><p><strong>Number 2: Check Duplicate entries</strong></p><p>Duplicate values impact the performance of analytical models and as they create noise in the data, we will remove them.</p><pre>#identify and remove duplicates<br>duplicates = df[df.duplicated(keep = &#39;last&#39;)]<br>duplicates</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6W_ckdUUDS1RJcUKAAsSmw.png" /></figure><p>The table above shows that there are 154 duplicate rows and so these will be removed using the <strong>drop_duplicates()</strong> function. We are now left with 17812 observations after removing the duplicate entries:</p><pre>#154 entires are duplicates, so we will remove them <br>df = df.drop_duplicates(keep=&#39;last&#39;)<br>df.shape<br><br>(17812, 9)</pre><p><strong>Number 3: Check for unnecessary white space</strong></p><p>Sometimes, <em>column names</em> and <em>column values </em>of type string tend to have blank spaces either before or after the text which can be excessively annoying especially when calling a particular column or visualizing data. For this purpose, it is a good practice to get rid of all such white spaces.</p><p>To identify any white spaces in column names, I simply used the <strong>list()</strong> function to get a list of names to inspect for any blank space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*Oy-S3nGK5fj5PUVDsF0wBQ.png" /></figure><p>The output above shows that there are no leading or trailing whitespaces in the names and so they appear correct.</p><p>We will now look for any blank spaces in column values. I combined the unique() and ravel() functions to inspect all the unique string values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*Do-i3XiwBUvonRsZQptipA.png" /></figure><p>The output above shows there are some blank spaces in model names. As a result the model ‘focus’ appears twice. I used the <strong>str.strip()</strong> function to remove the whitespaces in the model column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*hZJfGhw32WIVbefHtiRnQQ.png" /></figure><p>So far, we have cleaned the more apparent aspects of our data such as ensuring correct data types, removing duplicates and white spaces and checking for null values. However, there are some additional checks we need to make sure there are no bogus entries our data. We will use the information from summary statistics to analyze that. The<strong> describe()</strong> function has been used to get the descriptive statistics table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*kWTYbu8elrxP-bVHpngz-g.png" /></figure><p>The above table highlights 3 important points to be addressed. These are as follows:</p><ol><li>The year column has a max value of 2060 which appears to be a wrong entry and therefore needs to be removed.</li><li>The engineSize and tax columns have a minimum value of 0 which does not appear intuitive.</li><li>There appear to be some outliers in the price, mileage and mpg columns that need to be addressed.</li></ol><p><strong>Number 4: Check minimum and maximum values</strong></p><p>In order to fix the maximum value of 2060 in year column, we will simple remove those row/rows from the data using the <strong>drop()</strong> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*Rp39FhHpNraoheT4vLy8kQ.png" /></figure><p>As there was only 1 row with year as 2060, dropping this observation did not have any significant impact on the data.</p><p>Next, we need to treat the minimum value of 0 in engize size and tax columns. A value of 0 appears counterintuitive as it is not possible for a car to have engine size as 0 or no tax amount. Therefore, it needs to be addressed. There are 2 ways this can be done:</p><ol><li>Drop the rows where the value for engineSize and tax is 0.</li><li>Replace the zero with another value — mean/mode/median</li></ol><p>It is important to note here that simply removing the rows may not be a wise approach in this case as it might shrink the size of data leaving less data available for analysis. Hence, we will first look at the number of instances where the value of 0 appears in engineSize and tax columns. The occurances of 0 have been converted to blanks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*xL4xv8OMcvMyNAulUcYpdA.png" /></figure><p>While the number of 0s in the engineSize and tax columns is not significant and dropping the rows may not create any significant issues, we will use the fillna method to replace the blanks with an appropriate value.</p><p>An important consideration when deciding the <strong>method</strong> to use to fill missing values (i.e mean, mode or median), is to see if there are any <strong>outliers in the columns</strong>. Looking for outliers is important because outliers inflate/deflate the mean values making them less representative of the actual possible value. In case of outliers in the data, we can not rely on mean values to fill in the missing spaces.</p><pre>#boxplot for engine size<br>sns.boxplot(data=df[[&#39;engineSize&#39;]], orient=&#39;v&#39;)<br>plt.show()<br><br>#boxplot for tax<br>sns.boxplot(data=df[[&#39;tax&#39;]], orient=&#39;v&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*_HepUn2Vh9aKkqrtv2JHAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*_TpDASVXl-YAooJV-4MsaQ.png" /></figure><p>There appear to be some outliers in both the columns. Therefore, filling the missing values using mean may not be appropriate. Consequently, <strong>we will use median values to fill the missing data</strong>. To make the replacement as close as possible to the actual, an additional consideration has been made with regards to filling the data as follows:</p><ol><li>Missing values for engineSize are filled by <strong>grouping together model and fuelType columns</strong> so missing values with similar combination of model and fuelType are filled accordingly.</li><li>Missing values for tax are filled by <strong>grouping together model and year columns</strong> for the same reason as above.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*BOuByuQKdMOiJ9TW01ba3w.png" /></figure><p>Running the above code releaved that one missing value still remains in the engineSize column. We will just drop that remaining 1 row.</p><p>Moving on to the tax column, asimilar approach has been used to fill the values in the tax column. The combination of model and year is taken with the assumption that for a particular model in a given year, the value of tax will not be starkly different and so using these values will ensure they are to some extent representative of what the actual value would have been.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*LsUhjTodBPVd3K5ZOTxdpg.png" /></figure><p>We will look at the data summary again. The table below shows that our minimum values for engineSIze and tax columns have been changed from 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*1WWPojLkyshRxDeDg3w84A.png" /></figure><p>So far, we have adjusted our data to account for incorrect minimum and maximum values. We will now move on to identifying and treating outliers in the data.</p><p><strong>Number 5: Check for Outliers</strong></p><p>It is important to identify and treat any outliers in our data as they can cause unnecessary noise and distort the results. One approach to identify the outliers is the Inter Quartile Range method. With this method we will set upper and lower bounds by multiplying our interquartile value with 1.5. We will then add this value to the 75th percentile value and subtract from 25th percentile value to get our upper and lower limits respectively. Eventually, any values beyond these limits will be treated as outliers.</p><p>These updates have been made for each numerical variable in our descriptive_stat table as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*LRc_90d8Rk8OhR30aaE4xw.png" /></figure><p>After setting the upper and lower limits, we will now count the number of values greater than or less than these limits. These values have been calculated below and then stored as a list and then finally attached with our descriptive_stat column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*l5FSl_xACu-Qf7P1DFaOEg.png" /></figure><p>As the table above shows, the number of outliers is highest in the tax column followed by mileage and price. After identifying these, the next step is to remove these extreme values from our data. There are multiple options available to remove these outliers such as:</p><ol><li>removing the rows with outliers</li><li>replace the outlier values with mean/median/mode like we did for missing values above</li><li>flooring and capping the values</li></ol><p>We will use the <strong>flooring and capping</strong> technique to treat for outliers such that:</p><ul><li>All the values smaller than Lower Bound values will be assigned value of Lower Bound</li><li>All the values larger than Upper Bound values will be assigned value of Upper Bound</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*1pLLkt2rQP2i5I0glXuGoQ.png" /></figure><p>After making the above changes, we will look at the summary statistics table once again with the changes updated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*rnWi9DRnhB2khOFFAVFNYw.png" /></figure><p>The dataset is now ready to use. As a next step, this cleaned data can be used for different techniques such as clustering or regression. <a href="https://medium.com/@hadia.rbutt/from-theory-to-practice-implementing-multilinear-regression-in-python-a-step-by-step-guide-for-91f74af6fa44">You can read more about it here</a> where I used this data to build a multilinear regression model to predict the price of a car given various explanatory variables such as engineSize, transmission and fuelType.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c04fb9cb13ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Here’s how you can forecast for multiple products — An R introduction]]></title>
            <link>https://medium.com/@hadia.rbutt/heres-how-you-can-forecast-for-multiple-products-an-r-introduction-7a606a4d5b00?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a606a4d5b00</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[holt-winters]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 09:22:19 GMT</pubDate>
            <atom:updated>2023-08-19T16:15:22.393Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forecasting with multiple time series — An R introduction</h3><p>Advantages to forecasting are many. With excessive proliferation of media and technology and resultantly a rapidly changing consumer behavior, a business that appropriately forecasts is far better than one which doesn’t. A data-driven approach to forecasting helps to develop a realistic understanding of needs and demands of tomorrow enabling cross-functional teams to accurately plan inventories, set retail targets, make staffing and budgeting decisions, build relevant pricing and promotion strategies and consequently save up on multiple associated costs. Forecasting allows for better demand anticipation and helps reduce uncertainties.</p><p>In my previous <a href="https://medium.com/@hadia.rbutt/forecasting-101-a-beginners-guide-into-time-series-forecasting-in-r-bc094ff97fb1">post</a>, I presented a brief introduction into some of the most commonly used forecasting algorithms along with their implementation is R using time series data for one specific vitamin sold at one store. You can read it below:</p><p><a href="https://medium.com/@hadia.rbutt/forecasting-101-a-beginners-guide-into-time-series-forecasting-in-r-bc094ff97fb1">Forecasting 101 — A beginner’s guide into time-series forecasting in R</a></p><p>As far as measuring accuracy of forecasting models or showcasing implementation of a model was concerned, such an analysis made sense.</p><p>However, in the real world neither do businesses have one product nor do they have one store. And so one might ask, in the presence of this multi-store multi-brand situation, what are some of the tools and algorithms available to forecast for more than one product? This question essentially formed the basis of this project where I explored ways to forecast with multiple SKUs using simple libraries available in R. The Holt Winters triple exponential smoothing has been used as the forecasting algorithm for this analysis.</p><p>The focus of this article is on the R methods of building a forecasting model that predicts future demand with reasonable accuracy for more than 1 product. The data used for this analysis contains units sold for an online gummy production company. It contains 2 years of data for 8 SKUs.</p><h3><strong>The R implementation</strong></h3><p>As a first step, the required libraries were loaded. For this analysis, apart from the starter libraries like tidyverse and forecast, additional libraries such as <a href="https://business-science.github.io/tidyquant/">tidyquant</a>, <a href="https://business-science.github.io/timetk/">timetk</a> and <a href="https://business-science.github.io/sweep/articles/SW00_Introduction_to_sweep.html">sweep</a> have been used.</p><pre>## Read required libraries<br>library(readxl)<br>library(forecast)<br>library(tidyverse)<br>library(tidyquant)<br>library(timetk)<br>library(sweep)</pre><p>The dataset was then loaded and the basic R functions such as view(), head() and str() were used to get a quick glance at the data features.</p><pre>#Read the dataset<br>sales &lt;- read_excel(&quot;gummies_sold.xlsx&quot;, sheet = &quot;all_data&quot;)<br><br>head(sales)<br><br># A tibble: 6 × 3<br>  Month               Sales SKU        <br>  &lt;dttm&gt;              &lt;dbl&gt; &lt;chr&gt;      <br>1 2021-04-01 00:00:00   944 gummy_bunny<br>2 2021-05-01 00:00:00  1180 gummy_bunny<br>3 2021-06-01 00:00:00   944 gummy_bunny<br>4 2021-07-01 00:00:00   944 gummy_bunny<br>5 2021-08-01 00:00:00   948 gummy_bunny<br>6 2021-09-01 00:00:00  1035 gummy_bunny<br><br>str(sales)<br><br>tibble [192 × 3] (S3: tbl_df/tbl/data.frame)<br> $ Month: POSIXct[1:192], format: &quot;2021-04-01&quot; &quot;2021-05-01&quot; &quot;2021-06-01&quot; &quot;2021-07-01&quot; ...<br> $ Sales: num [1:192] 944 1180 944 944 948 ...<br> $ SKU  : chr [1:192] &quot;gummy_bunny&quot; &quot;gummy_bunny&quot; &quot;gummy_bunny&quot; &quot;gummy_bunny&quot; ...<br></pre><p>Data overview revealed the following:</p><ol><li>The data had 192 rows (24 months of data for 8 SKUs) and 3 columns called Month, Sales and SKU</li><li>The class of this dataset was a tibble</li><li>The data type of the Month column was POSIXct which was converted to a date object</li><li>Sales had the numeric data type and SKU wass of type character. These were kept as they were</li></ol><p>Next, the data type of the ‘month’ column was converted to date using the as.Date function from the zoo package.</p><pre>#convert month column to type Date<br>sales$Month &lt;- as.Date(sales$Month, &quot;%Y-%m-%d&quot;)</pre><p>The data was already quite clean and so no further data cleaning steps were performed. The line chart below plots the monthly sale of the gummies from 2021 to 2023.</p><pre>#visualize<br>ggplot(sales, aes(x = Month, y = Sales, group = SKU)) +<br>  geom_line(aes(color = SKU), size = 0.75) +<br>  geom_point(aes(color = SKU), size = 0.95) + labs(<br>    title = &quot;Gummies: Units Sold&quot;,<br>    subtitle = &quot;Data from 2021 to 2023&quot;)+<br>  theme_tq()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYCHnLU_50LEV3j3gbkbEA.png" /></figure><p>Next step involved fitting a forecasting algorithm on all the 8 products contained in the dataset. Sales data for each of the 8 SKUs was converted to a time series object. However, before that, the nest function was used to club the data for 8 SKUs together.</p><pre>#nest the data<br>sales_nest &lt;- sales %&gt;%<br>  group_by(SKU) %&gt;%<br>  nest()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*QT5m7EMwZH-YKfpcwm14AQ.png" /></figure><p>Once the dataset was nested, the map function from the purrr library was used to apply the tk_ts function (from the timetk library) to each element of the tibble to convert it into a time series object.</p><pre>#convert to ts<br>sales_ts &lt;- sales_nest %&gt;%<br>  mutate(data.ts = map(.x       = data, <br>                       .f       = tk_ts, <br>                       select   = -Month, <br>                       start    = c(2021,4),<br>                       freq     = 12))</pre><p>Within the map function, the following arguments were used:</p><ol><li>.x: the data to apply a function to</li><li>.f: the function to apply to each element</li><li>select: specify which columns to select to convert to time series. In this case, -Month was used to exclude it from the columns to apply the function on. Alternatively, Sales column could have been specified as well.</li><li>start: to indicate the start date of the data. In this case, it was April 2021 and so, (2021,4) was specified</li><li>freq: frequency specifies the time interval after which the pattern repeats. As this was a monthly data, frequency of 12 was used. Other possibilities include frequency = 4 for quarterly data or frequency = 52 for weekly data.</li></ol><p>The sales_ts dataframe can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*GSMyJY2fIgPVxmOzLDM5mA.png" /></figure><p>Next, the Holt Winters exponential smoothing algorithm was fit on this time series data. The map function was used again. The results were stored in the dataframe called sales_fit and the fitted values were stored in a list in the column fit.HoltWinters:</p><pre>#fit an exponential smoothing algorithm<br>sales_fit &lt;- sales_ts %&gt;%<br>  mutate(fit.HoltWinters = map(.x = data.ts,<br>                               .f = HoltWinters))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*VGZT3lzyNgrtiSOH3T2Fbg.png" /></figure><p>In order to view the model coefficients and the parameters used by the Holt Winters algorithm, the sw_tidy function from the sweep package was used.</p><pre>#tidying<br>tidydata &lt;- sales_fit %&gt;%<br>  mutate(tidy = map(fit.HoltWinters,sw_tidy))  %&gt;%<br>  unnest(tidy) %&gt;%<br>  spread(key = SKU, value = estimate)</pre><p>The values for alpha, beta and gamma were selected by the algorithm automatically to account for the unique seasonal and trend components of each of the 8 time series.</p><p>Next, the glance and the augment functions from the sweep package were used to take a look at the error metrics and the residuals respectively.</p><pre>#check model accuracy<br>glancedata &lt;- sales_fit %&gt;%<br>  mutate(glance = map(fit.HoltWinters, sw_glance)) %&gt;%<br>  unnest(glance)<br><br>glancedata&lt;- glancedata[,c(1, 5,6,10:16)]<br><br>#check fitted and residual values<br>augmentdata &lt;- sales_fit %&gt;%<br>  mutate(augment = map(fit.HoltWinters, sw_augment, timetk_idx = TRUE, rename_index = &quot;date&quot;)) %&gt;%<br>  unnest(augment)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*Ny-pN6dd73GVxVzbkqqUog.png" /></figure><p>The error metrics gave us an insight into the performance of the model. The MPE for all the time series was quite low. Similarly, in terms of MAPE, any value between 10%-25% is considered as acceptable accuracy and our model had the MAPE within this range for almost all of the 8 products.</p><p>While the accuracy metrics such as the mean error or the root mean squared error show how well a model fits the data, it is always recommended to compare these with the accuracy measures from a different model to see which model fits the data best and successfully minimizes the errors.</p><p>The residuals generated using the augment function have been visualized below:</p><pre>augmentdata %&gt;%<br>  ggplot(aes(x = date, y = .resid, group = SKU)) +<br>  geom_hline(yintercept = 0, color = &quot;grey40&quot;) +<br>  geom_line(color = palette_light()[[2]]) +<br>  geom_smooth(method = &quot;loess&quot;) +<br>  labs(title = &quot;Quantity Sold By SKU&quot;,<br>       subtitle = &quot;HoltWinters Model Residuals&quot;, x = &quot;&quot;) +<br>  theme_tq() +<br>  facet_wrap(~ SKU, scale = &quot;free_y&quot;, ncol = 3) +<br>  scale_x_date(date_labels = &quot;%Y&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gx32zqZGoSQl24rFw0b7Jw.png" /></figure><p>Next, a forecast was built for the upcoming 12 months using the fitted model. A combination of map and sw_sweep functions was used to build the forecast and tidy the result. The final result was stored in the dataframe called sales_forecast_tidy.</p><pre>#forecast with the model<br>sales_forecast &lt;- sales_fit %&gt;%<br>  mutate(forecast.HoltWinters = map(fit.HoltWinters, forecast, h = 12))<br>sales_forecast<br><br>#tidy the forecast<br>sales_forecast_tidy &lt;- sales_forecast %&gt;%<br>  mutate(sweep = map(forecast.HoltWinters, sw_sweep, timetk_idx = TRUE)) %&gt;%<br>  unnest(sweep)</pre><p>The resulting data frame contained the actual values, fitted values and the 80% and 95% confidence intervals. The forecasts generated from the model for each of the series has been visualized below:</p><pre>#Visualize the generated forecasts<br>sales_forecast_tidy %&gt;%<br>  ggplot(aes(x = index, y = Sales, color = key, group = SKU)) +<br>  geom_ribbon(aes(ymin = lo.95, ymax = hi.95), <br>              fill = &quot;#D5DBFF&quot;, color = NA, size = 0) +<br>  geom_ribbon(aes(ymin = lo.80, ymax = hi.80, fill = key), <br>              fill = &quot;#596DD5&quot;, color = NA, size = 0, alpha = 0.8) +<br>  geom_line() +<br>  labs(title = &quot;Quantity Sold By SKU&quot;,<br>       subtitle = &quot;Holt Winters Model Forecasts&quot;,<br>       x = &quot;&quot;, y = &quot;Units&quot;) +<br>  scale_x_date(date_breaks = &quot;1 year&quot;, date_labels = &quot;%Y&quot;) +<br>  scale_color_tq() +<br>  scale_fill_tq() +<br>  facet_wrap(~ SKU, scales = &quot;free_y&quot;, ncol = 3) +<br>  theme_tq() +<br>  theme(axis.text.x = element_text(angle = 45, hjust = 1))<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciQkU42kJ5PpH-_L6PZmpQ.png" /></figure><p>The point forecasts (or the predicted sales values) generated from this model were then stored in a new dataframe and exported to excel to share with relevant stakeholders and inform decision making.</p><pre>#write the tidy sales forecast to excel<br>point_forecasts &lt;- as.data.frame(sales_forecast_tidy[,c(1,6:12)])<br>writexl::write_xlsx(point_forecasts,&quot;Point Forecasts.xlsx&quot;)</pre><h3><strong>Conclusion</strong></h3><p>This article served to give a gentle introduction into forecasting with multiple SKUs. This was only a simplified version and there are quite a few other more complex methods and algorithms available. One other method involves using a loop to iterate over multiple time series and fit a model. Some other forecasting algorithms include Prophet, RNN and NBEATS. Another approach involves training a global deep learning forecasting model on multiple time series using forecasting models available within <a href="https://unit8.com/resources/training-forecasting-models/">Darts</a>. Darts is a python library which contains a variety of <a href="https://unit8co.github.io/darts/#forecasting-models">models</a>, from classics such as ARIMA to deep neural networks. It attempts to simplify time series processing and forecasting in Python. You can read up more about Darts <a href="https://medium.com/unit8-machine-learning-publication/darts-time-series-made-easy-in-python-5ac2947a8878">here</a>.</p><p>The dataset along with the complete script used in this post can be accessed <a href="https://github.com/HadiaRButt/forecasting-basics-in-R">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a606a4d5b00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting 101 — A beginner’s guide into time-series forecasting in R]]></title>
            <link>https://medium.com/@hadia.rbutt/forecasting-101-a-beginners-guide-into-time-series-forecasting-in-r-bc094ff97fb1?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc094ff97fb1</guid>
            <category><![CDATA[forecasting-models]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Sun, 28 May 2023 16:58:36 GMT</pubDate>
            <atom:updated>2023-05-29T09:45:57.714Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forecasting 101 — A beginner’s guide into time-series forecasting in R</h3><p>Intrigued by the many forecasting algorithms available and the wide application of forecasting models particularly in the retail space, I recently undertook a project to analyze the performance of some of the most popular forecasting algorithms and assess their accuracy in predicting future sales. The purpose of this article is to introduce these commonly used forecasting algorithms along with their implementation in R followed by some key insights from my analysis.</p><p>This article focuses on a particular kind of quantitative forecasting technique known as the time-series forecasting. Time-series data is a special type of data collected in regular time intervals including hourly, daily, weekly or monthly. Hourly temperature, daily gold prices, weekly stock prices and monthly sales are all examples of time-series data. For the sake of this analysis, I have used the daily sales data of a particular type of vitamin and predicted its sales by fitting 3 different models: Naive, Exponential Smoothing and ARIMA.</p><p>Before delving into the R implementation, following is a quick overview of the 3 methods mentioned above:</p><p><strong>Naive:</strong></p><p>Naive forecasting method, as the name suggests, is the most basic technique which assumes that the forecast in the next period will equal the forecast in the last period. A close variation to the Naive method is the seasonal Naive method which is useful for highly seasonal data. In this case, each forecast is set to be equal to the last observed value from the same season (e.g. the same month of the previous year). Such models, while fairly simple, are important as benchmark models i.e. any more complex model should perform at least better than a Naive model. In line with theoretical simplicity, the implementation of these models in R is fairly simple too.</p><p><strong>Exponential Smoothing:</strong></p><p>Exponential smoothing is a form of a weighted average method whereby past observations are assigned weights such that weights decay exponentially as the observations get older. In other words, recent observations are assigned higher weights and thereby are assumed to be closest and most reflective of future observations. While there are multiple exponential smoothing methods depending on the unique components of a time-series (trend, seasonality, errors), most commonly used exponential smoothing method is the Holt-Winters.</p><p>Another formulation of the exponential smoothing methods is the ETS (Error, Trend, Seasonality) formulation (also known as state-space models) in which the type of model selected is based on the type of error, trend and seasonality. These 3 key components of time-series can take either of the 3 forms — None, Additive, Multiplicative. For example, a time-series could have an additive trend and error with no seasonality. This would be the same as Holt’s linear trend method with additive errors(also referred to as double exponential smoothing). Similarly, another formulation could be additive trend, additive errors and additive seasonality. This is the same as Holt-Winters method with additive errors (or triple exponential smoothing).</p><p><strong>ARIMA:</strong></p><p>ARIMA or autoregressive integrated moving average is another commonly used forecasting algorithm comprised of 3 key parts: autoregressive part, integration part (or the lagged value/difference) and the moving averages part. The autoregressive component models the relationship between the current observation and a specified number of lagged observations. The differencing component transforms the series into a stationary form by taking differences between consecutive observations. The moving average component accounts for short-term dependencies by considering weighted averages of past error terms.</p><p>While the exact specific mathematical formulations of the algorithms discussed above are beyond the scope of this article, the above overview should be sufficient to dive into the implementation in R.</p><p><strong>R Implementation</strong></p><p>The data used for this analysis comprises of daily sales of a multivitamin sold at a particular pharmacy. This is approximately 3 years of data from July 2019–January 2022.</p><p>As a first step, all the required libraries were loaded in R. In case a library is not already installed, it can be done so simply by using the install.packages() function.</p><pre>#Load the required libraries <br>library(readxl)<br>library(ggplot2)<br>library(dplyr)<br>library(forecast)<br></pre><p>Next, the data set was read in the global environment and the head function was used to quickly examine the first 6 entries in the data. You can access the dataset <a href="https://github.com/HadiaRButt/forecasting-basics-in-R">here</a>:</p><pre>#Load the dataset<br>daily_sales &lt;- read_excel(&quot;Daily Vitamin Sales.xlsx&quot;)<br><br><br>head(daily_sales)<br><br>LocationID    Branch Name ProductName    Units sold - packs  TY Net Sls NetSalesIncTax ProductID          Date<br>1     123006     Store A   Vitamin Z                 10          300           2091        A2487         2019-07-01<br>2     123006     Store A   Vitamin Z                  2           60            418        A2487         2019-07-02<br>3     123006     Store A   Vitamin Z                  5          150           1046        A2487         2019-07-03<br>4     123006     Store A   Vitamin Z                  7          210           1464        A2487         2019-07-04<br>5     123006     Store A   Vitamin Z                  4          120            836        A2487         2019-07-05<br>6     123006     Store A   Vitamin Z                  6          180           1255        A2487         2019-07-06<br></pre><p>The dataset was cleaned to only include relevant columns which were the date and the net units. The forecasting models were fit on the units sold variable. Since the other columns are redundant for the sake of this analysis, they were removed.</p><pre>#Remove redundant columns and rename sales units column<br>daily_sales &lt;- daily_sales[,c(8,4)]<br>names(daily_sales)[names(daily_sales) == &quot;Units sold - packs&quot;] &lt;- &quot;sales_units&quot;</pre><p>As a next step, the daily sales were aggregated to monthly sales as monthly forecasts are to be built. The dplyr summarize and group_by functions were used to do this.</p><pre>#sum by month to get monthly data rather than daily<br>daily_sales &lt;- daily_sales %&gt;% <br>  mutate(month = floor_date(daily_sales$Date, &quot;month&quot;))<br><br>monthly_sales &lt;- daily_sales %&gt;% <br>  group_by(month) %&gt;% <br>  summarise(total = sum(sales_units))<br><br>head(monthly_sales)<br><br>  month               total<br>1 2019-07-01 00:00:00   136<br>2 2019-08-01 00:00:00   166<br>3 2019-09-01 00:00:00   136<br>4 2019-10-01 00:00:00   159<br>5 2019-11-01 00:00:00   140<br>6 2019-12-01 00:00:00   141</pre><p>The graphical representation of this monthly data can be seen below:</p><pre>#plot the data to see visually<br>ggplot(monthly_sales, aes(x = month, y = total)) + <br>  geom_line() + scale_x_date(date_breaks = &quot;2 months&quot;, date_labels =&quot;%b-%Y&quot;)+<br>  theme_light()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zkPFnbAqzAKHnSB5nvcPNw.png" /></figure><p>The line graph shows the sales of this particular vitamin from 2019–2022. The following was observed:</p><ol><li>There’s a slightly upward trend in sales.</li><li>There appeared to be some seasonality.</li><li>There were a few peaks and troughs with a sharp increase in sale in June 2020 followed by an equally sharp decline in July 2020. This appeared to be an unusual increase in demand causing a possible out-of-stock situation in the next month.</li></ol><p>Next, the monthly sales data was converted into a time-series object using the ts() function. Decompose function was then used to view the individual components of the series.</p><pre>#convert to time series object and check the individual components <br>monthly_sales_ts &lt;- ts(monthly_sales$total, frequency=12, start=c(2019,7))<br>plot(decompose(monthly_sales_ts))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOjCPF4pJAX0ai896x14xw.png" /></figure><p>The graph above confirms the initial observations regarding trend and seasonality.</p><p>As the next step, 3 forecasting models were fit to see how they compared against each other on the different error metrics. Generally, a model is a good fit if it is able to minimize all the errors (deviation of the fitted value from the actual value). The question then is how much lower should the value of error be for it to be acceptable. The answer is, it depends. It depends on how errors compare in different models. A good model then is one that minimizes the error the most as compared to all other models.</p><p><strong>Model 1: The Naive and Seasonal Naive</strong></p><p>Both the naive and seasonal naive algorithms were used from the forecast package on this series to see how differently they fit. This also served to give benchmark error metrics. Following were the results from the naive method:</p><pre>#fit a naive model<br>fit_naive &lt;- naive(monthly_sales_ts, h=12)<br>print(summary(fit_naive))<br>plot(fit_naive)<br>checkresiduals(fit_naive)<br><br><br>Forecast method: Naive method<br><br>Model Information:<br>Call: naive(y = monthly_sales_ts, h = 12) <br><br>Residual sd: 89.7587 <br><br>Error measures:<br>                   ME     RMSE      MAE       MPE     MAPE      MASE       ACF1<br>Training set 1.897701 89.75868 60.87701 -4.031236 24.99235 0.6122053 -0.3510192<br><br>Forecasts:<br>         Point Forecast       Lo 80    Hi 80      Lo 95    Hi 95<br>Jan 2022       191.0333   76.002962 306.0637   15.10956 366.9571<br>Feb 2022       191.0333   28.355823 353.7108  -57.76045 439.8271<br>Mar 2022       191.0333   -8.205114 390.2718 -113.67558 495.7422<br>Apr 2022       191.0333  -39.027409 421.0941 -160.81421 542.8809<br>May 2022       191.0333  -66.182396 448.2491 -202.34418 584.4108<br>Jun 2022       191.0333  -90.732380 472.7990 -239.89014 621.9568<br>Jul 2022       191.0333 -113.308421 495.3751 -274.41721 656.4839<br>Aug 2022       191.0333 -134.321688 516.3884 -306.55423 688.6209<br>Sep 2022       191.0333 -154.057780 536.1244 -336.73798 718.8046<br>Oct 2022       191.0333 -172.724639 554.7913 -365.28648 747.3531<br>Nov 2022       191.0333 -190.479247 572.5459 -392.43981 774.5065<br>Dec 2022       191.0333 -207.443561 589.5102 -418.38449 800.4512<br></pre><p>As the naive method assumes that the next forecast value equals the last forecast value, the 12 period forecast was all predicted as 191 units. The model had a mean error of 1.89 while the root mean squared error (RMSE) of 89.7. The rest of the error measures can be seen above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*LXJDAuC5KSHi_JTK6SPsZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*EVUZ2qZ5aiXCgOKaqzrKlw.png" /></figure><p>An analysis of the residuals revealed the following:</p><ol><li>While the time plot indicated some random fluctuations around zero at the start of the series, some systematic patters were observed in the later part indicating that the model did not capture all the information.</li><li>A check for outliers revealed that there were extreme values in the residuals which were not accounted for by the model. These outliers could also be seen in the histogram with extreme values at both ends.</li><li>Given that the time series exhibited slight seasonality, the residuals also exhibited systematic patterns related to seasonality in the later part of the series. These seasonal patterns in the residuals indicated that the model was not adequately capturing the seasonal component of the data.</li><li>Assessment of volatility revealed that over time, the variation of residuals increased and these fluctuations in the residuals suggest that the model was not effectively capturing the variability in the data.</li><li>The ACF plot showed that none of the spikes fell outside the confidence interval indicating that the residuals were independent and not correlated. However, the alternating behavior of the autocorrelation coefficients in the ACF plot revealed that there was some seasonal pattern in the residuals which meant that the model was not capturing all the seasonal information in the data.</li></ol><p>Hence, it was concluded that, the naive method did not fit the series well.</p><p>Given that the time series exhibited some seasonality as confirmed by our decomposed time-series and the residual plots, as a next step, a seasonal naive model was fit on the data. The results were as follows:</p><pre>#fit a seasonal naive model<br>fit_snaive &lt;- snaive(monthly_sales_ts, h=12)<br>print(summary(fit_snaive))<br>plot(fit_snaive)<br>checkresiduals(fit_snaive)<br><br><br>Forecast method: Seasonal naive method<br><br>Model Information:<br>Call: snaive(y = monthly_sales_ts, h = 12) <br><br>Residual sd: 119.828 <br><br>Error measures:<br>                   ME    RMSE      MAE      MPE     MAPE MASE      ACF1<br>Training set 49.92778 119.828 99.43889 14.25757 39.23952    1 0.1867912<br><br>Forecasts:<br>         Point Forecast     Lo 80    Hi 80       Lo 95    Hi 95<br>Jan 2022       274.0667 120.50089 427.6324  39.2080752 508.9253<br>Feb 2022       235.0000  81.43422 388.5658   0.1414085 469.8586<br>Mar 2022       356.0000 202.43422 509.5658 121.1414085 590.8586<br>Apr 2022       378.6667 225.10089 532.2324 143.8080752 613.5253<br>May 2022       306.0000 152.43422 459.5658  71.1414085 540.8586<br>Jun 2022       198.0000  44.43422 351.5658 -36.8585915 432.8586<br>Jul 2022       230.1000  76.53422 383.6658  -4.7585915 464.9586<br>Aug 2022       266.0000 112.43422 419.5658  31.1414085 500.8586<br>Sep 2022       298.5000 144.93422 452.0658  63.6414085 533.3586<br>Oct 2022       208.3333  54.76755 361.8991 -26.5252581 443.1919<br>Nov 2022       173.0000  19.43422 326.5658 -61.8585915 407.8586<br>Dec 2022       191.0333  37.46755 344.5991 -43.8252581 425.8919</pre><p>As the seasonal naive method sets each forecast to the last observed value from the same season, the next 12 period forecast was all predicted as values in the last 12 periods. This model had a mean error of 49.9 while the root mean squared error (RMSE) of 119.8. The rest of the error measures can be seen above.</p><p>While these errors were all higher when compared to the naive method, however, given the presence of seasonality and the analysis of residuals, the naive method did not seem to be a very robust model for this series. The forecast generated from the seasonal naive model along with residual plots can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*49NrOvYl32eP2FpcFFTAgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*ycmdKq0bzRCfw_eL2EH0Aw.png" /></figure><p>An analysis of the residuals from the seasonal naive method revealed the following:</p><ol><li>The fluctuation of the residuals was mostly around zero with exception of a few error terms due to the presence of outliers in the data.</li><li>Assessment of volatility revealed that over time, the variation of residuals was more or less the same.</li><li>The ACF plot showed that there were no significant spikes and the autocorrelation coefficients hovered around zero suggesting that the residuals were independent and uncorrelated, indicating a good fit of the model.</li><li>The histogram of residuals appeared to be left-skewed which meant that the residuals had a longer tail on the left side, suggesting unusually large negative residuals.</li></ol><p>Based on the above analysis, the seasonal naive model has been used as the benchmark model and all upcoming models have been compared against this model.</p><p>Next, ETS models have been fit on the time-series.</p><p><strong>Model 2: The ETS Method</strong></p><p>Having fit a basic seasonal naive model, the next step was to test a more advanced algorithm on the time series and evaluate its performance and prediction accuracy. Hence, an ETS model was fit. As highlighted above, ETS is a state-space exponential smoothing model with multiple variations according to the components of the time-series. Given the unique combination of trend, error and seasonality, 18 possible models can be fit within the ETS framework. However, 3 different models were tested to see which fit the time-series the best.</p><p>The R implementation of an ETS model is quite simple. The ets() function is used to fit an ETS model. In R, when defining the model to be fit, each component (error, trend and seasonality) can take 3 possible values — none, additive or multiplicative. R also has a nice feature which automatically selects the type of error, trend and seasonality by simply calling the letter “Z”. So, for example, “ANN” is simple exponential smoothing with additive errors, no trend and no seasonality. “MAM” is multiplicative Holt-Winters’ method with multiplicative errors, additive trend and additive seasonality and so on. 3 different combinations of models were used to see how well each of them performed.</p><pre>#fit 3 ets models AAA, ZZZ, MAM<br>fit_ets1 &lt;- ets(monthly_sales_ts, model = &quot;AAA&quot;)<br>fit_ets2 &lt;- ets(monthy_sales_ts, mode = &quot;ZZZ&quot;)<br>fit_ets3 &lt;- ets(monthy_sales_ts, mode = &quot;MAM&quot;)<br><br>print(summary(fit_ets1))<br>print(summary(fit_ets2))<br>print(summary(fit_ets3))<br><br><br><br>Training set error measures:<br>              sigma      ME     RMSE      MAE       MPE     MAPE      MASE      ACF1<br>ets1 - &quot;AAA&quot;: 114.046 1.685794 77.90835 44.63025 -3.638205 19.18534 0.4488208 0.1780448<br>ets2 - &quot;ZZZ&quot;: 77.707  7.925332 75.07239 47.27516 -2.208781 18.95189 0.4754192 0.07365344<br>ets3 - &quot;MAM&quot;: 0.2713 -15.83236 112.3259 42.52546 -10.18379 20.04101 0.4276542 0.0668796</pre><p>The residual plots along with the forecasts generated from this model can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*xj7SPLtn2xOsbd-wNh4FSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*FhQNmJ_qdhqmOM9QFM0drw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*L1m24UhZnO3IpnBPmMH8ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*unbw1W8zr-8NEUwN0nsdZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*zAVrBqihzusSNSwXgfPUtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*35fxHO3ZKrSybZNFrm0wYQ.png" /></figure><p>3 ETS models were fit and the following was inferred from the model summary and residual plots:</p><ol><li>A comparison of the summary of the 3 models showed that the model with multiplicative errors, additive trend and multiplicative seasonality had the lowest sigma value indicating lower variability or dispersion of the residuals. It suggested that the model fit the data well and the residuals exhibitedd less scatter around the predicted values.</li><li>Similarly, in terms of the training set error measures, the “MAM” model had the lowest values for ME, MAE, MPE and MASE indicating it was a better performing model when compared to others. These values were even lower than the error terms from the seasonal naive method which meant it was a better model and fit the data well.</li><li>An analysis of model residuals showed that the error terms were mostly fluctuating around the zero with no significant spikes in autocorrelation coefficients. This implied that the model captured the variation well and the residuals were independent and uncorrelated, indicating a good fit model.</li></ol><p>Next, an ARIMA was fit as the last algorithm.</p><p><strong>Model 3: The ARIMA Method</strong></p><p>As a final step, an Arima model was fit to see if it performed better than the seasonal naive and ETS models tested above.</p><pre>#fit the Arima <br>fit_arima &lt;- auto.arima(monthly_sales_ts, d=1, D=1, stepwise = FALSE, approximation = FALSE, trace = TRUE)<br>print(summary(fit_arima))<br>checkresiduals(fit_arima)<br><br>Training set error measures:<br>        sigma     ME     RMSE    MAE       MPE     MAPE      MASE       ACF1<br>ARIMA   118.9  -13.726 86.86947 40.022 -9.343383 17.84043 0.4024783 0.07645897</pre><p>The auto.arima() function from the forecast package was used which iterated over multiple combinations of coefficients for each of the component of the ARIMA (p,q,d) model. The best model chosen was ARIMA(0,1,1). In this case, the AR component (p) was 0, indicating that there were no lagged dependent variables included in the model. The differencing component (d) was 1, suggesting that the data has been differenced once to achieve stationarity. The MA component (q) was 1 as well, indicating that there had been one lagged moving average term included in the model.</p><p>The residual plots from the ARIMA model can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*Y6lEhEFKng1BlqIwMHvxmA.png" /></figure><p>The following can be said about the prediction accuracy:</p><ol><li>In terms of training set error measures, while the value of sigma was highest when compared against ETS models, the ARIMA had the lowest MAE, MAPE and MASE. It performed similar to other models in terms of other error terms with no significant deviation.</li><li>An analysis of the residuals revealed that there was less variation in the errors with errors mostly around zero.</li><li>The autocorrelation plot showed that the correlation coefficients were within the confidence interval which meant that the residuals are independents.</li></ol><p>The graphical representation of all the models together is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIWen-_bPeTP-hH2bRXA8g.png" /></figure><p><strong>Conclusion</strong></p><p>To summarize, this article covered a brief theory and R implementation of some of the most popular forecasting algorithms. While the exact choice of a model depends on the type of business/industry and the type of time-series data at hand, this article only served as a starting point if you are looking to explore the universe of time series forecasting. I call it a universe because the more you research about it, the more complex it gets and so a thorough understanding of the basics is crucial to building more advanced forecasting models such as neural network models, LSTM or N-BEATS.</p><p>You can get the complete script file along with the dataset uploaded on Github <a href="https://github.com/HadiaRButt/forecasting-basics-in-R">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc094ff97fb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Into the Tidyverse — 3 basic packages to get started in R]]></title>
            <link>https://medium.com/@hadia.rbutt/into-the-tidyverse-3-basic-packages-to-get-started-in-r-55f1a6111eb9?source=rss-6603b31526c------2</link>
            <guid isPermaLink="false">https://medium.com/p/55f1a6111eb9</guid>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[tidyverse]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[r-programming]]></category>
            <dc:creator><![CDATA[Hadia Butt]]></dc:creator>
            <pubDate>Tue, 02 May 2023 16:18:53 GMT</pubDate>
            <atom:updated>2023-05-02T16:18:53.379Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Into the Tidyverse — 3 basic packages to get started in R</strong></h3><p>If you are someone with even the slightest experience with programming in R (or python), you would be familiar with the concept of packages. Even if you are not, by the end of this article, you will know what packages are, where they are used and why they are so helpful.</p><p>Packages (also known as libraries) are nothing but a set of functions and tools developed for neat and quick data analysis, manipulation and visualization. They help keep your code crisp, helping you avoid longer and messy code blocks.</p><p>When I first started learning R, I came across a few very useful packages which I continue to use today for almost all my data science projects. With some research and coding experience, I later found out that they all belonged to one big family called the tidyverse. Developed by Hadley Wickham, tidyverse is an exhaustive collection of packages in R designed to make data manipulation and visualization easier and more consistent. In this article, I will be introducing<strong><em> 3 basic core tidyverse</em></strong> packages with examples that can help you get started with your data analysis projects in R. The examples used are beginner level so even if you don’t have any prior coding experience, you will still be able to follow along.</p><p>I will use the built in iris dataset to demonstrate these packages and functions. The iris dataset contains measurements on 4 attributes for 50 flowers from 3 species. These attributes are sepal length, sepal width, petal length and petal width. We can view the first six entries of the iris data set using the built-in head() function in R:</p><pre>#Store the iris dataset as variable &#39;myiris&#39; <br>myiris &lt;- iris<br><br>#View the firt 6 entries in the Iris dataset with the head function<br>head(myiris)<br><br>  Sepal.Length Sepal.Width Petal.Length Petal.Width Species<br>1          5.1         3.5          1.4         0.2  setosa<br>2          4.9         3.0          1.4         0.2  setosa<br>3          4.7         3.2          1.3         0.2  setosa<br>4          4.6         3.1          1.5         0.2  setosa<br>5          5.0         3.6          1.4         0.2  setosa<br>6          5.4         3.9          1.7         0.4  setosa</pre><p>We will now head towards the 3 core tidyverse packages — readr, dplyr and ggplot2.</p><p><strong>1. readr</strong></p><p>The <a href="https://readr.tidyverse.org/">readr </a>package is a part of the tidyverse in R, and is designed to make it easy to read structured data files into R. Reading data files is usually the first step in any data analysis project. The readr package provides a set of functions that are faster and more efficient than R’s built-in functions for reading data including read.csv() and read.table(). It is used to read rectangular data from delimited files such as comma-separated values (CSV) and tab-separated values (TSV).</p><p>I will use the readr functions to read the iris dataset (saved as iris.csv in my working directory) in R.</p><pre>#Install the library<br>install.packages(&quot;readr&quot;)<br><br>#load the library/package<br>library(readr)<br><br># read the CSV file into R using read_csv()<br>myiris &lt;- read_csv(&quot;iris.csv&quot;)<br><br># print the data<br>myiris<br><br>  Sepal.Length Sepal.Width Petal.Length Petal.Width    Species<br>1            5.1         3.5          1.4         0.2     setosa<br>2            4.9         3.0          1.4         0.2     setosa<br>3            4.7         3.2          1.3         0.2     setosa<br>4            4.6         3.1          1.5         0.2     setosa<br>5            5.0         3.6          1.4         0.2     setosa<br>6            5.4         3.9          1.7         0.4     setosa<br>7            4.6         3.4          1.4         0.3     setosa<br>8            5.0         3.4          1.5         0.2     setosa<br></pre><p>Sometimes, we may want to import data which is in a format other than a csv. This could be an excel file or even a google sheet. In R, we can conveniently read files with different formats. One way to read an excel file is to use the read_excel() function from the <a href="https://readxl.tidyverse.org/">readxl </a>package. To read data from a google sheet in R, we can use the <a href="https://googlesheets4.tidyverse.org/">googlesheets4 </a>package (also a part of the tidyverse). There’s one additional step involved where we will need to authenticate with Google in order to access the googlesheet.</p><p>You can explore more functions available within the readr package <a href="https://readr.tidyverse.org/reference/index.html">here</a>.</p><p><strong>2. dplyr</strong></p><p><a href="https://dplyr.tidyverse.org/index.html">dplyr</a> is another important package within the tidyverse that provides a set of functions for manipulating large data sets. Key functions of the dplyr package include filter(), select(), mutate(), summarise() and arrange().</p><pre>##Install the dplyr package<br>install.packages(&quot;dplyr&quot;)<br><br>##load the package<br>library(&quot;dplyr&quot;)</pre><p>The <strong>filter()</strong> function of the dplyr package allows you to subset a dataset by selecting specific rows that meet certain conditions. You can also specify multiple conditions on the dataset at once according to the information required.</p><pre>#Use the filter function to filter rows with species as &#39;versicolor&#39;<br>versicolor &lt;- filter(myiris, Species == &quot;versicolor&quot;)<br><br>head(versicolor)<br><br>  Sepal.Length Sepal.Width Petal.Length Petal.Width    Species<br>1          7.0         3.2          4.7         1.4 versicolor<br>2          6.4         3.2          4.5         1.5 versicolor<br>3          6.9         3.1          4.9         1.5 versicolor<br>4          5.5         2.3          4.0         1.3 versicolor<br>5          6.5         2.8          4.6         1.5 versicolor<br>6          5.7         2.8          4.5         1.3 versicolor<br><br>#Use the filter function to filter rows with species as &#39;versicolor&#39; and<br>#petal width greater than 1.5<br><br>versicolor_petal &lt;- filter(myiris, Species == &quot;versicolor&quot; &amp; Petal.Width &gt;1.5)<br><br>#print the data<br>versicolor_petal<br><br> Sepal.Length Sepal.Width Petal.Length Petal.Width    Species<br>1          6.3         3.3          4.7         1.6 versicolor<br>2          5.9         3.2          4.8         1.8 versicolor<br>3          6.7         3.0          5.0         1.7 versicolor<br>4          6.0         2.7          5.1         1.6 versicolor<br>5          6.0         3.4          4.5         1.6 versicolor</pre><p>Similar to the filter function, the <strong>select()</strong> function allows you to subset the dataset based on specific columns.</p><pre>#Use the select command to select columns sepal length, sepal width and species.<br>sepal_dimensions &lt;- select(myiris, Sepal.Length, Sepal.Width, Species)<br><br>#Alternatively, can also use notation x:y to specify column positions in the <br>#dataframe<br>sepal_dimensions &lt;- select(myiris, 1:2, Species)<br><br>#print the data<br>sepal_dimensions<br><br>  Sepal.Length Sepal.Width    Species<br>1            5.1         3.5     setosa<br>2            4.9         3.0     setosa<br>3            4.7         3.2     setosa<br>4            4.6         3.1     setosa<br>5            5.0         3.6     setosa<br>6            5.4         3.9     setosa<br>7            4.6         3.4     setosa</pre><p>Another important function in the dplyr package is <strong>mutate() </strong>which can be used to create either a completely new column in the dataset or create one based on some calculation on the existing columns.</p><pre>#Use the mutate funtion to create a new column sepal_area which multiplies<br>#sepal length and sepal width<br><br>myiris_sepal_area &lt;- mutate(myiris, sepal_area = Sepal.Length*Sepal.Width)<br><br>#print the data<br>myiris_sepal_area<br><br>    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species sepal_area<br>1            5.1         3.5          1.4         0.2     setosa      17.85<br>2            4.9         3.0          1.4         0.2     setosa      14.70<br>3            4.7         3.2          1.3         0.2     setosa      15.04<br>4            4.6         3.1          1.5         0.2     setosa      14.26<br>5            5.0         3.6          1.4         0.2     setosa      18.00<br>6            5.4         3.9          1.7         0.4     setosa      21.06<br>7            4.6         3.4          1.4         0.3     setosa      15.64</pre><p>An interesting aspect of the dplyr package is that you can combine multiple functions into one line of code by a technique called nesting. While demonstrating this with an example, I will be using the <strong>arrange()</strong> function as well.</p><pre>#Use the nesting method to create a new dataframe with multiple conditions<br><br>updated_iris &lt;- myiris %&gt;% <br>  select(Sepal.Length, Sepal.Width, Species) %&gt;% <br>  filter(Sepal.Length&gt;5 &amp; Sepal.Width&gt;2) %&gt;% <br>  mutate(sepal_area = Sepal.Length*Sepal.Width) %&gt;% <br>  arrange(desc(sepal_area))<br><br>#print the data<br>updated_iris<br><br>    Sepal.Length Sepal.Width    Species sepal_area<br>1            7.9         3.8  virginica      30.02<br>2            7.7         3.8  virginica      29.26<br>3            7.2         3.6  virginica      25.92<br>4            5.7         4.4     setosa      25.08<br>5            5.8         4.0     setosa      23.20<br>6            5.5         4.2     setosa      23.10</pre><p>The above code creates a new data frame, updated_iris which first selects the columns sepal length, sepal width and species and then filters the rows such that sepal length is greater than 5 and width is greater than 2. Next, it calculates the sepal area by multiplying the length and width and stores it in a new column sepal_area. Finally, it arranges the dataset on the sepal_area in a descending order.</p><p>dplyr is a powerful package for some basic but important data manipulation. Additional tools and functions include summarise() to aggregate data and calculate summary statistics and group_by() which can be used to combine data based on categorical variables.</p><pre>#Use the summarise and group_by funtions together to calculate the mean sepal_area<br>mean_area_by_species &lt;- updated_iris %&gt;%<br>  group_by(Species) %&gt;%<br>  summarise(mean_area = mean(sepal_area))<br><br>#printh the data<br>mean_area_by_species<br><br> Species    mean_area<br>1 setosa          19.8<br>2 versicolor      16.9<br>3 virginica       19.8</pre><p>You can explore more functions available within the dplyr package <a href="https://dplyr.tidyverse.org/reference/index.html">here</a>.</p><p><strong>3. ggplot2</strong></p><p><a href="https://ggplot2.tidyverse.org/">ggplot2</a> is a core package in R used for visualizations. It is a newer version of the original ggplot package in R that was created by Hadley Wickham. ggplot2 is a complete rewrite of the original ggplot package, and it provides a more robust and flexible system for creating graphics in R. We will use the iris data set to build some visuals. But first, let’s install the library and load it in R:</p><pre>#Install the package<br>install.packages(&quot;ggplot2&quot;)<br><br>#Load the package<br>library(&quot;ggplot2&quot;)</pre><p>Now, we will start with a basic visualization using ggplot2.</p><pre>#create a basic bar chart<br>ggplot(myiris, aes(x = Species)) + <br>  geom_bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*3PGPmTqiT_d_Bi8fasEiGw.png" /></figure><p>This is a basic bar chart showing the count of flowers for each specie. We can see that for each specie, there are 50 flowers. We simply used the ggplot() function by first specifying our data set and then defining the x aesthetic (x = Species). We also specified a layer using geom_bar() to tell R that we need to build a bar chart. We can add additional components to our chart by simply using the “+” sign and improve how our visualization looks.</p><pre>#add additional components to our basic chart<br>ggplot(myiris, aes(x = Species)) + <br>  theme_bw() +<br>  geom_bar() +<br>  labs(y = &quot;Flower Count&quot;,<br>       title = &quot;Flower count by Specie&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*iEZhAyTOuPK3Jkka4f4fQQ.png" /></figure><p>We have now modified our basic chart to include the y label and a title for our chart. We also specified a theme for our visualization using theme_bw(). There are additional themes available such as theme_linedraw(), theme_light(), theme_classic() etc. You can explore these further in R.</p><p>I will now create a scatterplot to visualize the relationship between 2 flower attributes, sepal length and petal length for each of the 3 species.</p><pre>#create a scatterplot to plot relationship between sepal length and petal length<br>ggplot(myiris, aes(x= Sepal.Length, y=Petal.Length)) + <br>  geom_point()+ theme_bw() + labs(title = &quot;Sepal Length vs Petal Length&quot;)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*LrPIjFgsRyftp3jpzrJeog.png" /></figure><p>This is not very clear at the moment as we can not tell what the relationship between sepal length and petal length for each specie is. We can use the color feature within the aesthetic mapping to give a unique color to each specie. We can also use an additional facet_wrap() function to clearly distinguish the 3 species.</p><pre>#modify our basic scatterplot<br>ggplot(myiris, aes(x= Sepal.Length, y=Petal.Length)) + <br>  geom_point(aes(color= Species)) + facet_wrap(~ Species)+<br>  theme_bw() + labs(title = &quot;Sepal Length vs Petal Length&quot;)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*VOOQw97YUHN0kBucehrmSw.png" /></figure><p>By looking at this visualization, we can now see that there is no visible relationship between petal length and sepal length for setosa. However, there is a positive relationship between these two attributes for versicolor and virginica i.e. as the sepal length increases, the petal length also increases.</p><p>ggplot2 is quite a robust library to build both simple and more complex visualizations. This article only focused on the basic framework necessary to build any visualization. You can find out more about the additional functions available within ggplot <a href="https://ggplot2.tidyverse.org/reference/">here</a>.</p><p><strong>Conclusion</strong></p><p>The tidyverse package is an essential tool for data wrangling and visualization in R. Its collection of packages provides a cohesive set of functions and syntax that are designed to work together seamlessly, making data analysis more efficient and intuitive. The dplyr package, in particular, is a powerful tool for data manipulation, and the ggplot2 package provides an elegant and flexible system for creating high-quality visualizations. The readr package provides a fast and efficient way to read in data from various sources. There are other packages in the tidyverse suite such as <a href="https://tidyr.tidyverse.org/">tidyr</a>, <a href="https://stringr.tidyverse.org/">stringr</a>, and <a href="https://purrr.tidyverse.org/">purr</a> which provide additional functionality for working with data in a <em>tidy </em>format. Overall, the tidyverse package is a valuable asset for any data scientist or analyst working in R.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55f1a6111eb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>