<?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 Cibaca Khandelwal on Medium]]></title>
        <description><![CDATA[Stories by Cibaca Khandelwal on Medium]]></description>
        <link>https://medium.com/@cibacakhandelwal?source=rss-3ef3acb31418------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vorWW5som0HBWZaP</url>
            <title>Stories by Cibaca Khandelwal on Medium</title>
            <link>https://medium.com/@cibacakhandelwal?source=rss-3ef3acb31418------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:47:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cibacakhandelwal/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[Crash Course in Causality Quiz]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-causality-quiz-6208ad59be8a?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/6208ad59be8a</guid>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 20:20:32 GMT</pubDate>
            <atom:updated>2023-04-29T20:20:32.657Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a quiz for the previous articles related to Causality.</p><ol><li><strong>Which of the following is an example of a mediator in a causal relationship?</strong></li></ol><ul><li>a) Smoking causing lung cancer</li><li>b) Physical activity reducing the risk of heart disease</li><li><strong><em>c) Stress causing high blood pressure</em></strong></li><li>d) None of the above</li></ul><p>2. <strong>Which of the following is a limitation of the counterfactual framework for causal inference?</strong></p><ul><li>a) It assumes that all confounding variables have been measured and controlled for.</li><li><strong><em>b) It cannot account for the possibility of reverse causation.</em></strong></li><li>c) It cannot account for the possibility of spurious correlations.</li><li>d) It assumes that the treatment effect is the same for all units in the population.</li></ul><p><strong>3. What is the difference between correlation and causation?</strong></p><ul><li><strong><em>a) Correlation involves a relationship between two variables, while causation involves one variable causing changes in another.</em></strong></li><li>b) Correlation involves one variable causing changes in another, while causation involves a relationship between two variables.</li><li>c) Correlation and causation are interchangeable terms that mean the same thing.</li><li>d) None of the above.</li></ul><p><strong>4. Which of the following is an example of a third variable that could affect the relationship between two variables?</strong></p><ul><li>a) Age</li><li>b) Gender</li><li>c) Education level</li><li><strong><em>d) All of the above</em></strong></li></ul><p><strong>5. Which of the following is an example of a confounding variable?</strong></p><ul><li>a) The amount of sunlight a plant receives</li><li><strong><em>b) The type of fertilizer used on a plant</em></strong></li><li>c) The height of a plant</li><li>d) None of the above</li></ul><p><strong>6. What is a potential outcome?</strong></p><ul><li><strong><em>a) The outcome of an experiment if a certain intervention is implemented</em></strong></li><li>b) The outcome of an experiment if no intervention is implemented</li><li>c) The outcome of a study based on observations of a natural experiment</li><li>d) None of the above</li></ul><p><strong>7. In causal inference, what is the purpose of propensity score matching?</strong></p><ul><li><strong><em>A) To balance covariates between treatment and control groups</em></strong></li><li>B) To estimate the average treatment effect</li><li>C) To ensure random assignment of subjects to treatment and control groups</li><li>D) To identify confounding variables</li></ul><p><em>Explanation: Propensity score matching is a technique used in causal inference to balance covariates between treatment and control groups. It involves creating a score for each subject based on their probability of being assigned to the treatment group, given their covariate values. Subjects in the treatment and control groups with similar propensity scores are then matched, which helps to balance out any differences in covariate distributions between the groups. The purpose of this is to reduce the impact of confounding variables and improve the validity of the estimated treatment effect.</em></p><p><strong>8. A pharmaceutical company is testing a new drug to treat a rare disease. In a clinical trial, patients with the disease are randomly assigned to receive either the new drug or a placebo, and their symptoms are monitored over the course of several weeks. Which of the following best describes the causal relationship being investigated in this scenario?</strong></p><ul><li><strong><em>A) The effect of the new drug on patients’ symptoms</em></strong></li><li>B) The effect of the disease on patients’ health</li><li>C) The effect of the placebo on patients’ symptoms</li><li>D) The effect of the clinical trial on patients’ outcomes</li></ul><p><em>Explanation: In this scenario, the causal relationship being investigated is the effect of the new drug on patients’ symptoms. The drug is the treatment variable, and the symptoms are the outcome variable. By randomly assigning patients to receive either the drug or a placebo, the researchers are controlling for confounding variables and increasing the validity of the estimated treatment effect.</em></p><p><strong>9. A company is testing the effectiveness of a new employee training program to increase productivity. The company measures productivity using the number of tasks completed per hour. They compare the productivity of employees who received the training to those who did not. However, they fail to account for the fact that employees who received the training were also given a new software tool to help them complete tasks more efficiently. This is an example of which common pitfall in causal inference?</strong></p><ul><li><strong><em>A) Failing to control for confounding variables</em></strong></li><li>B) Overfitting the model to the data</li><li>C) Not collecting enough data to achieve statistical significance</li><li>D) Ignoring outliers in the data</li></ul><p><em>Explanation: This scenario is an example of failing to control for confounding variables, as the introduction of the new software tool could potentially influence productivity and bias the estimated treatment effect. To obtain a valid estimate of the causal effect of the training program, the company should control for the effect of the new software tool by adjusting for it in their analysis, either by using regression or another appropriate technique.</em></p><p><strong>10. A study is conducted to investigate the effect of a new drug on blood pressure. The study involves 50 participants who were randomly assigned to either receive the drug or a placebo. After one week, their blood pressure was measured. The results are shown below:</strong></p><ul><li><strong>The mean blood pressure of participants who received the drug was 120 mmHg with a standard deviation of 5 mmHg.</strong></li><li><strong>The mean blood pressure of participants who received the placebo was 130 mmHg with a standard deviation of 6 mmHg.</strong></li></ul><p><strong>What is the estimated average treatment effect (ATE) of the new drug on blood pressure?</strong></p><ul><li>A) 10 mmHg</li><li><strong><em>B) -10 mmHg</em></strong></li><li>C) 1 mmHg</li><li>D) -1 mmHg</li></ul><p><em>Explanation: The estimated ATE is calculated by taking the difference in mean blood pressure between the treatment and control groups. In this case, the estimated ATE is:</em></p><p><em>ATE = mean blood pressure (treatment) — mean blood pressure (placebo) ATE = 120 mmHg — 130 mmHg ATE = -10 mmHg</em></p><p><em>This means that, on average, participants who received the new drug had a blood pressure that was 10 mmHg lower than those who received the placebo.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6208ad59be8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-causality-quiz-6208ad59be8a">Crash Course in Causality Quiz</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crash Course in Causality — A simplified guide to Casual Inference]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-causality-a-simplified-guide-to-casual-inference-4ae146d9700f?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ae146d9700f</guid>
            <category><![CDATA[causality]]></category>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 20:58:48 GMT</pubDate>
            <atom:updated>2023-04-28T20:58:48.442Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash Course in Causality — A simplified guide to Casual Inference</h3><p>This article explains the concept of Causality, terminology related to casual effects and then deep dive into the area of Casual Inference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iymXZmXNkrA7GVPlECpLpQ.jpeg" /><figcaption><a href="https://www.rawpixel.com/image/396163"><strong>Image</strong></a> by <a href="https://www.rawpixel.com/"><strong>rawpixel.com</strong></a></figcaption></figure><p>The above image is the most common example that we come across in our day to day life. Global warming is the caused by the effects of Pollution caused by vehicles and industries, effect of weather changes.</p><p>Here Pollution, weather are the cause while global warming is the effect.</p><h3>Table of contents</h3><ol><li>Introduction</li><li>Terminology</li><li>Basics of Causality</li><li>Potential Outcomes and Counterfactuals</li><li>Casual Assumptions</li><li>Methods of Casual Inferences</li><li>Common Pitfall to avoid</li><li>Evaluation metrics for Casual models</li><li>Conclusion</li><li>References</li></ol><h3>Introduction</h3><p>A cause is something that produces or occasions an effect. Causality describes ideas about the nature of the relations of cause and effect. Causal inference is the thought process that tests whether a relationship of cause to effect exists.</p><p>Causal inference is the process of determining the causal relationship between two variables. It is the study of how one variable affects another variable. For example, in a medical study, causal inference would be used to determine whether a particular treatment caused a particular outcome.</p><p>Causal inference is an essential tool in many fields, including economics, political science, and epidemiology. In this article, we will provide a crash course in causal inference, covering the basics of causality, methods of causal inference, and some common pitfalls to avoid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ex7d9GHw9b8u5md-egF4_A.png" /></figure><h3>Terminology</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*aSjcH-_sCTG4BOVxDgbjEg.png" /></figure><ol><li><strong>Causal effect</strong>: The difference in outcome between a group that receives a treatment and a group that does not receive the treatment.</li><li><strong>Treatment</strong>: The intervention that is being studied or evaluated.</li><li><strong>Outcome</strong>: The variable that represents the outcome of interest in the study.</li><li><strong>Confounding</strong>: The presence of a third variable that is associated with both the treatment and the outcome, making it difficult to determine the true causal effect of the treatment.</li><li><strong>Counterfactual</strong>: The hypothetical outcome that would have occurred if a subject had received a different treatment.</li><li><strong>Randomization</strong>: The process of randomly assigning subjects to treatment and control groups to minimize the impact of confounding variables.</li><li><strong>Propensity score</strong>: A measure of the likelihood of receiving a treatment based on a set of observed confounding variables.</li><li><strong>Standardization</strong>: A statistical technique that adjusts for confounding variables by comparing treatment and control groups with similar distributions of the confounding variables.</li><li><strong>Stratification</strong>: A statistical technique that divides the study population into subgroups based on levels of a confounding variable to compare the treatment and control groups within each subgroup.</li><li><strong>Mediation</strong>: A causal mechanism by which the treatment affects the outcome through an intermediate variable or set of variables.</li></ol><h3>The Basics of Causality</h3><p>Before we dive into the methods of causal inference, it’s essential to understand the basics of causality. Causality is the relationship between two events, where one event is the cause of the other event. There are three essential criteria for causality</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tw8DWzyvmQQx7h7vVBhbHg.png" /></figure><h4>1. Temporal Order</h4><p>The first criterion, temporal order, is relatively straightforward. The cause must come before the effect. For example, if we are studying the effect of smoking on lung cancer, smoking must occur before lung cancer to be considered a cause.</p><h4>2. Covariation</h4><p>This principle states that there must be a relationship between the cause and effect. This means that as the cause changes, the effect should change as well. This principle is important because it helps to establish a connection between the cause and effect, and to rule out the possibility that the relationship between the two variables is simply due to chance.</p><h4>3. Non-spuriousness</h4><p>The third criterion, non-spuriousness, is perhaps the most challenging to understand. Non-spuriousness means that the association between the cause and effect cannot be explained by a third variable. For example, if we find an association between smoking and lung cancer, we must consider the possibility that a third variable, such as age, could be driving the association. Perhaps older people are more likely to smoke and more likely to develop lung cancer. In this case, age would be a spurious variable, meaning that it explains the association between smoking and lung cancer. To determine causality, we must control for spurious variables.</p><h3>Potential Outcomes and Counterfactuals</h3><blockquote>Potential outcomes refer to the different outcomes or results that could occur under different conditions or treatments in a research study or experiment.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*eLGGOXBsYQ-rdvviZPBXlw.png" /></figure><ul><li>Specifically, potential outcomes are the hypothetical values that an outcome variable (such as a health outcome or a test score) could take for an individual or a group of individuals under different conditions.</li><li><strong><em>For example,</em></strong> in a medical study comparing the effectiveness of two treatments for a certain condition, potential outcomes would refer to the possible health outcomes (e.g., symptom improvement or worsening, side effects) that could occur under each treatment for each individual in the study.</li><li>The concept of potential outcomes is central to the framework of causal inference in statistics and research methodology, as it helps researchers identify the causal effects of different interventions or treatments on outcomes of interest.</li><li>Sure, here are some examples of potential outcomes:</li></ul><ol><li>In a study investigating the effect of a new drug on blood pressure, the potential outcomes for each participant could be the blood pressure level they would have if they received the drug (treatment) and the blood pressure level they would have if they did not receive the drug (control).</li><li>In a study examining the effect of a parenting intervention on child behavior, the potential outcomes for each child could be the behavior they would exhibit if their parents received the intervention (treatment) and the behavior they would exhibit if their parents did not receive the intervention (control).</li><li>In a study investigating the impact of a new teaching method on student test scores, the potential outcomes for each student could be the test score they would achieve if they were taught using the new method (treatment) and the test score they would achieve if they were taught using the traditional method (control).</li></ol><p>In each of these examples, potential outcomes refer to the different outcomes that could occur under different conditions or treatments.</p><blockquote>Counterfactuals refer to hypothetical scenarios or situations that could have occurred, but did not actually happen.</blockquote><ul><li>In the context of research methodology and causal inference, counterfactuals are used to assess the causal effect of an intervention or treatment by comparing what actually happened to what could have happened under different conditions.</li><li><strong><em>For example,</em></strong> imagine a study investigating the effect of a new medication on patient outcomes. The counterfactual scenario for a patient who received the medication would be what would have happened to the patient if they had not received the medication. The comparison of the actual outcome to the counterfactual outcome allows researchers to estimate the causal effect of the medication on the patient’s outcome.</li><li>Counterfactuals are important in determining causality because they provide a way to compare what happened to what could have happened. By considering counterfactual scenarios, researchers can make inferences about the causal effect of an intervention or treatment, even if that treatment was not randomly assigned or if the outcome cannot be directly observed under both treatment and control conditions.</li></ul><p><strong><em>Example of potential outcomes and counterfactuals:</em></strong> A study is conducted to evaluate the effect of a new teaching method on student test scores. The potential outcomes for each student are the test score they would achieve if they were taught using the new method (treatment) and the test score they would achieve if they were taught using the traditional method (control). The counterfactual scenario for a student who received the new teaching method would be what would have happened to the student if they had been taught using the traditional method instead. By comparing the actual outcome to the counterfactual outcome, researchers can estimate the causal effect of the new teaching method on test scores.</p><h3>Casual Assumptions</h3><p>Causal assumptions in causal effects models are assumptions made about the underlying causal relationships between variables in a study or experiment. These assumptions are necessary to estimate the causal effect of an intervention or treatment on an outcome of interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*ahRqjDRtx-kaGWsHw3zSIg.png" /></figure><p>Causal assumptions typically include two key components: (1) the treatment assignment mechanism and (2) the ignorability assumption.</p><ol><li>The treatment assignment mechanism refers to the process by which participants are assigned to the treatment or control group. It is assumed that the assignment mechanism is independent of the potential outcomes, meaning that treatment assignment is not related to the outcomes themselves.</li><li>The ignorability assumption, also known as the unconfoundedness assumption, states that the potential outcomes for each participant are independent of the treatment assignment, given a set of covariates or confounding variables. In other words, it is assumed that the treatment and control groups are comparable with respect to all relevant covariates, so that any differences in outcome can be attributed to the treatment itself.</li></ol><p>Other causal assumptions may be made depending on the specific study design and research question, such as the stable unit treatment value assumption (SUTVA), which assumes that the treatment effect on an individual does not depend on the treatment status of other individuals, or the consistency assumption, which assumes that the potential outcomes are consistent with the treatment assignment for each individual.</p><p>Causal assumptions are important in causal effects models because they guide the selection of appropriate statistical methods and the interpretation of study results. Violations of these assumptions can lead to biased estimates of causal effects and incorrect conclusions about the effectiveness of interventions or treatments.</p><h3>Methods of Causal Inference</h3><p>There are several methods of causal inference, each with its strengths and weaknesses. We will discuss three methods of causal inference: randomized controlled trials, natural experiments, and regression analysis.</p><h4>1. Randomized Controlled Trials</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddAR_H-L8kJ9bWnn0XN0-w.jpeg" /></figure><p>Randomized controlled trials (RCTs) are considered the gold standard for causal inference. In an RCT, participants are randomly assigned to a treatment or control group. The treatment group receives the intervention, and the control group does not. The two groups are then compared to determine the effect of the intervention.</p><p>RCTs are powerful because they control for spurious variables. Because participants are randomly assigned to treatment or control groups, any differences between the groups can be attributed to the intervention. For example, in a medical study, RCTs can control for age, gender, and other demographic factors that might affect the outcome.</p><p>However, RCTs can be expensive and time-consuming, and they may not be feasible in all situations. For example, it would not be ethical to conduct an RCT to determine the effect of smoking on lung cancer because it would require intentionally exposing participants to a harmful substance.</p><h4>2. Natural Experiments</h4><p>Natural experiments are situations in which the treatment and control groups are not assigned randomly but are created by natural circumstances. For example, if a new law is passed in one state but not another, the two states can be compared to determine the effect of the law.</p><p>Natural experiments are situations in which the treatment and control groups are not assigned randomly but are created by natural circumstances. For example, if a new law is passed in one state but not another, the two states can be compared to determine the effect of the law.</p><p>Natural experiments can be useful when RCTs are not feasible, but they have limitations. Unlike RCTs, natural experiments cannot control for spurious variables, making it more challenging to determine causality. Researchers must carefully select natural experiments to ensure that the treatment and control groups are comparable and that any differences between the groups can be attributed to the intervention.</p><h4>3. Regression Analysis</h4><p>Regression analysis is a statistical method used to determine the relationship between two or more variables. In causal inference, regression analysis can be used to control for spurious variables. For example, if we are studying the effect of education on income, we might use regression analysis to control for factors such as age, gender, and occupation.</p><p>Regression analysis is a powerful tool for causal inference, but it has limitations. It can only control for variables that are included in the analysis. If important spurious variables are left out of the analysis, the results can be misleading.</p><h3>Common Pitfalls to Avoid</h3><p>Causal inference is a complex process, and there are several common pitfalls to avoid. Here are three common pitfalls to keep in mind:</p><h4>1. Confounding Variables</h4><p>Confounding variables are variables that affect both the cause and the effect. For example, in a study of the effect of exercise on weight loss, age could be a confounding variable. Older people may be less likely to exercise and more likely to gain weight, making it difficult to determine the effect of exercise.</p><p>To avoid confounding variables, researchers must carefully control for all variables that could affect the outcome.</p><h4>2. Selection Bias</h4><p>Selection bias occurs when participants in a study are not representative of the population being studied. For example, if a study of the effect of a new drug is conducted only on healthy adults, the results may not apply to people with underlying health conditions.</p><p>To avoid selection bias, researchers must carefully select participants to ensure that they are representative of the population being studied.</p><h4>3. Reverse Causality</h4><p>Reverse causality occurs when the cause and effect are reversed. For example, if a study finds an association between depression and heart disease, it is possible that heart disease is causing depression, not the other way around.</p><p>To avoid reverse causality, researchers must carefully consider the temporal order of events and control for all possible confounding variables.</p><h3>Evaluation metrics for causal inference</h3><p>There are several evaluation metrics for causal inference, depending on the specific method used. Here are some commonly used metrics:</p><ol><li><strong>Average Treatment Effect (ATE)</strong>: This is the most basic and commonly used evaluation metric in causal inference. ATE is defined as the difference in the expected outcome between the treatment and control groups. It represents the average causal effect of the treatment on the outcome variable. ATE can be estimated using various methods, such as regression models, propensity score matching, and inverse probability weighting.</li><li><strong>Treatment Effect Heterogeneity (TEH)</strong>: TEH is a measure of how the causal effect of the treatment varies across different subgroups of the population. It can be estimated using methods such as stratification, interaction models, and subgroup analysis.</li><li><strong>Counterfactual Evaluation Metrics</strong>: These metrics compare the observed outcome to the counterfactual outcome that would have occurred if the treatment had not been given. Common counterfactual evaluation metrics include the Average Treatment Effect on the Treated (ATT), which measures the causal effect of the treatment on the treated individuals, and the Average Treatment Effect on the Control (ATC), which measures the causal effect of the treatment on the control group.</li><li><strong>Causal Inference Performance Metrics</strong>: These metrics evaluate the performance of the causal inference method itself, rather than the accuracy of the causal effect estimate. Common performance metrics include balance diagnostics, which assess whether the treatment and control groups are balanced on confounding variables, and sensitivity analysis, which assesses the robustness of the causal effect estimate to various assumptions and model specifications.</li></ol><p>Overall, the choice of evaluation metric depends on the specific research question and the causal inference method used. It is important to carefully select the appropriate metric and interpret the results in the context of the research question and the assumptions underlying the causal inference method.</p><h3>Example of Casual Inference on Titanic Dataset</h3><ol><li>Install the casual inference library</li></ol><pre>! pip install causalinference</pre><p>2. Import libraries, Load and clean the Dataset</p><pre>import pandas as pd<br>import numpy as np<br>import causalinference as ci<br><br># Load the &quot;Titanic&quot; dataset<br>url = &#39;https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv&#39;<br>data = pd.read_csv(url)<br><br># Remove columns that are not relevant for causal inference<br>data = data[[ &#39;Sex&#39;, &#39;Age&#39;, &#39;SibSp&#39;, &#39;Parch&#39;, &#39;Fare&#39;, &#39;Survived&#39;, &#39;Pclass&#39;]]<br><br># Convert categorical variables to binary indicators<br>data = pd.get_dummies(data, columns=[&#39;Pclass&#39;])<br><br># Create the Sex variable, and change boolean values to 1 and 0<br>data[&#39;Sex&#39;] = data[&#39;Sex&#39;].apply(lambda x: 1 if x == True else 0)<br># Remove missing values<br>data = data.dropna()<br><br># Rename columns<br>df = data.rename({&#39;Pclass_3&#39;: &#39;treatment_Pclass_3&#39;, &#39;Survived&#39;: &#39;outcome_Survived&#39;}, axis=1)<br><br>df = df[[&#39;Age&#39;, &#39;SibSp&#39;, &#39;Parch&#39;, &#39;Fare&#39;, &#39;Sex&#39;,&#39;Pclass_1&#39;, &#39;Pclass_2&#39;, &#39;treatment_Pclass_3&#39;, &#39;outcome_Survived&#39;]]</pre><p>3. Lets see how the data looks like now</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9ACXrm71jxqBtnH-2Mf4w.png" /></figure><p>4. Divide the data into treatment and control group</p><pre>TREATMENT = &#39;treatment_Pclass_3&#39;<br>OUTCOME = &#39;outcome_Survived&#39;<br>df.groupby(TREATMENT)[OUTCOME].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jY5mX7T_IIc-_A0hTmOZaA.png" /></figure><p>5. Run Casual Model</p><pre># Run causal model<br>causal = ci.CausalModel(Y = df[&#39;outcome_Survived&#39;].values, D = df[&#39;treatment_Pclass_3&#39;].values, X = df[[&#39;Age&#39;, &#39;SibSp&#39;, &#39;Parch&#39;, &#39;Fare&#39;, &#39;Sex&#39;,&#39;Pclass_1&#39;, &#39;Pclass_2&#39;]].values)<br># Print summary statistics<br>print(causal.summary_stats)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SqiKZ2-Rbty5t9IldLQhw.png" /></figure><p>Here we can see that there are 359 control group and 355 treated observations</p><p>6. Calculate the propensity score</p><pre># Automated propensity score estimation<br>causal.est_propensity_s()<br># Propensity model results<br>print(causal.propensity)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZX6g-rixusZ_UUDyPci9A.png" /></figure><h3>Conclusion</h3><p>Causal inference is a powerful tool for understanding the relationship between two variables. It is essential for making informed decisions in many fields, including medicine, economics, and political science. By understanding the basics of causality, the methods of causal inference, and the common pitfalls to avoid, researchers can make accurate causal inferences and make better-informed decisions. While there is no one-size-fits-all approach to causal inference, understanding the strengths and limitations of different methods can help researchers choose the best approach for their specific research question.</p><h3>References</h3><ol><li>ChatGPT</li><li>Morgan, S. L., &amp; Winship, C. (2015). Counterfactuals and Causal Inference: Methods and Principles for Social Research (2nd ed.). Cambridge University Press.</li><li>“Causal Inference for Observational Studies” by MIT OpenCourseWare (<a href="https://www.youtube.com/watch?v=zS1jBwfoYuk">https://www.youtube.com/watch?v=zS1jBwfoYuk</a>)</li><li>“Causal Inference 101” by Andrew Gelman (<a href="https://www.youtube.com/watch?v=3R3PL5qraGw">https://www.youtube.com/watch?v=3R3PL5qraGw</a>)</li><li>“Causal Inference in Statistics” by Jamie Robins (<a href="https://www.youtube.com/watch?v=7bRJ8tWFO7U">https://www.youtube.com/watch?v=7bRJ8tWFO7U</a>)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ae146d9700f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-causality-a-simplified-guide-to-casual-inference-4ae146d9700f">Crash Course in Causality — A simplified guide to Casual Inference</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crash course in Causality Worked Examples — Pima Indians Diabetics Dataset Causal Inference using…]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-causality-worked-examples-pima-indians-diabetics-dataset-causal-inference-using-1a4adfed9cf0?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a4adfed9cf0</guid>
            <category><![CDATA[causality]]></category>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 20:57:50 GMT</pubDate>
            <atom:updated>2023-04-28T20:57:50.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash course in Causality Worked Examples — Pima Indians Diabetics Dataset Causal Inference using OLS estimates</h3><p>In the Pima Indians Diabetes Database, the columns correspond to the following variables:</p><ul><li>Pregnancies: number of times pregnant</li><li>Glucose: plasma glucose concentration at 2 hours in an oral glucose tolerance test</li><li>BloodPressure: diastolic blood pressure (mm Hg)</li><li>SkinThickness: triceps skin fold thickness (mm)</li><li>Insulin: 2-Hour serum insulin (mu U/ml)</li><li>BMI: body mass index (weight in kg/(height in m)^2)</li><li>DiabetesPedigreeFunction: diabetes pedigree function (a function which scores likelihood of diabetes based on family history)</li><li>Age: age (years)</li><li>Outcome: diabetes outcome (0 or 1)</li></ul><p>To use the Y, D, X notation with this dataset, we need to choose a treatment variable, an outcome variable, and a set of covariates. For example, we could choose:</p><ul><li>Treatment variable D: a binary variable indicating whether a patient is prescribed a medication for diabetes.</li><li>Outcome variable Y: a binary variable indicating whether a patient experiences a diabetes-related complication (such as hospitalization or amputation).</li><li>Covariates X: a set of variables that might influence both the treatment assignment and the outcome, such as age, BMI, and family history.</li></ul><p>To represent these variables in the Y, D, X notation, we would set:</p><ul><li>Y: the Outcome column</li><li>D: a new column that we create based on the Insulin column (for example, we might choose to treat patients with insulin levels above a certain threshold).</li><li>X: a matrix containing columns for the Pregnancies, Glucose, BloodPressure, SkinThickness, BMI, DiabetesPedigreeFunction, and Age variables.</li></ul><h3>Example of Casual Inference on PIMA Indian Diabetic Dataset</h3><ol><li>Install the casual inference library</li></ol><pre>! pip install causalinference</pre><p>2. Import libraries, Load and clean the Dataset</p><pre>import pandas as pd<br>import numpy as np<br>from causalinference import CausalModel</pre><pre># Load the dataset</pre><pre>url = &#39;https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv&#39;</pre><pre>df = pd.read_csv(url, header=None)</pre><pre>df.columns = [&#39;Pregnancies&#39;, &#39;Glucose&#39;, &#39;BloodPressure&#39;, &#39;SkinThickness&#39;, &#39;Insulin&#39;, &#39;BMI&#39;, &#39;DiabetesPedigreeFunction&#39;, &#39;Age&#39;, &#39;Outcome&#39;]</pre><p>3. Lets see how the data looks like now</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AtWB7G2KXnIOa2NxTNKhA.png" /></figure><p>4. Divide the data into treatment and control group</p><pre>TREATMENT = &#39;Insulin&#39;<br>OUTCOME = &#39;Outcome&#39;<br>df.groupby(TREATMENT)[OUTCOME].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*O4jO9ssWuN2L3PBWzuEdXw.png" /></figure><p>5. DefineCasual Model</p><pre># Create the treatment variable D based on insulin levels<br>D = (df[&#39;Insulin&#39;] &gt; 100).astype(int)<br><br># Set the outcome variable Y to the &#39;Outcome&#39; column<br>Y = df[&#39;Outcome&#39;]<br><br># Set the covariates X to all columns except for &#39;Outcome&#39; and &#39;Insulin&#39;<br>X = df.drop([&#39;Outcome&#39;, &#39;Insulin&#39;], axis=1)<br><br># Create the causal model and estimate the treatment effect<br>causal_model = CausalModel(Y, D, X)</pre><p>6. Run Casual Model</p><p>The CausalModel class uses OLS regression to estimate the treatment effect. OLS is a common approach to estimate the causal effect of a treatment in a linear regression framework.</p><p>In particular, the est_via_ols() method of the CausalModel class fits a linear regression model of the form:</p><pre>Y = b0 + b1*D + b2*X2 + ... + bn*Xn + e</pre><p>where Y is the outcome variable, D is the treatment variable, and X2, ..., Xn are the covariates. The coefficients b1 estimate the treatment effect, and the remaining coefficients estimate the effects of the covariates on the outcome.</p><p>The est_via_ols() method uses this linear regression model to estimate the treatment effect by comparing the mean outcomes of the treatment and control groups, after controlling for the covariates. The resulting treatment effect estimate is a weighted average of the coefficients on the treatment variable in the regression model.</p><p>It is important to note that OLS regression assumes linearity, independence, and homoscedasticity of the error terms, among other assumptions. Therefore, the validity of the causal inference results depends on the accuracy of these assumptions. If these assumptions are not met, alternative methods, such as propensity score matching or instrumental variables regression, may be more appropriate.</p><pre>causal_model.est_via_ols(adj=1)<br>print(causal_model.summary_stats)<br>print(causal_model.estimates)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTKIIybJD2-4Ix-LjiE3og.png" /></figure><p>In this example, we create the treatment variable D based on whether a patient&#39;s Insulin level is above 100. We set the outcome variable Y to the Outcome column and the covariates X to all other columns except for Insulin and Outcome. We then create a CausalModel object and estimate the treatment effect using ordinary least squares (OLS) regression. Finally, we print the summary statistics and treatment effect estimates.</p><p>Note that this is just one possible way to implement a causal inference model using the Pima Indians Diabetes Database. The specific choice of variables and their roles in the causal model will depend on the research question of interest.</p><h3>Conclusion</h3><p>The output of the causal model will include various summary statistics, such as the means and standard deviations of the treatment and control groups, as well as the treatment effect estimate and its standard error.</p><p>The treatment effect estimate represents the causal effect of the insulin levels on the diabetes outcome. A positive treatment effect indicates that higher insulin levels are associated with an increased risk of diabetes, while a negative treatment effect indicates the opposite.</p><p>Based on the output of the causal model, we can draw conclusions about the direction and significance of the treatment effect. However, it is important to note that causal inference is always subject to various assumptions and limitations, and therefore the conclusions should be interpreted with caution and in the context of the research question and data at hand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a4adfed9cf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-causality-worked-examples-pima-indians-diabetics-dataset-causal-inference-using-1a4adfed9cf0">Crash course in Causality Worked Examples — Pima Indians Diabetics Dataset Causal Inference using…</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crash course in Forecasting Worked Examples — Step-by-Step Guide for Time Series Analysis using…]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-forecasting-worked-examples-step-by-step-guide-for-time-series-analysis-using-42d938981994?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/42d938981994</guid>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 13:01:39 GMT</pubDate>
            <atom:updated>2023-04-10T13:01:39.425Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash course in Forecasting Worked Examples — Step-by-Step Guide for Time Series Analysis using Exponential Smoothing</h3><p>Exponential smoothing is a popular technique for smoothing time series data and forecasting future values based on past observations. In this article, we will walk through an example of applying exponential smoothing to web traffic data using Python.</p><h3>Advantages of Exponential Smoothing</h3><ol><li>Simple and easy to understand: Exponential smoothing is a straightforward technique that does not require advanced statistical knowledge to apply. The technique is based on the idea that recent data points are more relevant than older ones, and it adjusts the weights of the observations accordingly.</li><li>Flexibility: Exponential smoothing can handle various types of time series data, including trend, seasonality, and irregularity. By adjusting the smoothing parameters, the technique can be customized to fit a wide range of time series patterns.</li><li>Efficient computation: Exponential smoothing requires less computation time than other time series techniques, making it well suited for large datasets.</li><li>Accurate forecasting: Exponential smoothing can produce accurate forecasts for short-term horizons when the underlying time series has a stable pattern.</li></ol><h3>Disadvantages of Exponential Smoothing</h3><ol><li>Limited accuracy: Exponential smoothing may not produce accurate forecasts when the underlying time series has a complex or non-linear pattern, such as sudden changes or extreme events.</li><li>Overfitting: Exponential smoothing may overfit the data if the smoothing parameters are not selected correctly. The technique can be prone to producing spurious patterns or noise in the forecasts if the parameters are not well-tuned.</li><li>Limited applicability: Exponential smoothing may not be suitable for all types of time series data, especially when the underlying patterns are difficult to identify or interpret.</li><li>Lack of transparency: Exponential smoothing is often criticized for being a “black box” technique, as it can be difficult to interpret the results or understand how the smoothing parameters are affecting the forecasts.</li></ol><h3>Mathematics for Exponential Smoothing</h3><p>The math behind exponential smoothing can be broken down into several steps:</p><ol><li>Initialization: The technique requires an initial value for the smoothed series, often referred to as the level. The level is usually set to the first observation in the time series.</li><li>Smoothing: Exponential smoothing calculates a weighted average of past observations, where the weights decrease exponentially as the observations become older. The smoothed value at time t is calculated as follows:</li><li>S_t = α*y_t + (1-α)*S_{t-1}</li><li>where S_t is the smoothed value at time t, y_t is the actual value at time t, and S_{t-1} is the smoothed value at time t-1. The parameter α (0&lt;α&lt;1) is the smoothing factor or smoothing coefficient, which determines the weight given to the most recent observation.</li><li>Updating the level: Exponential smoothing updates the level as follows:</li><li>L_t = α*y_t + (1-α)*L_{t-1}</li><li>where L_t is the updated level at time t, y_t is the actual value at time t, and L_{t-1} is the previous level.</li><li>Forecasting: Exponential smoothing can be used to forecast future values of the time series by using the updated level and the smoothing factor. The forecast at time t+k is given by:</li><li>F_{t+k} = L_t + k*(S_t)</li><li>where F_{t+k} is the forecast at time t+k, L_t is the updated level at time t, S_t is the smoothed value at time t, and k is the number of periods ahead to forecast.</li></ol><p>The effectiveness of exponential smoothing depends on the choice of the smoothing factor α. A high value of α gives more weight to recent observations, making the method more responsive to changes in the data but more prone to noise and overfitting. A low value of α gives more weight to past observations, making the method smoother but less responsive to changes in the data.</p><h3>Example — Web Traffic Time Series Forecasting</h3><p>The data we will be working with is from a Kaggle dataset of daily web page traffic for various Wikipedia pages from 2015 to 2017. We will be using the Holt’s linear method with additive trend and no seasonality to forecast the next 30 days of web traffic for a selected Wikipedia page.</p><p>Let’s get started!</p><p>Step 1: Importing Libraries First, we need to import the necessary libraries: Pandas for data manipulation, NumPy for numerical computing, Matplotlib for data visualization, and ExponentialSmoothing from statsmodels.tsa.api for applying exponential smoothing.pythonCopy cod</p><pre>import pandas as pd <br>import numpy as np <br>import matplotlib.pyplot as plt <br>fromstatsmodels.tsa.api import ExponentialSmoothing</pre><p>Step 2: Loading Data Next, we load the web traffic data from the Kaggle dataset into a Pandas DataFrame using the read_csv function.pythonCopy cod</p><pre>train = pd.read_csv(&#39;train_1.cs</pre><p>Step 3: Reshaping Data The train DataFrame is in a wide format with a separate column for each Wikipedia page and a separate row for each day. To apply exponential smoothing, we need to reshape the DataFrame into a long format with a separate row for each day and page. We do this by using the melt function to unpivot the DataFrame, resulting in a tall and narrow DataFrame with three columns: &#39;Page&#39;, &#39;Date&#39;, and &#39;Visits&#39;.</p><pre>train = train.melt(id_vars=[&#39;Page&#39;], var_name=&#39;Date&#39;, value_name=&#39;Visits&#39;)</pre><p>Step 4: Converting Date to Datetime Object The ‘Date’ column is currently a string, so we convert it to a datetime object using the to_datetime function.</p><pre>train[&#39;Date&#39;] = pd.to_datetime(train[&#39;Date&#39;], format=&#39;%Y-%m-%d&#39;)</pre><p>Step 5: Setting Index We set the ‘Date’ column as the DataFrame’s index using the set_index method.</p><pre>train.set_index(&#39;Date&#39;, inplace=True</pre><p>Step 6: Grouping Data We group the data by page and take the median for each day using the groupby method.</p><pre>df = train.groupby([&#39;Page&#39;, pd.Grouper(freq=&#39;D&#39;)])[&#39;Visits&#39;].median().unstack(&#39;Page&#39;)</pre><p>Step 7: Selecting Subset of Data We select a single Wikipedia page to forecast and create a subset of the data for that page using the dropna method to remove any missing values.</p><pre>page = &#39;2NE1_zh.wikipedia.org_all-access_spider&#39; df_subset = df[[page]].dropna()</pre><p>Step 8: Applying Exponential Smoothing</p><p>We apply exponential smoothing to the data for the selected page using the Holt’s linear method with additive trend and no seasonality. We create an ExponentialSmoothing object named model with the parameters for the method, and then fit it to the data using the fit method and the specified smoothing parameters.</p><pre>model = ExponentialSmoothing(df_subset[page], trend=&#39;add&#39;, seasonal=None) fit = model.fit(smoothing_level=0.2, smoothing_slope=0.1, optimized=False)</pre><p>Step 9: Forecasting</p><p>We predict the next 30 days using the fitted model using the forecast method and specifying the number of periods to forecast.</p><pre>forecast = fit.forecast(steps=30)</pre><p>Step 10: Visualizing Results</p><p>Finally, we visualize the results by plotting the original web traffic data and the predicted values for the selected page using Matplotlib.</p><pre>plt.figure(figsize=(15, 6))<br>plt.plot(df_subset.index, df_subset[page], label=&#39;Actual&#39;)<br>plt.plot(forecast.index, forecast, label=&#39;Forecast&#39;)<br>plt.title(&#39;Web Traffic Forecast for {} Wikipedia Page&#39;.format(page))<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Visits&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUTv_o-YxpsS6aBsOk7bsQ.png" /></figure><h3>Conclusion</h3><p>In this article, we explored the concept of exponential smoothing and its application in time series analysis. We discussed the steps involved in implementing exponential smoothing in Python and demonstrated its usage on a Kaggle dataset.</p><p>We also looked at the advantages and disadvantages of exponential smoothing and its real-world applications, including sales forecasting, economic forecasting, supply chain management, finance, and energy forecasting.</p><p>Finally, we delved into the mathematical principles underlying exponential smoothing, including initialization, smoothing, updating the level, and forecasting, and discussed the importance of selecting the appropriate smoothing factor for accurate predictions.</p><p>Overall, exponential smoothing is a versatile and powerful tool in time series analysis that can help decision-makers make informed predictions based on historical data. Its simplicity and flexibility make it a popular choice for data analysts and researchers in various fields, and its potential for improving efficiency and reducing costs makes it an essential tool for businesses and organizations looking to stay ahead of the curve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42d938981994" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-forecasting-worked-examples-step-by-step-guide-for-time-series-analysis-using-42d938981994">Crash course in Forecasting Worked Examples — Step-by-Step Guide for Time Series Analysis using…</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crash Course in Forecasting: Time Series Forecasting Quiz]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-forecasting-time-series-forecasting-quiz-d7652fef9254?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7652fef9254</guid>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 12:57:59 GMT</pubDate>
            <atom:updated>2023-04-10T12:57:59.487Z</atom:updated>
            <content:encoded><![CDATA[<p>This article contains quiz questions on the topic of Time Series Forecasting</p><ol><li><strong>What is Time Series Forecasting?</strong></li></ol><ul><li>a. A technique to analyze cross-sectional data</li><li>b. A technique to analyze panel data</li><li>c. A technique to analyze time-dependent data</li><li>d. A technique to analyze spatial data</li></ul><p><em>Answer</em>: <strong>c. A technique to analyze time-dependent data</strong></p><p><strong>2. What is the purpose of time series forecasting?</strong></p><ul><li>a. To analyze the relationship between two or more variables</li><li>b. To predict future values of a variable based on its past values</li><li>c. To analyze the impact of an intervention on a variable</li><li>d. To forecast the behavior of a variable in a particular market</li></ul><p><em>Answer</em>: <strong>b. To predict future values of a variable based on its past values</strong></p><p>3. <strong>What is the difference between a stationary and non-stationary time series?</strong></p><ul><li>a. Stationary time series have a constant mean and variance over time, while non-stationary time series have a changing mean and variance over time.</li><li>b. Stationary time series have a changing mean and variance over time, while non-stationary time series have a constant mean and variance over time.</li><li>c. Stationary time series have a constant mean over time, while non-stationary time series have a changing mean over time.</li><li>d. Stationary time series have a changing mean over time, while non-stationary time series have a constant mean over time.</li></ul><p><em>Answer</em>: <strong>a. Stationary time series have a constant mean and variance over time, while non-stationary time series have a changing mean and variance over time.</strong></p><p><strong>4. What is the purpose of differencing in time series forecasting?</strong></p><ul><li>a. To remove the trend and seasonality in a time series</li><li>b. To reduce the number of observations in a time series</li><li>c. To make a non-stationary time series stationary</li><li>d. To smooth out the noise in a time series</li></ul><p><em>Answer</em>: <strong>c. To make a non-stationary time series stationary</strong></p><p><strong>5. What is the difference between AR and MA models in time series forecasting?</strong></p><ul><li>a. AR models consider the effect of past values of the variable on its current value, while MA models consider the effect of past errors on its current value.</li><li>b. AR models consider the effect of past errors on its current value, while MA models consider the effect of past values of the variable on its current value.</li><li>c. AR models consider the effect of future values of the variable on its current value, while MA models consider the effect of future errors on its current value.</li><li>d. AR models consider the effect of future errors on its current value, while MA models consider the effect of future values of the variable on its current value.</li></ul><p><em>Answer</em>: <strong>a. AR models consider the effect of past values of the variable on its current value, while MA models consider the effect of past errors on its current value.</strong></p><p>6<strong>. What is the difference between ARIMA and SARIMA models in time series forecasting?</strong></p><ul><li>a. ARIMA models are used for non-seasonal time series data, while SARIMA models are used for seasonal time series data.</li><li>b. SARIMA models are used for non-seasonal time series data, while ARIMA models are used for seasonal time series data.</li><li>c. ARIMA models consider the effect of past values of the variable and past errors on its current value, while SARIMA models consider the effect of past values of the variable, past errors, and seasonal factors on its current value.</li><li>d. SARIMA models consider the effect of past values of the variable and past errors on its current value, while ARIMA models consider the effect of past values of the variable, past errors, and seasonal factors on its current value.</li></ul><p><em>Answer</em>: <strong>a. ARIMA models are used for non-seasonal time series data, while SARIMA models are used for seasonal time series data.</strong></p><p><strong>7. Which of the following is a characteristic of ARIMA models?</strong></p><ul><li>a) It is a non-parametric model</li><li>b) It is a linear model</li><li>c) It requires that the time series be stationary</li><li>d) It is not suitable for seasonal time series</li></ul><p>Answer: c) It requires that the time series be stationary</p><p><strong>8. Which of the following is a characteristic of exponential smoothing (ES) models?</strong></p><ul><li>a) It can handle non-linear trends</li><li>b) It can handle seasonal time series</li><li>c) It requires that the time series be stationary</li><li>d) It can handle non-monotonic trends</li></ul><p>Answer: <strong>a) It can handle non-linear trends</strong></p><p><strong>9. Which of the following is an advantage of ARIMA models over ES models?</strong></p><ul><li>a) It can handle multiple seasonal periods</li><li>b) It is easier to interpret the parameters</li><li>c) It can handle non-linear trends</li><li>d) It is computationally faster</li></ul><p>Answer: <strong>a) It can handle multiple seasonal periods</strong></p><p><strong>10. Which of the following is true regarding ARIMA and ES models?</strong></p><ul><li>a) ARIMA models always outperform ES models</li><li>b) ES models always outperform ARIMA models</li><li>c) The performance of the models depends on the specific time series being forecasted</li><li>d) ARIMA and ES models have the same forecasting accuracy</li></ul><p>Answer: <strong>c) The performance of the models depends on the specific time series being forecasted</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7652fef9254" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-forecasting-time-series-forecasting-quiz-d7652fef9254">Crash Course in Forecasting: Time Series Forecasting Quiz</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crash course in Time Series Forecasting — Techniques, Tools, and Best Practices]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-time-series-forecasting-techniques-tools-and-best-practices-c03f38aeda1c?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/c03f38aeda1c</guid>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 12:53:24 GMT</pubDate>
            <atom:updated>2023-04-10T12:53:24.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash course in Forecasting — Time Series Forecasting Techniques, Tools, and Best Practices</h3><p>The article “Crash course in Time Series Forecasting — Techniques, Tools, and Best Practices” provides a comprehensive guide to time series forecasting. The article covers various techniques, tools, and best practices that can be used to build accurate forecasting models.</p><p>Dataset used in this crash course is the Microsoft Stock Data from Kaggle that can be downloaded from below link</p><p><a href="https://www.kaggle.com/datasets/vijayvvenkitesh/microsoft-stock-time-series-analysis?select=Microsoft_Stock.csv">Microsoft_stock.csv</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*gcnNZgytFrj92BowZ2YkQw.jpeg" /></figure><h3><strong>Table of Contents</strong></h3><ol><li><strong>Introduction to Time Series Forecasting</strong></li></ol><p>2. <strong>Understanding Time Series Data</strong></p><p>3. <strong>Time Series Forecasting Techniques</strong></p><p>4. <strong>Evaluating Time Series Forecasts</strong></p><p>5. <strong>Best Practices in Time Series Forecasting</strong></p><p>6. <strong>Tools and Libraries for Time Series Forecasting</strong></p><p>7. <strong>Conclusion and Future Directions</strong></p><p>8. <strong>References</strong></p><h3><strong>Introduction to Time Series Forecasting</strong></h3><p><strong><em>What is Time Series Forecasting ?</em></strong></p><p><strong>Time series forecasting</strong> is a technique used to <em>predict future values</em> of a <em>time-dependent variable</em> <em>based on its past values</em>. It is a widely used technique in many domains, including finance, economics, weather forecasting, and engineering. In this article, we will provide an overview of time series forecasting, including its definition, importance, and applications.</p><ul><li>Time series forecasting is the process of predicting future values of a time-dependent variable based on its past values.</li><li>Time-dependent variables are those that change over time and can be measured at regular intervals.</li><li><em>Examples</em> of time-dependent variables include stock prices, temperature readings, and website traffic.</li></ul><p><strong><em>Importance of Time Series Forecasting</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5e8nkTxeJ01G88ZCjhz7g.png" /></figure><p><strong><em>Industry Usage of Time Series Forecasting</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*DBnMy1VK3xj8kw4UbZ25pg.png" /></figure><h3>Understanding Time Series Data</h3><p>What is Time Series Data ?</p><p>Time series data refers to a type of data that is collected over time, with each observation corresponding to a specific point in time. Examples of time series data include stock prices, weather patterns, and economic indicators.</p><p>Types of Time Series Data</p><ol><li>Univariate Time Series Data — refers to time series data contain only one variable multivariate</li><li>Multivariate Time Series Data — refers to time series data contain multiple variables</li></ol><p>Components of Time Series Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rx4uPEfEnp3CNgEcYmDsyg.png" /></figure><h3>Time Series Forecasting Techniques</h3><p>There are several time series forecasting techniques that we can use to predict future values of a time-dependent variable. Out of which we will be discussing 5 techniques as mentioned below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZPXmPd2Qn3HT13iDLFN7A.png" /></figure><ol><li><strong>Autoregressive Integrated Moving Average (ARIMA):</strong> ARIMA is a widely used technique for time series forecasting that models the relationship between the current value of a time series and its past values. It can handle both trend and seasonal patterns in the data.</li><li><strong>Exponential Smoothing (ETS):</strong> ETS is a family of methods that models the time series as a combination of trend, seasonality, and irregularity. It is a simple yet effective technique for short-term forecasting.</li><li><strong>Seasonal Autoregressive Integrated Moving Average (SARIMA):</strong> SARIMA is an extension of ARIMA that takes into account the seasonal patterns in the data. It is suitable for data that exhibit both trend and seasonal patterns.</li><li><strong>Prophet:</strong> Prophet is a time series forecasting framework developed by Facebook that uses a decomposable model to capture trend, seasonality, and holiday effects. It is designed to handle datasets with missing values and outliers.</li><li><strong>Long Short-Term Memory (LSTM):</strong> LSTM is a type of neural network that is well-suited for processing sequential data such as time series. It can handle complex patterns in the data and is often used for long-term forecasting.</li><li><strong>Vector Autoregression (VAR):</strong> VAR is a technique for modeling the relationships between multiple time series. It can capture the interdependencies between different variables and can be used for forecasting in various domains such as finance and economics.</li><li><strong>Gaussian Process Regression (GPR):</strong> GPR is a probabilistic technique that models the time series as a sample from a Gaussian process. It is suitable for datasets with a small number of observations and can handle non-linear relationships in the data.</li><li><strong>Seasonal Decomposition of Time Series (STL):</strong> STL is a technique that decomposes the time series into three components: trend, seasonal, and residual. It is useful for understanding the underlying patterns in the data and can be used for short-term forecasting.</li><li><strong>Dynamic Linear Models (DLM):</strong> DLM is a framework that models the time series as a combination of different components, including trend, seasonal, and regression effects. It is suitable for data with multiple variables and can handle missing data.</li><li><strong>Ensemble Methods:</strong> Ensemble methods involve combining multiple forecasting models to improve the accuracy of the forecasts. Examples include Bagging, Boosting, and Stacking.</li></ol><p><strong><em>Example with python code using ARIMA model on Microsoft Stock data</em></strong></p><p>In this code, we first load the Microsoft Stock dataset using the read_csv function from the pandas library. We then convert the &#39;Date&#39; column to a datetime object using the to_datetime function and set it as the index of the dataframe using the set_index function.</p><p>Next, we create a time series from the ‘Close’ column and create an ARIMA model with (p,d,q) = (2,1,2) using the ARIMA function from the statsmodels.tsa.arima_model library. We fit the model to the data using the fit method.</p><p>Finally, we make a prediction for the next 30 days using the forecast method and plot the historical and predicted data using the plot function from the matplotlib.pyplot library. We add labels to the x and y-axis using the xlabel and ylabel functions, respectively, and add a title to the plot using the title function. We also add a legend using the legend function and display the plot using the show function.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from statsmodels.tsa.arima.model import ARIMA<br><br># Load the Bitcoin historical dataset from Kaggle<br>df = pd.read_csv(&#39;Microsoft_Stock.csv&#39;)<br><br># Define the ARIMA parameters<br>p = 5  # AR parameter<br>d = 1  # Integrated parameter<br>q = 2  # MA parameter<br><br># Fit the ARIMA model to the Bitcoin data<br>model = ARIMA(df[&#39;Close&#39;], order=(p, d, q))<br>results = model.fit()<br><br># Make predictions for the next 30 days<br>forecast = results.forecast(steps=30)<br><br># Plot the Microsoft Stock data and the forecasted values<br>plt.plot(ts.index, ts, label=&#39;Microsoft Stock&#39;)<br>plt.plot(pd.date_range(start=ts.index[-1], periods=31, freq=&#39;D&#39;)[1:], forecast, label=&#39;Predicted Data&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Price (USD)&#39;)<br>plt.title(&#39;Microsoft Stock Price Prediction with ARIMA&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*GpX36loo75Rfx43EIT9VOg.png" /><figcaption>output of above code</figcaption></figure><p><strong><em>Example with python code using Exponential Smoothing model on Microsoft Stock data</em></strong></p><p>In this code, we first load the Microsoft Stock dataset using the read_csv function from the pandas library. We then convert the &#39;Date&#39; column to a datetime object using the to_datetime function and set it as the index of the dataframe using the set_index function.</p><p>Next, we create a time series from the ‘Close’ column and create an Exponential Smoothing (ES) model with trend=&#39;add&#39;, seasonal=&#39;add&#39;, and seasonal_periods=12 using the ExponentialSmoothing function from the statsmodels.tsa.holtwinters library. We fit the model to the data using the fit method.</p><p>Finally, we make a prediction for the next 30 days using the forecast method and plot the historical and predicted data using the plot function from the matplotlib.pyplot library. We add labels to the x and y-axis using the xlabel and ylabel functions, respectively, and add a title to the plot using the title function. We also add a legend using the legend function and display the plot using the show function.</p><p>Exponential Smoothing (ES) is a popular time series forecasting method that models the underlying trend and seasonality in the data using exponential functions. It is a simple and effective technique that can handle non-linear trends and seasonality in the data. The ExponentialSmoothing function from the statsmodels.tsa.holtwinters library allows us to easily create an ES model and fit it to the data. The fit method fits the model to the data and the forecast method allows us to make predictions for future time periods.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from statsmodels.tsa.holtwinters import ExponentialSmoothing<br><br># Load the Microsoft Stock dataset<br>df = pd.read_csv(&#39;Microsoft_Stock.csv&#39;)<br><br># Convert the &#39;Date&#39; column to a datetime object<br>df[&#39;Date&#39;] = pd.to_datetime(df[&#39;Date&#39;])<br><br># Set the &#39;Date&#39; column as the index<br>df.set_index(&#39;Date&#39;, inplace=True)<br><br># Create a series of the &#39;Close&#39; column<br>ts = df[&#39;Close&#39;]<br><br># Create the ES model with smoothing_level=0.6 and smoothing_slope=0.2<br>model = ExponentialSmoothing(ts, trend=&#39;add&#39;, seasonal=&#39;add&#39;, seasonal_periods=12)<br>model_fit = model.fit()<br><br># Make a prediction for the next 30 days<br>forecast = model_fit.forecast(steps=30)<br><br># Plot the historical and predicted data<br>plt.plot(ts.index, ts, label=&#39;Historical Data&#39;)<br>plt.plot(pd.date_range(start=ts.index[-1], periods=31, freq=&#39;D&#39;)[1:], forecast, label=&#39;Predicted Data&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Price (USD)&#39;)<br>plt.title(&#39;Microsoft Stock Price Prediction with Exponential Smoothing&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*0EXygdZ-_W8sRVMHprrmuQ.png" /></figure><h3>Evaluating Time Series Forecasts</h3><p>Once we have generated time series forecasts, we need to evaluate their accuracy. There are several metrics for evaluating time series forecasts, such as Mean Absolute Error (MAE), Mean Squared Error (MSE), and Root Mean Squared Error (RMSE). We can also use cross-validation techniques to evaluate the performance of our models on new data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8Cv0hUxm85PEfUJIknddg.png" /></figure><ol><li><strong>Mean Absolute Error (MAE): </strong>The MAE is a commonly used metric to evaluate the accuracy of time series forecasts. It measures the average absolute difference between the predicted and actual values.</li><li><strong>Mean Squared Error (MSE):</strong> The MSE is another popular evaluation metric that measures the average squared difference between the predicted and actual values.</li><li><strong>Root Mean Squared Error (RMSE)</strong>: The RMSE is a variation of the MSE that takes the square root of the average squared difference between the predicted and actual values.</li><li><strong>Mean Absolute Percentage Error (MAPE):</strong> The MAPE is a commonly used metric to evaluate the accuracy of time series forecasts as a percentage of the actual values.</li><li><strong>Symmetric Mean Absolute Percentage Error (SMAPE)</strong>: The SMAPE is another popular evaluation metric that measures the percentage difference between the predicted and actual values.</li></ol><h3>Best Practices in Time Series Forecasting</h3><p>To generate accurate time series forecasts, we need to follow best practices in time series forecasting. These practices include feature engineering, hyperparameter tuning, dealing with missing data and outliers, and ensembling multiple models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6k_ASVOMerFCHC01R9sww.png" /></figure><h3>Tools and Libraries for Time Series Forecasting</h3><p>As the use of time series data becomes increasingly common across industries, there are now many tools available to help with the process of forecasting. In this article, we’ll take a look at some of the top tools available for time series forecasting.</p><ol><li><strong>Python</strong>: Python is a popular language for data analysis and has a number of libraries that are widely used for time series forecasting. Some popular libraries include StatsModels, Prophet, and scikit-learn. Python provides an extensive range of tools for data preprocessing, model selection, and evaluation, making it a popular choice for time series forecasting.</li><li><strong>R</strong>: R is another popular language used in data analysis, and it also has a number of libraries specifically designed for time series forecasting. Some popular libraries include forecast, tseries, and zoo. R has been widely used for time series forecasting, and its user community is very active and supportive.</li><li><strong>Excel</strong>: Excel is widely used for business applications, and it has a number of built-in tools that can be used for time series forecasting. Excel provides a range of statistical functions that can be used to analyze time series data, including the ability to perform regression analysis and time series decomposition. Excel’s ease of use and familiarity make it a popular choice for basic time series forecasting tasks.</li><li><strong>Tableau</strong>: Tableau is a powerful data visualization tool that can also be used for time series forecasting. Tableau provides a range of visualization options for time series data, including line charts, scatter plots, and heatmaps. Tableau’s drag-and-drop interface and interactive features make it an excellent tool for exploring and visualizing time series data.</li><li><strong>MATLAB</strong>: MATLAB is a powerful computing environment that can be used for scientific computing, data analysis, and visualization. It has a range of built-in functions and toolboxes that can be used for time series forecasting, including the Signal Processing Toolbox and the Econometrics Toolbox. MATLAB provides a range of visualization options and can be used to build custom models for time series forecasting.</li><li><strong>SAS</strong>: SAS is a statistical software package widely used in the business world. It provides a range of functions for time series forecasting, including the ability to perform ARIMA modeling, exponential smoothing, and regression analysis. SAS is a powerful tool for forecasting and is widely used in industries such as finance and healthcare.</li><li><strong>Gretl</strong>: Gretl is an open-source software package that can be used for econometric analysis and time series forecasting. It provides a range of statistical functions and models, including ARIMA modeling and regression analysis. Gretl is a user-friendly tool and is a good choice for those who are new to time series forecasting.</li><li><strong>Prophet</strong>: Prophet is an open-source forecasting tool developed by Facebook. It uses a decomposable time series model to forecast time series data and has become popular due to its ease of use and ability to handle seasonality and non-linear trends.</li><li><strong>Keras</strong>: Keras is a popular deep learning library that can be used for time series forecasting. It provides a range of neural network models that can be used for time series forecasting, including Long Short-Term Memory (LSTM) models and Convolutional Neural Networks (CNNs). Keras is a powerful tool for forecasting and is widely used in industries such as finance and healthcare.</li><li><strong>TensorFlow</strong>: TensorFlow is an open-source machine learning library that can be used for time series forecasting. It provides a range of deep learning models that can be used for time series forecasting, including LSTM models and CNNs. TensorFlow is a powerful tool for forecasting and is widely used in industries such as finance and healthcare.</li></ol><h3>Conclusion</h3><p>In this article, we discussed various aspects of time series forecasting, including its importance, benefits, applications, and techniques. We also looked at some popular tools and datasets used for time series forecasting and saw code snippets in Python for applying different forecasting techniques.</p><p>From our discussion, we can conclude that time series forecasting is a vital aspect of many industries and domains, including finance, retail, energy, and healthcare. It helps in making informed decisions, reducing risk, and improving the overall efficiency of businesses.</p><p>To perform time series forecasting effectively, it is essential to follow best practices such as cleaning and preprocessing data, selecting appropriate forecasting techniques, evaluating models with metrics, and continuously monitoring and updating models as necessary.</p><p>Various tools and libraries are available for time series forecasting, such as ARIMA, Prophet, and ES models, along with visualization tools like matplotlib and seaborn. These tools enable users to analyze and model time series data, make forecasts, and visualize the results.</p><p>However, while these tools provide great capabilities for time series forecasting, it is essential to have a sound understanding of the underlying techniques and concepts to use them effectively. Moreover, it is necessary to choose the right tool for the specific problem and data at hand, along with continuously monitoring and refining the models to maintain their accuracy.</p><p>In conclusion, time series forecasting is an important aspect of modern businesses and industries, and it can provide valuable insights and improve decision-making. With the right tools, techniques, and best practices, businesses can harness the power of time series forecasting to stay ahead of the curve and achieve their goals.</p><h3>Future Scope</h3><p>Time series forecasting has come a long way in recent years and has become an essential tool for various industries. With advancements in technology and machine learning, time series forecasting has become more accurate and efficient. However, there is still a lot of scope for improvement and development in this field.</p><p>One of the major areas of future development in time series forecasting is the integration of deep learning models. Deep learning models have shown great potential in various fields and can be applied to time series forecasting to improve accuracy and efficiency. Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) models have been found to be particularly effective in time series forecasting.</p><p>Another area of future development is the integration of external factors into the time series forecasting model. This involves incorporating external variables that may have an impact on the time series data, such as weather conditions, economic indicators, and social media trends. This can lead to more accurate predictions and better decision-making.</p><p>Furthermore, the integration of uncertainty estimates in time series forecasting can help in making informed decisions. With the use of probabilistic forecasting models, the level of uncertainty in the predictions can be estimated, allowing decision-makers to make informed decisions and take necessary actions.</p><p>Another area of future development is the development of explainable AI models for time series forecasting. Explainable AI models can help in understanding the underlying patterns and factors that are affecting the time series data. This can lead to more effective decision-making and better understanding of the predictions.</p><p>Moreover, with the growth of the Internet of Things (IoT), the amount of time series data being generated is increasing rapidly. This presents both opportunities and challenges for time series forecasting. The challenge is to develop models that can handle large volumes of data, while the opportunity lies in the potential for more accurate predictions and better decision-making.</p><p>In conclusion, time series forecasting is an essential tool for various industries, and there is a lot of scope for future development and improvement. With the integration of deep learning models, external factors, uncertainty estimates, explainable AI models, and the growth of IoT, the future of time series forecasting looks promising. These advancements can lead to more accurate predictions, better decision-making, and improved overall performance.</p><h3><strong>References</strong></h3><ul><li>Hyndman, R.J., &amp; Athanasopoulos, G. (2018). Forecasting: principles and practice (2nd ed.). OTexts: Melbourne, Australia. Available at: <a href="https://otexts.com/fpp2/">https://otexts.com/fpp2/</a></li><li>Box, G. E. P., Jenkins, G. M., Reinsel, G. C., &amp; Ljung, G. M. (2015). Time series analysis: forecasting and control. John Wiley &amp; Sons.</li><li>Zhang, G. P. (2003). Time series forecasting using a hybrid ARIMA and neural network model. Neurocomputing, 50, 159–175.</li><li>Lütkepohl, H. (2005). New introduction to multiple time series analysis. Springer Science &amp; Business Media.</li><li>Brownlee, J. (2021). Time Series Forecasting: A Tutorial for Beginners. Machine Learning Mastery. Available at: <a href="https://machinelearningmastery.com/time-series-forecasting/">https://machinelearningmastery.com/time-series-forecasting/</a></li><li>Kaggle datasets. Available at: <a href="https://www.kaggle.com/datasets">https://www.kaggle.com/datasets</a></li><li>Prophet. Available at: <a href="https://facebook.github.io/prophet/">https://facebook.github.io/prophet/</a></li><li>Statsmodels. Available at: <a href="https://www.statsmodels.org/stable/index.html">https://www.statsmodels.org/stable/index.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c03f38aeda1c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-time-series-forecasting-techniques-tools-and-best-practices-c03f38aeda1c">Crash course in Time Series Forecasting — Techniques, Tools, and Best Practices</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crash Course in Data — Drawing Insights in Parallel: Understanding Complex Multivariate Data with…]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-data-drawing-insights-in-parallel-understanding-complex-multivariate-data-with-6c5c2c8bc7c7?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c5c2c8bc7c7</guid>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 02:01:58 GMT</pubDate>
            <atom:updated>2023-03-28T02:01:58.760Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash Course in Data — Drawing Insights in Parallel: Understanding Complex Multivariate Data with Parallel Coordinates</h3><ul><li>A Parallel coordinates plot is used to analyze multivariate numerical data. It allows a comparison of the samples or observations across multiple numerical variables.</li><li>Each feature/variable is represented by a separate axis. All the axes are equally spaced and parallel to each other. Each axis can have a different scale and unit of measurement.</li><li>Each sample/observation is plotted horizontally.</li></ul><p>Parallel coordinates plot is a useful tool for visualizing high-dimensional data. Here are some use cases of parallel coordinates plot:</p><ol><li><strong>Multivariate analysis</strong>:</li></ol><p>Parallel coordinates plot can be used to visualize and analyze multivariate data. It allows us to plot multiple variables on the same plot and observe the patterns and relationships between them.</p><pre>! pip install plotly</pre><pre>import plotly.express as px<br>df_iris = px.data.iris()<br><br>fig = px.parallel_coordinates(df_iris, color=&quot;species_id&quot;,<br>                              dimensions=[&#39;sepal_width&#39;, &#39;sepal_length&#39;, &#39;petal_width&#39;,<br>                                          &#39;petal_length&#39;],<br>                              color_continuous_scale=px.colors.diverging.Tealrose,<br>                              color_continuous_midpoint=2)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*79ehUav0m_fpZpnIqirm0A.png" /></figure><pre>df_iris.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*658L61hEfy9PZkP3gFF2Cw.png" /></figure><p><strong>2. Classification</strong>:</p><p>Parallel coordinates plot can be used to classify data points based on their values. By plotting the different classes on the same plot, we can observe how they differ from each other and identify any patterns or trends that can help us distinguish them.</p><pre><br>fig = px.parallel_coordinates(df_iris, color=&quot;species_id&quot;,<br>                              color_continuous_scale=px.colors.diverging.Tealrose,<br>                              color_continuous_midpoint=2)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*QDV5LKeppcaUjdKyxYEOYg.png" /></figure><p><strong>3. Outlier detection</strong>:</p><p>Parallel coordinates plot can be used to identify outliers in the data. Outliers are data points that have values significantly different from the rest of the data, and they can be easily identified in a parallel coordinates plot as they do not follow the same pattern as the other data points.</p><pre><br>fig = px.parallel_coordinates(df_iris, color=&quot;species_id&quot;,<br>                              dimensions=[&#39;sepal_width&#39;, &#39;sepal_length&#39;, &#39;petal_width&#39;,<br>                                          &#39;petal_length&#39;])<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*Qwf3hseeaYeY_63WU1wKIg.png" /></figure><p><strong>4. Feature selection</strong>:</p><p>Parallel coordinates plot can be used to select the most important features for a predictive model. By plotting the different features on the same plot and observing their patterns and relationships with the target variable, we can identify the features that are most relevant for the prediction task.</p><pre>fig = px.parallel_coordinates(df_iris, dimensions=[&#39;sepal_width&#39;, &#39;sepal_length&#39;, &#39;petal_width&#39;,<br>                                          &#39;petal_length&#39;],<br>                              color_continuous_scale=px.colors.diverging.Tealrose,<br>                              color_continuous_midpoint=2)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*8j4rOM5f-HfNnjpnEj0M9A.png" /></figure><p><strong>5. Data exploration</strong>:</p><p>Parallel coordinates plot can be used to explore the data and gain insights about its structure and patterns. It allows us to visualize and analyze high-dimensional data in a more intuitive way and identify any interesting relationships or trends that may not be apparent in lower-dimensional visualizations.</p><pre><br>fig = px.parallel_coordinates(df_iris, dimensions=[&#39;sepal_width&#39;, &#39;sepal_length&#39;, &#39;petal_width&#39;,<br>                                          &#39;petal_length&#39;], color=&quot;species_id&quot;, color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=2)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*kIjjebsrpvmYuU7UsRa2nA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c5c2c8bc7c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-data-drawing-insights-in-parallel-understanding-complex-multivariate-data-with-6c5c2c8bc7c7">Crash Course in Data — Drawing Insights in Parallel: Understanding Complex Multivariate Data with…</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quiz__data_A_tour_through_visualization_zoo]]></title>
            <link>https://medium.com/aiskunks/quiz-data-a-tour-through-visualization-zoo-c3da97b658a0?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3da97b658a0</guid>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 17:07:03 GMT</pubDate>
            <atom:updated>2023-03-27T17:07:03.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash Course in Data Quiz — Journey Through the Data Visualization Zoo: Test Your Knowledge of Statistical and Hierarchical Data Visualization</h3><p>This section contains 10 quiz questions on A Tour of Visualization zoo Introduction for Statistical and hierarchical Data</p><h3>Q.1. In which year was the term “Visualization Zoo” introduced in the published paper by Prof. Jeffrey Heer?</h3><ul><li>A. 2000</li><li>B. 2005</li><li>C. 2010</li><li>D. 2015</li></ul><h4><strong>Ans — C. 2010</strong></h4><h3>Q.2. Can we use QQ plot for distributions other than Normal Distributions?</h3><h4><strong>Ans.</strong></h4><p>Q-Q plots can be used to compare any probability distribution to a reference distribution, including beta distributions.</p><p>To create a Q-Q plot for a beta distribution, you would first need to generate a random sample from the beta distribution that you want to compare to the reference distribution. Then, you would plot the quantiles of the sample against the quantiles of the reference distribution on a scatter plot.</p><p>The Q-Q plot will show how well the beta distribution fits the reference distribution. If the data points on the Q-Q plot follow a straight line, it suggests that the beta distribution is a good fit for the reference distribution. If the data points deviate from the straight line, it indicates that the beta distribution is not a good fit.</p><p>It’s worth noting that beta distributions can take on different shapes depending on the values of the parameters alpha and beta. Therefore, it may be useful to create multiple Q-Q plots with different parameter values to compare how well the beta distribution fits the reference distribution under different scenarios.</p><h3>Q.3. List the use case of QQ Plot?</h3><h4><strong>Ans.</strong></h4><ol><li>Testing for normality:</li><li>Comparing distributions:</li><li>Identifying outliers:</li><li>Checking for linearity:</li><li>Assessing model assumptions:</li></ol><h3>Q.4. Name the parameter to create a different axis in the Parallel Coordinates Plot?</h3><h4><strong>Ans. — dimensions</strong></h4><p>fig = px.parallel_coordinates(df_iris, color=”species_id”, dimensions=[‘sepal_width’, ‘sepal_length’, ‘petal_width’, ‘petal_length’], color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=2)</p><h3>Q.5. Explain Visualizations for hierarchies dataset</h3><p>While some data is just a flat collection of numbers, most can be organized into natural hierarchies.</p><p>Consider spatial units such as counties, states and countries; corporate and government command structures; software packages and phylogenetic trees. Even for data without an obvious hierarchy, statistical methods (eg k-means clustering) can be used to organize the data empirically.</p><p>To take advantage of the hierarchical structure, there are special imaging techniques that allow rapid multidimensional inference: micro-observations of individual elements and macro-observations of large groups.</p><figure><img alt="Image1" src="https://cdn-images-1.medium.com/proxy/0*uTIqdbZiYFiAlLDp" /></figure><figure><img alt="Image1" src="https://cdn-images-1.medium.com/proxy/0*tznFUREfgwQ5b1me" /></figure><h3>Q.5. Prepare an ordered stem and leaf plot for the data. Briefly comment on what the analysis shows.</h3><p>The weights (to the nearest tenth of a kilogram) of 30 students were measured and recorded as follows:</p><p>59.2, 61.5, 62.3, 61.4, 60.9, 59.8, 60.5, 59.0, 61.1, 60.7, 61.6, 56.3, 61.9, 65.7, 60.4, 58.9, 59.0, 61.2, 62.1, 61.4, 58.4, 60.8, 60.2, 62.7, 60.0, 59.3, 61.9, 61.7, 58.4, 62.2</p><pre>! pip install stemgraphic</pre><pre>Requirement already satisfied: stemgraphic in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (0.9.1)<br>Requirement already satisfied: seaborn in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from stemgraphic) (0.11.2)<br>Requirement already satisfied: pandas in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from stemgraphic) (1.3.4)<br>Requirement already satisfied: docopt in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from stemgraphic) (0.6.2)<br>Requirement already satisfied: matplotlib in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from stemgraphic) (3.7.1)<br>Requirement already satisfied: pyparsing&gt;=2.3.1 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (3.0.4)<br>Requirement already satisfied: pillow&gt;=6.2.0 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (8.4.0)<br>Requirement already satisfied: importlib-resources&gt;=3.2.0 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (5.4.0)<br>Requirement already satisfied: fonttools&gt;=4.22.0 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (4.25.0)<br>Requirement already satisfied: packaging&gt;=20.0 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (21.0)<br>Requirement already satisfied: kiwisolver&gt;=1.0.1 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (1.3.1)<br>Requirement already satisfied: python-dateutil&gt;=2.7 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (2.8.2)<br>Requirement already satisfied: numpy&gt;=1.20 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (1.22.4)<br>Requirement already satisfied: contourpy&gt;=1.0.1 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (1.0.7)<br>Requirement already satisfied: cycler&gt;=0.10 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from matplotlib-&gt;stemgraphic) (0.10.0)<br>Requirement already satisfied: six in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from cycler&gt;=0.10-&gt;matplotlib-&gt;stemgraphic) (1.16.0)<br>Requirement already satisfied: zipp&gt;=3.1.0 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from importlib-resources&gt;=3.2.0-&gt;matplotlib-&gt;stemgraphic) (3.6.0)<br>Requirement already satisfied: pytz&gt;=2017.3 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from pandas-&gt;stemgraphic) (2021.3)<br>Requirement already satisfied: scipy&gt;=1.0 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from seaborn-&gt;stemgraphic) (1.7.1)</pre><pre># importing the module<br>import stemgraphic<br>  <br>data = [59.2, 61.5, 62.3, 61.4, 60.9, 59.8, 60.5, 59.0, 61.1, 60.7, 61.6, 56.3, 61.9, 65.7, 60.4, 58.9, 59.0, 61.2, 62.1, 61.4, 58.4, 60.8, 60.2, 62.7, 60.0, 59.3, 61.9, 61.7, 58.4, 62.2]<br>  <br># calling stem_graphic with required parameters,<br># data and scale<br>stemgraphic.stem_graphic(data, scale = 1)</pre><pre>(&lt;Figure size 540x234 with 1 Axes&gt;, &lt;Axes: &gt;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*ftJYfOU8pZmnQmCdS4GBIg.png" /></figure><p>We will use the scale of 1 to get the decimal points plotted</p><p>In this case, the stems will be the whole number values and the leaves will be the decimal values. The data range from 56.3 to 65.7, so the stems should start at 56 and finish at 65.</p><p>In this example, it was not necessary to split stems because the leaves are not crowded on too few stems; nor was it necessary to round the values, since the range of values is not large. This stem and leaf plot reveals that the group with the highest number of observations recorded is the 61.0 to 61.9 group.</p><h3>Q.6.</h3><p>Britney is a swimmer training for a competition. The number of 50-metre laps she swam each day for 30 days is as follows:</p><p>22, 21, 24, 19, 27, 28, 24, 25, 29, 28, 26, 31, 28, 27, 22, 39, 20, 10, 26, 24, 27, 28, 26, 28, 18, 32, 29, 25, 31, 27</p><p>Prepare an ordered stem and leaf plot.</p><p>for, Laps swum by Britney in 30 days</p><pre># importing the module<br>import stemgraphic<br>  <br>data = [22, 21, 24, 19, 27, 28, 24, 25, 29, 28, 26, 31, 28, 27, 22, 39, 20, 10, 26, 24, 27, 28, 26, 28, 18, 32, 29, 25, 31, 27]<br># calling stem_graphic with required parameters,<br># data and scale<br>stemgraphic.stem_graphic(data, scale = 10)</pre><pre>(&lt;Figure size 540x108 with 1 Axes&gt;, &lt;Axes: &gt;)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*TUTNpL0BZWZcWdc0wR18XA.png" /></figure><h3>Q.7. Which method shows hierarchical data in a nested format?</h3><ul><li>A. Adajency Diagrams</li><li>B. Scatter Plot</li><li>C. Q-Q Plot</li><li>D. Parallel Coordinates</li></ul><h4><strong>Ans — A. Adajency Diagrams</strong></h4><h3>Q.8. which chart is used for displaying multiple variables</h3><h4><strong>Ans. — Scatter plot Matrix</strong></h4><h3>Q.9. which chart is used for plotting non numerical data</h3><h4><strong>Ans. — Stem and Leaf Plot</strong></h4><h3>Q.10. Explain Enclosure Diagrams and its use in machine learning with example</h3><h4><strong>Ans.</strong></h4><p>An enclosed diagram is a type of diagram that uses enclosed shapes to represent different groups or classes within a dataset. The shapes are often color-coded or labeled to indicate the class they represent, and the diagram can help identify patterns or clusters of data points that belong to the same class.</p><p>In machine learning, enclosed diagrams can be useful for visualizing the output of clustering algorithms, such as k-means or hierarchical clustering. By grouping similar data points into clusters, these algorithms can help identify patterns and structure in large datasets. Enclosed diagrams can then be used to visualize the results of the clustering, making it easier to interpret the results and identify any outliers or anomalies in the data.</p><p>Overall, enclosed diagrams can be a valuable tool for visualizing complex datasets and identifying patterns or clusters of data points, especially in unsupervised learning tasks such as clustering.</p><pre>! pip install gapminder</pre><pre>Requirement already satisfied: gapminder in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (0.1)<br>Requirement already satisfied: pandas in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from gapminder) (1.3.4)<br>Requirement already satisfied: python-dateutil&gt;=2.7.3 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from pandas-&gt;gapminder) (2.8.2)<br>Requirement already satisfied: pytz&gt;=2017.3 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from pandas-&gt;gapminder) (2021.3)<br>Requirement already satisfied: numpy&gt;=1.17.3 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from pandas-&gt;gapminder) (1.22.4)<br>Requirement already satisfied: six&gt;=1.5 in /Users/cibaca/opt/anaconda3/lib/python3.8/site-packages (from python-dateutil&gt;=2.7.3-&gt;pandas-&gt;gapminder) (1.16.0)</pre><pre># libraries<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from gapminder import gapminder # data set<br><br># data<br>data = gapminder.loc[gapminder.year == 2007]<br><br># use the scatterplot function to build the bubble map<br>sns.scatterplot(data=data, x=&quot;gdpPercap&quot;, y=&quot;lifeExp&quot;, size=&quot;pop&quot;, legend=False, sizes=(20, 2000))<br><br># show the graph<br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*MDefDQh9n5B2uEYmPUvJrA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3da97b658a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/quiz-data-a-tour-through-visualization-zoo-c3da97b658a0">Quiz__data_A_tour_through_visualization_zoo</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crash Course in Data — Uncovering Relationships: Visualizing Multivariate Data with Scatter Plot…]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-data-uncovering-relationships-visualizing-multivariate-data-with-scatter-plot-6b98d6acbe5e?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b98d6acbe5e</guid>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 19:07:36 GMT</pubDate>
            <atom:updated>2023-03-14T19:07:36.040Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash Course in Data — Uncovering Relationships: Visualizing Multivariate Data with Scatter Plot Matrices</h3><p>Scatter plot matrix is a matrix (or grid) of scatter plots where each scatter plot in the grid is created between different combinations of variables.</p><p>In other words, scatter plot matrix represents bi-variate or pairwise relationship between different combinations of variables while laying them in grid form.</p><p>A scatterplot matrix, also known as a pair plot or SPLOM, is a visualization tool that allows you to explore relationships between multiple variables. Here are some of the more common uses of the scatter matrix:</p><ol><li><strong>Exploratory Data Analysis</strong>:</li></ol><p>The scatter matrix is ​​often used in exploratory data analysis to visualize relationships between multiple variables in a data set. By looking at scatter plots, you can quickly identify interesting patterns or trends in the data, as well as any outliers or outliers.</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br>sns.set_theme(style=&quot;ticks&quot;)<br><br>df_penguins = sns.load_dataset(&quot;penguins&quot;)<br>sns.pairplot(df_penguins, hue=&quot;species&quot;)</pre><pre>&lt;seaborn.axisgrid.PairGrid at 0x7f9080964be0&gt;</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*oG2VMsaenplT9cIqla0GnQ.png" /></figure><p><strong>2. Correlation analysis</strong>:</p><p>A covariance matrix can be used to analyze the correlation between variables. By looking at scatterplots, you can see whether there is a linear or non-linear relationship between each pair of variables, and whether the relationship is positive or negative.</p><pre>sns.pairplot(df_penguins, hue=&#39;species&#39;)<br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*ny6SP7hNKd854hbuFJPrwA.png" /></figure><p><strong>3. Multivariate Analysis</strong>:</p><p>A covariance matrix can be used to visualize the relationship between multiple variables in a data set. This can be useful if you have many variables and want to see how they relate to each other.</p><pre>df_tips = sns.load_dataset(&#39;tips&#39;)<br>sns.pairplot(df_tips, hue=&#39;sex&#39;)<br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*DVYdmwFJGmc8f-gtmJ0wsA.png" /></figure><p><strong>4. Feature Selection</strong>:</p><p>A disambiguation matrix can be used to select the most important features for a predictive model. By looking at scatterplots, you can see which variables are most strongly correlated with the target variable and which are not.</p><pre>sns.pairplot(df_tips, vars=[&#39;total_bill&#39;, &#39;tip&#39;])<br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*QqBS287CerzALXGyGfkkTQ.png" /></figure><p><strong>5. Outlier Detection</strong>:</p><p>A scatter matrix can be used to detect outliers in a dataset. Outliers are data points that are significantly different from other data points and can be identified by looking at scatterplots.</p><pre>import plotly.express as px<br>df_iris = px.data.iris()</pre><pre>sns.pairplot(df_iris, diag_kind=&#39;hist&#39;)<br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*Ll68MPSJrnffE3wXu9Zm4w.png" /></figure><p>In conclusion, the disc matrix is ​​a powerful tool for exploring the relationships between multiple variables in a dataset and can be used for a variety of data analysis tasks, from exploratory data analysis to feature selection and outlier detection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b98d6acbe5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-data-uncovering-relationships-visualizing-multivariate-data-with-scatter-plot-6b98d6acbe5e">Crash Course in Data — Uncovering Relationships: Visualizing Multivariate Data with Scatter Plot…</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crash Course in Data — Seeing is Believing: Exploring Data Distributions with Q-Q Plots]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-data-seeing-is-believing-exploring-data-distributions-with-q-q-plots-803992fae0da?source=rss-3ef3acb31418------2</link>
            <guid isPermaLink="false">https://medium.com/p/803992fae0da</guid>
            <dc:creator><![CDATA[Cibaca Khandelwal]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 19:04:35 GMT</pubDate>
            <atom:updated>2023-03-14T19:04:35.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crash Course in Data — Seeing is Believing: Exploring Data Distributions with Q-Q Plots</h3><ul><li>In statistics, a Q–Q plot (quantile-quantile plot) is a probability plot, a graphical method for comparing two probability distributions by plotting their quantiles against each other.</li><li>A point (x, y) on the plot corresponds to one of the quantiles of the second distribution (y-coordinate) plotted against the same quantile of the first distribution (x-coordinate).</li><li>This defines a parametric curve where the parameter is the index of the quantile interval.</li></ul><figure><img alt="Image" src="https://cdn-images-1.medium.com/proxy/0*lsbu809F5gOZrrKX" /></figure><p>The quantiles of the first data set are plotted against the quantiles of the second data set in a q-q graphic. A quantile is the percentage of points that fall below the specified number. In other words, the 0.3 (or 30%) quantile is the value at which 30% of the data are below it and 70% are above it.</p><p>Moreover, <strong>a 45-degree reference line is plotted.</strong> The points should roughly lie along this reference line if the two sets are drawn from a population with the same distribution. The further the two data sets deviate from this reference line, the more evidence there is that they came from populations with different distributions.</p><pre>import numpy as np<br><br>#create dataset with 100 values that follow a normal distribution<br>np.random.seed(0)<br>data = np.random.normal(0,1, 1000)<br><br>#view first 10 values<br>data[:10]</pre><pre>array([ 1.76405235,  0.40015721,  0.97873798,  2.2408932 ,  1.86755799,<br>       -0.97727788,  0.95008842, -0.15135721, -0.10321885,  0.4105985 ])</pre><pre>import statsmodels.api as sm<br>import matplotlib.pyplot as plt<br><br>#create Q-Q plot with 45-degree line added to plot<br>fig = sm.qqplot(data, line=&#39;45&#39;)<br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*pnCJY70xBwwK7PbC2-N7NA.png" /></figure><p>The q-q plot is formed by:</p><ul><li>Vertical axis: Estimated quantiles from data set 1</li><li>Horizontal axis: Estimated quantiles from data set 2</li></ul><p>The units on both axes correspond to the corresponding data sets. The real quantile level is not plotted, in other words. The quantile level for a specific point on the q-q plot is known to be the same for both points, but its precise value is unknown.</p><p>The q-q plot is essentially a plot of sorted data set 1 against sorted data set 2 if the data sets are the same size. The quantiles are often chosen to match the sorted values from the smaller data set in cases when the data sets are not equal in size, and the quantiles for the bigger data set are then interpolated.</p><p>The following inquiries are addressed with the q-q plot:</p><ul><li>Are there common distributions between the two data sets?</li><li>Do the scale and location of two data sets match up?</li><li>Do the distributional forms of two data sets compare?</li><li>Do the tails of two data sets compare?</li></ul><h4>Usage of Q-Q plot</h4><p>Q-Q plots (Quantile-Quantile plots) are a type of graphical technique used to compare two probability distributions. The primary use cases of Q-Q plots are:</p><ol><li><strong>Testing for normality</strong>:</li></ol><p>Q-Q plots are commonly used to test if a dataset follows a normal distribution. If the data points fall close to the straight line on the Q-Q plot, it indicates that the data follows a normal distribution. If the data points deviate from the straight line, it suggests that the data does not follow a normal distribution.</p><ol><li><strong>Comparing distributions</strong>:</li></ol><p>Q-Q plots can be used to compare two distributions to see if they are similar or different. If the two distributions are similar, the Q-Q plot will show the data points falling close to the straight line. If the two distributions are different, the Q-Q plot will show the data points deviating from the straight line.</p><ol><li><strong>Identifying outliers</strong>:</li></ol><p>Q-Q plots can be used to identify outliers in a dataset. Outliers are data points that are significantly different from the other data points in the dataset. These data points will appear as points that deviate from the straight line on the Q-Q plot.</p><ol><li><strong>Checking for linearity</strong>:</li></ol><p>Q-Q plots can be used to check the linearity of a relationship between two variables. If the data points fall close to the straight line on the Q-Q plot, it suggests that the relationship between the two variables is linear.</p><ol><li><strong>Assessing model assumptions</strong>:</li></ol><p>Q-Q plots can be used to assess the assumptions of statistical models. If the residuals (the difference between the predicted values and the actual values) of a model follow a normal distribution, the Q-Q plot of the residuals will show the data points falling close to the straight line. If the residuals do not follow a normal distribution, the Q-Q plot will show the data points deviating from the straight line.</p><p>Overall, Q-Q plots are a useful tool for visualizing and comparing probability distributions, and can help identify patterns and anomalies in the data.</p><h4>1. Testing for normality</h4><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br>def qqplot_normality_test(data):<br>    &quot;&quot;&quot;<br>    This function generates a QQ plot for testing normality of a given data sample.<br><br>    Parameters:<br>        data (numpy array or pandas series): The data sample to test for normality.<br><br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    # Sort the data in ascending order<br>    sorted_data = np.sort(data)<br><br>    # Compute the expected quantiles for a normal distribution<br>    expected_quantiles = stats.norm.ppf(np.linspace(0.01, 0.99, len(data)))<br><br>    # Generate the QQ plot<br>    plt.figure(figsize=(8, 6))<br>    plt.scatter(expected_quantiles, sorted_data)<br>    plt.xlabel(&#39;Expected Quantiles (Normal Distribution)&#39;)<br>    plt.ylabel(&#39;Observed Quantiles (Data Sample)&#39;)<br>    plt.title(&#39;Q-Q Plot for Normality Test&#39;)<br>    plt.show()</pre><p>This function takes a data sample as input and generates a QQ plot for testing the normality of the data.</p><p>First, the function sorts the data in ascending order using the np.sort() function. It then computes the expected quantiles for a normal distribution using the stats.norm.ppf() function, which computes the inverse of the cumulative distribution function for a normal distribution. We generate 100 quantiles between 0.01 and 0.99, which should be sufficient for most cases.</p><p>Finally, the function generates the QQ plot using the plt.scatter() function and adds labels and a title to the plot using the plt.xlabel(), plt.ylabel(), and plt.title() functions. The resulting plot will show how closely the data sample follows a normal distribution. If the points fall along a straight line, it suggests that the data is normally distributed. If the points deviate from the straight line, it indicates that the data is not normally distributed.</p><p>To use this function, you simply need to pass in a numpy array or pandas series containing your data sample. For example, if you have a numpy array called my_data containing your data, you would call the function like this:</p><pre>my_data = np.random.normal(0,1, 1000)<br>qqplot_normality_test(my_data)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*AQuS2Vul3wcLTMiBJbRK1Q.png" /></figure><pre># Set the parameters of the beta distribution<br>alpha = 2<br>beta = 5<br><br># Generate a sample of 1000 random numbers from the beta distribution<br>sample = np.random.beta(alpha, beta, size=1000)</pre><pre>qqplot_normality_test(sample)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*zl5EqU28YHRww2n8yjsctA.png" /></figure><p>The first graphs forms straight line and confirms that it is a normal distribution but the second graph is a curve which proves that QQ plot can be used as a test of Normality.</p><h4>2. Comparing Distributions</h4><p>Q-Q plots can be used to compare any probability distribution to a reference distribution, including beta distributions.</p><p>To create a Q-Q plot for a beta distribution, you would first need to generate a random sample from the beta distribution that you want to compare to the reference distribution. Then, you would plot the quantiles of the sample against the quantiles of the reference distribution on a scatter plot.</p><p>The Q-Q plot will show how well the beta distribution fits the reference distribution. If the data points on the Q-Q plot follow a straight line, it suggests that the beta distribution is a good fit for the reference distribution. If the data points deviate from the straight line, it indicates that the beta distribution is not a good fit.</p><p>It’s worth noting that beta distributions can take on different shapes depending on the values of the parameters alpha and beta. Therefore, it may be useful to create multiple Q-Q plots with different parameter values to compare how well the beta distribution fits the reference distribution under different scenarios.</p><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br># Set the parameters of the beta distribution<br>alpha = 2<br>beta = 5<br><br># Generate a sample of 1000 random numbers from the beta distribution<br>sample = np.random.beta(alpha, beta, size=1000)<br><br># Generate the theoretical quantiles for a beta distribution with the same parameters<br>beta_dist = stats.beta(alpha, beta)<br>quantiles = beta_dist.ppf(np.linspace(0.01, 0.99, 100))<br><br># Create the Q-Q plot<br>plt.figure(figsize=(8, 6))<br>stats.probplot(sample, dist=beta_dist, plot=plt)<br>plt.plot(quantiles, quantiles, color=&#39;red&#39;, linestyle=&#39;--&#39;)<br>plt.xlabel(&#39;Theoretical Quantiles&#39;)<br>plt.ylabel(&#39;Sample Quantiles&#39;)<br>plt.title(&#39;Q-Q Plot for Beta Distribution&#39;)<br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*LAKnUNxs10NvqTCV-XjPQw.png" /></figure><p>In this code, we first set the parameters alpha and beta for the beta distribution. We then generate a sample of 1000 random numbers from the beta distribution using the np.random.beta() function.</p><p>Next, we generate the theoretical quantiles for the beta distribution with the same parameters using the stats.beta.ppf() function, which computes the inverse of the cumulative distribution function for the beta distribution. We generate 100 quantiles between 0.01 and 0.99.</p><p>Finally, we create the Q-Q plot using the stats.probplot() function, which takes the sample and the reference distribution as arguments. We also plot the line of perfect fit using the plt.plot() function, and add labels and a title to the plot using the plt.xlabel(), plt.ylabel(), and plt.title() functions.</p><p>This code will create a Q-Q plot showing how well the sample of data fits a beta distribution with the given parameters. You can change the values of alpha and beta to create Q-Q plots for different beta distributions.</p><h4>3. Identifying outliers</h4><p>This function works in a similar way to the previous function, but with an additional step for identifying outliers. After computing the expected quantiles and sorting the data, the function computes the absolute differences between the observed and expected quantiles using np.abs(). It then computes the median absolute deviation (MAD) of these differences using np.median().</p><p>The MAD is a robust measure of dispersion that is less sensitive to outliers than the standard deviation. We can use the MAD to identify outliers in the QQ plot by drawing a horizontal line at a distance of 1.5 times the MAD from the expected quantiles. Any points that fall above or below this line may be considered outliers.</p><p>To generate the QQ plot with the outlier detection line, we simply add a plt.plot() call after the scatter plot. The plt.plot() call specifies the endpoints of the line as the first and last expected quantiles, and the MAD times 1.5 above and below these quantiles. The resulting plot will show the data points along with the expected quantiles and the outlier detection line.</p><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br>def qqplot_outliers(data):<br>    &quot;&quot;&quot;<br>    This function generates a QQ plot for identifying outliers in a given data sample.<br><br>    Parameters:<br>        data (numpy array or pandas series): The data sample to test for outliers.<br><br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    # Sort the data in ascending order<br>    sorted_data = np.sort(data)<br><br>    # Compute the expected quantiles for a normal distribution<br>    expected_quantiles = stats.norm.ppf(np.linspace(0.01, 0.99, len(data)))<br><br>    # Compute the absolute differences between observed and expected quantiles<br>    absolute_diff = np.abs(sorted_data - expected_quantiles)<br><br>    # Compute the median absolute deviation<br>    mad = np.median(absolute_diff)<br><br>    # Generate the QQ plot<br>    plt.figure(figsize=(8, 6))<br>    plt.scatter(expected_quantiles, sorted_data)<br>    plt.xlabel(&#39;Expected Quantiles (Normal Distribution)&#39;)<br>    plt.ylabel(&#39;Observed Quantiles (Data Sample)&#39;)<br>    plt.title(&#39;Q-Q Plot for Identifying Outliers&#39;)<br>    plt.plot([expected_quantiles[0], expected_quantiles[-1]], [expected_quantiles[0] - mad, expected_quantiles[-1] + mad], color=&#39;r&#39;)<br>    plt.show()</pre><pre>qqplot_outliers(my_data)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*uOVfd5xFwySwiyT2qPbheA.png" /></figure><h4>4. Checking for linearity</h4><p>This function takes two arguments, x and y, which should be numpy arrays or pandas series containing the values of the two variables you want to check for linearity. The function computes the expected quantiles for a normal distribution using stats.norm.ppf(), and sorts the data for each variable in ascending order using np.sort(). It then computes the quantiles for each variable using stats.rankdata(), which converts the sorted data to a percentage of the total number of observations.</p><p>The QQ plot is generated using plt.scatter(), with the expected quantiles on the x-axis and the quantiles for the second variable on the y-axis. We add a red line to the plot using plt.plot(), which represents a perfectly linear relationship between the two variables. If the scatter plot of the quantiles closely follows the red line, it suggests that the two variables are linearly related.</p><p>To use this function, you simply need to pass in the numpy arrays or pandas series containing your two variables. For example, if you have numpy arrays called x and y containing your variables, you would call the function like this:</p><pre>import numpy as np<br>import scipy.stats as stats<br>import matplotlib.pyplot as plt<br><br>def qqplot_linearity(x, y):<br>    &quot;&quot;&quot;<br>    This function generates a QQ plot to check for linearity between two variables.<br><br>    Parameters:<br>        x (numpy array or pandas series): The values of the first variable.<br>        y (numpy array or pandas series): The values of the second variable.<br><br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    # Compute the expected quantiles for a normal distribution<br>    expected_quantiles = stats.norm.ppf(np.linspace(0.01, 0.99, len(x)))<br><br>    # Sort the data for each variable in ascending order<br>    sorted_x = np.sort(x)<br>    sorted_y = np.sort(y)<br><br>    # Compute the quantiles for each variable<br>    quantiles_x = stats.rankdata(sorted_x) / len(sorted_x)<br>    quantiles_y = stats.rankdata(sorted_y) / len(sorted_y)<br><br>    # Generate the QQ plot<br>    plt.figure(figsize=(8, 6))<br>    plt.scatter(expected_quantiles, quantiles_y)<br>    plt.xlabel(&#39;Expected Quantiles (Normal Distribution)&#39;)<br>    plt.ylabel(&#39;Observed Quantiles (Second Variable)&#39;)<br>    plt.title(&#39;Q-Q Plot for Checking Linearity&#39;)<br>    plt.plot([0, 1], [0, 1], color=&#39;r&#39;)<br>    plt.show()</pre><pre>x1 = np.random.normal(1,2,1000)<br>x2 = np.random.normal(1,2,1000)<br>qqplot_linearity(x1, x2)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*bNLSw1oIgEjRLonVRgfHKA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=803992fae0da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-data-seeing-is-believing-exploring-data-distributions-with-q-q-plots-803992fae0da">Crash Course in Data — Seeing is Believing: Exploring Data Distributions with Q-Q Plots</a> was originally published in <a href="https://medium.com/aiskunks">AI Skunks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>