<?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 Harshit Mittal on Medium]]></title>
        <description><![CDATA[Stories by Harshit Mittal on Medium]]></description>
        <link>https://medium.com/@hmittal15?source=rss-d66a43d41e01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*40U0bVSnalg16pRiA5AbFg.jpeg</url>
            <title>Stories by Harshit Mittal on Medium</title>
            <link>https://medium.com/@hmittal15?source=rss-d66a43d41e01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:09:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hmittal15/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[Check your knowledge: Causality in Data Science]]></title>
            <link>https://medium.com/aiskunks/check-your-knowledge-causality-in-data-science-95a27824ead?source=rss-d66a43d41e01------2</link>
            <guid isPermaLink="false">https://medium.com/p/95a27824ead</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[treatment-effect]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[causality]]></category>
            <dc:creator><![CDATA[Harshit Mittal]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 02:34:34 GMT</pubDate>
            <atom:updated>2023-04-24T16:23:55.823Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the Causal Inference Quiz! Test your knowledge on the concepts of causality, treatment effects, challenges in inferring causality, and more. This quiz consists of 10 multiple-choice questions with 4 options each. Choose the best answer and see how much you know about causal inference.</p><ol><li><strong>What is the difference between correlation and causation?</strong></li></ol><p>a) Correlation implies causation, while causation does not imply correlation</p><p>b) Correlation is the relationship between two variables where they change together, while causation is the relationship between two variables where one variable causes a change in the other variable</p><p>c) There is no difference between correlation and causation</p><p>d) Causation always implies correlation</p><p><em>Answer</em>: b)</p><p><strong>2. What are the three fundamental criteria for establishing causality?</strong></p><p>a) Temporal precedence, correlation, and magnitude</p><p>b) Correlation, magnitude, and consistency</p><p>c) Temporal precedence, correlation, and non-spuriousness</p><p>d) Temporal precedence, Correlation, and consistency</p><p><em>Answer:</em> c)</p><p>3. <strong>What is the difference between a confounder and a mediator?</strong></p><p>a) A confounder is a variable that affects both the independent and dependent variables, while a mediator explains the relationship between the independent and dependent variables</p><p>b) A confounder explains the relationship between the independent and dependent variables, while a mediator is a variable that affects both the independent and dependent variables</p><p>c) There is no difference between a confounder and a mediator</p><p>d) A mediator explains the relationship between the independent and dependent variables, while a confounder is a variable that affects both the independent and dependent variables</p><p><em>Answer:</em> a)</p><p>4. <strong>What is the average treatment effect (ATE)?</strong></p><p>a) The difference between the treatment and control groups</p><p>b) The difference in outcomes between the treatment and control groups, adjusted for confounding variables</p><p>c) The ratio of outcomes between the treated and untreated groups</p><p>d) The probability of treatment success</p><p><em>Answer</em>: b)</p><p>5. <strong>What is the difference between the average treatment effect on the treated (ATT) and the conditional average treatment effect (CATE)?</strong></p><p>a) The ATT measures the effect of treatment on those who received it, while the CATE measures the effect of treatment on different subgroups</p><p>b) The ATT measures the effect of treatment on different subgroups, while the CATE measures the effect of treatment on those who received it</p><p>c) There is no difference between the ATT and CATE</p><p>d) ATE is the effect of the treatment on a subgroup of the population, while CATE is the effect of the treatment on the whole population.</p><p><em>Answer:</em> a)</p><p>6. <strong>What is a randomized control trial (RCT)?</strong></p><p>a) A study design where participants are randomly assigned to treatment and control groups</p><p>b) A study design where participants self-select into treatment and control groups</p><p>c) A study design where the researcher assigns participants to treatment and control groups based on their characteristics</p><p>d) The difference between the treatment and control groups</p><p><em>Answer:</em> a)</p><p>7. <strong>What is the role of instrumental variables in causal inference?</strong></p><p>a) To control for confounding variables in observational studies</p><p>b) To create a control group in randomized controlled trials</p><p>c) To estimate the effect of a treatment on a specific subgroup</p><p>d) To identify the causal effect of a treatment in the presence of unobserved confounders</p><p><em>Answer:</em> d)</p><p>8. <strong>What is the difference between the Average Treatment Effect (ATE) and the Average Treatment Effect on the Treated (ATT)?</strong></p><p>a) ATE is the effect of the treatment on the whole population, while ATT is the effect of the treatment on a subgroup of the population.</p><p>b) ATE is the effect of the treatment on a subgroup of the population, while ATT is the effect of the treatment on the whole population.</p><p>c) ATE and ATT are the same thing. d) ATE and ATT are not related to treatment effects.</p><p>d) The ATT measures the effect of treatment on different subgroups, while the ATT measures the effect of treatment on those who received it</p><p><em>Answer:</em> a)</p><p>9. <strong>What is selection bias?</strong></p><p>a) Bias that arises when the sample size is too small.</p><p>b) Bias that arises when the sample is not representative of the population.</p><p>c) Bias that arises when there are confounding variables in the analysis.</p><p>d) Bias that arises when the data is missing.</p><p><em>Answer:</em> b)</p><p>10. <strong>What is the purpose of propensity score matching?</strong></p><p>a) To adjust for confounding variables in observational studies</p><p>b) To create a control group in randomized controlled trials</p><p>c) To estimate the effect of a treatment on a specific subgroup</p><p>d) To control for reverse causality</p><p><em>Answer:</em> a)</p><p>Congratulations, you have completed the Causal Inference Quiz! I hope this quiz has deepened your understanding of causal inference and its related concepts. Keep exploring the fascinating world of causality, and remember, correlation does not always equal causation!</p><p>Want to learn more about Causality? Dive deep into the pool of knowledge <a href="https://medium.com/@hmittal15/crash-course-in-causality-2cc7eccf3f41">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95a27824ead" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/check-your-knowledge-causality-in-data-science-95a27824ead">Check your knowledge: Causality in Data Science</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]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-causality-2cc7eccf3f41?source=rss-d66a43d41e01------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cc7eccf3f41</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[causality]]></category>
            <category><![CDATA[treatment-effect]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Harshit Mittal]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 02:12:21 GMT</pubDate>
            <atom:updated>2023-04-24T16:22:28.847Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine that you are walking down the street and you see a puddle of water. You can see that the puddle is caused by the rain, but you cannot see the rain itself. This is because the rain is a hidden variable.</p><p>Causal inference is the process of trying to figure out what the hidden variables are. In this case, we are trying to figure out what caused the puddle of water. We know that the rain caused the puddle, but we cannot see the rain itself. Causal inference is a challenging task, but it is an important one. By understanding causality, we can make better decisions and have a real impact on the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*9ONRJtpUuOl0zvHpltFurQ.jpeg" /><figcaption>The dynamo effect</figcaption></figure><p>In data science, we often aim to answer questions about causality: Does X cause Y? If so, how strong is the causal effect of X on Y? These questions are important for understanding the world around us and making data-driven decisions. In this article, we’ll explore the concepts of causality and causal inference in data science, and discuss some of the challenges and techniques for inferring causal relationships from data.</p><h3>Table of contents</h3><ul><li>What is Causality?</li><li>Correlation v/s Causation</li><li>Causal inference fundamentals</li><li>The language of causation</li><li>Treatment effects</li><li>Challenges in inferreing causality</li><li>Inferreing causality in air pollution</li><li>Conclusion</li><li>References</li></ul><h3>What is Causality?</h3><p>Causality is a fundamental concept in science and philosophy, referring to the relationship between an event (the cause) and a second event (the effect), where the second event is understood as a consequence of the first. Causality implies that there is a direct and meaningful relationship between two events, where the first event is necessary for the second to occur.</p><p>In data science, we often want to understand causal relationships between variables. For example, we may want to know if smoking causes lung cancer, or if a marketing campaign causes an increase in sales. However, inferring causality from observational data can be difficult, as there are often confounding variables that can affect both the cause and effect.</p><h3>Correlation v/s Causation</h3><p>While these two terms are often used interchangeably, they actually have very different meanings.</p><p><strong>Correlation </strong>refers to a statistical relationship between two variables. When two variables are correlated, it means that there is a pattern or tendency for one variable to change in a predictable way when the other variable changes.</p><p><strong><em>For example</em></strong>, there may be a positive correlation between ice cream sales and temperature, which means that as temperature increases, ice cream sales tend to increase as well. Correlation can be measured using a variety of statistical methods, such as Pearson’s correlation coefficient or Spearman’s rank correlation coefficient.</p><p><strong>Causation</strong>, on the other hand, refers to a relationship where one variable directly causes another variable to change. In other words, causation implies that there is a mechanism or process that links the two variables together. Causation is much more difficult to establish than correlation, and typically requires experimental or quasi-experimental designs that can control for confounding variables.</p><p>One way to remember the difference between correlation and causation is the phrase “correlation does not imply causation.” Just because two variables are correlated, it does not necessarily mean that one variable causes the other. There may be other factors or variables that influence both variables, or the relationship may be purely coincidental.</p><p>Here’s an <strong><em>example</em></strong> to illustrate the difference between correlation and causation: Suppose we are interested in studying the relationship between ice cream sales and crime rates. We collect data on ice cream sales and crime rates in a particular city over several months, and find that there is a strong positive correlation between the two variables. In other words, as ice cream sales increase, crime rates tend to increase as well. However, it would be a mistake to conclude that ice cream sales cause crime. There are likely other variables that influence both variables, such as temperature or time of day. It’s also possible that the relationship is purely coincidental, and there is no causal link between the two variables at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ato6S5rvNIDy7WveK1iC5A.png" /><figcaption>Correlation VS Causation</figcaption></figure><h3>Causal inference fundamentals</h3><ul><li><strong>Counterfactuals:</strong></li></ul><p>Counterfactuals refer to the notion of what would have happened if a particular event or intervention had not occurred or if a different action had been taken. In other words, it is the hypothetical scenario of what would have been observed if the treatment or exposure was different from what it actually was.</p><p><strong><em>For example</em></strong>, consider a study that investigates the effectiveness of a new medication on reducing blood pressure. The group of participants who received the medication is referred to as the treatment group, while the group that did not receive the medication is the control group. The outcome of interest is the change in blood pressure after a certain period.</p><p>The counterfactual outcome for a participant in the treatment group is the hypothetical outcome if they did not receive the medication. Similarly, the counterfactual outcome for a participant in the control group is the hypothetical outcome if they did receive the medication.</p><ul><li><strong>Instrumental variables:</strong></li></ul><p>Instrumental variables (IV) are a statistical technique used to estimate causal effects when there is unobserved confounding between the treatment and the outcome variable. IVs use a third variable, known as an instrument, that affects the treatment variable but has no direct effect on the outcome variable, to estimate the causal effect.</p><p>An <strong><em>example</em></strong> of instrumental variables could be in estimating the causal effect of education on earnings. Let’s say we are interested in knowing if a college degree causes higher earnings. However, there could be confounding variables that affect both education and earnings, such as natural abilities or socioeconomic status. An instrumental variable could be the distance to the nearest college. Distance to the nearest college is related to the likelihood of attending college, but has no direct effect on earnings. The idea is that people who live closer to a college are more likely to attend college, but their proximity to a college does not affect their earnings directly. By using distance to the nearest college as an instrument, we can estimate the causal effect of education on earnings.</p><p>The IV inference equation is:</p><p>Y = a + bX + e X = c + zD + u</p><p>Where:</p><p>Y is the outcome variable (e.g., earnings)</p><p>X is the treatment variable (e.g., education)</p><p>D is the instrument variable (e.g., distance to the nearest college)</p><p>a, b, c, and z are coefficients to be estimated</p><p>e and u are error terms</p><ul><li><strong>Randomized Control Trials (RCTs):</strong></li></ul><p>Randomized Control Trials (RCTs) are experiments in which individuals or groups are randomly assigned to either a treatment group or a control group to determine the causal effect of the treatment. This method is widely used in medical research, psychology, education, and social sciences.</p><p>Let’s look into an <strong><em>example</em></strong> of an RCT in the medical field:</p><p>Suppose a pharmaceutical company has developed a new drug for treating high blood pressure. To determine whether the drug is effective, the company conducts an RCT. They randomly select 500 patients with high blood pressure and divide them into two groups — a treatment group and a control group. The treatment group is given the new drug, and the control group is given a placebo (a harmless pill that looks identical to the drug). Both groups are unaware of whether they are receiving the drug or the placebo.</p><p>After a certain period, the company measures the blood pressure of both groups and compares the results. They find that the treatment group’s blood pressure has decreased significantly compared to the control group. Thus, they can conclude that the new drug is effective in treating high blood pressure.</p><p>The key advantage of RCTs is that they eliminate the possibility of confounding variables, which are factors that could affect the outcome but are not controlled for in the study. By randomly assigning participants to the treatment and control groups, any confounding variables are equally distributed between the two groups, making it easier to determine the causal effect of the treatment.</p><ul><li><strong>Propensity score matching:</strong></li></ul><p>Propensity score matching is a statistical technique used in observational studies to reduce the effects of confounding variables and estimate treatment effects. It involves creating a score, known as the propensity score, which predicts the likelihood of a participant receiving a treatment based on their observed covariates. Participants who received the treatment are then matched with those who did not receive the treatment, but have similar propensity scores.</p><p><strong><em>For example,</em></strong> suppose a study is investigating the effect of a new drug on reducing cholesterol levels. The researchers recruit 100 participants, 50 of whom are randomly assigned to receive the drug and 50 who are assigned to receive a placebo. However, the researchers notice that the group receiving the drug has a higher percentage of males, older participants, and participants with a family history of high cholesterol. These variables are known to be associated with cholesterol levels, so the researchers decide to use propensity score matching to adjust for these variables.</p><p>The researchers use logistic regression to create a propensity score for each participant, which takes into account their age, sex, and family history of high cholesterol. They then match each participant who received the drug with a participant who did not receive the drug, but has a similar propensity score. The researchers can then compare the cholesterol levels between the matched pairs to estimate the treatment effect of the drug.</p><h3>The language of causation</h3><p>The language of causation refers to the set of tools and concepts used in data science and statistics to understand the relationships between variables and to establish causal effects. This includes the use of causal models, which are mathematical representations of the mechanisms by which variables influence each other, and the study of causal effects, which involve the investigation of the effects of interventions on variables of interest.</p><ul><li><strong>Causal Models:</strong></li></ul><p>Causal models are representations of the causal relationships between variables, often expressed as directed acyclic graphs (DAGs). In a DAG, variables are represented as nodes, and arrows indicate the direction of influence between variables.</p><p><strong><em>For example</em></strong>, if we were interested in understanding the causal relationship between smoking and lung cancer, we could represent this relationship as a DAG with smoking as the cause and lung cancer as the effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*z7y2i9i22EwXBADHAOfVGg.png" /><figcaption>DAG representation</figcaption></figure><p>Causal models are useful because they allow us to make predictions about the effects of interventions on variables of interest. By simulating the effects of different interventions on a causal model, we can explore the potential outcomes of different courses of action and make informed decisions.</p><ul><li><strong>Causal Effects:</strong></li></ul><p>Causal effects refer to the changes in a variable that result from a specific intervention. In other words, the causal effect of an intervention is the difference between what happens when the intervention is applied and what would have happened if the intervention had not been applied.</p><p>There are several different types of causal effects, including average causal effects, conditional causal effects, and counterfactual effects. Average causal effects refer to the overall effect of an intervention on a population, while conditional causal effects refer to the effect of an intervention on a specific subpopulation. Counterfactual effects refer to the difference in outcome that would have occurred if a different intervention had been applied.</p><ul><li><strong>Model checking:</strong></li></ul><p>To check whether a causal model is consistent with the data, researchers use a process called model checking. This involves comparing the predictions of the causal model to the observed data to determine whether they match.</p><p><strong><em>For example</em></strong>, if we have a causal model that predicts that smoking causes lung cancer, we can test this by comparing the rate of lung cancer in smokers versus non-smokers. If the data shows a higher rate of lung cancer in smokers, this supports the causal model.</p><p>However, there are many factors that can affect the relationship between smoking and lung cancer, such as age, gender, and genetics. Therefore, researchers must take these factors into account when constructing the causal model and performing model checking.</p><h3>Treatment effects</h3><p>Treatment effects refer to the causal effect of a treatment or intervention on an outcome. In other words, it is the difference in outcome that can be attributed to the treatment itself, as opposed to other factors.</p><p>There are several types of treatment effects:</p><ul><li><strong>Average treatment effect (ATE):</strong></li></ul><p>The ATE is the average difference in outcome between a treatment group and a control group. It provides an estimate of the overall effect of the treatment on the population.</p><p><strong><em>Example:</em></strong> A study is conducted to evaluate the effectiveness of a new medication for reducing blood pressure. Participants are randomly assigned to either receive the medication or a placebo. The ATE would be the average difference in blood pressure between the two groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*g2epmupFuTwLAmGuGV963A.png" /></figure><ul><li><strong>Treatment effect heterogeneity:</strong></li></ul><p>Treatment effect heterogeneity refers to the variation in treatment effects across different subgroups of the population. This can be useful for understanding which groups of people benefit most from the treatment.</p><p><strong><em>Example:</em></strong> In the same study as above, treatment effect heterogeneity could be evaluated by examining whether the treatment is more effective for men or women, or for people with different levels of baseline blood pressure.</p><ul><li><strong>Intention-to-treat effect (ITT):</strong></li></ul><p>The ITT refers to the effect of being assigned to a treatment group, regardless of whether the participant actually received the treatment. This is important because in some cases, participants may not comply with the treatment or may drop out of the study.</p><p><strong><em>Example:</em></strong> In a study evaluating the effectiveness of a weight loss program, some participants may not adhere to the program and may not lose weight. The ITT analysis would still include all participants in the treatment group, regardless of their level of adherence.</p><ul><li><strong>Causal mediation effect:</strong></li></ul><p>The causal mediation effect refers to the extent to which the treatment effect is explained by changes in a mediator variable (i.e., a variable that is affected by the treatment and in turn affects the outcome).</p><p><strong><em>Example:</em></strong> In a study evaluating the effectiveness of a smoking cessation program, the mediator variable could be the number of cigarettes smoked per day. The causal mediation effect would estimate the extent to which the treatment effect is explained by the reduction in cigarette smoking.</p><ul><li><strong>Average Treatment Effect on the Treated (ATT):</strong></li></ul><p>The Average Treatment Effect on the Treated (ATT) is the average treatment effect for the subset of the treatment group who actually received the treatment. This measure tells us what is the effect of the treatment for those individuals who actually received it. ATT is calculated by comparing the average outcome of the treated group with the average outcome of the control group for the subset of individuals who actually received the treatment.</p><p><strong><em>Example:</em></strong> In a study of a job training program, we may be interested in the effect of the program for those who actually complete the training (the treated group). In this case, we would estimate the average treatment effect on the treated (ATT), which is the difference in outcomes between those who completed the program and those who did not, taking the average only among those who completed the program. For example, if the program completers had an average increase in earnings of $5000 per year, while the non-completers had an average increase of $2000 per year, the ATT would be $3000 per year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*lU_6XRZchQ-Lrvo-f2q-Wg.png" /></figure><ul><li><strong>Conditional Average Treatment Effect (CATE):</strong></li></ul><p>The Conditional Average Treatment Effect (CATE) is a measure of treatment effect for a specific subgroup within the treatment group based on their characteristics. This measure tells us the effect of treatment for individuals with specific characteristics. For example, we may want to know the effect of a new drug for individuals with a certain genetic mutation. CATE is calculated by comparing the average outcome of the treated group with the average outcome of the control group for individuals with a specific characteristic or set of characteristics.</p><p><strong><em>Example:</em></strong> For the same study of class size and academic performance, we may be interested in the effect of class size for certain subgroups of students, such as those who are low-income or have learning disabilities. In this case, we may estimate the conditional average treatment effect (CATE) for each subgroup separately. For example, we may find that for low-income students, the effect of class size is much larger, with an ATE of 10 points, while for students without low-income status, the ATE is only 3 points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*Mev-j-2I5sRCRVrEH43cKw.png" /></figure><p>Overall, understanding different types of treatment effects can help researchers to better evaluate the effectiveness of interventions and to identify which subgroups of the population may benefit most from the treatment.</p><h3>Challenges in inferreing causality</h3><p>Inferring causality is a challenging task in data science and statistics. Some of the key challenges include:</p><ul><li><strong>Confounding variables:</strong></li></ul><p>One of the biggest challenges in inferring causality from observational data is the presence of confounding variables. Confounding variables are variables that are related to both the cause and the effect, making it difficult to determine whether the cause is directly responsible for the effect.</p><p>For example, suppose we want to determine whether smoking causes lung cancer. We might collect data on smoking behavior and lung cancer rates and find a strong correlation between the two variables. However, there are many confounding variables that could be responsible for this correlation, such as age, gender, and exposure to other toxins. If we don’t take these variables into account, we may incorrectly conclude that smoking causes lung cancer when in fact it does not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xW0luNMdxh0Bud3ixYLelg.png" /><figcaption>Confounder representation</figcaption></figure><p>To address the problem of confounding variables, we can use a technique called regression analysis. Regression analysis allows us to control for the effects of other variables and isolate the effect of the cause on the effect. By controlling for confounding variables, we can better infer causality from observational data.</p><ul><li><strong>Reverse causality:</strong></li></ul><p>Reverse causality is a situation in which the presumed cause of an effect may actually be the result of that effect. In other words, the direction of the causation is reversed from what is initially assumed. This can lead to misleading or incorrect conclusions when attempting to establish causal relationships between variables.</p><p>An <strong><em>example</em></strong> of reverse causality is the relationship between exercise and weight loss. Initially, it is commonly assumed that exercise causes weight loss. However, in some cases, the direction of the causation can be reversed, and weight loss can actually cause exercise. For example, if a person loses a significant amount of weight due to an illness or other factor, they may subsequently engage in more exercise as a result of feeling better and having more energy. In this case, the weight loss is the cause and the exercise is the effect, even though the initial assumption was the opposite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*ZrxOA6a7DCcpP0TNbye4Xw.jpeg" /><figcaption>Reverse causality representation</figcaption></figure><ul><li><strong>Selection bias:</strong></li></ul><p>Selection bias is a type of bias that occurs when the sample or population being studied is not representative of the entire population, leading to incorrect or misleading conclusions. It arises when the selection of participants into a study or experiment is not random, resulting in a non-representative sample.</p><p><strong><em>For example,</em></strong> consider a study that aims to investigate the effectiveness of a new medication for a certain disease. The study only recruits patients from a single hospital, which is a specialized center for treating the disease. The study finds that the medication is highly effective in treating the disease. However, the conclusion is biased because the sample only includes patients who are receiving specialized care at the hospital and may not be representative of the larger population with the disease. Patients who are not receiving specialized care may have different characteristics and experiences that could affect the effectiveness of the medication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ha0iL97EoOJU4dNJiwzTWQ.png" /><figcaption>Selection bias representation</figcaption></figure><ul><li><strong>Sample size:</strong></li></ul><p>Sample size refers to the number of individuals or units that are included in a study or experiment. In statistical analysis, sample size plays an important role in determining the reliability and generalizability of the findings. Small sample sizes can lead to low statistical power and increase the risk of Type II errors, meaning that a true effect is not detected. This can impact the ability to establish causality. In general, larger sample sizes are more desirable as they provide greater statistical power and precision, but they also come with increased costs and resources. Determining the appropriate sample size for a study depends on various factors, including the research question, study design, and available resources.</p><h3>Inferreing causality in air pollution</h3><h4>Dataset description</h4><p>(<a href="https://www.kaggle.com/datasets/hasibalmuzdadid/global-air-pollution-dataset">https://www.kaggle.com/datasets/hasibalmuzdadid/global-air-pollution-dataset</a>):</p><p>This dataset provides geolocated information about major air pollutants, including Nitrogen Dioxide, Ozone, Carbon Monoxide, and Particulate Matter. These pollutants are harmful to human health and can cause respiratory and other diseases, as well as contribute to morbidity and mortality. The dataset also highlights the sources of these pollutants, such as cars, trucks, power plants, and household combustion devices.</p><p>The dataset includes the following features:</p><ul><li><strong>Country</strong>: name of the country</li><li><strong>City</strong>: name of the city</li><li><strong>AQI Value</strong>: overall air quality index value of the city</li><li><strong>AQI Category</strong>: overall air quality index category of the city</li><li><strong>CO AQI Value</strong>: air quality index value of carbon monoxide of the city</li><li><strong>CO AQI Category</strong>: air quality index category of carbon monoxide of the city</li><li><strong>Ozone AQI Value</strong>: air quality index value of ozone of the city</li><li><strong>Ozone AQI Category</strong>: air quality index category of ozone of the city</li><li><strong>NO2 AQI Value</strong>: air quality index value of nitrogen dioxide of the city</li><li><strong>NO2 AQI Category</strong>: air quality index category of nitrogen dioxide of the city</li><li><strong>PM2.5 AQI Value</strong>: air quality index value of particulate matter with a diameter of 2.5 micrometers or less of the city</li><li><strong>PM2.5 AQI Category</strong>: air quality index category of particulate matter with a diameter of 2.5 micrometers or less of the city</li></ul><pre>dataset = &quot;C:\\Users\\hmitt\\Downloads\\archive (1)\\global air pollution dataset.csv&quot;</pre><pre># Importing required packages<br><br>import numpy as np # linear algebra<br>import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)<br>%matplotlib inline<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>from IPython.display import Image<br>import category_encoders as ce<br><br>import graphviz<br>import lingam<br>from lingam.utils import make_dot, make_prior_knowledge</pre><pre>df=pd.read_csv(dataset)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bOfm1jldf9wQqDeA-KSzg.png" /></figure><pre># Identify total no. of countries in the dataset<br>df[&#39;Country&#39;].nunique()</pre><pre># Identify total no. of cities in the dataset<br>df[&#39;City&#39;].nunique()</pre><pre># Checking for any city<br>df[df[&#39;City&#39;]==&#39;Boston&#39;]</pre><p>The below code is creating a set of five subplots, each representing the distribution of a particular air quality index value — AQI Value, CO AQI Value, Ozone AQI Value, NO2 AQI Value, PM2.5 AQI Value. The seaborn distplot() function is used to create a histogram and a density plot on the same axis.</p><pre>my_column = [&#39;AQI Value&#39;, &#39;CO AQI Value&#39;, &#39;Ozone AQI Value&#39;,&#39;NO2 AQI Value&#39;, &#39;PM2.5 AQI Value&#39;]<br>fig = plt.figure (figsize=(15,5))<br><br>for i in range(len(my_column)):<br>    plt.subplot (1,5,i+1)<br>    plt.title (my_column[i])<br>    sns.distplot (df, x=df[my_column[i]])<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZD4oy6pss1Hdi1JgyEkIQ.png" /></figure><p>The <strong>distplot </strong>in each subplot represents the distribution of each of the air quality index values. From the plot, we can observe the shape of the distribution, which can give us an idea about the skewness and kurtosis of the variable. It can also help us identify the presence of outliers and the range of values that the variable takes.</p><p><strong>Boxplots </strong>give us a visual representation of the distribution of the air quality index values, broken down by the AQI Category. This allows us to compare the distribution of the variable across categories and identify any patterns or differences in the data.</p><pre>fig = plt.figure (figsize=(15,5))<br><br>for i in range(len(my_column)):<br>    plt.subplot (2,3,i+1)<br>    plt.title (my_column[i])<br>    sns.boxplot (data=df, x=df[my_column[i]], y=df[&#39;AQI Category&#39;])<br>    <br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9G-n0p_q0ZA36PdrujAjg.png" /></figure><p>The boxplot for each air quality index value is broken down by the AQI Category, allowing us to compare the distribution of the variable across different categories. From the plot, we can observe the spread and central tendency of the data for each category, as well as any outliers that may be present. It can also help us identify if there are any systematic differences in the distribution of the variable across categories.</p><p>The <strong>pairplot()</strong> function creates a grid of scatterplots and histograms that allows us to visualize the relationships between pairs of variables in the DataFrame. This can be useful in identifying patterns and relationships between variables</p><pre>sns.pairplot(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*KAryZ8D3_tPhMDT24cxIqA.png" /></figure><p>When applied to the given DataFrame, the pairplot() function generates a grid of scatterplots for all possible combinations of the numeric columns. The plot for each pair of columns displays a scatterplot along with the histograms for both variables. We can observe there is a positive correlation between AQI Value and PM2.5 AQI, as the data points in the scatterplot form a roughly upward sloping pattern. Conversely, if there is a negative correlation, the data points would form a roughly downward sloping pattern. We can also use the histograms to identify the distribution of each variable and detect any outliers.</p><p>The <strong>sns.heatmap()</strong> function in Seaborn library creates a colored matrix where the color of each cell represents the correlation between two variables. The darker colors indicate stronger correlations, and lighter colors indicate weaker correlations or no correlation.</p><pre>sns.heatmap (df.corr(), cbar=False, annot=True, fmt=&#39;.2f&#39;, cmap=&#39;Blues&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*Vnwg7-d_G1tj8Hgpfst2TQ.png" /></figure><p>The heatmap can be useful in identifying which variables are strongly correlated with each other. For example, if we see a dark blue square between two variables, that means they have a strong positive correlation. On the other hand, if we see a dark red square, that means they have a strong negative correlation. Identifying these patterns can help us in selecting variables for our causal models. Here, we can observe AQI Value and PM2.5 AQI have high correlation of 98%.</p><p><strong>Lmplot </strong>between AQI Value and PM2.5 AQI Value with AQI Category</p><pre>sns.lmplot (data=df, x=&#39;AQI Value&#39;, y=&#39;PM2.5 AQI Value&#39;, hue=&quot;AQI Category&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epJCCfF6h_QsUx_4fdNjXg.png" /></figure><p>This lmplot creates a scatter plot between two variables, ‘AQI Value’ and ‘PM2.5 AQI Value’, with the data points colored based on their ‘AQI Category’. It also fits a linear regression line to the data points, which can help in understanding the relationship between the two variables.The line of best fit can also help to estimate the value of one variable given the value of the other variable.</p><pre>updated_df = df.drop ([&quot;Country&quot;, &quot;City&quot;, &quot;AQI Value&quot;, &quot;AQI Category&quot;, &quot;CO AQI Category&quot;, &quot;Ozone AQI Category&quot;, &quot;NO2 AQI Category&quot;, &quot;PM2.5 AQI Category&quot;], axis=1)<br>updated_df = updated_df.dropna(how=&#39;any&#39;)<br><br>df_list = updated_df.columns.to_list()<br>my_data_dictionary = {}<br><br>for i, column in zip (range(len(df_list)), df_list):<br>    my_data_dictionary[column] = i<br><br>print(&quot;Elements in the dictionary: &quot;, len(df_list))<br>print(&quot;Dictionary: &quot;, my_data_dictionary)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpA0s-FaL16Ml468fkuvSg.png" /></figure><h4>PyGAM</h4><p>PyGAM is a Python package for building and estimating generalized additive models (GAMs). GAMs are a flexible extension of linear models that allow for non-linear relationships between the dependent variable and independent variables. PyGAM provides a high-level interface for building GAMs, making it easier for researchers and data scientists to fit complex models and explore non-linear relationships in their data. It supports a variety of GAMs, including smoothing spline models, thin plate regression splines, and cubic regression splines. PyGAM also supports a wide range of distribution families and link functions, allowing for flexible specification of the response variable distribution.</p><h4>LinGAM</h4><p>LinGAM (Linear non-Gaussian Acyclic Models) is a statistical method for inferring causal relationships from multivariate time series data. It is particularly useful for dealing with non-Gaussian and nonlinear relationships between variables.</p><p>The basic idea behind LinGAM is to model the causal relationships between variables as a directed acyclic graph (DAG) and use a linear model to estimate the causal effect of each variable on the others. The algorithm tries to find a DAG that best represents the causal relationships between the variables, subject to the assumption that the errors in the model are non-Gaussian and linearly independent.</p><p>One of the key advantages of LinGAM is that it can handle both instantaneous and lagged causal effects. It also works well with high-dimensional data, where there are many variables to consider. The resulting causal graph can be useful for identifying key drivers of a system, predicting the effect of interventions, and understanding the underlying mechanisms of complex processes.</p><p>This code creates a LiNGAM model and fits it to the input data ‘updated_df’ which is assumed to contain variables that are causally related to each other. The ‘prior_knowledge’ parameter specifies any prior knowledge about the causal relationships that is available to the model.</p><pre>prior_knowledge = make_prior_knowledge(4, paths = [[my_data_dictionary [&#39;CO AQI Value&#39;], my_data_dictionary [&#39;NO2 AQI Value&#39;]]])<br><br>model = lingam.DirectLiNGAM(<br>                    random_state=10,<br>                    prior_knowledge = prior_knowledge,<br>                    measure = &#39;pwling&#39;,<br>                    )<br><br>model.fit(updated_df)</pre><pre>dot = make_dot(<br>     model.adjacency_matrix_,<br>     labels=updated_df.columns.to_list(),<br>    )<br><br>dot.format = &#39;png&#39;<br>dot.render(&#39;PM2.5_Graph&#39;)<br><br>Image(&quot;PM2.5_Graph.png&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*1Csmd3buleWrNe_ZEjE43Q.png" /></figure><p>After fitting the model, the code generates a causal graph visualization using the ‘make_dot’ function from the ‘graphviz’ library. The graph represents the causal relationships inferred by the LiNGAM algorithm. The nodes in the graph represent the variables in the input data, and the edges between the nodes represent the causal relationships inferred by the algorithm. The direction of the edges indicates the direction of causality, with the arrowhead pointing from the cause to the effect.</p><p>We can observe from the graph that CO AQI value has the highest correlation coefficient with PM2.5 AQI value, followed by NO2 AQI value.</p><h3>Conclusion</h3><p>In conclusion, understanding causality is crucial in many fields, including public health, economics, and social sciences. Correlation and causation can often be confused, but causal inference methods help us distinguish between the two. Causal diagrams and model checking help us identify potential confounding factors and design appropriate experiments to infer causality. Treatment effects are a key component of causal inference, and different types of treatment effects can be estimated depending on the research question. However, there are many challenges in inferring causality, such as selection bias, reverse causality, and unobserved confounding. Applying causal inference methods to real-world problems, such as air pollution, can help us identify interventions that can improve public health. By incorporating these concepts into research and decision-making, we can make more informed and impactful decisions.</p><h3>References</h3><ul><li>CausalInference: <a href="https://causalinferenceinpython.org/">https://causalinferenceinpython.org/</a></li><li>Causal inference- Carnegie melon University: <a href="https://blog.ml.cmu.edu/2020/08/31/7-causality/">https://blog.ml.cmu.edu/2020/08/31/7-causality/</a></li><li><a href="https://www.kaggle.com/code/sasakitetsuya/what-causes-pm2-5/notebook">https://www.kaggle.com/code/sasakitetsuya/what-causes-pm2-5/notebook</a></li></ul><p>Take a <a href="https://medium.com/@hmittal15/check-your-knowledge-causality-in-data-science-95a27824ead"><strong>quiz </strong></a>to test your knowledge now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cc7eccf3f41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-causality-2cc7eccf3f41">Crash course in Causality</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[Check your knowledge: Time-series Forecasting]]></title>
            <link>https://medium.com/aiskunks/check-your-knowledge-time-series-forecasting-93e475b12130?source=rss-d66a43d41e01------2</link>
            <guid isPermaLink="false">https://medium.com/p/93e475b12130</guid>
            <category><![CDATA[predictive-analyses]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Harshit Mittal]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 03:38:17 GMT</pubDate>
            <atom:updated>2023-04-22T19:56:26.463Z</atom:updated>
            <content:encoded><![CDATA[<p>Time-series forecasting is an essential technique used in various industries, from finance to healthcare. It involves analyzing historical data to predict future trends and patterns. If you want to test your knowledge about time-series forecasting, you’re in the right place! Take this quiz to see how much you know about this topic.</p><ol><li><strong>What is the purpose of time-series forecasting?</strong></li></ol><p>a) To understand the historical trends and patterns in the data</p><p>b) To predict future values based on past observations</p><p>c) To analyze the impact of external factors on the data</p><p>d) All of the above</p><p><em>Answer:</em> b)</p><p><strong>2. Which of the following is NOT a common type of time-series model?</strong></p><p>a) ARIMA</p><p>b) XGBoost</p><p>c) LSTM</p><p>d) SVM</p><p><em>Answer</em>: d)</p><p><strong>3. What does the acronym ARIMA stand for?</strong></p><p>a) Automated Recursive Integrated Moving Average</p><p>b) Autoregressive Index of Moving Averages</p><p>c) Autoregressive Integrated Moving Average</p><p>d) Automated Index of Moving Averages</p><p><em>Answer</em>: c)</p><p><strong>4. Which of the following is NOT a step in the Box-Jenkins method for ARIMA modeling?</strong></p><p>a) Identify the order of differencing needed to make the series stationary</p><p>b) Estimate the autoregressive and moving average parameters</p><p>c) Plot the autocorrelation and partial autocorrelation functions</p><p>d) Transform the data into a different time domain</p><p><em>Answer</em>: d)</p><p><strong>5. Which of the following is a common evaluation metric for time-series models?</strong></p><p>a) Mean Absolute Error (MAE)</p><p>b) Root Mean Squared Error (RMSE)</p><p>c) Mean Absolute Percentage Error (MAPE)</p><p>d) All of the above</p><p><em>Answer</em>: d)</p><p><strong>6. Which of the following is a limitation of ARIMA models?</strong></p><p>a) They can only model linear relationships between variables</p><p>b) They cannot handle seasonality in the data</p><p>c) They require a large amount of data to produce accurate forecasts</p><p>d) They are not suitable for predicting long-term trends</p><p><em>Answer</em>: b)</p><p><strong>7. Which of the following is NOT a type of ensemble model for time-series forecasting?</strong></p><p>a) XGBoost</p><p>b) Random Forest</p><p>c) Prophet</p><p>d) ARIMA</p><p><em>Answer</em>: d)</p><p><strong>8. Which of the following is a feature engineering technique for time-series data?</strong></p><p>a) Lagging variables</p><p>b) Moving averages</p><p>c) Seasonal decomposition</p><p>d) All of the above</p><p><em>Answer</em>: d)</p><p><strong>9. Which of the following is a disadvantage of using deep learning models for time-series forecasting?</strong></p><p>a) They require a large amount of data to train</p><p>b) They are computationally expensive</p><p>c) They can be difficult to interpret</p><p>d) All of the above</p><p><em>Answer</em>: d)</p><p><strong>10. Which of the following is NOT a consideration when selecting a time-series model?</strong></p><p>a) The amount of data available</p><p>b) The presence of seasonality in the data</p><p>c) The interpretability of the model</p><p>d) The type of external factors affecting the data</p><p><em>Answer</em>: d)</p><p>Congratulations on completing the time-series forecasting quiz! I hope you learned something new and had fun at the same time. Whether you aced the quiz or not, don’t forget that there is always more to learn about this exciting field. Keep exploring and stay curious!</p><p>Want to learn more about Time-series forecasting? Dive deep into the pool of knowledge <a href="https://medium.com/@hmittal15/crash-course-in-time-forecasting-analysing-cryptocurreny-data-3f45fa07f0a8">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93e475b12130" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/check-your-knowledge-time-series-forecasting-93e475b12130">Check your knowledge: Time-series Forecasting</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: Analysing Cryptocurrency data]]></title>
            <link>https://medium.com/aiskunks/crash-course-in-time-forecasting-analysing-cryptocurreny-data-3f45fa07f0a8?source=rss-d66a43d41e01------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f45fa07f0a8</guid>
            <category><![CDATA[cryptocurrency-data]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <dc:creator><![CDATA[Harshit Mittal]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 03:37:06 GMT</pubDate>
            <atom:updated>2023-04-16T22:28:26.391Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you have a magic crystal ball that can tell you the future. Now, let’s say you want to use this crystal ball to predict the stock prices of your favourite company. You might be thinking, “how can a crystal ball predict stock prices?” Well, that’s where time-series forecasting comes in. Time-series forecasting is like having a crystal ball for data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbbhczZAkwynJHntq3DrSA.png" /></figure><p>In simple terms, time-series forecasting is the art of predicting future values based on patterns and trends from past data. It’s like looking at the historical data of a stock price and using that information to predict what the stock price will be in the future.</p><p>Just like we might look for patterns in the stock market to predict future prices, time-series forecasting algorithms use mathematical models to identify trends, seasonality, and other patterns in data to make predictions. These models can be as simple as a moving average or as complex as a neural network.</p><p>There are many factors that can affect the accuracy of time-series forecasts. For example, unexpected events like a pandemic can disrupt patterns and trends in data, making it difficult to make accurate predictions. That’s why it’s important to constantly monitor and adjust the forecasts as new data becomes available.</p><h3>Table of contents:</h3><ul><li>Why time-series forecasting techniques?</li><li>Let’s begin</li><li>Introducing the dataset</li><li>Handling missing data</li><li>Exploring time series data properties</li><li>Visualizing the Time-Series Data</li><li>Predictive modelling for time-series data</li><li>Conclusion</li><li>References</li></ul><h3>Why time-series forecasting techniques?</h3><p>Perhaps you’re wondering about the distinction between time-series forecasting and algorithmic predictions utilizing machine learning. Although machine learning techniques like random forest, gradient boosting regressor, and time delay neural networks can be leveraged to extrapolate time-series data, there are other alternatives available that may be more suitable. As we’ll soon discover in this article, the ability to extrapolate patterns outside the training data domain is a crucial characteristic of a time-series algorithm, which most machine learning methods lack by default. Luckily, there are specialized time-series forecasting approaches that can fill this gap.</p><h3>Let’s begin!</h3><p>Let’s look at some crucial concepts which are needed for analyzing and forecasting time-series.</p><p><strong>Stationarity:</strong><br>The concept of stationarity is crucial in time-series forecasting. A time series is said to be stationary if its statistical properties like mean, variance, and autocorrelation do not change over time. Stationarity is important because many time-series forecasting models assume that the data is stationary. If the data is not stationary, it may need to be transformed before it can be used in these models.</p><p><strong>Autocorrelation:</strong><br>Autocorrelation is the correlation between a time series and a delayed version of itself. It’s an important concept in time-series forecasting because it can help identify patterns and trends in the data. For example, if there is a high positive autocorrelation at a lag of 12 months, it might indicate a yearly pattern in the data.</p><p><strong>Seasonality:</strong><br>Seasonality refers to patterns that repeat themselves at regular intervals, such as weekly, monthly, or yearly. Seasonality is important in time-series forecasting because it can help identify trends and make accurate predictions. For example, if a time series exhibits weekly seasonality, a forecasting model can be trained to predict the values for each day of the week.</p><p><strong>Trend:</strong><br>Trend refers to the long-term movement of a time series. It can be upward, downward, or flat. Trend is important in time-series forecasting because it can help identify the direction of future values. For example, if a time series has an upward trend, it’s likely that future values will also be higher.</p><p><strong>Forecasting models:</strong><br>There are several forecasting models that can be used for time-series analysis, including exponential smoothing, autoregressive integrated moving average (ARIMA), and machine learning models such as neural networks. Each model has its own strengths and weaknesses and may be more appropriate for certain types of data.</p><p><strong>Error Metrics:</strong><br>Error metrics are used to evaluate the performance of time-series forecasting models. These metrics include mean absolute error (MAE), mean squared error (MSE), root mean squared error (RMSE), and mean absolute percentage error (MAPE). Understanding these metrics is important because they help you determine which forecasting model is the most accurate for your data.</p><p><strong>Forecasting Horizon:</strong><br>The forecasting horizon is the length of time into the future for which you want to make predictions. The forecasting horizon is important because it can affect the accuracy of your forecasts. Short-term forecasts are generally more accurate than long-term forecasts.</p><h3>Introducing the dataset</h3><p>To gain a deeper understanding of the concepts of time-series forecasting, we will apply essential principles to the “G-Research Crypto Forecasting” dataset (<a href="https://www.kaggle.com/competitions/g-research-crypto-forecasting/data">https://www.kaggle.com/competitions/g-research-crypto-forecasting/data</a>), which is readily available on Kaggle. This will provide a practical and tangible example of the techniques involved.</p><p><em>Importing required libraries:</em></p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br>import plotly.express as px<br>import plotly.graph_objects as go<br>import seaborn as sns<br>import time<br>from datetime import datetime<br>import xgboost as xgb<br>from xgboost.callback import EarlyStopping<br>from sklearn.metrics import mean_squared_error<br>from lightgbm import LGBMRegressor</pre><h4>Dataset description:</h4><p>This dataset is a valuable resource for anyone looking to predict the future returns of crypto-assets such as Bitcoin and Ethereum. It consists of historic trades and provides a range of features such as timestamp, asset ID, count of trades, opening, closing, high and low prices, volume, and VWAP. The primary goal is to predict the 15-minute residualized returns using time series forecasting techniques.</p><p><strong>Files</strong></p><ul><li>train.csv - The training set</li></ul><p>timestamp - A timestamp for the minute covered by the row.<br> Asset_ID - An ID code for the crypto-asset.<br> Count - The number of trades that took place this minute.<br> Open - The USD price at the beginning of the minute.<br> High - The highest USD price during the minute.<br> Low - The lowest USD price during the minute.<br> Close - The USD price at the end of the minute.<br> Volume - The number of cryptoasset units traded during the minute.<br> VWAP - The volume weighted average price for the minute.<br> Target - 15 minute residualized returns. See the &#39;Prediction and Evaluation&#39; section of this notebook for details of how the target is calculated.</p><ul><li>example_test.csv - An example of the data that will be delivered by the time series API.</li><li>example_sample_submission.csv - An example of the data that will be delivered by the time series API. The data is just copied from train.csv.</li><li>asset_details.csv - Provides the real name and of the cryptoasset for each Asset_ID and the weight each cryptoasset receives in the metric.</li><li>gresearch_crypto - An unoptimized version of the time series API files for offline work. You may need Python 3.7 and a Linux environment to run it without errors.</li><li>supplemental_train.csv - After the submission period is over this file&#39;s data will be replaced with cryptoasset prices from the entire submission period.</li></ul><pre>df = pd.read_csv(&quot;C:\\Users\\hmitt\\Downloads\\g-research-crypto-forecasting\\train.csv&quot;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JIr_2sjC3uHMHE5OG2U3A.png" /></figure><pre>asset_details = pd.read_csv(&quot;C:\\Users\\hmitt\\Downloads\\g-research-crypto-forecasting\\asset_details.csv&quot;)<br>asset_details</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*m1lE6btVsJdiOXMjkoA5hQ.png" /></figure><p>Our dataset contains 14 different cryptocurrencies which will be analyse dmoving forward.</p><h3>Handling missing data</h3><p>Handling and managing missing data in a time-series dataset is a critical step in ensuring accurate and reliable analysis. Here are some techniques that can be used to handle and manage missing data:</p><p><strong>Imputation</strong>: This involves filling in the missing values with estimated values based on the patterns observed in the available data. There are several methods for imputation such as mean imputation, interpolation, and regression imputation.</p><p><strong>Dropping missing values</strong>: In some cases, if the amount of missing data is relatively small, it may be reasonable to remove the rows with missing data. However, this approach should be used with caution as it can result in a loss of valuable information.</p><p><strong>Using machine learning algorithms</strong>: Another approach to handling missing data is to use machine learning algorithms that can handle missing data, such as XGBoost and LightGBM.</p><p><strong>Handling missing data in the model</strong>: Some models can handle missing data, such as the Kalman filter, which can estimate missing values in real-time.</p><p>In general, imputation is a common and effective method for handling missing data, but it can introduce bias and should be used with caution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*HfBcTXsKTmkbHd4pmam8jw.png" /></figure><p>There are ~75k null values in our dataset which is a very small portion of the total data, approximately 3%. We can proceed to remove the null data values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S80OtH8IrupTgWLR5fi30g.png" /></figure><h3>Exploring time series data properties</h3><p>Analyzing time-series data can be challenging due to its unique characteristics such as seasonality, trend, and autocorrelation. Exploratory data analysis (EDA) is a crucial first step in understanding time-series data and making informed decisions.</p><h4>Examining Seasonality:</h4><p>Seasonality refers to the repeating patterns in the data that occur over regular intervals. For example, retail sales data may have higher values during the holiday season. Examining seasonality in time-series data can help understand the cyclical nature of the data and identify trends that are dependent on time of year. Let’s try to observe how a seasonal pattern looks like.</p><pre>def identify_pattern (time_season):<br>    return np.where (time_season &lt; 0.45, np.cos(time_season * 2 *np.pi), 1 / np.exp(3*time_season))<br><br>def identify_seasonality (time, period, phase, amplitude):<br>    time_season = ((time + phase) %  period ) / period<br>    return amplitude * identify_pattern(time_season)<br><br>time = np.arange(5*365 + 1 )<br><br>def plot_data (time , series , format = &quot;-&quot; , start = 0, end = None ,  label = None , color = None):<br>    plt.plot(time[start:end] , series[start:end] , format , color = color)<br>    plt.ylabel(&quot;Value&quot;)<br>    plt.xlabel(&quot;Time&quot;)<br>    if label:<br>        plt.legend(fontsize = 20)<br>    plt.grid(True)<br><br>series = identify_seasonality (time , period = 365, phase = 0, amplitude = 30)<br>plt.figure (figsize=(20,6))<br>plt.title (&quot;#1 Seasonality Plot&quot;, fontdict = {&#39;fontsize&#39; : 22} )<br>plot_data (time , series, color = &quot;red&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fupwpolg35IbffB7GSPuA.png" /></figure><pre>series = identify_seasonality(time , period = 90, phase = 25, amplitude = 80)<br>plt.figure(figsize=(20,6))<br>plt.title(&quot;#2 Seasonality Plot&quot;, fontdict = {&#39;fontsize&#39; : 22} )<br>plot_data (time , series, color = &quot;red&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FVd9OzsxTtWPD0a-XTC5w.png" /></figure><p>Above 2 graphs depict how a seasonal data looks like. If we observe similar characteristics in our dataset, we can state that our data is seasonal.</p><h4>Analyzing Autocorrelation:</h4><p>Time-series data often exhibits autocorrelation due to the temporal dependency of the data. Analyzing autocorrelation can help identify patterns in the data, such as periodicity, and can be used to build models that capture the time-series behavior. Let’s understand with help of an illustration.</p><pre>def identify_1_autocorrelation (time , amplitude , seed = None):<br>    rand_var = np.random.RandomState (seed)<br>    rnd_array = rand_var.randn (len(time) + 50)<br>    a1 = 0.5<br>    a2 = -0.1<br>    rnd_array[:50] = 100<br>    for step in range (50, len (time) + 50 ):<br>        rnd_array[step] += a1 * rnd_array[step - 50]<br>        rnd_array[step] += a2 * rnd_array[step - 33]<br>    return rnd_array[50:] * amplitude<br><br>def identify_2_autocorrelation (time, amplitude, seed=None):<br>    rand_var = np.random.RandomState (seed)<br>    rnd_array = rand_var.randn (len(time) + 1)<br>    a1 = 0.8<br>    for step in range (1, len(time) + 1):<br>        rnd_array[step] += a1 * rnd_array[step - 1]<br>    return rnd_array[1:] * amplitude</pre><pre>my_series_auto = identify_1_autocorrelation (time , amplitude , seed = 20)<br>plt.figure (figsize= (20,6))<br>plt.title (&quot;#1 Autocorrelation Plot&quot;, fontdict = {&#39;fontsize&#39; : 22} )<br>plot_data (time[:200] , my_series_auto[:200] , color = &quot;red&quot; )<br>plt.show ()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPymlbGXijcIttu6bPDp9Q.png" /></figure><pre>my_series_auto = identify_2_autocorrelation (time , amplitude , seed = 30)<br>plt.figure (figsize=(20,6))<br>plt.title (&quot;#2 Autocorrelation Plot&quot;, fontdict = {&#39;fontsize&#39; : 22} )<br>plot_data (time[:200] , my_series_auto[:200] , color = &quot;red&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1ZlNStDWjLBjCPQt4u69A.png" /></figure><p>This is how we can identify autocorrelation in a dataset. Please take note of the periodicity and repetitiveness in the pattern. If our dataset exhibits similar pattern, we can state that features are autocorrelated.</p><h4>Identifying Correlation:</h4><p>Correlation is often used to identify relationships between different time series and can help in predicting future trends. However, it’s important to note that correlation does not necessarily imply causation, and the relationship between two time series may be spurious.</p><p>There are several methods for measuring correlation in time-series data, including:</p><p><strong>Pearson correlation coefficient</strong>: This measures the linear relationship between two time series. It assumes that the relationship between the two variables is linear and that the data is normally distributed.</p><p><strong>Spearman rank correlation coefficient</strong>: This measures the relationship between two time series based on their ranks rather than their actual values. It’s less sensitive to outliers than Pearson correlation and can capture non-linear relationships.</p><p><strong>Cross-correlation</strong>: This measures the similarity between two time series at different lags. It can help identify if there is a lagged relationship between two variables.</p><pre>asset_names_dict = {row[&quot;Asset_Name&quot;]:row[&quot;Asset_ID&quot;] for ind, row in asset_details.iterrows()}<br><br>names_of_assets = [<br>    &#39;Bitcoin&#39;,<br>    &#39;Ethereum&#39;,<br>    &#39;Cardano&#39;,<br>    &#39;Binance Coin&#39;,<br>    &#39;Dogecoin&#39;,<br>    &#39;Bitcoin Cash&#39;,<br>    &#39;Litecoin&#39;,<br>    &#39;Ethereum Classic&#39;,<br>    &#39;Stellar&#39;,<br>    &#39;TRON&#39;,<br>    &#39;Monero&#39;,<br>    &#39;EOS.IO&#39;,<br>    &#39;IOTA&#39;,<br>    &#39;Maker&#39;<br>]<br><br>my_assets_combined = pd.DataFrame([])<br>for ind, coin in enumerate(names_of_assets):<br>    coin_cryptocurrency_df = df[df[&quot;Asset_ID&quot;]==asset_names_dict[coin]].set_index(&quot;timestamp&quot;)<br>    coin_cryptocurrency_df = coin_cryptocurrency_df.reindex (range (coin_cryptocurrency_df.index[0], coin_cryptocurrency_df.index[-1]+60,60), method=&#39;pad&#39;)<br>    coin_cryptocurrency_df = coin_cryptocurrency_df.loc[totimestamp (&#39;01/07/2021&#39;):totimestamp (&#39;21/09/2021&#39;)]<br>    close_values = coin_cryptocurrency_df[&quot;Close&quot;].fillna(0)<br>    close_values.name = coin<br>    my_assets_combined = my_assets_combined.join (close_values, how=&quot;outer&quot;)<br><br>correlation_matrix = my_assets_combined.corr()<br>fig, ax = plt.subplots (figsize=(14, 14))<br>sns.heatmap(correlation_matrix, vmax=1., cmap=&#39;coolwarm&#39;, square=True)<br>plt.title(&quot;Cryptocurrency correlation map on actual price values&quot;, fontsize = 18)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*0eSWDHdLu3o0_a9_7F61iA.png" /></figure><p><strong><em>Inference</em></strong>: The correlation between various assets is evident, with even the lowest correlation being in the 0.4x range. Bitcoin and Ethereum, Cardano and Binance Coin, and Bitcoin Cash and Litecoin exhibit a strong correlation.</p><h3>Visualizing the Time-Series Data</h3><p>Time-series data can be plotted in various ways, such as line plots, scatter plots, and histograms. These plots can help identify the overall behavior of the data, such as whether it is stationary or non-stationary, and whether it has any outliers or gaps.</p><ul><li>A <strong><em>candlestick graph</em></strong>, is a type of financial chart used to represent the price movement of an asset. It displays four pieces of information: the opening price, the closing price, the highest price, and the lowest price for a specific time period. Each candlestick represents a single time period, such as a day or an hour, and the color of the candlestick can indicate whether the price increased (green or white candle) or decreased (red or black candle) during that period.</li></ul><pre>def cryptocurrency_dataframe (asset_id ,data= df ):<br>    df = data[data[&quot;Asset_ID&quot;]==asset_id].reset_index(drop = True)<br>    df[&#39;timestamp&#39;] = pd.to_datetime (df[&#39;timestamp&#39;], unit=&#39;s&#39;)<br>    df = df.set_index (&#39;timestamp&#39;)<br>    return df<br><br>btc = cryptocurrency_dataframe(asset_id = 1)<br>eth = cryptocurrency_dataframe (asset_id = 6 )<br>ltc = cryptocurrency_dataframe(asset_id = 9 )<br><br>def crypto_candelstick(df, title):<br>    crypto_candle = go.Figure(data = [go.Candlestick(x =df.index, <br>                                               open = df[(&#39;Open&#39;)], <br>                                               high = df[(&#39;High&#39;)], <br>                                               low = df[(&#39;Low&#39;)], <br>                                               close = df[(&#39;Close&#39;)])])<br>    crypto_candle.update_xaxes(title_text = &#39;Time&#39;,<br>                             rangeslider_visible = True)<br><br>    crypto_candle.update_layout(<br>    title = {<br>        &#39;text&#39;: &#39;{:} Candelstick Chart&#39;.format(title),<br>        &#39;xanchor&#39;: &#39;center&#39;,<br>        &#39;yanchor&#39;: &#39;top&#39;,<br>        &#39;y&#39;:0.90,<br>        &#39;x&#39;:0.5<br>        } , <br>    template=&quot;plotly_white&quot;)<br><br>    crypto_candle.update_yaxes (title_text = &#39;Price in USD&#39;, ticksuffix = &#39;$&#39;)<br>    return crypto_candle</pre><pre>bitcoin_candle = crypto_candelstick(btc[-100:],title = &quot;Bitcoin(BTC)&quot;)<br>bitcoin_candle.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHuHr4AtLuPa5RAh4pSzwA.png" /></figure><pre>lightcoin_candle = crypto_candelstick(ltc[-2500:],title = &quot;Litecoin(LTC)&quot;)<br>lightcoin_candle.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3J8QOxzId-0JqM4JsSWg_w.png" /></figure><p><strong><em>Inference</em></strong>: From 22:40 to 22:50, there was a sequence of red candles for BTC indicating a downward trend, which could suggest overselling. As per the theoretical assumption, the price may increase after an overselling period. Overselling implies that the price is trading below the typical or average range, which is sometimes referred to as the “true value” by investors. Typically, buyers are drawn to the market during an oversold period.</p><ul><li>An <strong><em>area plot graph</em></strong>, displays the cumulative values of a variable over time. The area between the x-axis and the plotted line is typically filled with color, creating a stacked appearance. This type of graph is often used to show changes in a variable over time, such as sales or revenue. Area plot graphs can be helpful for identifying patterns in data, such as seasonal trends or changes in growth rates.</li></ul><pre>def traded_volume (data ,title,color):<br>    area_traded = px.area(data_frame=data,<br>               markers = True,<br>               x = data.index ,<br>               y = &quot;Volume&quot;<br>               )<br>    area_traded.update_traces (line_color = color)<br>    area_traded.update_yaxes (title_text = &#39;Number of trades every minute&#39;)<br>    area_traded.update_xaxes(<br>        title_text = &#39;Time&#39;,<br>        rangeslider_visible = True)<br>    area_traded.update_layout (showlegend = True,<br>        title = {<br>            &#39;text&#39;: &#39;{:} Volume Traded&#39;.format(title),<br>            &#39;xanchor&#39;: &#39;center&#39;,<br>            &#39;yanchor&#39;: &#39;top&#39;,<br>            &#39;y&#39;:0.94,<br>            &#39;x&#39;:0.5,<br>            },<br>        template=&quot;plotly_white&quot;)<br>    return area_traded<br><br>traded_volume (eth[-50:], &quot;Ethereum (ETH)&quot;,color = &quot;Red&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2x6QF_sqf75thwB_vmGIw.png" /></figure><p><strong><em>Inference</em></strong>: The area plot graph for Ethereum volume traded over a 1-hour window does not reveal a clear trend. The graph appears to fluctuate frequently, with the volume increasing and decreasing at different intervals.</p><p>Let’s take a look at the training data visualization to observe the changes in the coin prices over time.</p><pre>cmap = sns.color_palette()<br><br># plot close values as time series for all the assets<br>f = plt.figure (figsize= (15,30))<br><br>for ind, crypto in enumerate (names_of_assets):<br>    cryptocurrency_dataframe = df[df[&quot;Asset_ID&quot;]==asset_names_dict[crypto]].set_index(&quot;timestamp&quot;)<br>    # fill missing values <br>    cryptocurrency_dataframe = cryptocurrency_dataframe.reindex(range(cryptocurrency_dataframe.index[0], cryptocurrency_dataframe.index[-1]+60,60), method=&#39;pad&#39;)<br>    ax = f.add_subplot(7,2,ind+1)<br>    plt.plot(cryptocurrency_dataframe[&#39;Close&#39;], color=cmap[ind%10], label=crypto)<br>    plt.xlabel (&#39;Time&#39;)<br>    plt.ylabel (crypto)<br>    plt.legend()<br>    plt.title (crypto)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*K5v-jrEWZ0eaKdW3XiD07g.png" /></figure><p><strong><em>Inference</em></strong>: It appears that there is a significant correlation among various cryptocurrency assets, which appears to vary across different timeframes. The dataset contains bear data from the 2018 timeframe, bull data from the 2021 timeframe, and sideways data from the 2019 and 2020 timeframes, allowing us to model different market conditions. Moreover, different cryptocurrencies have varying timelines in the provided graph. Therefore, we will narrow our focus to the data after July 1, 2021, and analyze the price movements of various assets.</p><pre># auxiliary function, from datetime to timestamp<br>totimestamp = lambda s: np.int32 (time.mktime (datetime.strptime (s, &quot;%d/%m/%Y&quot;).timetuple()))<br><br># create intervals<br>f = plt.figure(figsize=(15,30))<br><br>for ind, crypto in enumerate (asset_names):<br>    cryptocurrency_dataframe = df[df[&quot;Asset_ID&quot;]==asset_names_dict[crypto]].set_index (&quot;timestamp&quot;)<br>    # fill missing values <br>    cryptocurrency_dataframe = cryptocurrency_dataframe.reindex(range (cryptocurrency_dataframe.index[0], cryptocurrency_dataframe.index[-1]+60,60),method=&#39;pad&#39;)<br>    cryptocurrency_dataframe = cryptocurrency_dataframe.loc[totimestam p(&#39;01/07/2021&#39;):totimestamp (&#39;21/09/2021&#39;)]<br>    ax = f.add_subplot(7,2,ind+1)<br>    plt.plot (cryptocurrency_dataframe[&#39;Close&#39;], color=cmap[ind%10], label=crypto)<br>    plt.xlabel (&#39;Time&#39;)<br>    plt.ylabel (crypto)<br>    plt.legend()<br>    plt.title (crypto)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*lih1f1kKh7rgjtdqKMayYw.png" /></figure><p><strong><em>Inference</em></strong>: The graph clearly depicts correlation among various coins, when plotted over the same time range. Similarities in trends in different currencies is a symbol of the cryptocurrency market trend as a whole.</p><h3>Predictive modelling for time-series data</h3><p>Time-series forecasting is a popular machine learning problem that involves predicting future values of a time-dependent variable based on its historical values. In this context, several machine learning models are commonly used for time-series forecasting. In this article, we will go through three popular models for time-series forecasting: ARIMA, XGBoost, and Light GBM. We will check-out the pros and cons of each model and analyse examples to illustrate their usage.</p><h4>XGBoost (Extreme Gradient Boosting):</h4><p>XGBoost is an ensemble model that combines multiple decision trees to make predictions. The model works by sequentially adding decision trees, each of which is trained to correct the errors made by the previous trees.</p><p><strong>Pros</strong>:</p><ul><li>XGBoost models can capture complex patterns in the time series data, including trend, seasonality, and cyclical behavior.</li><li>XGBoost models can handle both univariate and multivariate time series data.</li><li>XGBoost models are known for their accuracy and performance in a wide range of applications.</li></ul><p><strong>Cons</strong>:</p><ul><li>XGBoost models can be computationally intensive and may require significant computational resources.</li><li>XGBoost models may not be as interpretable as other models, such as ARIMA.</li><li>XGBoost models may overfit the data if not properly regularized.</li></ul><p><strong>Example</strong>: XGBoost can be used for predicting energy consumption, as energy consumption often exhibits complex patterns that can be captured by XGBoost models.</p><p>Let’s understand in detail by training the XGBoost model on our dataset and using the same for cryptocurrency value prediction.</p><pre># Two new features<br># Calculates the upper shadow of a financial asset.<br>def calculate_up_shadow (dataframe):<br>    return dataframe[&#39;High&#39;] - np.maximum (dataframe[&#39;Close&#39;], dataframe[&#39;Open&#39;])<br><br># Calculates the lower shadow of a financial asset.<br>def calculate_low_shadow (dataframe):<br>    return np.minimum (dataframe[&#39;Close&#39;], dataframe[&#39;Open&#39;]) - dataframe[&#39;Low&#39;]<br><br># A utility function to build features from the original dataframe. It works for rows to, so we can reutilize it.<br># Extracts features from a pandas dataframe containing the data of a financial asset.<br>def get_features (dataframe):<br>    dataframe_feat = dataframe[[&#39;Count&#39;, &#39;Open&#39;, &#39;High&#39;, &#39;Low&#39;, &#39;Close&#39;, &#39;Volume&#39;, &#39;VWAP&#39;]].copy()<br>    dataframe_feat [&#39;calculate_up_shadow&#39;] = calculate_up_shadow (dataframe_feat)<br>    dataframe_feat [&#39;calculate_low_shadow&#39;] = calculate_low_shadow (dataframe_feat)<br>    return dataframe_feat<br><br>dataframe[&#39;datetime&#39;] = pd.to_datetime (dataframe[&#39;timestamp&#39;], unit=&#39;s&#39;)<br>dataframe_train = dataframe [dataframe[&#39;datetime&#39;] &lt; &#39;2021-06-13 00:00:00&#39;]<br>dataframe_test = dataframe [dataframe[&#39;datetime&#39;] &gt;= &#39;2021-06-13 00:00:00&#39;]<br><br>print (&quot;Number of samples in dataframe_train: &quot;,len (dataframe_train))<br>print (&quot;Number of samples in dataframe_test: &quot;,len (dataframe_test))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*TcGNSRVUezdgdGgshJ7sSQ.png" /></figure><pre># Calculates the logarithmic return of a series over a given period.<br>def log_return(series, periods=1):<br>    return np.log(series).diff(periods=periods)<br><br>def calculate_up_shadow(dataframe):<br>    return dataframe[&#39;High&#39;] - np.maximum(dataframe[&#39;Close&#39;], dataframe[&#39;Open&#39;])<br><br>def calculate_low_shadow(dataframe):<br>    return np.minimum(dataframe[&#39;Close&#39;], dataframe[&#39;Open&#39;]) - dataframe[&#39;Low&#39;]<br><br>def fill_nan_inf(dataframe):<br>    dataframe = dataframe.fillna(0)<br>    dataframe = dataframe.replace([np.inf, -np.inf], 0)<br>    <br>    return dataframe<br><br># Features<br>my_featues = [&quot;Count&quot;, &quot;Open&quot;, &quot;High&quot;, &quot;Low&quot;, &quot;Close&quot;, &quot;Volume&quot;, &quot;VWAP&quot;]<br><br># Creates a feature matrix from a pandas dataframe containing the data of a financial asset.<br>def create_features(dataframe, label=False):<br>    # Build features<br>    up_shadow = calculate_up_shadow(dataframe)<br>    low_shadow = calculate_low_shadow(dataframe)    <br>    five_mininmum_log = log_return(dataframe.VWAP, periods=5)<br>    absolute_one_minimum_log = log_return(dataframe.VWAP,periods=1).abs()    <br>    features = dataframe [my_featues]<br><br>    # Concat all the features into one dataframe<br>    X = pd.concat ([features, up_shadow, low_shadow, five_mininmum_log, absolute_one_minimum_log], axis=1)<br>    <br>    # Rename feature columns<br>    X.columns = my_featues + [&quot;up_shadow&quot;, &quot;low_shadow&quot;, &quot;five_mininmum_log&quot;, &quot;absolute_one_minimum_log&quot;]<br>    <br>    # Fill NaN and Inf<br>    X = fill_nan_inf(X)<br>    <br>    if label:<br>        y = dataframe.Target<br>        y = fill_nan_inf(y)<br>        return X, y<br>    <br>    return X<br><br># Get single crypto trading data<br>train_bitcoin = dataframe_train [dataframe_train.Asset_ID==1]<br>test_bitcoin = dataframe_test [dataframe_test.Asset_ID==1]<br><br># Fill missing value<br>train_bitcoin = train_bitcoin.reindex (range(train_bitcoin.index[0],train_bitcoin.index[-1]+60,60),method=&#39;pad&#39;)<br>test_bitcoin = test_bitcoin.reindex (range(test_bitcoin.index[0],test_bitcoin.index[-1]+60,60),method=&#39;pad&#39;)<br><br># Create features<br>dataframe_train, y_train = create_features (train_bitcoin, label=True)<br>X_test, y_test = create_features (test_bitcoin, label=True)<br><br>D_train = xgb.DMatrix (dataframe_train, label=y_train)<br>D_test = xgb.DMatrix (X_test, label=y_test)<br><br>xgb_params = {<br>    &quot;n_estimators&quot;: 500,<br>    &quot;learning_rate&quot;: 0.05,<br>    &quot;subsample&quot;: 0.9,<br>    &quot;max_depth&quot;: 11,<br>    &quot;missing&quot;: -999,<br>    &quot;colsample_bytree&quot;: 0.7,<br>    &quot;random_state&quot;: 2023,<br>}<br><br>#Model training.<br>watchlist= [(D_train, &quot;train&quot;)]<br>model = xgb.train (params=xgb_params, dtrain=D_train, num_boost_round = 80, evals = watchlist, verbose_eval = 10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*MgAZiWDmkjgkrN_Gp2s99A.png" /></figure><pre>probability = model.predict(D_test)<br><br># RMSE Computation<br>rmse = np.sqrt(mean_squared_error(y_test, probability))<br>print(&quot;RMSE : % f&quot; %(rmse))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*AqfL4yP3tWKgf8h1d295Cg.png" /></figure><h4>Light GBM:</h4><p>Light GBM, short for Light Gradient Boosting Machine, is a gradient boosting framework developed by Microsoft. It is a type of decision tree ensemble model that is designed to handle large datasets and high-dimensional features. It uses a leaf-wise approach to grow the decision trees, which can result in better accuracy and faster training times than other gradient boosting algorithms.</p><p><strong>Pros</strong>:</p><ul><li>Efficient and fast training, especially on large datasets.</li><li>Can handle both numerical and categorical features.</li><li>Supports GPU acceleration for even faster training times.</li><li>Can handle missing values and outliers.</li><li>Can be used for both regression and classification tasks</li></ul><p><strong>Cons</strong>:</p><ul><li>Prone to overfitting if not properly tuned.</li><li>Requires careful hyperparameter tuning for optimal performance.</li><li>May not perform as well as other models on smaller datasets.</li><li>Can be sensitive to noise and outliers in the data</li></ul><p><strong>Example</strong>: A common use case for Light GBM in time-series forecasting is predicting stock prices. For example, a financial institution might use Light GBM to forecast the price of a particular stock based on historical price data, as well as other relevant features such as news articles, economic indicators, and social media sentiment.</p><p>Let’s understand in detail by training the Light GBM model on our dataset and using the same for cryptocurrency value prediction.</p><pre># Initialize the LGBMRegressor model with specified hyperparameters<br>def training_model(X,y):<br>    # Training the LBGM model<br>    lgmb_model = LGBMRegressor (n_estimators=5000, learning_rate=0.1, num_leaves=500)<br>    # Fit the model on the input X and y data<br>    lgmb_model.fit(X, y)<br>    <br>    # Return the trained model<br>    return lgmb_model<br><br># Function to extract features from input data<br>def features_extract (data):<br>    # Feature extraction for data as row of DataFrame<br>    <br>    features_dataframe = data [[&#39;Count&#39;, &#39;Open&#39;, &#39;High&#39;, &#39;Low&#39;, &#39;Close&#39;, &#39;Volume&#39;, &#39;VWAP&#39;]].copy()<br>    features_dataframe [&#39;Upper_Shadow&#39;] = features_dataframe [&#39;High&#39;] - np.maximum (features_dataframe [&#39;Close&#39;], features_dataframe [&#39;Open&#39;])<br>    features_dataframe [&#39;Lower_Shadow&#39;] = np.minimum (features_dataframe [&#39;Close&#39;],features_dataframe [&#39;Open&#39;]) - features_dataframe [&#39;Low&#39;]<br>    <br>    features_dataframe [&#39;high2low&#39;] = features_dataframe [&#39;High&#39;] / features_dataframe[&#39;Low&#39;]<br>    features_dataframe [&#39;volume2count&#39;] = features_dataframe [&#39;Volume&#39;] / (features_dataframe[&#39;Count&#39;] + 1)<br>    <br>    return features_dataframe<br><br># Function to get X and y data for a given asset ID<br>def get_data_for_asset(dataframe, asset_id):<br>    # Get X and y<br>    <br>    dataframe = dataframe [dataframe[&quot;Asset_ID&quot;] == asset_id]    <br>    df_proc = features_extract (dataframe)<br>    df_proc [&#39;y&#39;] = dataframe [&#39;Target&#39;]<br>    df_proc = df_proc.dropna (how=&quot;any&quot;)<br>    y = df_proc[&quot;y&quot;]<br>    X = df_proc.drop(&quot;y&quot;, axis=1)<br>    <br>    return X, y<br><br>%%time<br>models = {}<br>Xs = {}<br>ys = {}<br><br>for my_asset_id, asset_name in zip(asset_details[&#39;Asset_ID&#39;], asset_details[&#39;Asset_Name&#39;]):<br>    print (f&quot;Training model for {asset_name:&lt;16} (ID={my_asset_id:&lt;2})&quot;)<br>    X, y = get_data_for_asset (df, my_asset_id)    <br>    lgmb_model = training_model(X,y)<br>    Xs[my_asset_id], ys[my_asset_id], models[my_asset_id] = X, y, lgmb_model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*QZsl4qHOaRA4ePmOG1cGWw.png" /></figure><pre># Check the model and it&#39;s possibility for the prediction <br>print (&quot;Check the model and it&#39;s possibility for the prediction&quot;)<br><br>x = features_extract(df.iloc[1])<br>y_pred = models[0].predict([x])<br>y_pred[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*Z2mNU2Wj9a8dlh8DV6dJvA.png" /></figure><h3>Conclusion</h3><p>In summary, time-series forecasting is a dynamic field that requires a combination of technical skills and creative problem solving. Here are some key takeaways to keep in mind:</p><ul><li>When working with time-series data, it’s important to understand the underlying patterns and trends, such as seasonality and cyclical patterns.</li><li>ARIMA models are a great starting point for time-series forecasting, especially when working with stationary data. They are simple to implement and interpret, and can be a good baseline for more complex models.</li><li>XGBoost and Light GBM are powerful machine learning algorithms that are highly effective at handling large and complex datasets with non-linear relationships. They are great options when working with non-stationary data or when seeking higher accuracy in predictions.</li><li>It’s important to carefully consider missing data and how to handle it, as it can have a significant impact on the accuracy of your models.</li><li>It’s important to select the appropriate evaluation metrics for your specific use case, and to understand the strengths and limitations of each metric.</li></ul><p>Overall, time-series forecasting is a fascinating field with endless possibilities. By leveraging the right models and techniques, we can gain insights and make informed decisions that can drive real-world impact.</p><h3>References</h3><ul><li>WandB.ai: <a href="https://wandb.ai/iamleonie/A-Gentle-Introduction-to-Time-Series-Analysis-Forecasting/reports/A-Gentle-Introduction-to-Time-Series-Analysis-Forecasting--VmlldzoyNjkxOTMz">https://wandb.ai/iamleonie/A-Gentle-Introduction-to-Time-Series-Analysis-Forecasting/reports/A-Gentle-Introduction-to-Time-Series-Analysis-Forecasting--VmlldzoyNjkxOTMz</a></li><li>Brownlee, J. (2021). Time Series Forecasting: A Tutorial for Beginners. Machine Learning Mastery: <a href="https://machinelearningmastery.com/time-series-forecasting/">https://machinelearningmastery.com/time-series-forecasting/</a></li><li><a href="https://www.kaggle.com/code/vbmokin/g-research-crypto-forecasting-baseline-fe">https://www.kaggle.com/code/vbmokin/g-research-crypto-forecasting-baseline-fe</a></li><li><a href="https://www.kaggle.com/code/odins0n/g-research-plots-eda">https://www.kaggle.com/code/odins0n/g-research-plots-eda</a></li></ul><p>Take a <a href="https://medium.com/@hmittal15/check-your-knowledge-time-series-forecasting-93e475b12130"><strong>quiz </strong></a>to test your knowledge now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f45fa07f0a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/crash-course-in-time-forecasting-analysing-cryptocurreny-data-3f45fa07f0a8">Crash Course in Time Series Forecasting: Analysing Cryptocurrency data</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[Check your knowledge: DALL·E]]></title>
            <link>https://medium.com/aiskunks/check-your-knowledge-dall-e-ca1c16ef338e?source=rss-d66a43d41e01------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca1c16ef338e</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[dalle-2]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[clip]]></category>
            <dc:creator><![CDATA[Harshit Mittal]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 19:09:42 GMT</pubDate>
            <atom:updated>2023-04-10T22:56:54.005Z</atom:updated>
            <content:encoded><![CDATA[<p>DALL·E is an artificial intelligence program developed by OpenAI that generates images from textual descriptions. It has gained a lot of attention since its release in 2021 due to its impressive ability to generate realistic images based on written prompts. If you’re interested in AI or digital art, then you might have heard of DALL·E. But, how much do you really know about it? Let’s put your knowledge to the test with these quiz questions!</p><p><strong>1. When was DALL-E 2 opened to everyone and the waitlist requirement removed?</strong></p><p>A) April 2022</p><p>B) January 2021</p><p>C) July 20, 2022</p><p>D) September 28, 2022</p><p><em>Answer: D</em></p><p><strong>2. What is the maximum pixel size of images that DALL·E 1 can generate from text?</strong></p><p>A) 256 x 256</p><p>B) 1024 x 1024</p><p>C) 512 x 512</p><p>D) 128 x 128</p><p><em>Answer: A</em></p><p><strong>3. How does DALL·E 2 differ from DALL·E 1 in terms of image resolution and parameter models used?</strong></p><p>A) DALL·E 2 can generate images of higher resolution using a 12-billion parameter model.</p><p>B) DALL·E 2 can generate images of higher resolution using a 3.5-billion parameter model and another 1.5-billion parameter model to enhance resolution.</p><p>C) DALL·E 2 can generate images of lower resolution using a 3.5-billion parameter model.</p><p>D) DALL·E 2 can generate images of lower resolution using a 1.5-billion parameter model.</p><p><em>Answer: B</em></p><p><strong>4. What is a text embedding, which is generated by CLIP model in DALL·E</strong> <strong>2?</strong></p><p>A) A pre-determined set of numbers that represent a text or image</p><p>B) A set of numbers acquired through a neural network’s learning process that depict a text or image</p><p>C) A type of attention mechanism used in natural language processing and computer vision tasks</p><p>D) A method that introduces increasingly more randomness over a series of time steps until an image becomes unrecognizable</p><p><em>Answer: B</em></p><p><strong>5. What is CLIP model?</strong></p><p>A) A type of image embedding used in DALL·E 2</p><p>B) A model that generates new image embeddings based on a given text description</p><p>C) A type of machine learning model used in natural language processing and computer vision tasks</p><p>D) A neural network model that determines the most fitting caption for a given image</p><p><em>Answer: D</em></p><p><strong>6. What is the objective of CLIP?</strong></p><p>A) To predict an image or classify it</p><p>B) To learn the link between the textual and visual representations of the same object</p><p>C) To generate new image embeddings based on a given text description</p><p>D) To remove noise over a series of time steps and produce a realistic image</p><p><em>Answer: B</em></p><p><strong>7. What is the Diffusion model?</strong></p><p>A) A method that introduces increasingly more randomness over a series of time steps until an image becomes unrecognizable</p><p>B) A type of machine learning model used in natural language processing and computer vision tasks</p><p>C) A model that generates new image embeddings based on a given text description</p><p>D) A model that learns to create new images or other forms of data by adding noise and then removing it</p><p><em>Answer: D</em></p><p><strong>8. What is a Transformer?</strong></p><p>A) A type of attention mechanism used in natural language processing and computer vision tasks</p><p>B) A model that generates new image embeddings based on a given text description</p><p>C) A method that introduces increasingly more randomness over a series of time steps until an image becomes unrecognizable</p><p>D) A type of machine learning model used in natural language processing and computer vision tasks that transforms input data into a different representation by considering the relationships between different elements in the input data</p><p><em>Answer: D</em></p><p><strong>9. How does GLIDE differ from the standard Diffusion Model?</strong></p><p>A) GLIDE starts from random Gaussian noise</p><p>B) GLIDE lacks direction</p><p>C) GLIDE incorporates textual information into the training process</p><p>D) All of the above</p><p><em>Answer: C</em></p><p><strong>10. What is one type of image that DALL-E 2 may struggle with generating?</strong></p><p>A) Images with multiple colors</p><p>B) Images with intricate details and textures</p><p>C) Images of complex scenes involving multiple objects and interactions between them</p><p>D) Images of abstract concepts</p><p><em>Answer: C</em></p><p>So, how did you do? Whether you aced the quiz or learned something new, one thing is for sure: DALL·E is an exciting development in the field of artificial intelligence, and its potential applications are only just beginning to be explored. Who knows what the future holds for this remarkable technology?</p><p>Want to learn more about DALL·E? Dive deep into the pool of knowledge <a href="https://medium.com/@hmittal15/what-is-dall-e-b92c29bc24e4">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca1c16ef338e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/check-your-knowledge-dall-e-ca1c16ef338e">Check your knowledge: DALL·E</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[What is DALL·E?]]></title>
            <link>https://medium.com/aiskunks/what-is-dall-e-b92c29bc24e4?source=rss-d66a43d41e01------2</link>
            <guid isPermaLink="false">https://medium.com/p/b92c29bc24e4</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[clip]]></category>
            <category><![CDATA[glide]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[dalle-2]]></category>
            <dc:creator><![CDATA[Harshit Mittal]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 02:40:12 GMT</pubDate>
            <atom:updated>2023-03-27T16:57:25.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*tQHPLkRLODtdtJdkpHus-A.png" /></figure><p>Dialling into the 1980s, Detective Jones walks into the room with a file in hand. He approaches a sketch artist, Sarah, who is seated at her desk with a pencil and sketchpad. Detective Jones explained the crime scene to the artist: the witness saw a man running away from the scene, he was a tall guy, around 6&#39;2, with a muscular build and short, dark hair. Sarah carefully adds all the details to the sketch and produces it before the detective. Detective Jones examined the sketch and lauds, “Perfect. This is exactly what we needed. Thanks, Sarah.”</p><p>What if I say that we all have such a sketch artist available with us 24*7 at our fingertips? Yes, with advancements in technology, this fascination has come to life!</p><p>DALL·E is a state-of-the-art artificial intelligence program developed by OpenAI that creates images from textual descriptions. Given a textual prompt, DALL·E generates an original image based on that description, showcasing its ability to understand and execute creative tasks. The model has been trained on a diverse dataset of images and can generate a wide range of images, from photorealistic to highly stylized illustrations. This technology has the potential to revolutionize fields such as advertising, product design, and visual storytelling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0k9Jzz8ymFOJ6M_SC654Ig.png" /><figcaption>DALL·E drawing robots which are drawing robots!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVEB5ub5Xb3A6r2_nq5Hhw.png" /><figcaption>DALL·E drawing robots which are drawing robots!</figcaption></figure><h3>Evolution of DALL·E</h3><ul><li><strong>January 2021</strong>: OpenAI reveals DALL-E in a blog post. DALL-E is a model that uses a modified version of GPT-3 to generate images.</li><li><strong>April 2022</strong>: OpenAI announces the development of DALL-E 2, a successor designed to generate more realistic images at higher resolutions and combine concepts, attributes, and styles. OpenAI does not release source code for either model.</li><li><strong>July 20, 2022</strong>: DALL-E 2 enters into beta phase with invitations sent to 1 million waitlisted individuals. Access to DALL-E 2 was previously restricted to pre-selected users for a research preview due to concerns about ethics and safety.</li><li><strong>September 28, 2022</strong>: DALL-E 2 is opened to anyone and the waitlist requirement is removed.</li><li><strong>Early November 2022</strong>: OpenAI releases DALL-E 2 as an API, allowing developers to integrate the model into their own applications.</li></ul><h3>Incalculable applications</h3><p>DALL-E has a wide range of potential applications in various industries, some of which include:</p><ul><li><strong>Art and Design</strong>: DALL-E’s ability to generate unique and imaginative images based on textual descriptions opens up new possibilities for artists and designers. For example, an artist could describe a concept they have in mind, and DALL-E could generate an image that captures the essence of that idea. This could be especially useful for digital artists who work with 3D modeling, animation, and other digital media.</li><li><strong>Advertising</strong>: DALL-E can be used to generate images for advertisements, making it easier for marketers to create engaging and memorable campaigns. For example, a company could describe the product or service they want to advertise, and DALL-E could generate images that capture the essence of that offering. This could be useful for creating visual content for social media, online advertisements, or print materials.</li><li><strong>Product Visualization</strong>: DALL-E can be used to generate images of products, allowing companies to quickly and easily showcase new offerings. For example, a company could describe a new product, and DALL-E could generate images that give consumers an idea of what the product looks like and how it functions. This could be especially useful for companies in the retail or e-commerce industries that need to showcase their products in a visually appealing way.</li><li><strong>Movie and Video Game Concept Art</strong>: DALL-E can be used to generate concept art for movies and video games. For example, a movie director or video game designer could describe a scene or character they have in mind, and DALL-E could generate images that capture the essence of that idea. This could be useful for quickly generating initial concept art or for exploring different visual directions for a project.</li><li><strong>Web Design</strong>: DALL-E could be used to generate unique and imaginative images for websites. For example, a web designer could describe the look and feel they want for a particular section of a website, and DALL-E could generate images that match that description. This could be useful for creating custom graphics or backgrounds for websites.</li></ul><p>These are just a few examples of the potential applications of DALL-E. The technology is still new, and it’s likely that creative individuals and businesses will find new and innovative ways to use it in the future.</p><h3>Superpowers of DALL·E 2</h3><p>The model is trained on a large dataset of text-image pairs and can generate diverse images with different styles and contents.</p><p>Here’s a list of what superpowers DALL·E has and what can it do:</p><ul><li><strong>Image synthesis</strong>: One of the key capabilities of DALL·E 2 is its ability to generate new images from textual descriptions. For example, if we provide the model with a description such as “a giraffe reading a book on a sunny day,” it can generate a unique, high-resolution image of such a scene. The model is capable of synthesizing images of diverse objects, scenes, and animals, and can generate images with intricate details and textures.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2amSu148Qmubsh1qAdaXA.png" /><figcaption>DALL·E drawing “a giraffe reading a book on a sunny day”</figcaption></figure><ul><li><strong>Style transfer</strong>: DALL·E 2 can also apply specific styles to existing images. For instance, it can turn a photograph into a painting or a comic book, or make a piece of architecture look like it was made of candy. The model can transfer the style of any reference image to a target image, resulting in a unique and creative output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHmbpsvKopJmlJFTHfoLgA.png" /><figcaption>DALL·E drawing “portrait of mr. bean, monalisa style”</figcaption></figure><ul><li><strong>Image completion</strong>: DALL·E 2 can also complete missing parts of an image based on the surrounding context. For example, if we provide the model with an image of a partially-obscured object, it can fill in the missing parts based on the visible parts and the surrounding context. This capability can be useful in a variety of applications, such as restoring damaged or corrupted images.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8ih0Tp_Kx06LRj7GwfnEA.png" /><figcaption>Original image given to DALL·E</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNrvou91AAM8O6t8FnXbHQ.png" /><figcaption>Completed image</figcaption></figure><h3>DALL·E 1 V/S DALL·E 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nYWxjtLhXeeASQk6Hxbcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*HbVUH_kt0ASJ7iDYK_2E2Q.png" /></figure><h3>How does DALL·E 2 work?</h3><p>As previously mentioned, DALL-E 2 operates by accepting text inputs and generating corresponding images as outputs. However, this capability is not achieved through a single process, but rather through the integration of various techniques that have undergone gradual development and refinement over recent years. These techniques are layered upon each other, much like building blocks, to form the complete model. To grasp a comprehension of DALL-E 2, it is important to recognize the individual components and their functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*G2G8a9w9qvQjTrDsk3Zw9g.png" /><figcaption>DALL·E 2 architecture</figcaption></figure><h4>A 2-min read explanation</h4><p>At its core, DALL-E 2 operates in a straightforward manner:</p><ol><li>First, a text prompt is fed into a text encoder that has been trained to convert the prompt into a representative space.</li><li>Then, a component referred to as the ‘prior’ takes the text encoding and maps it to a corresponding image encoding that reflects the semantic content of the text encoding.</li><li>Finally, an image decoder generates a visual representation of this semantic information in the form of an image.</li></ol><h4>Let’s dive deep now!</h4><p>Let’s commence our examination by exploring the process through which DALL-E 2 associates and blends textual and visual abstractions.</p><p><strong>Step 1: Text encoding</strong></p><p>The process begins by feeding a text encoder with the prompt which converts it into <em>‘text embeddings’</em>. But what is a text embedding? An embedding can be described as an organized set of numbers that depict a text or image. A basic illustration of embeddings is seen in the ASCII representation of characters and numbers. However, unlike ASCII, embeddings are not predetermined but rather acquired through a neural network’s learning process.</p><p>The text embeddings used by DALL·E 2 are produced by a separate neural network known as <em>‘CLIP’</em>, developed by OpenAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ERODPU72J-Q4ouXhCs2kUw.png" /><figcaption>Text embedding illustration</figcaption></figure><p><strong><em>Sidenote: CLIP model training</em></strong><br>CLIP, which stands for ‘Contrastive Language-Image Pre-training’, is a neural network model that determines the most fitting caption for a given image. It has been trained on 400 million images and their accompanying captions, allowing it to comprehend the correlation between a specific text snippet and an image. Unlike other models that attempt to predict a caption given an image, CLIP focuses on understanding the relationship between a caption and an image. This contrastive approach to learning enables CLIP to identify the connection between the textual and visual depictions of the same object. In contrast to DALL·E 2’s text-to-image generation, CLIP’s objective is not to predict an image or classify it, but rather to learn the link between the textual and visual representations of the same object. The basic concept behind CLIP’s training is straightforward.</p><ol><li>Produce encodings of both image and text for each image-caption pair.</li><li>Determine the cosine similarity between each image and text embedding pair.</li><li>Continuously reduce the cosine similarity between mismatched image-caption pairs and increase the cosine similarity between corresponding image-caption pairs.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QnjS7-EHS_Kgg61hu623Q.png" /><figcaption>CLIP training</figcaption></figure><p>Once the training is complete, the CLIP model is frozen, and CLIP text encoder is used to generate embeddings from the provided text prompt.</p><p><strong>Step 2: Image encoding</strong></p><p>The generation of text and image encoding intermediates in the DALL·E 2 model are referred to as CLIP embeddings, however it is not the CLIP encoder itself that produces the image embeddings. Instead, a separate model called the <em>‘prior’</em> is utilized to generate the <em>‘image embeddings’</em> based on the text embeddings generated by the CLIP text encoder. During the development of DALL·E 2, two options were considered for the prior: an Autoregressive model and a Diffusion model. Both options showed similar performance, but the Diffusion model was found to be more computationally efficient and was ultimately chosen as the preferred prior for DALL·E 2. The use of a prior enables DALL·E 2 to create variations of images.<br>The diffusion prior is a method that helps generate new image embeddings based on a given text description. This method uses a special type of machine learning model called a <em>‘Transformer’</em>, which is trained on several different inputs.</p><p>The inputs to the Transformer include:<br>(i) The encoded text: This is the encoded text description that is fed into the model.<br>(ii) The CLIP text embedding: This is a special representation of the text that is created by encoding the description using CLIP model.<br>(iii) An embedding for the diffusion timestep: This is a representation of the current step in the image generation process.<br>(iv) The noised CLIP image embedding: This is a representation of an image that has been deliberately altered to make the model more robust to overfitting.<br>(v) A final embedding: This is a representation of the output from the Transformer, which is used to predict the unnoised CLIP image embedding.</p><p>In order to improve the quality of the generated images, the model does not use a simple dot product to condition the diffusion prior. Instead, it generates two samples of an image embedding and selects the one with a higher dot product with the text embedding. This helps ensure that the generated image is a better match for the text description.</p><p><strong><em>Sidenote: Diffusion models</em></strong><br>Diffusion models utilize the transformer architecture to generate data. The process begins by taking a piece of information, such as an image, and introducing increasingly more randomness over a series of time steps until it becomes unrecognizable. Then, the model attempts to restore the image back to its original form. Through this process, the model learns to create new images or other forms of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfaZX-00wtzjY4y_EfI5VA.png" /></figure><p>The process of adding noise, depicted in the illustration, is seen as a Markov chain that modifies an image through incremental amounts of randomness until it becomes indistinguishable from pure Gaussian noise. The Diffusion Model is trained to retrace the steps of this process by removing the noise over a series of time steps. After completing training, the Diffusion Model can be divided into two parts, one of which can be utilized to generate new images by randomly sampling Gaussian noise and then using the model to remove the noise and produce a realistic image.</p><p><strong><em>Sidenote: Transformer</em></strong><br>A Transformer is a type of machine-learning model used in natural language processing and computer vision tasks. In the case of the diffusion prior, the Transformer is being used to generate new image embeddings based on a given text description. A Transformer is called this because it uses a type of attention mechanism called <em>‘self-attention”</em> to transform input data into a different representation. It does this by considering the relationships between different elements in the input data, such as words in a sentence or pixels in an image. The Transformer-based approach is used in the diffusion prior because it allows the model to consider the relationships between different elements in the input data. This is particularly important when generating an image based on a text description, as the model needs to understand the relationships between the words in the text and the pixels in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*7T2ffKfIHTnw0maoGH5QHQ.png" /><figcaption>Transformer model</figcaption></figure><p><strong>Step 3: Decoding</strong></p><p>OpenAI has also developed a model known as <em>‘GLIDE’</em> (Guided Language to Image Diffusion for Generation and Editing) as a variation of the decoder. Unlike an autoencoder which solely aims to reconstruct an image given its embedding, GLIDE’s objective is to generate an image that preserves the key features of the original image based on its embedding. GLIDE represents an advanced form of the Diffusion Model by incorporating textual information into the training process. Unlike the standard Diffusion Model, which starts from random Gaussian noise and lacks direction, GLIDE enhances the Diffusion Model’s generative capabilities by integrating additional textual embeddings into the model’s existing time step embedding. This leads to the capability of text-conditional image generation. DALL-E 2 further enhanced the GLIDE model by integrating four additional context tokens into the output sequence of the GLIDE text encoder, resulting in the ability to edit images through the use of text prompts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*T9gtL7La_vuYa3vP_7SN1w.png" /><figcaption>GLIDE model working</figcaption></figure><h3>Implementing DALL·E 2 through python script:</h3><p>Below is an implementation of image generation from DALL·E 2 through the OpenAI DALL·E 2 API. To use the DALL-E 2 API, we will need to sign up for an API key on the OpenAI website. Once we have an API key, we can make API calls to generate images. The API is a REST API, which means you can make requests to it using HTTP methods like GET, POST, and DELETE.</p><pre>import base64<br>import json<br>import urllib<br>import urllib.request<br>import math<br>import time<br>from pathlib import Path<br>import os<br>import requests<br>import pandas as pd<br><br>pd.options.display.max_colwidth = 1000<br><br>class Dalle2_picture_generation():<br>    <br>    #initializes some important parameters, such as the bearer token and batch sizes for inpainting and regular images.<br>    def __init__(self, bearer):<br>        self.bearer = bearer<br>        self.batch_size = 4<br>        self.inpainting_batch_size = 4<br>        self.task_sleep_seconds = 2<br><br>    #takes in a prompt as an argument and creates an image based on the prompt using the OpenAI API.<br>    def create_image(self, prompt):<br>        body = { &quot;task_type&quot;: &quot;text2im&quot;, &quot;prompt&quot;: { &quot;caption&quot;: prompt, &quot;batch_size&quot;: self.batch_size } }<br>        return self.action_proceedings(body)<br>    <br>    #takes in a prompt and a number of images to generate and returns a list of generated images.<br>    def create_number(self, prompt, number_image):<br>        if number_image &lt; self.batch_size:<br>            raise ValueError(&quot;Please provide more number of images to generate&quot;)<br>        return [self.create_image(prompt) for _ in range (math.ceil (number_image / self.batch_size))]<br><br>    #takes in a prompt and an optional image directory and returns a downloaded image.<br>    def create_with_download(self, prompt, image_dir=os.getcwd()):<br>        my_image = self.create_image(prompt)<br>        if not my_image:<br>            return None<br>        return self.download_image(my_image, image_dir)<br><br>    #takes in a JSON body as an argument, which contains the prompt and other necessary information.<br>    #returns the task ID. It then sends GET requests to the API to check the status of the task until the task is either completed, failed, or rejected.<br>    def action_proceedings(self, body):<br>        openAIUrl= &quot;https://labs.openai.com/api/labs/tasks&quot;<br>        headers= { &#39;Authorization&#39;: &quot;Bearer &quot; + self.bearer, &#39;Content-Type&#39;: &quot;application/json&quot; }<br><br>        response= requests.post (openAIUrl, headers=headers, data=json.dumps(body))<br>        if response.status_code != 200:<br>            print(response.text)<br>            return None<br>        data= response.json()<br>        print(f&quot;Task created and respecive ID is: {data[&#39;id&#39;]}&quot;)<br>        print(&quot;Task in progress...&quot;)<br><br>        while True:<br>            requested_url = f&quot;https://labs.openai.com/api/labs/tasks/{data[&#39;id&#39;]}&quot;<br>            response = requests.get(requested_url, headers=headers)<br>            data = response.json()<br><br>            if data[&quot;status&quot;] == &quot;failed&quot;:<br>                print(f&quot;Requested task failed. Please find the details: {data[&#39;status_information&#39;]}&quot;)<br>                return None<br><br>            if data[&quot;status&quot;] == &quot;rejected&quot;:<br>                print(f&quot;Requested task got rejected. Please find the details: {data[&#39;status_information&#39;]}&quot;)<br>                return None<br><br>            if not response.ok:<br>                print(f&quot;Request got failed. Please find the status: {response.status_code}, data: {response.json()}&quot;)<br>                return None<br>            <br>            if data[&quot;status&quot;] == &quot;succeeded&quot;:<br>                print(&quot;Task completed successfully!&quot;)<br>                return data[&quot;generations&quot;][&quot;data&quot;]<br><br>            time.sleep(self.task_sleep_seconds)<br><br>    #takes in a generated image and an optional directory path and downloads the image to the specified directory.<br>    #It returns a dictionary containing the URL and path of the downloaded image.<br>    def download_image(self, my_image, image_dir=os.getcwd()):<br>        if not my_image:<br>            raise ValueError(&quot;Couldn&#39;t create image as data is empty!&quot;)<br><br>        file_directory = []<br>        url_directory = []<br>        <br>        for image in my_image:<br>            url_image = image[&quot;generation&quot;][&quot;image_path&quot;]<br>            file_path = Path(image_dir, image[&#39;id&#39;]).with_suffix(&#39;.webp&#39;)<br>            file_directory.append(str(file_path))<br>            url_directory.append(str(url_image))<br>            urllib.request.urlretrieve (url_image, file_path)<br>            print(f&quot;Image downloaded successfully: {file_path}&quot;)<br><br>        df= pd.DataFrame(columns=[&#39;Image URL&#39;,&#39;Downloaded image filepath&#39;])<br>        for i, fd in enumerate(file_directory):<br>          df.loc[i]= [url_directory[i], file_directory[i]]<br><br>        return df</pre><p>To generate the desired images, we’ll pass on the text prompt as an argument in “create_with_download()” method. This would return web URLs for the generated images under “Image URL” column heading, and would also download the images into a local directory.</p><pre>dalle = Dalle2_picture_generation(secrets[&#39;Dalle_API_KEY&#39;]) #Passing in OpenAI account&#39;s secret API key to establish connection<br>file_path=dalle.create_with_download(&quot;a skunk robot drawing a picture of skunk robot&quot;)<br>file_path</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JpEKuhskalNEJLU4r68Hg.png" /></figure><h3>Use DALL·E 2 effectively:</h3><p>Here are some tips on how to feed effective prompts to DALLE-2 to get good images:</p><ul><li><strong>Be clear and specific:</strong><br>DALLE2 works based on the prompts given to it, so it’s important to be clear and specific about what we want the image to be. This includes details such as the <em>style, subject, and colors</em> we want in the image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8wBLL2TipanPFHY_Rt-YJw.png" /><figcaption>Before: “Generate a picture of a car”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8nDpMRYGVMCAe8yhJlVNg.png" /><figcaption>After: “Please generate an image of a red sports car, with a glossy finish and racing stripes”</figcaption></figure><ul><li><strong>Use simple language:</strong><br>Use simple and straightforward language when writing prompts for DALLE2. Avoid complex or convoluted phrasing, which could confuse the AI and result in suboptimal images.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZYkEamcw8eG8DHk5Y0pLg.png" /><figcaption>Before: “Please generate a picture of a big red balloon floating in the sky”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMHTdKKkJjkBqlhcWRhyVQ.png" /><figcaption>After: “Please generate an image of a large red balloon in the sky, floating gracefully above the clouds”</figcaption></figure><p>Simplifying the language and using straightforward instructions can help DALLE2 better understand the prompt and generate more accurate images.</p><ul><li><strong>Provide context:</strong><br>Provide context for the image we want DALLE2 to create. This could include information on the intended use of the image, the target audience, and any specific requirements or constraints.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWqtYsK7FxM2vVzDxY4i2Q.png" /><figcaption>Before: “Generate a picture of a cake”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eElSxZnthsxm4vd_xeE7ew.png" /><figcaption>After: “Please generate an image of a three-tiered wedding cake, with white frosting and pink flowers, suitable for a traditional wedding reception”</figcaption></figure><p>Providing context for the image, such as its intended use for a wedding reception, can help DALLE2 better understand the requirements and generate an image that meets the requester’s needs.</p><ul><li><strong>Use examples:</strong><br>Providing examples of images that we like or want to emulate can help DALLE2 understand what we’re looking for. We could include links to images or describe them in detail.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVxa3KuMGsuAZlCcnFa8vQ.png" /><figcaption>Before: “Generate a picture of a house”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IB0SNPaHcT5aK6kYKZA3xg.png" /><figcaption>After: “Please generate an image of a large two-story house, with a wrap-around porch and white picket fence, similar to this picture [link to a reference image]”</figcaption></figure><p>Providing examples or reference images can help DALLE2 better understand the requester’s preferences and generate an image that matches their expectations.</p><ul><li><strong>Iterate and refine:</strong><br>DALLE2 may not always produce the exact image we’re looking for on the first try. Try giving different variations of the same prompt and providing feedback to DALLE2 to help it improve its output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pn1PLKsSJ3Kz0Esi-29qng.png" /><figcaption>Before: “Generate a picture of a tree”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cdUG-wMmTA2IAfzT7kIhg.png" /><figcaption>After: “Please generate an image of an oak tree with sprawling branches and golden leaves, as shown in the attached reference image. Could you make the leaves more vibrant and the trunk thicker?”</figcaption></figure><p>Providing feedback and making minor adjustments to the prompt can help DALLE2 generate images that are more closely aligned with the requester’s needs and preferences.</p><p>DALLE2 is an AI model and can only work with the information given to it in the prompt. By providing clear and specific instructions, we can help it produce high-quality images that meet our needs.</p><h3>Limitations of DALL·E 2</h3><p>DALL-E 2 is an advanced AI model that is capable of generating highly realistic and detailed images based on text descriptions. However, like any machine learning model, it has certain limitations, particularly in generating certain types of images.</p><ul><li><strong>Scenes with multiple objects:</strong> DALL-E 2 may struggle with generating complex scenes that involve multiple objects and interactions between them. This is because it may not have sufficient training data to learn the complex relationships between different objects in a scene. Even in cases where the two characters are pop culture references that the model “knows” separately — for example, Batman and Superman — it can’t seem to help blending them together. This means DALL-E 2 is often unable to meaningfully merge multiple objects or object properties such as shape, orientation, and color.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51IiPiuqOymKnY2_VJPA-w.png" /></figure><ul><li><strong>Dataset bias</strong>: DALL-E 2 has biases and tendencies to depict people and environments as White/Western and engage in gender stereotypes, which is called representational bias. This occurs when the model reinforces stereotypes seen in the dataset that categorize people based on their identity. Specificity in prompts could reduce this problem, but the biases are inevitable since the internet has been predominantly white and Western, and datasets extracted from there will fall under the same biases. It also engages in gender stereotypes which can be seen in below illustration. When asked to draw a picture of a nurse, 3 out of the 4 returned images depicted a woman.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFJJ17oDyspaLzYkt7umCw.png" /></figure><ul><li><strong>Spelling</strong>: DALL-E 2 is great at drawing but horrible at spelling words because it doesn’t encode spelling information from the text present in dataset images. When prompted with a phrase, it outputs approximations of the correct phrase, which isn’t sufficient for spelling words. However, if DALL-E 2 were trained to encode the words in the images, it could be better at this task.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smV9kXCaQX5DldXLfLm2Hw.png" /></figure><p>Take a <a href="https://medium.com/@hmittal15/check-your-knowledge-dall-e-ca1c16ef338e">quiz </a>to test your knowledge now!</p><h3>References:</h3><ol><li>DALLE2 published paper: <a href="https://arxiv.org/abs/2204.06125">https://arxiv.org/abs/2204.06125</a></li><li>OpenAI model details: <a href="https://openai.com/dall-e-2/">https://openai.com/dall-e-2/</a></li><li>Diffusion model published paper: <a href="https://arxiv.org/abs/2209.00796">https://arxiv.org/abs/2209.00796</a></li><li>CLIP model published paper: <a href="https://arxiv.org/abs/2103.00020">https://arxiv.org/abs/2103.00020</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b92c29bc24e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aiskunks/what-is-dall-e-b92c29bc24e4">What is DALL·E?</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>