<?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 Dan VanLunen (DVL) on Medium]]></title>
        <description><![CDATA[Stories by Dan VanLunen (DVL) on Medium]]></description>
        <link>https://medium.com/@dvl-data?source=rss-534d9d75f626------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zlYxKm4jPTGj1gnd.</url>
            <title>Stories by Dan VanLunen (DVL) on Medium</title>
            <link>https://medium.com/@dvl-data?source=rss-534d9d75f626------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:00:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dvl-data/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[3 Easy Ways to Make Your Plots Better]]></title>
            <link>https://medium.com/data-science/3-easy-ways-to-make-your-plots-better-d94147059470?source=rss-534d9d75f626------2</link>
            <guid isPermaLink="false">https://medium.com/p/d94147059470</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Dan VanLunen (DVL)]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 07:00:39 GMT</pubDate>
            <atom:updated>2021-03-23T07:00:39.328Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Emphasize the takeaway!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IMvOH5RKPKdZ_ZAL" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=medium&amp;utm_medium=referral">Isaac Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Charts are frequently the best way to communicate data-driven recommendations. Visual elements draw attention and illustrate complex ideas much more simply than words: “a picture is worth a thousand words.”</p><p>But not all charts are created equal. <strong>Charts should communicate a takeaway without <em>any </em>voiceover</strong>. This post lists three simple tips to make your charts more effective.</p><h4><strong>Example - productivity levels vs number of hours worked per week</strong></h4><p>In “Scrum: The Art of Doing Twice the Work in Half the Time” by Jeff and J.J. Sutherland, they discuss research that found teams working more than 40 hours per week accomplished less than teams working less than 40 hours per week (in fact, Henry Ford measured this in 1929 and implemented a 40 hour work week! <a href="https://www.history.com/this-day-in-history/ford-factory-workers-get-40-hour-week">https://www.history.com/this-day-in-history/ford-factory-workers-get-40-hour-week</a>). This is counter-intuitive. You might think teams have diminishing returns to longer work-weeks, but that surely they continue to accomplish more when they put in more time. However, this research shows that at around 40 hours, you start getting negative returns! This is an interesting point that could be illustrated in a chart.</p><p>Let’s work with a simulated data set for a technology company that shows “hours” (what hour of the work day. e.g., 1 = the first working hour of the day) and “productivity” (the average number of bugs fixed by teams in each hour of the day). We’ll start with a ggplot2 chart showing the relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*fi9eWNbzgi1NLTShyYlRoQ.png" /><figcaption>an unclear chart</figcaption></figure><p>Now ask yourself, would you understand what this chart is trying to illustrate by looking at it without any context other than the chart? Probably not. That’s where the first tip comes in.</p><h4><strong>Tip #1 — Make the Title the Takeaway</strong></h4><p>Always make the title of your chart the conclusion you want the reader to take away from it. This accomplishes 2 things.</p><ol><li>It clearly emphasizes the point of your chart and</li><li>It forces you to think about why you are showing the chart in the first place.</li></ol><p>Going back to our example, the recommendation is to have at most an 8 hour work day (because beyond 8 hours a day more bugs are created than fixed). Let’s make that the title. Also, it’s much easier to think of other improvements to the chart with this takeaway in mind: a horizontal line at 0 to show that after 8 hours a day there is a cost to continuing to work instead of a benefit + red and green shading to emphasize bad and good regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*8lgGJ45u5HNG-viufdlQwQ.png" /><figcaption>Takeaway emphasized in the title. Titled using labs(), shaded using annotate().</figcaption></figure><p>This is better, but you still can’t get the meaning without an explanation, which brings us to our second tip.</p><h4><strong>Tip #2 — Always Make Clear Axes and Legends</strong></h4><p>The chart above has poor axes: it is unclear what “productivity” measures and what “hours” is referring to. We can also clean up the x axis so that it displays cleaner numbers, which will make the key value (8) easier to read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*xjiakzISyHcAe5W_WuZ6Uw.png" /><figcaption>Clearer and cleaner axes. Axis titles using labs(), breaks using scale_x_continuous().</figcaption></figure><p>Much cleaner, but the key point where the trend crosses the 0 line could still be emphasized more.</p><h4><strong>Tip #3 — Use Callouts Within The Chart Area to Highlight Key Points</strong></h4><p>We can make the takeaway even more clear by using a big callout directly in the chart to highlight the key point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmenxPdriyg5s8EZBAAUVA.jpeg" /><figcaption>Callout emphasizes key point. These could also be added in the ggplot2 code (<a href="https://ggplot2-book.org/annotations.html">https://ggplot2-book.org/annotations.html</a>) like all of the previous edits. However, I find that it is often faster and more impactful to copy and paste the chart into something like google slides and then add text boxes and arrows for these callouts.</figcaption></figure><h4><strong>Summary</strong></h4><p>Be goal-first with your charts. First, figure out what takeaway you are trying to communicate. Then, do everything you can to make that message clear.</p><p><strong>Charts should communicate a takeaway without <em>any </em>voice over.</strong></p><ol><li>Titles should communicate the takeaway</li><li>Axes and Legends should be clear enough to understand to remove the need for a voice over</li><li>Callouts emphasize additional key points within the chart area</li></ol><h4>Appendix</h4><p>This is the code used to make the chart</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*uVhbYoqC2phJyrYByVgotA.jpeg" /></figure><p>Where df is a simple data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*yICGI5pBJDFXx-oXXZAaEA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d94147059470" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/3-easy-ways-to-make-your-plots-better-d94147059470">3 Easy Ways to Make Your Plots Better</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The #1 Data Science Case Interview Question You Should Be Ready For]]></title>
            <link>https://medium.com/data-science/the-1-data-science-case-interview-question-you-should-be-ready-for-bda1f80bf945?source=rss-534d9d75f626------2</link>
            <guid isPermaLink="false">https://medium.com/p/bda1f80bf945</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[entry-level]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Dan VanLunen (DVL)]]></dc:creator>
            <pubDate>Sat, 06 Feb 2021 04:45:20 GMT</pubDate>
            <atom:updated>2021-02-06T04:45:20.109Z</atom:updated>
            <content:encoded><![CDATA[<h4>One Question Reveals Foundational Skills</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmUf9smSja1BOTHOTtIFew.jpeg" /><figcaption><a href="https://unsplash.com/photos/s9CC2SKySJM">https://unsplash.com/photos/s9CC2SKySJM</a></figcaption></figure><p>Case interviews are a helpful way to evaluate a potential hire’s hard and soft skills. They begin by posing a realistic business scenario. For example, how would you evaluate the impact highlight a product on an online retailers home page?</p><p>Then you must scope the problem to a tangible solution. For example, designing an experiment and running a regression to determine the treatment effect of highlighting a product.</p><p>I’ve given / sat in on 50+ case interviews for data scientists at various levels. Many interviews start out similarly where the candidate is describing a solution vaguely at a high level. To get straight to the crux of it and see if you have the foundational skills needed, I’ve found one question is more important than any other:</p><blockquote><strong>What does your data set look like?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bd7UX4O4EL3clA4mFxeLEw.jpeg" /><figcaption><a href="https://unsplash.com/photos/uAFjFsMS3YY">https://unsplash.com/photos/uAFjFsMS3YY</a></figcaption></figure><p>The question may seem simple at first, but it contains a lot of the meat of any data science solution. This question gets at…</p><ul><li><strong>Data manipulation and generation </strong>— because you have to describe what uniquely identifies a row in the data set, how you are encoding categoricals/numericals. What are the pros and cons of those encoding methods? How will you be handling null values?</li><li><strong>Intuition for what kind of data is important for the problem </strong>— because you will have to describe what columns will go into the data set as features and why those features should be predictive.</li><li><strong>Technical communication </strong>— describing a data set requires being extremely specific. Once on the job, you’ll need to be able to describe the data you’re using with colleagues to be able to effectively collaborate.</li><li><strong>Knowledge of modeling </strong>— what the data looks like has strong implications for the interpretation of the results.</li></ul><p>You should be prepared for follow up questions to dig deep into your data until it is crystal clear how you have set things up. To improve clarity, I recommend you go to the white board and draw the data set with example values in rows and columns.</p><p>Let’s walk through an example to see how this question might play out and how digging on each point can reveal the depth of knowledge the candidate has.</p><p><strong>Example: Measuring a Treatment Effect — Promotional Exposure</strong></p><p>Let’s assume you are interviewing at an online retailer. In the case, they ask how would you evaluate how much of an increase in orders can be expected when they highlight a product on the homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjtMBGNByk7UR4wu5FHWfg.jpeg" /><figcaption><a href="https://unsplash.com/photos/zVdAkU4s9lI">https://unsplash.com/photos/zVdAkU4s9lI</a></figcaption></figure><p>After some discussion, you may suggest to run an experiment with two groups. One where we randomly select a product to be highlighted on the home page and other “control” group. Then, we can use data from the test to run a linear regression to determine the impact. <strong>What does your data set look like?</strong></p><p>First, what uniquely identifies a row in your data set?</p><ul><li>Is it a treatment group so you only have 2 rows? How do you account for how much data goes into each of those rows?</li><li>Is there 1 row for each customer? How might this affect our ability to determine the impact of <em>which</em> product we decided to highlight?</li><li>Is there 1 row for each customer-product? How would you account for the fact that each customer is likely to have similar outcomes (idea here is that you’d need to understand that each row is not an independent draw from a distribution, so standard errors based on <a href="https://towardsdatascience.com/all-assumptions-and-implications-of-linear-regression-in-one-chart-5674c060025f">the assumptions of a classical linear regression</a> would not be accurate — <a href="https://towardsdatascience.com/practical-experiment-fundamentals-all-data-scientists-should-know-f11c77fea1b2">see a better way to get confidence intervals here</a>)?</li></ul><p>How is your outcome defined? Perhaps the number of total orders because that’s what we are aiming for. Does the fact that orders are whole numbers (not continuous) mean anything for our analysis?</p><p>What other columns are in your data set? (<a href="https://towardsdatascience.com/get-a-grip-when-to-add-covariates-in-a-linear-regression-f6a5a47930e5">see how to decide what covariates to add to a linear regression here</a>)</p><ul><li>Treatment indicator (0/1). This is key to later answer how you’ll get the impact of the strategy from the results of the regression (coefficient on treatment).</li><li>Customer/time/product characteristics to improve our ability to predict orders for the customer. How would these be encoded? Note here that depending on what you said uniquely identified a row, you’ll have different options for what kind of additional covariates you can add (e.g. a customer-level regression can’t have product-level characteristics).</li></ul><p>Will you apply any filters to your data set? For example, will you keep customers without any orders in the data? How does that decision affect the interpretation of your results? For example, if you remove all customers with 0 orders, the interpretation of the coefficient on the treatment becomes impact on average order quantity, not the total impact!</p><p><strong>Words of Advice</strong></p><p>Before interviewing for any data scientist role, you should try to think of some problems that likely face that organization and how a data science model might solve them. Then, run through the exercise of describing your data set and think about all the implications of the decisions you are making along the way. You should be able to describe your approach so specifically that someone could go and code up your solution after speaking with you. After conducting this exercise a few times, you’ll be more confident going into interviews knowing that you can describe a solution with clarity no matter how many questions you get about your approach. Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bda1f80bf945" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-1-data-science-case-interview-question-you-should-be-ready-for-bda1f80bf945">The #1 Data Science Case Interview Question You Should Be Ready For</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All Assumptions and Implications of Linear Regression in One Chart]]></title>
            <link>https://medium.com/data-science/all-assumptions-and-implications-of-linear-regression-in-one-chart-5674c060025f?source=rss-534d9d75f626------2</link>
            <guid isPermaLink="false">https://medium.com/p/5674c060025f</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[assumptions]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Dan VanLunen (DVL)]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 13:49:23 GMT</pubDate>
            <atom:updated>2020-04-03T18:34:56.430Z</atom:updated>
            <content:encoded><![CDATA[<h4>The only chart you need + video explanation</h4><p>Post by Dan Vanlunen</p><p>In order to appropriately interpret a linear regression, you need to understand what assumptions are met and what they imply.</p><p>The key assumptions and their implications are summarized in the charts below (first for finite, aka small, sample OLS, then for asymptotic OLS). Then I share a video where I discuss the assumptions of experiments and how they fit with the assumptions of regression. Finally, I conclude with some key points regarding the assumptions of linear regression.</p><h3>Key Assumptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T70X0eEG5UBa5Ceo-NewGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*bl4v-ux72Q55KeS9fe5jNA.png" /></figure><h3>Video Discussion of Assumptions</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhtpZ6_2Dk0k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhtpZ6_2Dk0k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhtpZ6_2Dk0k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bf3f9bcf7c12d9b3aaca502f26c12c0/href">https://medium.com/media/7bf3f9bcf7c12d9b3aaca502f26c12c0/href</a></iframe><h3>Linear Regression Assumptions: Key Points</h3><h4><strong>Unbiasedness / Consistency</strong></h4><p>We want our coefficients to be right on average (unbiased) or at least right if we have a lot of data (consistent).</p><p>If you want unbiased coefficients, the key assumption is strict exogeneity. This means that the average value of the error term in the regression is 0 given the covariates used in the regression.</p><p>For consistent coefficients, the key assumption is “predetermined regressors” which is fancy talk for: there is no correlation between the error term and any of the covariates of the regression.</p><p>Strictly speaking, there is no way to confirm these assumptions are right without randomly assigning the covariate whose coefficient you want to get right. Without random assignment, you have to make a qualitative argument that the assumptions are met. However, if you make a scatter plot of residuals on the y axis and the predicted outcome value on the x axis and there is a systematic trend away from 0, that’s a sign this assumption is not met.</p><p>For example, let’s assume we are modeling the amount of money a person spends on dog grooming as a function of the dogs size. Let’s also assume that people who like big dogs tend to spend more money on dog grooming (a confounder we are not controlling for). The code below creates an example data set for this example and the plot suggested above, which shows that the assumption is not met. This explains why the coefficient we estimate on size is far from the true value we set as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe4f4cd60ca27e9cbc19ba87face974f/href">https://medium.com/media/fe4f4cd60ca27e9cbc19ba87face974f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*WsTWfZrUwhfcNfjbochzMA.jpeg" /><figcaption>coefficient far from true effect of +2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eYyS1eyCLAk8njtovqTzUQ.png" /></figure><p>Assumptions are also important to understand the precision of coefficient estimates.</p><h4><strong>Understanding the Precision of the Coefficients</strong></h4><p>Homoskedasticity and normality are not needed for unbiased/consistent coefficients. You only need these additional assumptions if you want to get a sense of the precision with which you are measuring your coefficients with shortcut methods (e.g. F tests). However, you can always use heteroskedasticity robust standard errors, <a href="https://towardsdatascience.com/practical-experiment-fundamentals-all-data-scientists-should-know-f11c77fea1b2">bootstrapping, or randomization inference</a> to understand precision instead.</p><p>If you enjoyed this post, please upvote <a href="https://stats.stackexchange.com/questions/16381/what-is-a-complete-list-of-the-usual-assumptions-for-linear-regression/400600?fbclid=IwAR10LYIhI0DCGCLPidZgqRsw0j_A62Uu6BgOclu5clsfHrPLVh-Edf_dyCA#400600">my answer on statsexchange</a> so more people can learn from it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5674c060025f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/all-assumptions-and-implications-of-linear-regression-in-one-chart-5674c060025f">All Assumptions and Implications of Linear Regression in One Chart</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get a Grip! When to Add Covariates in a Linear Regression]]></title>
            <link>https://medium.com/data-science/get-a-grip-when-to-add-covariates-in-a-linear-regression-f6a5a47930e5?source=rss-534d9d75f626------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6a5a47930e5</guid>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[precision]]></category>
            <dc:creator><![CDATA[Dan VanLunen (DVL)]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 21:29:49 GMT</pubDate>
            <atom:updated>2020-03-16T00:43:16.580Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>A Guide to Accurately and Precisely Measuring Effects!</h4><p>by Dan VanLunen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AuhxMx67jLUY2abl5SO7g.jpeg" /><figcaption><a href="https://pixabay.com/photos/mixer-dj-controller-buttons-4197733/">Image via Pixabay</a></figcaption></figure><p>Linear regression models make it easy to measure the effect of a treatment holding other variables (covariates) fixed. But when and why should covariates be included?</p><p>This post will answer that question.</p><p>First, we’ll talk about covariates in the context of prediction: add them when they improve out of sample fit.</p><p>Then, we’ll discuss when you should use covariates to measure a causal effect and when you shouldn’t:</p><p><strong>Getting the Measurement Right</strong></p><ul><li>Add Confounders that Could Bias the Estimate</li><li>Don’t Add Downstream Outcomes</li><li>Don’t Add Colliders</li></ul><p><strong>Get a Precise Estimate</strong></p><ul><li>Add controls that are predictive of outcomes, but not treatment to increase precision</li><li>Don’t add controls that are predictive of treatment, but not outcomes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpfAsjtbgwxbir6AFFC7iA.png" /><figcaption>Summary of Post</figcaption></figure><h3>Prediction: Use Out of Sample Performance</h3><p>If you are not influencing the value of any of the variables in the regression, you might only care about prediction. For example, if you were looking to sell an apartment, you might want to predict the sale price. You could train a regression on the sale price of other apartments including covariates like the number of bedrooms. In this case, you probably only care about getting a good prediction of the sale price. You likely are not looking to evaluate if you added another bedroom, how much more could you sell for (which, by contrast would be a causal problem).</p><p>To decide whether or not a covariate should be added to a regression in a prediction context, simply separate your data into a training set and a test set. Train the model with the covariate and without using the training data. Whichever model does a better job predicting in the test data should be used.</p><p>Adding covariates reduces the bias in your predictions, but increases the variance. Out of sample fit is the judge of this tradeoff. If you have many variables, techniques like L1 regularization can help determine which to include. You might also consider more complicated black box models because you are not concerned with interpretability.</p><p>Things get more complicated when you are trying to measure a causal effect.</p><h3>Causal Effects</h3><p>Regressions are interpretable. It is easy to identify how the change of a variable in a regression is associated with a change in the outcome through the coefficients of the regression. For example, if you own a lot of dog grooming salons, you might consider whether or not you want to give dogs bandanas as they leave so they look cute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*MmPVLl2JelKbmSG4KTRUFQ.png" /><figcaption>Teddy</figcaption></figure><p>You want to know if giving bandanas will increase revenue so you run a regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*GJ-7Hu5f9koxnNXSZ8s4UQ.png" /></figure><p>Where gives_bandanas is a 0, 1 indicator variable whether or not the salon gives bandanas. \beta_1 will exactly tell you the impact on revenue that is associated with giving bandanas.</p><p>The reasons for adding or not adding controls to a regression generally fall into two categories:</p><ol><li>Getting the Measurement right (eg reducing bias)</li><li>Precision of effect measurement</li></ol><h4>Getting the Measurement Right</h4><p>There are 3 main cases where adding a covariate to your regression can make or break your resulting treatment effect estimate.</p><ol><li>Confounders (include them)</li><li>Downstream outcomes (don’t include them)</li><li>Colliders (don’t include them)</li></ol><p><strong>Add Confounders that Could Bias the Estimate</strong><br>Confounders can make your treatment effect estimates incorrect if you don’t account for them. A confounder is something that influences the value of both the treatment and the outcome.</p><p>For example, let’s say customers in fancy neighborhoods are more inclined to request bandanas. Fancy neighborhoods also tend to have people that spend more money on dog grooming. Thus, fanciness influences both the treatment (whether or not the salon gives bandanas) and the outcome (revenue) and is a confounder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*Y1cebNJwvJ_LrovNW4sFZg.png" /></figure><p>Let’s illustrate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c23e0fee31a127654474f5b5b9bb6e82/href">https://medium.com/media/c23e0fee31a127654474f5b5b9bb6e82/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*TOLwdAuppXzotxdzvJzGpg.png" /></figure><p>Now let’s see what would happen if we don’t control for fanciness.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4600953a77a4cfc94efd1bb5f4a7f20/href">https://medium.com/media/d4600953a77a4cfc94efd1bb5f4a7f20/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*OdbO0wcZ8KqHVto6UVKdnQ.png" /><figcaption>confounded, biased model (gives_bandanas coefficient includes fanciness effect)</figcaption></figure><p>The true effect of gives_bandanas is a $10000 increase to revenue, but we measured a much larger effect. In fact, the true effect doesn’t even fall in our model’s 95% confidence interval for the effect.</p><p>But what if we add fanciness to the regression?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87ddf9a5928c8a4cf200d2c2746a832f/href">https://medium.com/media/87ddf9a5928c8a4cf200d2c2746a832f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*1QKA8RvA8G28fO3Q1oooSQ.png" /><figcaption>model that controls for the confound is unbiased</figcaption></figure><p>Now we have an accurate measurement of the effect!</p><p>A good way for checking for such confounds is running the regression with and without them. If the coefficient of interest (eg on gives_bandanas) changes a lot, it’s a sign that bias is present.</p><p><a href="https://stats.stackexchange.com/questions/16381/what-is-a-complete-list-of-the-usual-assumptions-for-linear-regression/400600#400600">Extension: check my stats stackexhange post to see what mathematical assumptions are required for unbiased coefficients</a>. The key assumption is strict exogeneity (similar to no correlation between the variable of interest like gives_bandanas and other variables that are not controlled for in the regression, but that also impact the outcome).</p><p>Though controlling for confounds is helpful, controlling for downstream outcomes or colliders can distort our estimated treatment effect.</p><p><strong>Don’t Add Downstream Outcomes</strong></p><p>If we add variables that are caused by our treatment and influence the outcome, we will remove the effect our treatment has on the outcome <em>through</em> the added variable. For example, let’s imagine a case where giving dogs bandanas causes customers to be more likely to come back to the salon and that revenue is influenced by how many customers return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*8qaPpe4ZsDTz20uHJGSfWg.png" /></figure><p>Let’s see how the effect of giving bandanas is lost when we add the return rate as a covariate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a76851aa518d59e4aad3de93f5602266/href">https://medium.com/media/a76851aa518d59e4aad3de93f5602266/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*SQBx9486e0E1W_rIa6c2uw.png" /></figure><p>Let’s see how running the regression works here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a9727fdfd20a2c47b77feab6192fd99/href">https://medium.com/media/5a9727fdfd20a2c47b77feab6192fd99/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*mgraiCfGg7tmdjBT0WmFDw.png" /><figcaption>what we want when no downstream effect included</figcaption></figure><p>We get an estimated effect that is very close to the true +100 effect when we don’t include the downstream variable.</p><p>But what if we <em>do</em> include it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d592ab980a2430d22f22a273ffaf2d6/href">https://medium.com/media/9d592ab980a2430d22f22a273ffaf2d6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*2q_INdGor9HXOQQRZ3xetw.png" /><figcaption>downstream effect sops up and removes impact of treatment</figcaption></figure><p>Adding the return_rate to the regression eliminates the effect of giving bandanas. This is because holding return_rate fixed, giving bandanas doesn’t actually have an impact. But we are still interested in the effect of giving bandanas (even if through other variables) so we shouldn’t control for downstream effects.</p><p>We don’t only need to worry about adding downstream effects, we also need to worry about adding colliders.</p><p><strong>Don’t Add Colliders</strong></p><p>A collider is a variable that is influenced by both the treatment and the outcome. Adding a collider to a regression can distort the measured association between the treatment and outcome. For example, whether a salon as a storage closet or not. If your salon gives bandanas, you likely need a closet to store them in and therefore giving bandanas influences whether or not there is a storage closet. Also, salons that have a lot of revenue likely see more customers who leave things behind and thus those salons need a place to store lost and found items. Let’s consider an example where bandanas don’t have any impact on revenue, but where an association can be found if we accidentally control for this collider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*twp5Te5rpfDRB9SyFDnoiQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8394df5ed90bce4a1fd6dd0aec5bde72/href">https://medium.com/media/8394df5ed90bce4a1fd6dd0aec5bde72/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*kvaiqBRbVyvtoyM6js5akw.png" /></figure><p>The regression works fine without a collider.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8a5c0554ff09504b6cb3eb196700ccd/href">https://medium.com/media/a8a5c0554ff09504b6cb3eb196700ccd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*rG-0x-kdt5ZU6XpuC0IFKA.png" /><figcaption>no collider, no problem</figcaption></figure><p>We don’t measure any effect of giving bandanas then the collider is not included. This a good thing because bandanas have no effect of revenue in this case. But what happens when we add the collider?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/485c953f5e1e643cdc2ab640aed4f4e8/href">https://medium.com/media/485c953f5e1e643cdc2ab640aed4f4e8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*GRqzcn86CCDGrLp0yzF6Ew.png" /><figcaption>collider makes it look like bandanas have an effect, when they don’t!</figcaption></figure><p>Now we measure a significant negative association between giving bandanas and revenue that does not actually exist. This is because of the “holding fixed” interpretation of a regression. For a given value of storage, revenue is negatively associated with giving bandanas.</p><p>Knowing whether or not to add covariates to accurately measure an effect is most important, but it is also important to know when a covariate could increase the precision of your estimates.</p><h4>The Impact of Covariates on the Precision of Coefficient Estimates</h4><p>Covariates can increase the precision with which you estimate a particular coefficient if they are predictive of the outcome and not highly correlated with the variable whose coefficient you are trying to estimate.</p><p>This result may seem counter intuitive: isn’t adding covariates supposed to increase variance and therefore reduce precision? That’s true in terms of the predictions of the outcome, but not the estimates of the coefficients in the regression.</p><p>If we meet some standard assumptions of ordinary least squares (the relationship between our outcome and covariates is linear, the units are not impacting each other, there is no correlation between the treatment and other covariates that impact the outcome, homoskedasticty — <a href="https://stats.stackexchange.com/questions/16381/what-is-a-complete-list-of-the-usual-assumptions-for-linear-regression/400600#400600">see my stats stackexchange post for all assumptions and implications</a>) the variance of the OLS estimate of the coefficient on the treatment is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*g_GJ7nbbDAjaD8cXYIgR2g.png" /></figure><p>The sum in the denominator refers to how much variance there is in the application of our treatment (giving bandanas). This is not related to what covariates we add.</p><p>\sigma² is the error variance of the regression. The better we are at making predictions of the outcome with the regression, the lower this value will be. Therefore, if we add covariates that are highly predictive of the outcome \sigma² will decrease and we will have more precision.</p><p>However, R²_{gives_bandanas} represents the R² if we ran a regression with gives_bandanas as the outcome and all the other covariates as explanatory variables. This means that if we add covariates that are highly correlated with the treatment our estimate of the coefficient on the treatment will have a higher variance. This speaks to the fact that you should not add variables that are highly correlated with the treatment, unless they are confounders that are also highly correlated to the outcome.</p><p>Let’s illustrate. Suppose giving bandanas is not correlated with the number of dogs where the salon is, but salon revenue is (adding number of dogs to the regression will increase precision). Also, suppose that whether or not the salon gets ads from local bandana suppliers influences whether or not the salon gives bandanas, but does not affect the salons revenue directly (adding whether the salon received ads will reduce precision).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*-ziElmc5uc7MossA3VrNGA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fed63da9d1638f2be102d51a55c51640/href">https://medium.com/media/fed63da9d1638f2be102d51a55c51640/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*lgL1LbbZAj22r3daC2ymVw.png" /></figure><p>Let’s start with a regression using just treatment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f292e941a878660734f1bc05dad376/href">https://medium.com/media/e8f292e941a878660734f1bc05dad376/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*fopAlivFZiu_B05NoxA5dw.png" /><figcaption>unbiased measurement with just treatment</figcaption></figure><p>We measure an accurate effect fairly close to the true impact of 5.</p><p>Now let’s add the predictive covariate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f15f6c820c80f148aa3b26cdc8309f2c/href">https://medium.com/media/f15f6c820c80f148aa3b26cdc8309f2c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*YNrHnZnWY5s0cA9S6vliEg.png" /><figcaption>more precise measurement when we add a good predictor</figcaption></figure><p>Now we measure an effect more precisely! The coefficient on gives_bandanas is much closer to 5 with a lower standard error.</p><p>But what if we had added a non-predictor that was correlated with treatment instead?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7683101b69d41dcb69f93c496c1f2528/href">https://medium.com/media/7683101b69d41dcb69f93c496c1f2528/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*UxJft02mAuVnbrA-WO8lMA.png" /><figcaption>less precision when we add a non-predictor that is correlated with treatment</figcaption></figure><p>Now we have less precision and are further away from the true effect of 5.</p><h3>Summary</h3><p>To summarize, please reference the chart below. If you would like to learn more about measuring effects through experiments check out my other posts:</p><ul><li><a href="https://towardsdatascience.com/practical-experiment-fundamentals-all-data-scientists-should-know-f11c77fea1b2">Practical Experiment Fundamentals All Data Scientists Should Know</a></li><li><a href="https://towardsdatascience.com/an-experiment-assignment-method-all-data-scientists-should-know-e4d57d96b26b">An Experiment Assignment Method All Data Scientists Should Know</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpfAsjtbgwxbir6AFFC7iA.png" /><figcaption>Summary of Post</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6a5a47930e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/get-a-grip-when-to-add-covariates-in-a-linear-regression-f6a5a47930e5">Get a Grip! When to Add Covariates in a Linear Regression</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Experiment Assignment Mechanism to Maximize Precision]]></title>
            <link>https://medium.com/data-science/an-experiment-assignment-method-all-data-scientists-should-know-e4d57d96b26b?source=rss-534d9d75f626------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4d57d96b26b</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[experimentation]]></category>
            <dc:creator><![CDATA[Dan VanLunen (DVL)]]></dc:creator>
            <pubDate>Sun, 08 Mar 2020 00:06:38 GMT</pubDate>
            <atom:updated>2020-04-05T18:54:15.966Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimal Stratified Random Assignment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22TEWo71_NnvqOj7FRoZvA.jpeg" /><figcaption><a href="https://pixabay.com/photos/vaccine-chemist-syringe-stopwatch-4892059/">https://pixabay.com/photos/vaccine-chemist-syringe-stopwatch-4892059/</a></figcaption></figure><p>by Dan VanLunen</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0dc9ec6cc4af245f6d841abfd4073d2/href">https://medium.com/media/e0dc9ec6cc4af245f6d841abfd4073d2/href</a></iframe><h3>Why This is Important</h3><p>Randomized experiments are the gold standard for causal inference: if you want to get an unbiased (the average value of your estimation method is the true value) estimate of an effect of a treatment, a randomized experiment is the best way to do so.</p><p>But experiments are expensive and the more data you have to collect, the more costly they are. Using the methodology in this post, you can increase your experimental precision so that you’ll be able to measure an effect with less data and thus less $.</p><p>If you’re interested in experiments, I recommend you also read my other posts</p><ul><li><a href="https://towardsdatascience.com/practical-experiment-fundamentals-all-data-scientists-should-know-f11c77fea1b2">Practical Experiment Fundamentals All Data Scientists Should Know</a></li><li><a href="https://towardsdatascience.com/get-a-grip-when-to-add-covariates-in-a-linear-regression-f6a5a47930e5?source=friends_link&amp;sk=fa2da69f55faa9641bdc8e19bb3ce4af">Get a Grip! When to Add Covariates to a Linear Regression</a></li></ul><h3>High Level Outline of the Approach</h3><p>This post outlines a method for <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiC-I_00P_nAhVOhOAKHaEBASUQFjAAegQIAhAC&amp;url=https%3A%2F%2Fscholar.harvard.edu%2Ffiles%2Ftbarrios%2Ffiles%2Fopstratv17_0.pdf&amp;usg=AOvVaw1NwZ4ew2X2CWugbWlzKEug">optimal stratification in randomized experiments</a>.</p><p>The strategy is as follows:</p><ol><li>Using pre-experiment covariates, build a model that predicts your outcome of interest.</li><li>Sort your experimental units (level of your population you assign treatment at: here regions) by their predicted outcome from the model trained in the previous step.</li><li>Randomly assign treatment to one of the two units with the highest predicted outcomes, and to one of the two units with the third and fourth highest predicted outcomes, and so forth until you assign treatment to one of the two units with the lowest predicted outcomes.</li><li>Then, to measure the effect of the treatment on the outcome regress outcome ~ b0 + b1 Treatment + b[2:N/2+1] pair_indicators. The coefficient on the treatment indicator in the final step is the impact of the treatment on the outcome.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*9GCaybANSVdRei6SF13Frg.png" /><figcaption>See page 18 of <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiC-I_00P_nAhVOhOAKHaEBASUQFjAAegQIAhAC&amp;url=https%3A%2F%2Fscholar.harvard.edu%2Ffiles%2Ftbarrios%2Ffiles%2Fopstratv17_0.pdf&amp;usg=AOvVaw1NwZ4ew2X2CWugbWlzKEug">paper</a></figcaption></figure><p>Intuitively, this is stratified random assignment where each stratum is a pair of experimental units that have very similar predicted values of the outcome of interest.</p><p>The remainder of this post will work through</p><ol><li>An example experiment with toy data to make things concrete</li><li>The simplest assignment and effect estimation strategy</li><li>The optimal strategy</li><li>Why covariates don’t work as well as the optimal strategy</li></ol><h3>Example Experiment</h3><p>Let’s say we own a company that specializes in dog travel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9dSfoJDKkU8zUSJ5T6vYw.jpeg" /><figcaption><a href="https://pixabay.com/photos/dog-mountain-mombarone-clouds-190056/">https://pixabay.com/photos/dog-mountain-mombarone-clouds-190056/</a></figcaption></figure><p>We want to measure the impact of a TV ad on our revenue. TV ads can be distributed to different geographic regions. In order to measure the impact of the TV ad, we can measure the difference between revenue from regions that we (i) displayed the TV ad in and (ii) did not display the TV ad in.</p><p>Let’s build a toy data set to illustrate this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0ad5785b0352d08b20653d61189539f/href">https://medium.com/media/c0ad5785b0352d08b20653d61189539f/href</a></iframe><p>The key elements of this data set are:</p><ul><li>Revenue is associated with covariates: population. The relationship is non-linear.</li><li>Revenue in the experiment period is on average 1% higher if the region receives treatment. This is the effect we are trying to measure.</li></ul><p>A scatter plot shows these elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQrgZ1b-EPTnoguvuOGAmg.png" /></figure><p>We’ll also make a helper function that will add the actually observed revenue given treatment assignment to our data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5785626162bf1263b21e0acb83f11f2b/href">https://medium.com/media/5785626162bf1263b21e0acb83f11f2b/href</a></iframe><p>Next let’s turn to a simple regression that can measure this treatment effect.</p><h3>Measuring the Effect</h3><h4>The Regression</h4><p>To measure the relative change in revenue we’ll can use the following regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*rC0IgvLOY-8r5X6dvIbzXg.png" /></figure><p>Treated is 1 if the region received treatment and 0 otherwise.</p><p>Then, β₁ can be interpreted as the proportional impact of treatment on revenue: if a unit is given treatment, revenue will increase by</p><p>100(1-e^β₁)% ≈ 100β₁%</p><p>This is a good approximation for the range we expect β₁ to be in (near 1% in our toy data).</p><h4>Simple Random Assignment</h4><p>As a first principle, we need assignment to be random. Otherwise, we’ll likely get a biased measurement. For example, if we decided to send the ad to all the regions with the largest revenue in the pre-period, then when we ran the regression above, we would likely see a very large treatment effect because we were attributing the effect of having a larger pre-period revenue to the treatment. But if we randomize treatment, no such confounding variables can exist.</p><p>The simplest way for us to measure the effect in this experiment is by assigning a random half of the geographies to get the ad and then running the regression from the previous section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce3d2a30ef40d2b23ea94324bc6af28c/href">https://medium.com/media/ce3d2a30ef40d2b23ea94324bc6af28c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*9V-xrnuGzjTB5Ltz0KI1pQ.png" /></figure><p>We find an estimate that isn’t as close as we would like to the actual effect level: we measure a 2.2% effect when it is a 1% effect.</p><p>How can we change our assignment mechanism to measure this 1% effect more precisely?</p><h3>Optimal Stratified Assignment</h3><p>The key question this post aims to solve is: how do we assign which geographies should get the ad (treatment) to get the data we need to estimate the impact of the ad as precisely as possible. The answer: stratified assignment where the strata have similar values of the outcome.</p><p>Let’s make functions for each step of the process.</p><ol><li>Predict outcomes to assign pairs of geographies (units) with similar predicted outcomes to strata (groups to assign treatment within randomly)</li><li>Assign treatment randomly within strata</li><li>Measure the effect</li></ol><h4>Predicting the Outcome and Stratifying Regions</h4><p>First, let’s make a function that uses a model to predict the outcome. Then, assigns pairs of regions (units) that have similar predicted outcomes to the same strata.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c77c83237b5242bd557ce860702da781/href">https://medium.com/media/c77c83237b5242bd557ce860702da781/href</a></iframe><h4>Random Assignment Within Strata</h4><p>Next, within each stratum, it will assign half of the units to treatment randomly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afd499f2b7ec348f898b4d1c6619ed1e/href">https://medium.com/media/afd499f2b7ec348f898b4d1c6619ed1e/href</a></iframe><h4>Measuring the Effect</h4><p>Finally, a function to measure the effect. Here we could run a regression that has dummies for each stratum, however this is equivalent to use strata fixed-effects with `plm`.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dae9b6ca9c7739dce6ab1609e792c69a/href">https://medium.com/media/dae9b6ca9c7739dce6ab1609e792c69a/href</a></iframe><h4>Putting it Together</h4><p>Let’s remeasure the effect with this optimal assignment method. We’ll use a simple regression to predict pre period revenue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21f8ff2b4541f2db3635e3e9fbe5e3e8/href">https://medium.com/media/21f8ff2b4541f2db3635e3e9fbe5e3e8/href</a></iframe><p>Then, we’ll use this model and the functions we created to measure the effect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec34d753c7f2cd3fe77d2aa4a622a9c8/href">https://medium.com/media/ec34d753c7f2cd3fe77d2aa4a622a9c8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*Ex9YhGespFUCddKGCO7FrA.png" /></figure><p>Now, the result is much closer to the 1% we are expecting to measure! The standard error* is an order of magnitude smaller than it was with the simple method.</p><p>That’s the method! Simple, but powerful!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrlb92QcFH8g4oyMysw8ZQ.jpeg" /><figcaption><a href="https://pixabay.com/photos/flash-thunderstorm-super-cell-2568381/">https://pixabay.com/photos/flash-thunderstorm-super-cell-2568381/</a></figcaption></figure><p>*Note that we are using the default errors the regression spits out because they show the key points of this post, but Randomization Inference is likely a better idea given our uncertainty is coming from assignment. See <a href="https://towardsdatascience.com/practical-experiment-fundamentals-all-data-scientists-should-know-f11c77fea1b2">this post to see how to do Randomization Inference</a>.</p><p>The remainder of this post digs into the details.</p><ul><li>Couldn’t we just accomplish the same thing with covariates?</li><li>Why does this method work?</li></ul><h3>Covariates</h3><p>Let’s use the data with the simple random assignment and see if we can accomplish the same thing with covariates:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09306e57cf11b48a03ff5e4ba7ed3260/href">https://medium.com/media/09306e57cf11b48a03ff5e4ba7ed3260/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Hksuzed2roWGc4scTBPQaw.png" /></figure><p>All of these results are still worse than the optimized assignment: as seen above they are less precise and the point estimates are further from the true value. Why?</p><h3>Why Optimized Stratified Assignment is Best</h3><p>If we meet some standard assumptions of ordinary least squares (the relationship between our outcome and covariates is linear, the units are not impacting each other, there is no correlation between the treatment and other covariates that impact the outcome, homoskedasticty — <a href="https://stats.stackexchange.com/questions/16381/what-is-a-complete-list-of-the-usual-assumptions-for-linear-regression/400600#400600">see my stats stackexchange post for key assumptions and implications</a>) the variance of the OLS estimate of the coefficient on the treatment is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*gObK_Jcwhdb-GkQAbdj3Ww.png" /></figure><p>The sum in the denominator is the total sample variation in the treatment. This can be maximized (and the higher it is the more precise our coefficient estimator is) by assigning half of the regions to treatment. We have done that in all of the examples.</p><p>The $(1 — R²_{-treated})$ term is the percent of the variation in the treatment that is not explained by all the elements of our model <strong>besides</strong> the treatment (it is 1 minus the R² if you run the regression of treatment as a function of all the other covariates). This is what shows that you’ll have less precision if you add a lot of features that are highly correlated with treatment. In our examples, the treatment is random in all cases, so we expect this term to be negligible (the other covariates shouldn’t explain the random treatment so $(1 — R²_{-treated})$ should be close to 1).</p><p>The numerator is the error variance of the regression: the precision increases if our model has more explanatory power. This is the key distinction between our examples.</p><ul><li>The random assignment with just the treated term in the regression performs worst because it doesn’t explain a lot of variation with only treatment in the model.</li><li>The models with covariates do better because they can explain more of the variation in the outcome with population and/or pre period revenue in the model.</li><li>The model with optimal assignment and fixed effects (same as indicators for strata) does best. This is because the model that predicts the outcome in the pre period does the best job at predicting post period outcomes given the non-linear relationship between population and revenue. We could add more flexible functions of the covariates to account for this relationship, but a model to predict the outcome will likely do better (especially if we used a more flexible model like a random forest).</li></ul><p>The other reason the models with covariates could be considered worse is because regressions yield variance-weighted average treatment effects: see <a href="https://economics.mit.edu/files/14922">page 477 of this paper</a>. When we use pure random assignment (not optimized stratified), we still might assign relatively more control or treatment regions to different levels of covariates. The levels of the covariate where we have more even levels of treatment and control (about 50% in each) will be given more weight in the final measurement. The optimized method avoids this because it ensures that we will always assign half treatment and half control within each pair such that all of the covariate space will roughly count equally.</p><h3>An Aside: Propensity Scores</h3><p>You should NOT use propensity scores to create strata to randomize within. Above we predict the outcome of interest, whereas propensity scores predict the treatment using past data. Using propensity scores to match end up creating more imbalance in your data and less robust results. See this video for details:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrBv39pK1iEs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrBv39pK1iEs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrBv39pK1iEs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb9ee4e6d3c003f6b7e9a832666815e7/href">https://medium.com/media/eb9ee4e6d3c003f6b7e9a832666815e7/href</a></iframe><p>If you’re interested in experiments, I recommend you also read my previous post: <a href="https://towardsdatascience.com/practical-experiment-fundamentals-all-data-scientists-should-know-f11c77fea1b2">Practical Experiment Fundamentals All Data Scientists Should Know</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4d57d96b26b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/an-experiment-assignment-method-all-data-scientists-should-know-e4d57d96b26b">An Experiment Assignment Mechanism to Maximize Precision</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magically Pull Arguments for PySpark UDFs and Pandas Functions]]></title>
            <link>https://medium.com/data-science/magically-pull-arguments-for-pyspark-udfs-and-pandas-functions-8f85f6b893f2?source=rss-534d9d75f626------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f85f6b893f2</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Dan VanLunen (DVL)]]></dc:creator>
            <pubDate>Mon, 02 Mar 2020 03:39:03 GMT</pubDate>
            <atom:updated>2020-03-02T03:39:03.146Z</atom:updated>
            <content:encoded><![CDATA[<h4>change functions without replacing arguments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvmCR3y8bZ-fotMnDvqXvw.png" /><figcaption>Let argument names flow <a href="https://pixabay.com/photos/prairie-river-stream-curved-sunset-679014/">https://pixabay.com/photos/prairie-river-stream-curved-sunset-679014/</a></figcaption></figure><p>PySpark User-Defined Functions (UDFs) allow you to take a python function and apply it to the rows of your PySpark DataFrames. When the functions you use change a lot, it can be annoying to have to update both the functions and where you use them. This post will explain how to have arguments automatically pulled given the function. The method also works for functions that take Pandas Series as inputs (see the end of the post).</p><p><strong>Setup</strong></p><p>Let’s start with some setup: importing things we’ll use along the way and creating a toy data set. Let’s say our data contains information about prices, quantities sold, shipping costs collected from customers, and a list of other costs. We’ll make some simple UDFs to calculate revenue and profit from these numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5488f0b9697a57e710bfeb043dc04b1/href">https://medium.com/media/a5488f0b9697a57e710bfeb043dc04b1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*_z1Q1lW-WoLpnnROL0tqSA.png" /></figure><p><strong>Revenue UDF</strong></p><p>Let’s say we want to create a simple UDF that uses the price and revenuecolumns to create a new revenue_wo_shipcolumn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e952499bcfd9f2a67df0b2d6a50a6dff/href">https://medium.com/media/e952499bcfd9f2a67df0b2d6a50a6dff/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*Ik4jax6FZamcktKalkWdfg.png" /></figure><p><strong>Changed Revenue UDF</strong></p><p>There are many situations where the demands of the moment might change. For example, let’s say that we change our definition of revenue to not only include the price of the item, but the shipping fees we have collected from customers as well. This requires two changes</p><ol><li>Adjust the function to add shipping costs into the revenue calculation</li><li>Adjust the withColumn call to change the arguments</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e7950bf0a0daf1fa2153dec7e3f0d51/href">https://medium.com/media/2e7950bf0a0daf1fa2153dec7e3f0d51/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*48OBLgWkAtFfLjm5LZ55VA.png" /></figure><p><strong>Removing the Second Step with </strong><strong>inspect</strong></p><p>In this case, where the extra information was already in our data frame, it is annoying to have to make both of these code changes. We should be able to just change the function and have the arguments be pulled automatically by name.</p><p>To do this, I took the following strategy:</p><ol><li>Start with a function. As its definition changes, we should be able to automatically change which arguments to pull.</li><li>Loop over the functions arguments.</li></ol><p>A. If the argument is a key in a passed in dictionary, use the value of that key. Otherwise,</p><p>B. If any of the columns in the spark data frame have a name that matches the argument name, use them as the argument. Otherwise,</p><p>C. If the argument has a default specified by the function, use it. Otherwise,</p><p>D. Throw an exception because we don’t know what value to use for the argument.</p><p>The strategy is implemented by looping over the argument names of a function. That’s where inspect comes in: it allows us to get the argument names and default values of a function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c078271eaf34fce5891eb14469cbf4a2/href">https://medium.com/media/c078271eaf34fce5891eb14469cbf4a2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*cB6lw9bTLBxEEdDd5BgQSQ.png" /></figure><p><strong>Putting it together: the function</strong></p><p>Now we can put it all together into a function to handle this strategy for us. Comments are included to guide you throughout the code.</p><p>We start with a helper function that inputs constant values as arguments into the UDF to handle 2A and 2C from the strategy described above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/687e499b7f6fd9262d84ccd6184fb7b0/href">https://medium.com/media/687e499b7f6fd9262d84ccd6184fb7b0/href</a></iframe><p>Then, the real magic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f0ffc294bffd69772cc1b165d6e504c/href">https://medium.com/media/3f0ffc294bffd69772cc1b165d6e504c/href</a></iframe><p><strong>Seeing it in action</strong></p><p>Now we can make simple calls to this function without changing how we input things into the UDF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*HBTGiDVk3V3l9J6AfIq7tQ.png" /></figure><p>It also works with list inputs. For example, if we wanted to define profit as the difference between the product of price and quantity and the sum of the costs column:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1f473f381907f910fd1b819f1322faa/href">https://medium.com/media/a1f473f381907f910fd1b819f1322faa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*4QBE8YRbnt2hS2RselxUuA.png" /></figure><p>There you have it. Magic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3_IiNWeoSgk9nsWa" /><figcaption>Photo by <a href="https://unsplash.com/@almosbech?utm_source=medium&amp;utm_medium=referral">Almos Bechtold</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Extension: Pandas</strong></p><p>Note that this method would work equally well for Pandas:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c78963dc175256d3d7ca7012b4fbcde/href">https://medium.com/media/9c78963dc175256d3d7ca7012b4fbcde/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*wAAXixR2UG7ig6X4sjrcqg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f85f6b893f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/magically-pull-arguments-for-pyspark-udfs-and-pandas-functions-8f85f6b893f2">Magically Pull Arguments for PySpark UDFs and Pandas Functions</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[D&D: When to Choose a Worse Roll Type for a Larger Modifier]]></title>
            <link>https://medium.com/data-science/d-d-when-to-choose-a-worse-roll-type-for-a-larger-modifier-b5a4eb37409d?source=rss-534d9d75f626------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5a4eb37409d</guid>
            <category><![CDATA[critical-role]]></category>
            <category><![CDATA[dungeons-and-dragons]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Dan VanLunen (DVL)]]></dc:creator>
            <pubDate>Mon, 20 Jan 2020 05:01:40 GMT</pubDate>
            <atom:updated>2020-01-20T05:01:40.566Z</atom:updated>
            <content:encoded><![CDATA[<h4>An algorithm using R and probability</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*d8e9PVAHm5gV5ReZ094g5w.jpeg" /></figure><p>While listening to Matt Mercer DM Dungeons and Dragons on <a href="https://critrole.com/">Critical Role</a>, I sometimes hear him offer a choice to the players:</p><ol><li>Use a natural roll (one d20 and take the value) + modifier, or</li><li>Use a disadvantage roll (two d20 and take the lower value) + different modifier.</li></ol><p>For example, if you are a monk trying to scale large pile of rocks, you may roll a straight athletics check (choice 1.) to pull yourself up. The DM may also offer that you could roll an acrobatics check (and you have a higher acrobatics modifier because you have a high Dex) with disadvantage hopping along the rocks (choice 2.). The value you need total to succeed on the check is the same for either roll: e.g., 15 (this value is called the DC).</p><p>How should you choose? Well, the choice <em>should </em>reflect your character and what they <em>would</em> do.</p><p>However, if you want to maximize the chance that you will succeed on the check, then use the following algorithm. Note you could also imagine that you could get the choice between i) advantage (two d20 and take the higher value) and a natural roll or ii) advantage and a disadvantage roll, so the algorithm takes that into account as well.</p><ol><li><strong>Estimate the DC of the check.</strong> As a player, you won’t know the DC, but you can guess opening rotting wooden box on a sunken boat might be easier to open than an adamantine chest in the king’s armory. General guidance is that Easy tasks have a DC around 10 (even those unskilled have a good chance of succeeding), Medium around 15 (those who are skilled have a good chance of succeeding), Hard around 20 (those who are skilled still need some luck to succeed), and Very Hard around 25 (those who are skilled still need a lot of luck to succeed).</li><li><strong>Get the adjusted DC</strong>:<strong> </strong>Subtract the lower modifier value (of the choice with the better type of roll) from the DC of the check. Following the monk example, if you have a +6 to acrobatics and a +3 to athletics, subtract the lower modifier (+3) from the estimated DC 15 to get an adjusted DC of 12.</li><li><strong>Get the difference in modifier values between roll types</strong>: For our monk that&#39;s (+6)-(+3) = 3.</li><li><strong>Look up the best choice in the chart below</strong>: to find where to look, first go to the panel that describes what decision you are making. For example, the monk is deciding between a natural roll and disadvantage, that’s the third panel. Second, find the adjusted DC you calculated in the previous step on the x axis (12). Third, find the difference in the modifier values on the y axis (3). Find the color where they meet (red dot for our monk example) and look it up on the legend on the right to determine the best choice. Here it is blue, which indicates the natural athletics check is more likely to succeed than the acrobatics check with disadvantage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*wq82vU-ul4lHk7kkaNIZPA.jpeg" /></figure><p>A good rule of thumb is that you should be willing to step down one (advantage to natural or natural to disadvantage) or two (advantage to disadvantage) levels if the task is very hard because there is no chance you’ll succeed without that additional modifier bonus. You should also be willing to step down one level if the difference in modifiers is 5 or greater.</p><p>If you are wondering: “What is this foul magic: how was this chart created?”, read on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*t2wITiBsTxuIL24Oz33DCg.jpeg" /><figcaption>R + probability = wizard magic.</figcaption></figure><p>Let’s start with the basics. When you roll a d20, there is an equal 5% chance of any number 1 to 20 being rolled: rolling a d20 is drawing from the discrete uniform distribution between 1 and 20. This distribution is shown in the plot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*fSn7ikh3uUliXT2sWo5KwA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*RaKXvji7Em9l-YK6pttcTA.png" /></figure><p>However, what we really care about is the chance we will succeed: the total chance greater than or equal to the DC (e.g. the total area of the bars to the right of the vertical red line representing a DC of 15). Mathematically, what we really care about is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*NEOe2FUaVr4vCvr-8VTgQw.jpeg" /><figcaption>if the right hand side is &lt; 0, it should just be 0, if greater than 100%, it should be 100%</figcaption></figure><p>This is a simple formula for one roll. For two rolls, we can take advantage of the fact that the rolls are independent (so the probability of something happening on both rolls is the square of it happening on one roll) and plug in the simple formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*Ai67cLSFu2T-ulV_5U6IEA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*bGYwxDxdinZ_vjrJgO0dAg.jpeg" /></figure><p>Now, we can use these formulas in code to determine which type of roll should be chosen for each modifier difference and adjusted DC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*dY44GNcy8ZOoLtdcAtMNRQ.jpeg" /></figure><p>The dataset created by the above looks like the below. The first two columns show the x and y axis for the magical chart (adjusted DC and modifier difference). The next 4 columns shown below are the probability of passing the check with a certain type of roll. The last 3 columns shown below tell you which type of roll to choose to maximize the probability of success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_8NGBXOkK5l7Fe6YODAaw.jpeg" /></figure><p>We can then pivot this data to make it easier to plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*Q6IWu1fPfWpCN27ijys6sg.jpeg" /></figure><p>Finally, we can send the data into the chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*-huzComIQ7PbAkGvgJijCw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*wgioOfe96vLnsv_z25bAgA.jpeg" /><figcaption>Magic!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5a4eb37409d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/d-d-when-to-choose-a-worse-roll-type-for-a-larger-modifier-b5a4eb37409d">D&amp;D: When to Choose a Worse Roll Type for a Larger Modifier</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A How-to for Non-Parametric Power Analyses, p-values, Confidence Intervals, Checking for Bias]]></title>
            <link>https://medium.com/data-science/practical-experiment-fundamentals-all-data-scientists-should-know-f11c77fea1b2?source=rss-534d9d75f626------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11c77fea1b2</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[experimentation]]></category>
            <dc:creator><![CDATA[Dan VanLunen (DVL)]]></dc:creator>
            <pubDate>Sat, 07 Sep 2019 20:56:42 GMT</pubDate>
            <atom:updated>2021-01-13T00:08:02.721Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>A How-to for Non-Parametric Power Analyses, p-values, Confidence Intervals, and Checking for Bias</h3><h4>Practical Experiment Fundamentals All Data Scientists Should Know</h4><h4>Code Setup</h4><p><a href="https://r4ds.had.co.nz/">R for Data Science</a> is a free, amazing read to learn how to use the tidyverse code used in this post.</p><pre># purrr in parallel<br>library(furrr)<br># Read R for Data Science if you haven&#39;t<br># to learn about the tidyverse<br>library(tidyverse)<br># process in parallel<br>plan(multiprocess)</pre><h3>Why what this post will teach you is important</h3><p>Randomized experiments are the gold standard for causal inference: if you want to get an <strong>unbiased</strong> (the average value of your estimation method is the true value) estimate of an effect of a treatment, a randomized experiment is the best way to do so.</p><p>But experiments are expensive. So if we are going to make the investment to do one, we need to know we’ll be able to collect enough data in the experiment to have a high chance of measuring an effect if it exists. A <strong>power analysis</strong> will tell us how much data we need.</p><p>We also want to know that the effect we measure isn’t just the result of chance. We declare our effect <strong>statistically significant</strong> only if the chance that we would measure an effect as extreme as the one we measure in our experiment if the treatment has no effect (the <strong>p-value</strong>) is sufficiently low.</p><p>Additionally, we would like to be able to give some sense of how precisely the effect is measured by providing a <strong>confidence interval</strong> — a range of values of the effect, which if calculated the same way for many experiments repeated the same way, would include the true effect a large percent of the time (e.g. 95%).</p><p>Finally, we’d like to know if our experimental design is flawed such that we don’t have a way to measure an effect in an unbiased way.</p><p>This post will enable you to do a power analysis, calculate p-values, get confidence intervals, and check for bias in your design without making any assumptions (<strong>non-parametrically</strong>).</p><h3>Example Experiment</h3><p>Let’s say I’m a dog football marketer. In previous advertisements, I’ve used the picture on the left below to showcase how fun dog footballs are. I hypothesize that if I add a funny note like “Teddy Approved”, a larger portion of people (p) who see the ad will purchase a football (p is called the “conversion rate”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5Ks6B9L2tqA_eAMtSZ3wA.png" /></figure><p>To test my hypothesis, every time a person is about to see one of my ads, I’ll randomly show them one of the two images: a <strong>control</strong> image (with no label) or a <strong>treatment</strong> image with “Teddy Approved”. Then, I’ll compare the conversion rates within the groups (p_{control} vs. p_{teddy_approved}) to see if the label improves conversion (conversion = # customers ordered football / # customers saw the ad).</p><h3>Hypotheses</h3><p>The <strong>null hypothesis</strong> is the assumption that there is no effect: that adding “Teddy Approved” to the ad will not increase conversion:</p><p>H_0: p_{teddy_approved} — p_{control} = 0</p><p>We test this against our <strong>alternative hypothesis</strong> that the label increases conversion.</p><p>H_a: p_{teddy_approved} - p_{control} &gt; 0</p><p>We do this by calculating the chance that we would see our experimental <strong>test statistic</strong> (the difference in conversion rates among customers that saw the label and those that didn’t \hat{p}_<em>{teddy_approved} - \hat{p}_</em>{control} ) given the null hypothesis is true (i.e., a <strong>p-value</strong>). If that chance is low enough (e.g., &lt;5%), we reject H_0 and can say that the label significantly (in the statistical sense) increases conversion. In our power analysis, we’ll determine how large the true difference p_{teddy_approved} — p_{control} will need to be or how much data we will need to collect to have a high chance (e.g. &gt;80%) of observing a test statistic with a significant p-value (i.e., a high <strong>power</strong>).</p><p>The key here is we need to be able to calculate the probability of seeing different values of our test statistic under the null hypothesis: we need to have a sense of what the distribution of the difference in our sample conversion rates \hat{p}_<em>{teddy_approved} - \hat{p}_</em>{control} looks like given the true difference in conversion rate is 0: p_{teddy_approved} - p_{control} = 0.</p><p>We could use some parametric assumptions. For example, we could assume normality and perform a t-test. However, in many settings, data is highly skewed and this assumption won’t hold. It would be better if we could simulate the difference in conversion rates non-parametrically (without any assumptions), and trace out this distribution ourselves. To do that, we’ll need some data.</p><h3>Historical Data</h3><p>Let’s assume we have historical information where the label was not applied: we have a data set of customers that have seen the control group image and whether or not they purchased a football. If the null hypothesis is true, the data generating process for this historical data’s conversion rates should be similar to the process during the experiment because adding the label has no impact on conversion.* That is, we could consider this historical data set to be similar to a realization of a hypothetical data set collected during the experiment under the null hypothesis.</p><p>*note we are assuming time isn’t impacting the variability in the conversion rate. If we aren’t interested in using the simulation to do a power analysis (e.g., we just want to calculate confidence intervals/p-values or confirm our design isn’t biased), we can apply randomization inference on the true experimental data to remove this assumption.</p><p>Let’s create a toy historical data set assuming conversion is independent between customers and that the true probability of purchase after seeing the control ad, p_{control} is 0.01.</p><pre># function to make historical data<br>make_historical_data &lt;- function(<br>  # one row per customer<br>  number_of_customers = 1000,<br>  # each customer&#39;s chance of ordering<br>  null_conversion_rate = .01,<br>  # to make results replicable<br>  seed = 22) <br>  <br>  {<br>  set.seed(seed)<br>  return(tibble(<br>    # each customer that saw an ad 1,2,3,...<br>    customer_id = 1:number_of_customers,<br>    # whether the customer bought a football or not<br>    # bernoulli draw with specified prob<br>    customer_purchased = rbinom(number_of_customers, 1, null_conversion_rate) #<br>  ))<br>}<br># make the data<br>historical_data &lt;- make_historical_data()<br># take a look<br># 1 row per customer<br># some purchases<br>historical_data %&gt;% head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*te7bWgdYzMc3DUudPWLZRA.png" /></figure><h3>Simulating Under the Null</h3><p>With our historical data set, there are 2 key ways to simulate example differences in observed conversion rates between groups \hat{p}<em>{teddy_approved} — \hat{p}</em>{control} under the null hypothesis:</p><ol><li><strong>Randomization Inference</strong> — explore how much variability comes from random assignment to control and treatment groups</li><li><strong>Bootstrapping</strong> — explore how much variability comes from the data generating process</li></ol><p>We’ll focus on randomization inference, but bootstrapping is also described at the end of this post.</p><h3>Randomization Inference</h3><p>Randomization Inference is my preferred method for identifying variability in your data. I first came across it in Field Experiments by Gerber and Green. This book is a rigorous, concise, and well-written introduction to notation for causal inference and experimental methods. I highly recommend it.</p><p>The idea behind randomization inference is that uncertainty arises naturally from the random assignment to treatment groups. It’s kind of like answering the question: what would the effect size have been if we just assigned our treatment groups differently?</p><p>The procedure to simulate your effect is as follows</p><ol><li>Have a data set that has the same number of experimental units as you will have in your experiment. You could use historical data to do a power analysis or the actual data from the outcome fo your experiment to get p-values and confidence intervals.</li><li>Randomly assign a hypothetical treatment within your data set. The treatment assignment methodology should follow the same assignment methodology you would use / used in your experiment (e.g. if you assigned clusters to treatment, do that here as well).</li><li>Calculate the test statistic using the hypothetical treatment assignment</li><li>Repeat the above steps many times</li><li>The distribution of the calculated test statistics from the various hypothetical random assignments can be considered the distribution of the test statistic under the null distribution.</li></ol><p>We can make this a function:</p><pre># run one simulation with<br>#   an assignment function<br>#   and an effect size calculating function<br>randomly_assign_and_find_effect_size &lt;- function(<br>  # data to use for randomization inference<br>  # historical for power analyses<br>  # experiment outcomes for p values and confidence intervals<br>  dataset,<br>  # function that adds a random treatment assignment to the dataset<br>  random_assignment_function,<br>  # function that calculates the effect size using the assignment<br>  effect_size_function,<br>  # dummy var to allow us to use furrr::future_map_dbl<br>  dummy<br>  ){<br>  return(<br>    # with your dataset<br>    dataset %&gt;% <br>      # assign hypothetical treatment randomly<br>      #   how you would in the experiment<br>      random_assignment_function() %&gt;%<br>      # estimate the effect given the hypothetical treatment<br>      effect_size_function()<br>  )<br>}</pre><pre># run the above function many times<br>randomization_inference &lt;- function(<br>  dataset,<br>  # number of simulations to run<br>  number_of_simulations,<br>  # function that adds a random treatment assignment to the dataset<br>  random_assignment_function,<br>  # function that calculates the effect size using the assignment<br>  effect_size_function,<br>  # allows us to make results reproducible<br>  seed = 42<br>){<br>  set.seed(seed)<br>  # purrr::map<br>  #   applies a function (here the assign and find effect function)<br>  #   to each element of the supplied vector 1:number_of_simulations<br>  # purrr::map_dbl<br>  #   is like map but returns a vector of doubles instead of a list<br>  # furrr::future_map_dbl<br>  #   is like map_dbl, but uses parallel computing to speed things up<br>  future_map_dbl(<br>    # for each simulation<br>    1:number_of_simulations,<br>    # randomly assign and find effect size<br>    randomly_assign_and_find_effect_size,<br>    # using the provided data set<br>    dataset = dataset,<br>    # and provided assignment function<br>    random_assignment_function = random_assignment_function,<br>    # and provided effect size generating function<br>    effect_size_function = effect_size_function<br>    )<br>}</pre><h4>Example</h4><p>In our example experiment, every customer who sees an ad will randomly see the picture without the label or the picture with the label with 50% probability. We can make an assignment function that follows this methodology:</p><pre>add_hypothetical_random_assignment &lt;- function(dataset){<br>  return(<br>  dataset %&gt;% dplyr::mutate(<br>    # randomly assign each customer to treatment or control<br>    # in_treatment is a new column with 1 if treated and 0 otherwise<br>    in_treatment=rbinom(n = nrow(dataset),<br>                        size = 1,<br>                        prob = 0.5 # treatment with 50% prob<br>                        )<br>    )<br>  )<br>}</pre><p>The effect we are measuring is the difference in conversion. So let’s make a function that gets the effect size: it calculates the mean conversion in the treatment and control groups and takes the difference.</p><pre>calculate_difference_in_conversion &lt;- function(dataset){<br>  return(<br>  dataset %&gt;% <br>    # get conversion for control and treatment<br>    dplyr::group_by(in_treatment) %&gt;% <br>    dplyr::summarise(conversion=mean(customer_purchased)) %&gt;%<br>    # get difference in conversion rates<br>    tidyr::spread(in_treatment,conversion) %&gt;% <br>    dplyr::mutate(difference_in_conversion = `1` - `0`) %&gt;% <br>    dplyr::pull(difference_in_conversion)<br>  )<br>}</pre><p>Now, let’s use randomization inference to visualize the distribution of our test statistic (the difference in conversion rate) under the null. The lines at the bottom of the chart show the effect size from each randomization. The height of the curve represents how many simulated effect sizes were found in that area of the x-axis.</p><pre>simulated_effect_sizes_ri &lt;- randomization_inference(<br>    dataset = historical_data,<br>    number_of_simulations = 10000,<br>    # use the assignment function we just defined<br>    random_assignment_function = add_hypothetical_random_assignment,<br>    # use the effect size function we just defined<br>    effect_size_function = calculate_difference_in_conversion<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*_m2gsKevr3jBHsZPY7y7Ig.png" /></figure><h3>Power Analysis</h3><p>Now that we know how to get simulated effect sizes, we are ready to perform a power analysis. The idea behind a power analysis is that we want to know how much data we need to have a high chance of getting a statistically significant result. We want to do this before the experiment begins so we don’t waste time and money running an experiment that can’t measure anything.</p><p>Let’s say we’ll declare the change in conversion significant if there is a 5% or less chance of seeing that change in conversion or greater under the null hypothesis. We traced out the effect size distribution under the null in the previous section, so it’s easy to find this critical value point (it’s just the 95th percentile of our simulated effect sizes).</p><pre>critical_point_ri_1000 &lt;- simulated_effect_sizes_ri %&gt;%<br>  # get 95th percentile<br>  quantile(.95)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*u7jx67QXiQdekoATspUV3A.png" /></figure><p>Let’s say we want to have at least an 80% chance of getting a significant result. The trick here is to assume that the true effect size is constant, such that we can just shift the distribution of effect sizes under the null by the true effect size. We shift the distribution until 80% of the area under it is beyond the critical region. The amount we need to shift is called the <strong>minimum measurable effect</strong> (“MME”) because it is the smallest true difference in conversion that we would be able to get a statistically significant result with at least 80% probability. This minimum measurable effect can be calculated by taking the difference between the critical value and the 20th percentile of the distribution of effect sizes simulated under the null.</p><pre>(minimum_measurable_effect_ri_1000 &lt;- critical_point_ri_1000 -<br>  simulated_effect_sizes_ri %&gt;% # 95th percentile<br>  quantile(.2) # 20th percentile<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*FswOjwqIaeC_Ors0IsFvug.png" /></figure><p>A minimum measurable difference in the conversion rate of 0.019 does not seem plausible given our conversion rate started at 0.01. However, all of this was assuming we would collect 1000 customers during the course of our experiment (just like we had in the historical data). We can get more power if we increase our sample size though. Let&#39;s see how the minimum measurable effect changes if we create a historical dataset that is 100x as large.</p><pre># 100x larger historical data<br>historical_data_100x &lt;-<br>  make_historical_data(number_of_customers = 100000)</pre><pre># randomization inference to simulate the null<br>simulated_effect_sizes_ri_100x &lt;- randomization_inference(<br>  dataset = historical_data_100x,<br>  number_of_simulations = 10000,<br>  random_assignment_function = add_hypothetical_random_assignment,<br>  effect_size_function = calculate_difference_in_conversion<br>)<br># critical point<br>critical_point_ri_100000 &lt;- simulated_effect_sizes_ri_100x %&gt;%<br>  quantile(.95)<br># mme<br>minimum_measurable_effect_ri_100000 &lt;- critical_point_ri_100000 -<br>  simulated_effect_sizes_ri_100x %&gt;%<br>  quantile(.2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*_AXql_tgp4gIluAxPiHRVA.png" /></figure><p>With a lot more data the minimum measurable effect is reduced to 0.0016, which is still big, but at least a possible effect size to measure.</p><p>The increased precision is more noticeable if we plot the two simulated distributions together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*SROEE6ao8yxEG37RscYxgg.png" /></figure><h3>p-values with Experiment Data</h3><p>p-values are easy to calculate using the simulated effect sizes. We want to know under the null, what is the chance we would have seen an effect size at least as extreme as the effect size we measured. We can find this by just finding what percentile the measured effect size is in our distribution of simulated effect sizes under the null. We could continue to use the effect sizes we simulated using the historical data, but we can apply randomization inference to the actual experimental data to get a better sense of the distribution of effect sizes under the null during the actual experiment.</p><p>Let’s assume the true effect size is 0.0005: that the label will increase conversion by 0.0005. Then, we’ll make a dataset that represents the result of our experiment.</p><pre>true_effect_size &lt;- 0.0005<br>experiment_data &lt;- make_historical_data(100000, seed = 2) %&gt;%<br>  add_hypothetical_random_assignment() %&gt;%<br>  # average conversion is<br>  # base conversion = 0.01<br>  #   + true_effect_size if in treatment<br>  mutate(customer_purchased = rbinom(100000, 1, prob = .01 + in_treatment * true_effect_size))</pre><pre># difference in conversion rates in the experimental data<br>(<br>  experiment_measured_effect &lt;-<br>    calculate_difference_in_conversion(experiment_data)<br>)<br>[1] 0.001496594</pre><p>We found a 0.0015 difference in conversion in our experiment. Now to get the p-value of our effect size, we&#39;ll</p><ol><li>apply randomization inference to trace out the distribution of the effect size under the null using the experimental data</li><li>find the percentile of that distribution that our measured effect size is</li><li>calculate 1 minus the percentile = the p-value</li></ol><pre># trace out the null<br>simulated_effect_sizes_ri_experiment &lt;- randomization_inference(<br>  dataset = experiment_data,<br>  number_of_simulations = 10000,<br>  random_assignment_function = add_hypothetical_random_assignment,<br>  effect_size_function = calculate_difference_in_conversion<br>)<br># what percentile in the simulated effects distribution<br>#   is the experiment measured effect<br># ecdf is the &quot;empirical cumulative distribution function&quot;<br># we are finding where in this function the experiment measured effect lies<br>percentile &lt;-<br>  ecdf(simulated_effect_sizes_ri_experiment)(experiment_measured_effect)<br>(p_value &lt;- 1 - percentile)<br>[1] 0.0105</pre><p>The p-value is 0.01. We have found that the label significantly increases conversion at the 95% level. The p-value is the area under the distribution to the right of the measured effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*ahaQGOzz8g5J39cUp0R_PQ.png" /></figure><h3>Confidence Intervals</h3><p>Confidence intervals with a simulated distribution of effect sizes under the null are easy so long as your experimental design is unbiased (see next section). Just shift the distribution so that it is centered at the experimentally measured effect size. Then, the bounds of a 95% confidence interval are the 2.5th and 97.5th percentiles of that shifted distribution.</p><pre># shift the distribution of simulated effect sizes<br>#   by the measured effect size<br>simulated_effect_sizes_ri_experiment_plus_measured_effect &lt;-<br>  simulated_effect_sizes_ri_experiment +<br>  experiment_measured_effect</pre><pre>(<br>  confidence_interval_ri_experiment &lt;-<br>    quantile(<br>      simulated_effect_sizes_ri_experiment_plus_measured_effect,<br>      c(.025, .975) # 2.5th and 97.5th percentile<br>    )<br>)<br>2.5%        97.5% <br>0.0002208507 0.0027817045</pre><p>This confidence interval contains the true effect: 0.0005.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*gzLgUgXkfarC9cSVYuOHNA.png" /></figure><h3>Check for Bias (important!)</h3><p>In our example, we have used a very clean experimental design: we compared apples to apples groups (because customers were randomly assigned to them) in the same period and calculated a difference in means. In this situation, the measured difference in conversion will be an <strong>unbiased</strong> estimate of the true difference in conversion caused by the added label: though the treatment effect we measure is random, on average, it will be the true treatment effect:</p><p>E[\hat{p}<em>{teddy_approved} — \hat{p}</em>{control}] = p_{teddy_approved} — p_{control}</p><p>We can do a gut check that this is true by confirming that the average of our simulations under the null of the effect size is near 0: under the null p_{teddy_approved} — p_{control}=0, so \hat{E}[\hat{p}<em>{teddy_approved} — \hat{p}</em>{control}] =\frac{1}{n}\sum_{i=1}^{n}\hat{p}<em>{teddy_approved} — \hat{p}</em>{control}\approx 0 if we have an unbiased design.</p><pre>mean(simulated_effect_sizes_ri_100x)<br>[1] 7.434415e-07</pre><p>We pass this gut check given the mean is so close to 0. Even though this doesn’t confirm the design is unbiased, it gives us more confidence that it is.</p><p>However, many experiments do not have such a clean design and the measured effect size can be prone to bias. In such a case, you should do all you can to correct the design so that it is unbiased. However, there may be a situation where you run an experiment and cannot correct the bias post-experiment. In such a case, you may still be able to use the same p-value methodology so long as the bias is applied uniformly: randomization inference still indicates the actual assignments measured effect size is in the top 95% of measured effect sizes under other hypothetical assignments even if all the measured effects are biased. However, you’ll need to adjust your reported effect size and thus confidence interval. One quick and dirty way to do so is to just report the measured effect size minus the average of the simulated effect sizes under the null distribution. Then, make a confidence interval the same way as above, but centered at that adjusted effect size instead.</p><h4>Example</h4><p>Let’s do an example. Let’s say that we can only show 1 type of ad to every customer in a geography (e.g., a certain metro-area). Now we can’t randomly assign treatment by customer. We could randomly assign half of the geographies to the treatment (label added) condition and the other half to the control (no label) condition. Then, take the difference in conversion between the groups, which would bring us back to the clean design above. However, this could have less precision given the high level clustered treatment.</p><p>To add more precision, someone proposes a design where we look at geographies in a pre-period as well to get more “control” data. Then, we will take the difference between the average conversion across geographies in treatment in the experimental period and the average conversion across geographies in the pre-period and those randomly assigned to control in the experimental period. To simplify things, let’s assume all geography-periods have the same number of customers (so we can take averages easily).</p><pre>add_hypothetical_random_assignment_geo &lt;- function(<br>  dataset<br>){<br>  # get the distinct geos<br>  randomized_geos &lt;- dataset %&gt;%<br>    dplyr::select(geo) %&gt;% <br>    dplyr::distinct() %&gt;% <br>    dplyr::pull(geo) %&gt;% <br>    # and randomize their order<br>    sample()<br>  <br>  # first half assigned to treatment<br>  treated_geos &lt;- randomized_geos[1:length(randomized_geos) %/% 2]<br>  <br>  # add treatment assignment as a column to the data<br>  return(<br>    dataset %&gt;% <br>      dplyr::mutate(<br>        in_treatment = dplyr::case_when(<br>          # treatment col is 1 only if in treated geo<br>          (geo %in% treated_geos) &amp; <br>            # and only during the second period<br>            #   (first period is all control)<br>            (period==2) ~ 1,<br>          T ~ 0<br>        )<br>      )<br>  )<br>}</pre><pre>get_effect_on_conversion_geos_biased &lt;- function(<br>  dataset<br>){<br>  return(<br>    # get mean of outcome for treatment and control period-groups<br>    dataset %&gt;% <br>      dplyr::group_by(in_treatment) %&gt;% <br>      dplyr::summarise(conversion_rate=mean(observed_conversion_rate)) %&gt;% <br>      # get differnce between treatment and control period-groups<br>      tidyr::spread(key=in_treatment,value=conversion_rate) %&gt;% <br>      dplyr::mutate(diff_in_conversion=`1` - `0`) %&gt;% <br>      dplyr::pull(diff_in_conversion)<br>  )<br>}</pre><p>This design is flawed because differences between the experimental period and the pre-period will accidentally be attributed to the treatment. For example, let’s assume the conversion rate is naturally going to double from the pre-period to the experimental period without applying treatment and see what happens.</p><p>We’ll have a data set with two rows per geography (one row per period). Let’s say the true effect size is 0.002.</p><pre>set.seed(42)<br>true_effect_size &lt;- .002</pre><pre>geo_design_experiment_data &lt;-<br>  tibble(<br>    # 2 periods<br>    period = rep(1:2, each = 26),<br>    # 26 geos a, b, c, ...<br>    geo = rep(letters, 2)<br>    ) %&gt;%<br>  # add treatment indicator (1 for half of classes in period 2 else 0)<br>  add_hypothetical_random_assignment_geo() %&gt;%<br>  # add conversion rates<br>  mutate(<br>    true_control_conversion_rate = case_when(<br>      # random between .02 and .05 in first period<br>      period == 1 ~ rep(seq(0.02, 0.05, length.out = 26), 2),<br>      # doubled in second period naturally without treatment<br>      T ~ rep(seq(0.02, 0.05, length.out = 26), 2) * 2<br>    ),<br>    # add some noise to the true rate for the measured rate<br>    observed_conversion_rate = true_control_conversion_rate +<br>      rnorm(52, sd = .001),<br>    # add the true effect size to the measured rate<br>    # for treatment groups (treatment will == 1 for half of geos in period 2)<br>    observed_conversion_rate = case_when(<br>      in_treatment == 1 ~ observed_conversion_rate + true_effect_size,<br>      T ~ observed_conversion_rate<br>    )<br>  )<br># look at the first 6 rows for each period<br># to see how preiod-geo data looks<br>geo_design_experiment_data %&gt;% <br>  group_by(period) %&gt;% <br>  slice(1:6)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*-Z3iW1S2U1R3plW_6chDXA.png" /></figure><p>Then, we observe an experimental result like the following.</p><pre>(<br>  measured_effect_size_geos_biased &lt;- geo_design_experiment_data %&gt;%<br>    get_effect_on_conversion_geos_biased()<br>)<br>[1] 0.02418268</pre><p>We get a measured difference in conversion that is more than 10x the true effect!</p><p>Now we can perform randomization inference to simulate the effect size under the null.</p><pre>simulated_effect_sizes_ri_geos_biased &lt;- randomization_inference(<br>  dataset = geo_design_experiment_data,<br>  number_of_simulations = 10000,<br>  random_assignment_function = add_hypothetical_random_assignment_geo,<br>  effect_size_function = get_effect_on_conversion_geos_biased<br>)</pre><p>The average under the null should be zero if we have an unbiased design. Let’s do our gut check of getting the average of our simulated values.</p><pre>(estimated_bias &lt;- mean(simulated_effect_sizes_ri_geos_biased))<br>[1] 0.02392901</pre><p>We failed the gut check because the mean is not close to 0. In this situation, we would want to see if there were a better, unbiased way to measure the effect (e.g., add period fixed effects or do a difference-in-differences design), but if we couldn’t find a better design we would at least want to adjust the effects we report.</p><p>For example, instead of reporting 0.024183 as the effect size, we could subtract out the estimated bias (0.023929: the average of simulated effects under the null) and report 0.024183 - 0.023929 = 0.000254 as the effect size. Note that this doesn&#39;t necessarily make your adjusted estimate unbiased, but it is a more honest result to report than the one you know to be biased.</p><p>We would also want to adjust our confidence interval by centering our simulated distribution of effect sizes under the null at this adjusted effect size (instead of the measured effect size) and getting the 2.5% and 97.5% percentiles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*w3Vq_aiXA6J7XL_97rt4-w.png" /></figure><h3>Summary</h3><p>In this post we’ve gone over non-parametric ways to</p><ul><li>simulate the effect size under the null distribution: hypothetically randomly reassign treatment and calculate the effect size with the hypothetical assignment many times.</li><li>do power analyses: the minimum measurable effect is the 95th percentile minus the 20th percentile of the simulated effect sizes under the null.</li><li>calculate p-values: find what proportion of simulated effect sizes under the null are more extreme than the measured effect size in the experimental data.</li><li>get confidence intervals: center the distribution of effect sizes under the null at the measured effect size and get the 2.5th and 97.5th percentiles for confidence bounds.</li><li>check and adjust for bias: mean of the simulated effect sizes under the null should be 0. If it isn’t, adjust the measured effect size by the mean of the simulated effect sizes under the null (and use the adjusted effect size for centering confidence intervals).</li></ul><p>Learn more in my other posts:</p><ul><li><a href="https://towardsdatascience.com/an-experiment-assignment-method-all-data-scientists-should-know-e4d57d96b26b?source=friends_link&amp;sk=e4580b55c82b514cadf41e07cf8eccbc">An Experiment Assignment Method All Data Scientists Should Know</a></li><li><a href="https://towardsdatascience.com/get-a-grip-when-to-add-covariates-in-a-linear-regression-f6a5a47930e5?source=email-534d9d75f626-1584307789520-layerCake.autoLayerCakeWriterNotification-------------------------5b264995_1b97_4e64_a82a_770b76c90329&amp;sk=fa2da69f55faa9641bdc8e19bb3ce4af">Get a Grip! When to Add Covariates to a Linear Regression</a></li></ul><p>If you want to know about bootstrapping, feel free to read on.</p><h3>Extra: What about bootstrapping?</h3><p>Bootstrapping is an additional way to simulate the distribution of the effect size.</p><p>Instead of using natural variation arising from the treatment assignment in your data, bootstrapping explores uncertainty over the specific sample of the population you draw. The idea is that the most natural distribution to assume your data follows is the one that was actually observed in your sample. So just sample from your data with replacement to create a simulation.</p><p>The procedure works as follows:</p><ol><li>You use historical data for a power analysis or to calculate a p-value for your experimentally measured effect. You use the actual data from the outcome of your experiment to build a confidence interval.</li><li>Randomly draw with replacement from your data set (at the highest cluster level if your assignment is clustered) until you create a data set the same size as in your experiment (a bootstrap). Drawing a lower level will artificially raise your precision.</li><li>Calculate the test statistic using the simulated data set</li><li>Repeat the above steps many times</li><li>The distribution of the calculated test statistics from the various hypothetical random samples with replacement can be considered the distribution of the test statistic under the null distribution when using historical data or under the true effect size when using the experimental data.</li><li>When using historical data, the minimum measurable effect for a power analysis is still the 95th minus the 20th percentile. The p-value is still 1 minus the percentile of the actual measured effect in the distribution of simulated effect sizes. The bounds of a confidence interval can be found using the 2.5th and 97.5th percentiles of the bootstrapped effect sizes when drawing with replacement from the true experimental results.</li></ol><pre>make_bootstrap_and_find_effect_size &lt;- function(<br>  dataset,<br>  cluster_variables_to_sample_with_replacement,<br>  num_clusters_to_sample,<br>  effect_size_function,<br>  dummy # so we can use map<br>  ){<br>  return(<br>    # with your dataset<br>    dataset %&gt;% <br>      # build a bootstrap<br>      # first get the distinct sets of cluster variables<br>      dplyr::select_at(cluster_variables_to_sample_with_replacement) %&gt;% <br>      dplyr::distinct() %&gt;% <br>      # sample these clusters with replacement until you reach<br>      # the specified size<br>      dplyr::sample_n(num_clusters_to_sample, replace=T) %&gt;%<br>      # attach back to the dataset to get the variables needed<br>      # to estimate the effect size<br>      dplyr::inner_join(dataset, by=cluster_variables_to_sample_with_replacement) %&gt;% <br>      # estimate the effect given the bootstrap<br>      effect_size_function()<br>  )<br>}</pre><pre>bootstrapping &lt;- function(<br>  dataset,<br>  number_of_simulations,<br>  cluster_variables_to_sample_with_replacement,<br>  num_clusters_to_sample,<br>  effect_size_function,<br>  seed=42<br>){<br>  set.seed(seed)<br>    future_map_dbl(<br>      # for each simulation<br>      1:number_of_simulations,<br>      # randomly assign and find effect size<br>      make_bootstrap_and_find_effect_size,<br>      # using the provided data set<br>      dataset = dataset,<br>      # and the specified clusters<br>      cluster_variables_to_sample_with_replacement = cluster_variables_to_sample_with_replacement,<br>      # with the specified number of samples with replacement<br>      num_clusters_to_sample=num_clusters_to_sample,<br>      # and provided effect size generating function<br>      effect_size_function = effect_size_function<br>  )<br>}</pre><h4>Example</h4><p>With bootstrapping, we need to have an initialized hypothetical treatment so when we sample with replacement, the treatment comes with it.</p><pre>set.seed(42)<br>historical_data_w_assignment &lt;- historical_data %&gt;% <br>  add_hypothetical_random_assignment()</pre><p>Then, we can apply the bootstrapping procedure (note that we aren’t clustering our data so we are just sampling using each unit).</p><pre>simulated_effect_sizes_bs &lt;- bootstrapping(<br>    dataset = historical_data_w_assignment,<br>    number_of_simulations = 10000,<br>    cluster_variables_to_sample_with_replacement = &quot;customer_id&quot;,<br>    # assume experiment data is the same size as input data<br>    num_clusters_to_sample = nrow(historical_data_w_assignment),<br>    effect_size_function = calculate_difference_in_conversion<br>  )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*jHkikgtb481ilRdrpvQYKw.png" /></figure><h4>Randomization Inference vs Bootstrapping</h4><p>Titans of causal inference Susan Athey and Guido Ambens <a href="https://arxiv.org/abs/1607.00698">“stress randomization-based inference as opposed to sampling-based inference.”</a> That link is a great one to read for more information. I prefer randomization inference to bootstrapping for a couple of reasons.</p><ul><li>It is easier to identify bias in your design using randomization inference. As shown in the article, we have a simple gut check on the experimental data to determine whether or not our design methodology is biased: check if the simulated effect sizes under the null using the experimental data has mean 0. It is much harder to do this check with bootstrapping because if you resample the experimental data, it should be centered at the measured effect size, not 0. You could use historical data and see if the bootstraps aren’t mean 0, but often some non-linear time difference in the experimental period causes the bias (which cannot be seen with historical data).</li><li>Randomization inference automatically accounts for correlation in clusters in your sample. A very common error in statistical analysis is to not account for clustered standard errors. If we assign treatment at the cluster level (like geography above) and then perform an analysis at the unit level (e.g., customer), the default standard errors that regressions or a t-test would spit out don’t account for correlation in the assignment of treatment and you can overestimate how much precision you actually have. But with randomization inference, as long as you assign treatment the same way as in your experiment in the simulations, it will automatically account for these clustered standard errors. This is a big reason why I recommend bootstrapping at the cluster level as well: resampling at the unit level for a cluster assigned treatment can produce an inconsistent estimate of the variance.</li><li>Randomization inference is usually faster. Bootstrapping requires a very computationally expensive random sampling with replacement for each simulation, whereas randomization inference just requires a reassignment of treatment. However, randomization inference can be slower if reassigning the treatment is expensive (e.g., if you expose half of products classes to treatment and then calculate each customer’s percent of products seen as their applied treatment, you’d have to calculate for each customer the percent of products seen with treatment for each new treatment assignment, which would be very expensive).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11c77fea1b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/practical-experiment-fundamentals-all-data-scientists-should-know-f11c77fea1b2">A How-to for Non-Parametric Power Analyses, p-values, Confidence Intervals, Checking for Bias</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>