<?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 Pablo Alcain on Medium]]></title>
        <description><![CDATA[Stories by Pablo Alcain on Medium]]></description>
        <link>https://medium.com/@pabloalcain?source=rss-822ce1efe96e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kKp2LQNKELRTiSKESHC2ew.jpeg</url>
            <title>Stories by Pablo Alcain on Medium</title>
            <link>https://medium.com/@pabloalcain?source=rss-822ce1efe96e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:03:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pabloalcain/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[You don’t like Bayesian Statistics, you like Modeling]]></title>
            <link>https://medium.com/@pabloalcain/you-dont-like-bayesian-statistics-you-like-modeling-436c7d2e3805?source=rss-822ce1efe96e------2</link>
            <guid isPermaLink="false">https://medium.com/p/436c7d2e3805</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Pablo Alcain]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 03:00:50 GMT</pubDate>
            <atom:updated>2026-08-31T12:31:01.385Z</atom:updated>
            <content:encoded><![CDATA[<p><em>To view a better formatted version of this post, go to </em><a href="https://blog.pabloalcain.ar/ds/you-like-modeling/"><em>https://blog.pabloalcain.ar/ds/you-like-modeling/</em></a></p><p>I’m not saying that you <em>dislike</em> Bayesian Statistics (disclaimer: I like it), I’m saying that many (not all) of the niceties that appear in Bayesian Statistics are actually in parametric statistics. To illustrate this, we will go through some well known results in the simple linear regression. You can model it in this classical fashion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*CWlhLMaN7T7_vENiHDtXjg.png" /></figure><p>We can estimate this paramaters by using the <a href="https://en.wikipedia.org/wiki/Ordinary_least_squares">Ordinary Least Squares estimator</a> (OLS), which minimises the quantity C = ∑(yᵢ − β̂xᵢ − α)², the sum of squares of the differences between yᵢ and the “inference” of β̂xᵢ − α. The result is well known:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*_N6afy0a6V6XDDhJ6fz8PQ.png" /></figure><p>It is relatively simple to prove the <a href="https://en.wikipedia.org/wiki/Gauss%E2%80%93Markov_theorem">Gauss-Markov theorem</a>, that says that under some conditions on the errors εᵢ (namely that they i. are uncorrelated, ii. have equal variance, and iii. have expectation value of zero) the Ordinary Least Squares estimator is the best linear unbiased estimator (BLUE).</p><h3>But can’t we model a bit more?</h3><p>A bit hidden in the first expression is the fact that <em>σ</em>²/<em>N</em> can be split in two parts: the first one depends on xᵢ ( βxᵢ + α) and the second one is completely random noise (εᵢ). So we can rewrite that expression to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*ngVugl8AeIWyLT5fbbCnsg.png" /></figure><p>And now it becomes a bit more clear that we were modeling the relationship between yᵢ and xᵢ through μᵢ, but not the errors themselves, \εᵢ. A simple way to model it that fulfills the conditions for Gauss-Markov is to say that they come from a zero-centered normal distribution: ε ∼ 𝒩(0, σ²). We can rearrange a bit the previous equations into</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*kG_Ho98WPo_rQP35M9rPZg.png" /></figure><p>We modeled explicitly the <em>sample generation process</em>: once you know everything there is to know about the relationship between the variables, how are samples actually generated? That’s the yᵢ ∼ 𝒩(μᵢ, σ²). From this point onwards you can very simply go down the Bayesian statistics path: pick a prior, sample with MCMC and calculate a posterior for β and α. My guess is that since this <em>sample generation process</em> is necessary to start the Bayesian machinery, modeling and Bayesian models start to get tightly coupled in practicioners views. Something (very crudely simplified) like frequentist -&gt; OLS, bayesian -&gt; modeling.</p><p>Let us use the frequentist machinery to estimate α andβ from this last set of equations. There are many possible frequentist estimators to do this, and one of the most extended ones due to its theoretical niceties is the <a href="https://en.wikipedia.org/wiki/Maximum_likelihood_estimation">Maximum Likelihood Estimator</a> (MLE). In a nutshell, a likelihood function ℒ(θ | x) = f(θ; x) measures how compatible the observed data x are with the possible parameters θ. In our case, the likelihood would look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*I2EaEa3KjXiGorIOXhOVaA.png" /></figure><p>From this expression you can see that to maximise the likelihood ℒ we need to maximise the exponent, which is the same as mimimising:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*vQgs2g54rCzrInUE6aWAkA.png" /></figure><p>returning again the OLS estimator.</p><h3>What have we won?</h3><p>After all this, we got to the same result. Even further, the OLS estimator is the BLUE under conditions much less strict than the one we used to find the MLE in this case (remember, we’ve only shown that the results match when the generation process is normally distributed). Staying in the realm of frequentist statistics, have we achieved anything?</p><p>I think that we have gained a lot more interpretation of the problem. And, although this cannot be seen directly in the simple linear regression model, the key is playing with the estimators. The <a href="https://en.wikipedia.org/wiki/Ridge_regression">Ridge regression</a> or Tikhonov regularisation is usually seen as a penalty term in the OLS. Instead of minimising C = ∑ᵢ₌₁ⁿ(yᵢ − βxᵢ − α)², you minimise C′ = ∑ᵢ₌₁ⁿ(yᵢ − βxᵢ − α)² + λβ². This new term will penalise large β and will therefore have smaller estimates than the OLS. The goal is that, although these estimators will be biased, they can compensate the overal error by <a href="https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff">reducing variance</a>.</p><p>This regression is usually explained in a conceptually very crisp way in the Bayesian framework through the <a href="https://en.wikipedia.org/wiki/Ridge_regression#Bayesian_interpretation">usage of priors are regularisers</a>. In the frequentist framework we could say that instead of using the Maximum Likelihood Estimator we are using an estimator of a modified likelihood ℒ′ = ℒ(θ) · exp(−C · β²).</p><h3>The value in modeling</h3><p>In the vanilla linear regression we analysed we saw that thanks to the model we used our MLE method is easy to interpret, but we needed to constrain the error generation process. OLS is a bit more obscure, but errors can be much more general and still maintain theoretical niceties. This value in modeling is also seen in this Ridge regression case: in OLS it’s a very obscure (almost out of the blue) penalisation. Through the likelihood it becomes clearer, and switching to the Bayesian framework, everything fit nicely through the concept of priors.</p><p>It is helpful to understand how much of the interpretation (in any given problem) we acheive thanks to modeling and how much is due to the framework we choose. After all, we only have data and models. With the proper translation, results in Bayesian and Frequentist framework should also be the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=436c7d2e3805" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The unbearable effectiveness of the Central Limit Theorem]]></title>
            <link>https://medium.com/@pabloalcain/the-unbearable-effectiveness-of-the-central-limit-theorem-d7e48a54135d?source=rss-822ce1efe96e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7e48a54135d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[experiment]]></category>
            <category><![CDATA[ab-testing]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Pablo Alcain]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 03:00:57 GMT</pubDate>
            <atom:updated>2025-08-12T15:53:28.182Z</atom:updated>
            <content:encoded><![CDATA[<p><em>To view a better formatted version of this post, go to </em><a href="https://blog.pabloalcain.ar/ds/central-limit-theorem/"><em>https://blog.pabloalcain.ar/ds/central-limit-theorem/</em></a><em>.</em></p><p>The Central Limit Theorem is one of the most astonishing results in statistics. Let’s cover briefly what it states (in one of its forms): if we have <em>N </em>independent and identically distributed random variables that come from a distribution (that we will call the <em>underlying distribution</em>) with mean <em>μ </em>and variance <em>σ</em>, then the average of those variables will, as <em>N</em> increases, resemble a normal distribution centered in <em>μ </em>with variance <em>σ</em>²/<em>N</em>. We can even replace <em>σ</em>² with the sample variance <em>S</em>² and the CLT still holds¹.</p><p>And let’s cover, just for clarity, what it’s not: the CLT <em>does not say</em> that the distribution of <em>X</em>i will be normal, and it does <strong>not</strong> say that the standard deviation of the distribution will be reduced as we draw more variables. This might seem obvious when you’re reading it in context and thoughtfully, but it is a source of confusion in a lot of discussions about the CLT, so it’s worth keeping in mind.</p><p>But there is one more thing that the CLT does not say, a critical one for practitioners of data science, statistics and the likes: when will I have enough <em>N</em>? Even more: how do I even <strong>know</strong> I have enough <em>N</em>? We will try to answer these questions analyzing first a scenario in which the math is relatively easy and well-known and taking advantage of the exact results to draw general conclusions.</p><h3>Start small: the underlying distribution is Normal</h3><p>If the underlying distribution were normal and we knew the variance we are in the presence of a very specific result in which the average is normally distributed for every sample size, even from <em>N</em>=2. This involves doing some math to find that the <a href="https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables">sum of two normal variables is normal</a> and then calculating the average dividing by <em>N</em>.</p><p>So let’s start with something that at least involves an approximation, right? Suppose we knew that the underlying distribution is Normal but, unlike the previous case, now we don’t know the variance. In this case, instead of using <em>σ</em>² we can use the sample variance <em>S</em>². Because of this we don’t expect the average to be <em>exactly</em> normally distributed, but we do expect it to tend to a normal distribution as <em>N </em>increases.</p><p>Although not as much as before, we are still lucky! The distribution of the average for this case can be calculated analytically. It was done more than 100 years ago by William Gosset, and it’s the famous <a href="https://en.wikipedia.org/wiki/Student%27s_t-distribution">t-distribution</a>². To compare the distribution of the averages with the expected normal from the CLT, we’ll do something very usual: standardizing the variable. If we expect to have a distribution N(<em>μ</em>, <em>S</em>²) we can standardize <em>X</em>¯ by substracting <em>μ </em>and dividing by <em>S </em>so that, in the regime of the Central Limit Theorem,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*hlRpdpfoDl4xztuRW8i8fA.png" /></figure><p>To check how good our approximation is, then, we just have to calculate this standardized variable and see how it compares with the standard normal distribution. In the following figure we’ve plotted the Cumulative Density Function for the t-distribution for <em>N</em>=2, <em>N</em>=10, <em>N</em>=30 and <em>N</em>=100 samples and compare it with the CDF of the normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hR9BOdtMbub3_m2FBKFuFg.png" /><figcaption>Comparison of the t-distribution CDF with the standard normal</figcaption></figure><p>It’s clear that, as <em>N</em> increases, the distributions start to look more like the standard normal³. We are almost there, we need only one more thing: try to quantify when it’s good enough. We could choose a lot of different ways to measure it, but we have to pick one. Arbitrarily⁴ we pick the Kolmogorov distance, defined as the maximum of the absolute value of the differences between our CDF and the standard normal, <em>D</em>=sup‖<em>F</em>(<em>x</em>)−Φ(<em>x</em>)‖</p><p>So this is how we are going to analyze the distributions similarity to the Normal distribution:</p><ol><li>For every value of <em>x </em>we will calculate the distance between our CDF and the standard normal,</li><li>Then pick the maximum among all of these <em>x</em>, this will be the Kolmogorov distance.</li><li>We’ll use this value to compare how “similar” the CDF is to the standard normal.</li><li>We will set an arbitrary threshold <em>D</em>=0.01 for “practical” convergence⁵.</li></ol><p>In our case for the t-distribution, this is reached at <em>Nc</em>=18.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*T9QbRwGEk3FgHNAKy9c1DQ.png" /><figcaption>Convergence of t-distribution to normal</figcaption></figure><p>We are almost there, we need to add only one more ingredient to the mix: what will we do when we don’t have exact results? In this case, we will have to rely on simulations⁶.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ww0Py_ZXW5VO1NPw3kd8IQ.png" /><figcaption>Simulated convergence of t-distribution to normal. See that the estimation of the error for the simulation is larger than the exact one.</figcaption></figure><h3>An unknown result: the underlying distribution is binomial</h3><p>OK, we have everything we need! Now we can do our analysis for every distribution, let’s try first the binomial. We will use the same strategy as before and now calculate the <em>Nc</em> at <em>D</em> = 0.01 as a function of the probability <em>Nc</em>.</p><p>Again, remember the idea: we compare the CDF of the average with the standard normal, calculate the maximum difference for different sample sizes <em>N </em>and see when it’s below our threshold of <em>D</em> = 0.01. This will be the critical sample size, <em>Nc</em>. Unlike the previous case, here we expect <em>Nc</em> to depend on the underlying probability, so in the following figure we plot <em>Nc </em>as a function of <em>p</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0lEsl4_6p3aXFlOb26A1Ug.png" /><figcaption>Critical sample size for the binomial distribution</figcaption></figure><p>Of course this is a noisy plot because the simulations take time and we can’t be as fine-grained as we wish⁷. Therefore we have a very coarse sampling of <em>p </em>and the sample sizes. But I hope you get the core idea: first of all, that the critical sample size depends on the underlying distribution and that, even for the same underlying distribution, it might vary a lot depending on its parameters. Nonetheless, we can see that the critical sample size is not that large when compared to the amount of data we are used to in most data science applications.</p><h3>What can I do with an unknown distribution?</h3><p>But let’s face it: the most common scenario is that we don’t know the underlying distribution. After all, if we knew it we could just infer the parameters with a technique like Maximum Likelihood Estimation and then calculate the mean of the distributions for the parameters. Or, if we were doing a hypothesis test, simply do a Likelihood Ratio Test. There is however an approach you can take: from all of the data you have, bootstrap <em>N</em> samples and use the simulations we’ve just made to calculate <em>D</em> for each of them. This will give you an idea of the sample size you need to approximate your distribution to a normal one.</p><p>Just as an example, suppose we are data scientists in All About Boxing, a company that sells cardboard boxes online. Our users will, with probability <em>p</em>0, buy nothing. With probability <em>p1</em> they will buy from a Poisson distribution with mean 10 and, with probability <em>p2 </em>they will buy from a Poisson distribution with mean 100. This is roughly what the distribution would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OS0Z2iz7wPORlJ9L0lWD_A.png" /><figcaption>Sales distribution for All About Boxing</figcaption></figure><p>Before you go on reading, test your intuition! How many samples would you say we need for this model to comply with our threshold of <em>D</em>=0.01. My guess (I haven’t run it yet!) is around <em>N</em>=1000. Now let’s plot <em>D </em>as a function of <em>N</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*sHAigMIEiUhTC6hEWwmEKw.png" /><figcaption>Convergence of unknown distribution to normal</figcaption></figure><p>I admit I’m surprised! I was being aggressive with <em>N</em>=1000, but it looks as even <em>N</em>=500 should be enough. To be honest, this result not only is surprising, but it also feels… demoralizing. One of the fun parts of statistics is the actual <em>modelling</em> of the underlying distribution, we’d love to take the empirical distribution of All about boxing and try to guess what’s the underlying distribution that fits best. This result shows that in some scenarios, when we are interested in estimating the mean of the distributions, we don’t need to go that far. This happens particularly in AB tests for online experiments (these have the characteristic that the sample size tends to be relatively large). For data scientists that spend quite some time analyzing AB tests the effectiveness of the Central Limit Theorem is unbearable: it renders useless some of the fun parts of statistics.</p><p>Don’t despair though: there are still a lot of challenging problems statistics-wise for AB tests, even using the CLT: sequential testing, effect size estimation, multiple comparisons, and many more. We will cover these topics in future posts, stay tuned.</p><p>¹ Of course this can be written much more precisely in mathematical terms, see for instance the concise definition on All of Statistics by Wasserman, p. 77</p><p>²I’ve written a small post about the t-distribution that you can find <a href="https://medium.com/@pabloalcain/where-does-the-t-distribution-come-from-sampling-with-unknown-variance-1061f0028d28">here</a></p><p>³I added <em>N</em>=30 because it’s “common knowledge” that the Central Limit Theorem “kicks in” once you have 30 samples. This “common knowledge” is wrong, as the value of <em>N </em>will obviously depend on the underlying distribution. But maybe this is the source for that very extended mistake.</p><p>⁴Actually this is not arbitrary at all: the <a href="https://en.wikipedia.org/wiki/Berry%E2%80%93Esseen_theorem">Berry-Esseen theorem</a> provides some theoretical bounds on it for the Central Limit Theorem.</p><p>⁵Of course this choice is as arbitrary as any, but it means that you are making an error in the probability distribution of, <em>at most</em>, 1%. This limit is usually smaller than many other errors in statistical models, AB tests, and so on. For example, if in an AB-test you have a p-value of 0.05 this would mean that the real p-value can be (again, a <strong>very conservative</strong> estimate) between 0.04 and 0.06, a difference that in most cases is not relevant.</p><p>⁶Adding simulations to the mix implies that we would also have to consider the error due to the sample size of the simulation. A proper treatment of this would be very lengthy and wouldn’t add a lot to the insights, but you are welcome to try to figure out the details.</p><p>⁷If you are wondering about it: yes, you can definitely do an exact calculation like the one we did for the t-distribution: after all, the sum of two binomial variables with the same probability <em>p </em>also has a binomial distribution. The <a href="https://en.wikipedia.org/wiki/De_Moivre%E2%80%93Laplace_theorem">De Moivre-Laplace theorem</a> proves that the limit of the binomial in fact tends to a normal distribution. <a href="https://blog.pabloalcain.ar/ds/central-limit-theorem/#fnref:7">↩</a></p><p><em>Originally published at </em><a href="https://blog.pabloalcain.ar/ds/central-limit-theorem/"><em>https://blog.pabloalcain.ar</em></a><em> on August 11, 2025. It’s better formatted over there, Medium can struggle with math sometimes.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7e48a54135d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every AB test is wrong]]></title>
            <link>https://medium.com/@pabloalcain/every-ab-test-is-wrong-496d748461c9?source=rss-822ce1efe96e------2</link>
            <guid isPermaLink="false">https://medium.com/p/496d748461c9</guid>
            <category><![CDATA[ab-testing]]></category>
            <category><![CDATA[experiment]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Pablo Alcain]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 03:00:42 GMT</pubDate>
            <atom:updated>2023-03-04T14:35:40.978Z</atom:updated>
            <content:encoded><![CDATA[<p>The industry, through concepts like agility and Lean Startups, has taken on rapidly the practice of performing AB tests. In a nutshell, the AB tests are controlled scenarios that help us decide which of two alternatives is better. One approach to make this decision is considering that we have a current state of a system and asking the question: <em>what would happen if we inflict a treatment?</em> The AB test way of answering the question is to split the population randomly into two groups (A and B, or <em>control</em> and <em>treatment</em>), measure both and then decide. But does an AB test really answer our question? In this post, we will see the core assumptions of AB tests in two dimensions (time and space) and whether they hold or not, following a real-life scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*JJb4qmyX1RXyQO1RhbU_BQ.png" /><figcaption>Expected “distribution” of a KPI on an AB test when everything goes well (spoiler: it never does)</figcaption></figure><p>In 2022, Twitter started the release of <a href="https://www.theverge.com/2022/5/3/23055515/twitter-circle-close-friends-private-tweets-150-people">Twitter Circles</a>. The main idea of Circles was to segregate the audience of tweets, allowing someone to decide whether they wanted the tweet to be “for everyone” or for a handpicked audience known as “circle”, in a similar fashion to the Close Friends on Instagram. We don’t know if the Circles functionality was actually AB-tested or not (although its rollout was definitely staged, meaning not everyone got it at the same time), but let’s try to see the challenges that would arise if we wanted to.</p><h3>Time Stability</h3><h4>Novelty Effect</h4><p>The effect of seeing a change for the first time is massive. Suppose that the whole interface of the news site you check every morning changed all of a sudden: you’d probably feel lost, not finding the sections you actually want to see, missclicking a lot. It will take some time for you to get used to the novelty. Similarly, in the case of Twitter Circles, you might receive the novel feature with an enthusiasm that won’t last. But we are not interested in these transient scenarios, since they don’t relate purely to the treatment effect: they also relate to the effect of <em>having done a treatment</em>. To measure the treatment effect itself we’d need to wait until this novelty effect fades out, but this is both hard to determine (because of the typical variance that comes with the metrics) and can take a lot of precious time that we might not have. Approaches that allocate the population dynamically to different treatments (like multi-armed bandits) are very exposed to this issue.</p><h4>Time extrapolation</h4><p>Even if you wait until the novelty effect fades out, you don’t know what the future holds. If you do an AB test during a period of time T and find that B is better than A (according to some significance criteria) you know only that: that B was better than A during T, and the future can be very different from T. Take, for example, seasonality: although you can probably sometimes account for weekly or even monthly seasonality, you won’t be able to do so for every AB test if you want to be fast-paced. Even beyond seasonality, you can have some events (like holidays season) that are very relevant for the business but during which you cannot test. What if B is <em>much worse</em> than A during that very important event? There is, unfortunately, no way to know. And finally, you have simply environmental conditions: people in the future can behave in a multitude of ways and, in some of them, B won’t perform better than A. The bottom line is that you won’t be able to <em>know</em> what will happen between B and A in the future.</p><h3>Spatial Stability</h3><p>When we try different settings for populations A and B we want both of them to be representative of the whole population: the effect on any of them represents the effect on every possible user. This is why A and B are chosen randomly, but it’s <em>not enough</em>. Consider an AB test in which we want to test the effect of circles. Twitter is a highly cohesive social network, in which interactions drive the behavior of users.</p><p>If you give users in population B the possibility of using circles, how do you handle the interaction with group A? There is no solution to this problem: if you allow people in group A to see that group B is using circles, then group A would <em>not</em> be representative of “what would happen if nobody had circles?”. On the other hand, if you don’t allow people in group A to see the tweets from B’s circles, then it’s group B that wouldn’t be representative. Of course, you can do some clever manipulation and try to choose groups A and B so that the interactions between them are minimized and therefore the effect is diminished. But it won’t go away, and it’s very hard to model. This is known in the literature as Stable Unit Treatment Validity Assumption (SUTVA) violation and, whenever people can communicate with each other beyond your application (fortunately always) you are exposed to it. Even if your treatment is a change in the background color of your webpage, someone from group B can call someone from group A and tell them: “Oh, I really dislike the new color” and you’re done.</p><h3>What is the impact?</h3><p>We all know that AB tests come with uncertainty, and we do our best to measure it (through p-values, significance levels, expected loss, and alike). But the main consequence of these effects is uncertainty of the worst kind: the one that is not quantifiable. All of our uncertainty measurements are built on top of these shaky grounds that we have already mentioned. And as if this was not enough, this variance also helps inflate our AB tests result. Suppose that there was no effect between A and B other than seasonality: on Jan-Jun B performs 2% better than A, and on Jul-Dec A performs 2% better than B (in our target KPI). In January we do an AB test and measure that B is definitely better than A so we roll out B. If by the end of the year, we were to measure the impact of our AB tests (for example, suppose that we froze a portion of the traffic with the configuration of the beginning of the year), we’ll find that instead of improving by 2% it decreased by the same amount! Our AB test effect would appear to be inflated in 4% and would be actually inflated in 2%.</p><p>As a general rule, every time we add variance to a metric that we are selecting, we will introduce selection bias. This is known as the <a href="https://en.wikipedia.org/wiki/Winner%27s_curse">winner’s curse</a>.</p><h3>So… should we stop doing AB tests?</h3><p>These unavoidable problems stack the odds against us, they make it harder for us to be confident in our results. But that’s OK: we don’t do AB tests because they will give us absolute confidence that one model is better than the other, but because they give us more confidence than choosing randomly. In the parts in which we have control, we have to be as rigorous as possible, and this implies (most of the time) doing AB tests. But their pitfalls are there, and if we cannot avoid them we need to find a way to measure them or, at least, their impact. Even if we are confident that all of our statistical techniques are correct, doing a meta-analysis on AB tests, along with techniques like long-term hold-out groups (see, for example, <a href="https://medium.com/pinterest-engineering/how-holdout-groups-drive-sustainable-growth-35a4786c3801">this post from Pinterest eng</a>) can help us see how good our AB tests are and measure our exposure to these problems. Sure, all experiments are wrong. But some are useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=496d748461c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No al clickbait: un botcito con GPT3]]></title>
            <link>https://medium.com/@pabloalcain/no-al-clickbait-un-botcito-con-gpt3-fd90dd90d51?source=rss-822ce1efe96e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd90dd90d51</guid>
            <dc:creator><![CDATA[Pablo Alcain]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 03:00:33 GMT</pubDate>
            <atom:updated>2023-01-22T21:31:51.290Z</atom:updated>
            <content:encoded><![CDATA[<p>Terminó el 2022, comenzó el 2023 y con él se refrescan los hypes: dejamos pasar el hype de crypto (por un ratito, seguramente en un tiempo vuelva) que tuvo pico en el 2021 y bienvenimos al hype de la inteligencia artificial gracias, entre otros, a los desarrollos de openAI. Esta vez el hype de la inteligencia artificial viene con el sabor del lenguaje natural (otros años fue con imágenes) y con la capacidad generativa de texto a través de los LLM (Large Language Models). Las experiencias con plataformas como <a href="https://chat.openai.com/chat">chatGPT3</a> son realmente impresionantes, a pesar de que (como pasa siempre) no van a poder vivir a la altura del hype que se generó.</p><blockquote><em>The current climate in AI has so many parallels to 2021 web3 it’s making me uncomfortable. Narratives based on zero data are accepted as self-evident. Everyone is expecting as a sure thing “civilization-altering” impact (&amp; 100x returns on investment) in the next 2–3 years</em></blockquote><blockquote><em>- François Chollet (@fchollet) </em><a href="https://twitter.com/fchollet/status/1612142423425138688?ref_src=twsrc%5Etfw"><em>January 8, 2023</em></a></blockquote><p>Hay una moda que no cambia desde que la internet se volvió un espacio de publicidad y métricas de <em>engagement</em>: el clickbait. Poner un titular que diga algo sospechoso, que hasta te enoja, pero entrás a la nota y… no dice lo que el titular sugiere. ¡Ahí está el truco! Mentira no es (necesariamente), es <em>técnicamente</em> cierto y, en la realidad concreta, una práctica bastante miserable. Hace unas semanas, por ejemplo, me pasó con este titular:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*dh7R7LkA1Dx9grzx.png" /></figure><p>“Se vuelven a encarecer los vuelos”, parece que va a ser algo gravísimo. Cuando leés el cuerpo de la nota, la tasa es de entre 200 y 500 pesos (menos de dos dólares). Nuevamente: técnicamente es correcto, pero todos sabemos que es mentira, que el titular insinúa algo tan exagerado que es incluso falso. En las redes sociales también pasa un montón. El objetivo es conseguir dirigir tráfico hacia el sitio. Otra estrategia para dirigir el tráfico al sitio es, por ejemplo, este tuit de ámbito:</p><blockquote><em>🎞ARGENTINA, 1985 VA POR MÁS: CUÁNDO Y POR DÓNDE VER LOS CRITICS’ CHOICE AWARDS</em></blockquote><blockquote><em>👉 Este domingo se entregan los premios elegidos por la crítica de Estados Unidos. Tras los Globos de Oro, la película argentina buscará repetir la hazaña.</em></blockquote><blockquote><em>📲 Leé más: </em><a href="https://t.co/AyqbbMjBY2"><em>https://t.co/AyqbbMjBY2</em></a><em> </em><a href="https://t.co/nPirJLx83k"><em>pic.twitter.com/nPirJLx83k</em></a></blockquote><blockquote><em>- Ámbito Financiero (@Ambitocom) </em><a href="https://twitter.com/Ambitocom/status/1614631302191251459?ref_src=twsrc%5Etfw"><em>January 15, 2023</em></a></blockquote><p>El tuit plantea una pregunta que se responde en la nota, pero que no hace falta. El tuit podría ser: ARGENTINA, 1985 VA POR MÁS: ESTE DOMINGO A LAS 21 HS POR TNT PODÉS VER LOS CRITICS’ CHOICE AWARDS. No les conviene hacerlo de esa manera porque pierden visitas. Pero claro, encima tienen que escribir toda una nota para justificarlo, de manera que la información está escondida en un montón de relleno bastante inútil. Ahí hay un uso posible de los modelos generativos: podríamos pedirle a GPT-3 que invente una nota de relleno “alrededor” de la información importante, el día y horario de la transmisión. La consecuencia es una peor calidad periodística, lectores menos informados y, encima, los editores pueden elegir títulos que sugieran cosas inexistentes. Es un juego que no se puede ganar, todos los incentivos van para generar más tráfico, que es más ingresos por publicidad, más “prestigio” en alguna métrica. Nosotres, les pobres lectores, tenemos que caer sí o sí en ese juego para informarnos.</p><h3>Enter GPT-3</h3><p>Pero si podemos usar GPT-3 para generar el “relleno”, también podemos usarlo para sacárnoslo de encima. Resumir las notas, tratar de extraer la información más relevante que entre en un tuit y disponibilizarla. Usar a la máquina para deshacer los esfuerzos de estos medios de ocultarnos la información. Eso es, esencialmente, <a href="https://twitter.com/teahorrotuclick">Te ahorro tu click</a>, un bot (aún en desarrollo) que sigue a cuentas de “noticias”, lee la nota asociada y responde los tuits con un resumen. No creo en la infalibilidad de GPT-3 (ni de cualquier modelo posterior), a pesar de que hasta ahora sus resultados me sorprendieron y casi siempre los resúmenes fueron fieles. Pero sí creo que este tipo de desarrollos puede ayudar a generar aunque sea algún incentivo para disminuir los clickbaits. No va a ser este el bot que acabe con ellos, pero fue <strong>muy</strong> sencillo de hacer. Lo que más tiempo tomó fue que twitter me aceptara la solicitud de los permisos para automatizarlo.</p><p>El resumen que da a la nota original de infobae es:</p><blockquote><em>Desde el lunes 9 de enero se aplicará un nuevo impuesto a los pasajes aéreos en todos los aeropuertos del SNA. La Tasa de Seguridad de la Aviación tendrá un costo base de $260 para vuelos domésticos y de USD 1,40 para vuelos internacionales y regionales. La tasa de uso aeroportuario también subirá a partir del 2 de febrero.</em></blockquote><p>El resumen de la de ámbito es:</p><blockquote><em>Tras el triunfo en los Globos de Oro, la película argentina “Argentina, 1985” busca repetir la hazaña este domingo en los Critics’ Choice Awards. Se emitirá en TNT y HBO Max desde las 21hs con comentarios de Ileana Rodríguez y Rafael Sarmiento.’</em></blockquote><p>Un par de problemas: el primero es que le cuesta mantener un límite de caracteres. A pesar de que el requisito es que el resumen tenga un máximo de 200 caracteres, el primer resumen tiene 325 y el segundo 244. Por ahora el bot corta el mensaje hasta 280 caracteres para garantizarse que entre en un tuit. El otro problema es que le cuesta reconocer qué es un clickbait y qué no (a nosotros los humanos nos cuesta ponernos de acuerdo incluso). La decisión por ahora es resumir todas las notas (incluso las que no son clickbaits) y agregar una pequeña encuesta después de la respuesta para ver si, en general, los usuarios consideran el tuit original como un clickbait. La respuesta al tuit de ámbito se ve así:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*GYYO_9Q5CNrjlKk4.png" /></figure><p>Por ahora responde automáticamente a las cuentas de <a href="https://twitter.com/ambitocom">Ambito</a> y <a href="https://twitter.com/minutounocom">Minuto Uno</a>. Para <a href="https://twitter.com/infobae">Infobae</a> hay que etiquetar al bot en las replies para que la resuma. No se puede hacer automáticamente porque tuitean mucho **mucho** y termina siendo muy costoso. Si bien es relativamente fácil agregar más fuentes, también es cierto que los medios pueden usar algunas estrategias para complicar la solución de este lado o incluso encarecerla. En general, el bot es más una prueba de concepto que un anti clickbait a prueba de balas.</p><p>Ojo, no es esto un canto a la tecnología. Fueron los propios desarrollos tecnológicos los que generaron los incentivos para esta situación actual, de clickbait insoportable. Pero a veces hay alguna manera de usar algunas herramientas de la tecnología para reclamar el control que otras herramientas nos quitan. Incluso quizás resulta que esta herramienta en concreto no es tan buena como parece, que puede terminar siendo más perjudicial que beneficiosa. Porque no es la tecnología la que va a resolver los problemas, sino los incentivos que queremos construir y, en gran medida, los usos que les demos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd90dd90d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where does the t-distribution come from? Sampling with unknown variance]]></title>
            <link>https://medium.com/@pabloalcain/where-does-the-t-distribution-come-from-sampling-with-unknown-variance-1061f0028d28?source=rss-822ce1efe96e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1061f0028d28</guid>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Pablo Alcain]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 12:01:56 GMT</pubDate>
            <atom:updated>2022-11-23T12:01:56.267Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://en.wikipedia.org/wiki/Student%27s_t-distribution">Student’s t-distribution</a> is ubiquitous in statistics, more specifically in the realm of hypothesis testing in continuous variables. What it means conceptually and why it arises in certain contexts with that specific functional form, however, is not always clearly understood. Explanations range from a very basic “like normal distribution but with heavier tails” to a complex interplay of uninformative priors, pivotal quantities, and Bayesian updates. There is a conceptual, easy-to-grasp explanation, that goes along the lines of “Student’s t-distribution is defined as the distribution of the random variable <em>t</em> which is (very loosely) the “best” that we can do not knowing .” In this brief post, we will dive into that sentence and see how the t-distribution arises from considering σ as unknown and factoring this into a minimal Bayesian framework.</p><h3>Estimating mean with a known variance</h3><p>Let’s first recap how we can deal, with Bayesian inference, to the estimation of the parameter of the mean knowing the variance. We will assume that we know for a fact that we will draw samples from an underlying distribution with unknown mean and with standard deviation σ. We draw <em>n</em> numbers (which we will call <em>xᵢ</em>). How do we estimate the true mean? We can calculate the mean of the sample we just got, but we need a bit more than a point estimate. This question (and questions that are very similar to it) can be answered in many different fashions, one of them is from the Bayesian inference framework:</p><p><em>p(μ | xᵢ) ∝ p(μ) ⋅ p(xᵢ | μ)</em></p><p>Considering an uninformative prior of <em>p(μ)</em> constant, we can reduce the equation to the well-known result (and a bit misleading!): <em>p(μ | xᵢ) ∼ 𝒩(x̅,σ²/n)</em>. When the variance is known, then, we “know” that the true mean is drawn from a normal distribution with those parameters.</p><h3>But we don’t know the variance</h3><p>But what happens if we don’t have that prior knowledge of the variance? What if we had to estimate it from our measurements? We can estimate the <em>true</em> variance with the variance of the sample we just got, but: you know where we are going, we again need a bit more than a point estimate, we need a <em>probability distribution for the parameter σ.</em> To calculate the distribution of the true mean we would need to first draw a <em>σ</em> from this distribution, and use this draw to get a sample of <em>μ</em>. We will repeat this multiple times in order to get a distribution.</p><p>Suppose we have drawn 5 samples from a normal distribution, that yielded a mean x̅ = 15 and a sample variance s² = 45. As we said, we want to add here the uncertainty that we have for the variance. We will do it crudely at first, let’s simply say that we will let the variance be everywhere between 0 and 90, uniformly distributed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7888983432da42074cdefb26cc37c703/href">https://medium.com/media/7888983432da42074cdefb26cc37c703/href</a></iframe><p>We plot the results and alongside the obtained distribution for <em>μ</em> we also plot the associated normal distribution. By introducing the variance as a distribution instead of a known point estimate, our distribution from <em>μ</em> started to differ from that of a normal distribution: it’s much sharper and it has slightly heavier tails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*jqISuYT-cKNQl8Wv433QSw.png" /><figcaption>Distribution of parameters with uniformly distributed variance</figcaption></figure><p>We know that a complete certainty on the value of <em>σ</em> (a <a href="https://en.wikipedia.org/wiki/Dirac_delta_function">Dirac’s delta distribution</a>) yields a normal distribution for <em>μ</em>, with variance equal to <em>σ²/n</em>. Modifying the probability density function of <em>σ</em> to a uniform distribution yielded (unsurprisingly) a different distribution for <em>μ</em>, no longer a normal one. Let’s think about the differences: as we said, this is analogous to drawing <em>σ</em> from the uniform distribution and using it to get a sample of <em>μ</em>. Since the <em>σ</em> distribution is uniform, we have a lot of samples that have very small <em>σ</em> and, therefore, sharpen the definition around <em>μ</em> when those low <em>σ</em> are drawn. Let’s change that a bit, and try to ease the weight of the low <em>σ</em> in the distribution. For example, let’s use a <em>lognormal</em> distribution for <em>σ</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee5b88bc890baba36a99f0a3a38e7739/href">https://medium.com/media/ee5b88bc890baba36a99f0a3a38e7739/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*whXGb20X8hLwg6PRqOtu9w.png" /><figcaption>Distribution of parameters with log-normally distributed variance</figcaption></figure><p>The center peak is still higher than that of a normal distribution, but lower than it was before. And the tails are starting to look much heavier than that of the normal distribution.</p><p>We can keep doing this with any distribution for <em>σ</em> and there is (at least for now) no reason to choose one over the other. And it’s clear that the moment we choose a distribution for <em>σ</em>, the distribution for <em>μ</em> will change, so there is an association between the distributions <em>ℱ(σ)</em> and <em>𝒢(μ)</em>. We have already discussed <em>ℱ </em>being the uniform and the lognormal distribution, and how it generated specific <em>𝒢 </em>distributions (we could give them a name if we wanted). But among all of the possible distributions for <em>ℱ</em> there is a special one.</p><h4>Finding the t-distribution</h4><p>Now we will propose another <em>ℱ</em> distribution for <em>σ</em>: <a href="https://en.wikipedia.org/wiki/Inverse-chi-squared_distribution">inverse-chi-squared distribution</a>, essentially a variation on the <em>Γ</em> distribution. It takes two parameters: the degrees of freedom ν and the location <em>x₀</em>. Since the mean of Inv−<em>χ²(ν, x₀) </em>is <em>x₀ </em>and ν has a very suggestive name, let’s check a distribution with ν =<em> n — 1 </em>and <em>x₀= s²</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb5c381320561a9876039a89ee040dac/href">https://medium.com/media/fb5c381320561a9876039a89ee040dac/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*QzeopnNWHbE3_KCBHp98eg.png" /><figcaption>Distribution of parameters with inverse-chi-squared distributed variance</figcaption></figure><p>Turns out that this specific <em>ℱ</em> distribution we set for the variance is so important that the generated <em>𝒢</em> function has already been named: it’s the Student’s t-distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*xEbfrhILwzfhHqOXborfYA.png" /><figcaption>Student’s t-distribution</figcaption></figure><p>As the sample size increases, we have more certainty on the variance, and the Inv−<em>χ²</em> distribution narrows towards the center. Since <em>ℱ</em> becomes better defined in the center (closer to a Dirac’s delta), the <em>𝒢</em> distribution becomes closer to a normal distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CcdJizB1Hy3_TgqIcu_kBg.gif" /><figcaption>Evolution of t-distribution as sample size increases</figcaption></figure><h4>OK, but why inverse-chi-squared?</h4><p>As a final note, let’s see quickly why inverse-chi-squared is of particular importance. In <a href="http://www.dcscience.net/Student-t-1908.pdf">Student’s original paper</a>, Willam Gosset expands the moment coefficients of the distribution of <em>σ</em> that could have resulted in the observed variance <em>s²</em> and, although not arriving at a formal proof, finds <em>ℱ </em>as the Inv−<em>χ²</em> (the derivation is in section I of the paper, only 4 pages long; it looks like he was not aware that he had arrived to a function related to <em>Γ</em>). As we mentioned in the introduction, nowadays the derivation can be greatly simplified through the Bayesian framework, with Inv−<em>χ²</em> as a posterior distribution for an uninformative prior for the variance. A derivation of this can be found in section 3.2 of the book <a href="http://www.stat.columbia.edu/~gelman/book">Bayesian Data Analysis</a>².</p><p>¹: <a href="https://mathworld.wolfram.com/Studentst-Distribution.html">https://mathworld.wolfram.com/Studentst-Distribution.html</a><br>²: To dive into the reason behind the σ⁻² as an uninformative prior, check section 2.7 as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1061f0028d28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software engineering for Machine Learning — Part III: Production-is-exploration]]></title>
            <link>https://medium.com/@pabloalcain/software-engineering-for-machine-learning-part-iii-production-is-exploration-c7d8d4733aba?source=rss-822ce1efe96e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7d8d4733aba</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pablo Alcain]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 12:01:52 GMT</pubDate>
            <atom:updated>2022-10-31T12:57:24.107Z</atom:updated>
            <content:encoded><![CDATA[<h3>Software engineering for Machine Learning — Part III: Production-is-exploration</h3><p>This is part of a series of posts in which we discuss the challenges and strategies for the productionization of machine learning code. If you haven’t, make sure to check <a href="https://medium.com/@pabloalcain/software-engineering-for-machine-learning-part-i-motivation-e23b87285279">part I</a> and <a href="https://medium.com/@pabloalcain/software-engineering-for-machine-learning-part-ii-an-overeager-implementation-54d84a36333b">part II</a> before diving into this one. In part II we got an exploration code and started working on it to get to production, splitting the code into “application” and “library”. While trying to do this, we ended up with a code that was too brittle and hard to modify in typical exploration settings. You can check on that specific commit on the repo what the <a href="https://github.com/pabloalcain/software-design-for-ml/blob/14ea162f1ce222b412dfc7e96cd41dd9258f1bd8/model.py">model.py</a> file ended looking like, which tempted us to fall back to the <em>deploy as a service</em> approach.</p><p>Reflecting on how we got there, we’ve been always one step behind the data scientist&#39;s ideas, chasing them one solution at a time. Let’s recall, just for context, what the model.py file looked like when we first started down this path:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad5953d5d2f629580d7dfc57b54d03c0/href">https://medium.com/media/ad5953d5d2f629580d7dfc57b54d03c0/href</a></iframe><p>The problem is that we are extremely coupled to the specific solution we are setting inside the Model constructor. Fortunately, we know the solution to this problem from Software Designs principles: the D in SOLID is for dependency injection, which is (ultimately) just a fancy name for <em>parametrization</em>. We want to parametrize the classifier altogether:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee9ff92b66563d6d976f7765e1fb44fe/href">https://medium.com/media/ee9ff92b66563d6d976f7765e1fb44fe/href</a></iframe><p>Two things to note here: first, we call the classifier the “backend model”. This comes with a realization of what we are building on the “library” code: it is a specific interface to scikit learn classifiers. The other thing is that the fit and the predict model are essentially delegations to the backend. We use this delegation to implement a well-known pattern in object oriented design: the <a href="https://en.wikipedia.org/wiki/Strategy_pattern"><em>strategy</em></a> pattern. The train.py file has to be modified as well to take into account this change</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a77515d1f4280b6aee577544b804a963/href">https://medium.com/media/a77515d1f4280b6aee577544b804a963/href</a></iframe><p>Through dependency injection, we have effectively decoupled the Model object from the classifier solution itself and crawled out of the hole we dug for ourselves.</p><p>Let’s go for another proposed modification and see how we can generalize our technique. Suppose that now we want to experiment on what would happen if we were to remove all instances with very long sepals, and keep only those with sepal length less than 5.0. It looks like doing a dependency injection might help (for example, we could load the dataset with pandas, do the modifications we want and then inject it into the dataset during the construction), but we can pause a bit and reflect on the approach we have just taken for the Model.</p><p>When doing the dependency injection, one of the side effects was to <em>expose</em> the scikit learn code that was on the “library” space to the “application” space, and all that belongs to the “application” space is easy to modify quickly (remember that the application space is the area of influence for the DS code modifications). Exposing this known library to the DS is what simplifies the exploration process. The price we are paying for it will become clear when we apply this concept to the Dataset object (see <a href="https://github.com/pabloalcain/software-design-for-ml/tree/31478a12d93285689099841fa1b7b1d1cf232c73">commit</a>). The dataset.py and train.py files now look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e50265ae56311a97e2db6a2533c49d1f/href">https://medium.com/media/e50265ae56311a97e2db6a2533c49d1f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c7432d3cbb75c4777c78281e44a1c20/href">https://medium.com/media/5c7432d3cbb75c4777c78281e44a1c20/href</a></iframe><p>There are some quirks in the implementation, but let’s analyze how our abstractions affect the exploration workflow. Of all the possible definitions of “abstraction”, my favorite is the one by Joel Spolsky: <em>an abstraction is a simplification of something much more complicated that is going on under the covers</em>. I like this definition because clearly shows the subjective nature of an abstraction: different people will regard different things as “too complicated” that should belong “under the covers”. When we regarded the model itself as something that belongs under the covers (in our terminology, the “library” code), the exploration phase was a force that consistently tried to uncover the implementation. It makes total sense: while from a software design perspective we can say “what matters is that we are <em>classifying</em>, the way we do it is an implementation detail”, from the DS perspective the implementation is everything but a detail: it’s the most important part.</p><p>In the same <a href="https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/">article</a> (and please, oh please! read it if you haven’t yet) in which Spolsky defines the abstraction, he coined the Law of Leaky Abstractions: <em>all non-trivial abstractions, to some degree, are leaky</em>. While this is a general law, and Spolsky lays out several examples, in this case the situation is even more extreme: we have a constant drive (the exploration) to leak the abstractions. Our strategy for the <em>production-is-exploration </em>approach is to own this reality and instead of fighting the leakage, we try to channel it. We know that the abstractions will leak sooner rather than later, so we choose how to. This is the price we are paying: by leaking the abstractions the API will be too wide and relatively shallow when interfacing with pandas, scikit-learn or whichever backend library we use.</p><p>Let’s see how this approach allows us to fulfill our four pillars:</p><h4>Fast and easy exploration</h4><p>We have already seen how easy it is to change the classifier itself. Let’s try out now our current challenge: what we have now is production code and we want to explore training the model without flowers with long sepals. The implementation is trivial for the data scientist, modifying only application code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9036db8dd64892804ee7dc9f6a4e7f56/href">https://medium.com/media/9036db8dd64892804ee7dc9f6a4e7f56/href</a></iframe><p>Not only for this change but for any other one they want to make, they will be able to use all the knowledge they already have of libraries that are well known and established in the domain.</p><h4>Declarative and intention revealing</h4><p>After the exploration, the DS decides to put this into production. When the code gets to production, we want it to be intention-revealing and probably the line we have just added is too verbose and cumbersome. Therefore, we reify the implementation of the long sepal filter to the Dataset object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59e9ec3385570cdc403ae2a8a848e25c/href">https://medium.com/media/59e9ec3385570cdc403ae2a8a848e25c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d4961073c56a198aade592329b91bdf/href">https://medium.com/media/7d4961073c56a198aade592329b91bdf/href</a></iframe><h4>Sensible checkpoints</h4><p>Along this development, we rolled back the interfaces of our methods. Instead of using our own class `Dataset` to fit the model, we decided to use pandas dataframes directly. This is a somewhat controversial decision that unlocks needed flexibility in the checkpoints: we can bring to the model any pandas dataframe created through any means, even loading a crude CSV file from disk. This is a slippery slope, and probably the decision depends both on the team and the problem we are solving. We should, at least, consider exposing to the application code “basic” types¹ instead of custom abstractions. But be weary of overdoing it and falling into the <a href="https://wiki.c2.com/?PrimitiveObsession">Primitive Obsession</a> antipattern.</p><h4>Seamless tracking and monitoring</h4><p>Being an intermediate layer between the application and the backend, the “library” space is a perfect place to put the logging code and other monitoring hooks, for example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ea313143e87296a8ef1b9279e4e0db5/href">https://medium.com/media/0ea313143e87296a8ef1b9279e4e0db5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b94ccd93d57f82674130918062e6269/href">https://medium.com/media/7b94ccd93d57f82674130918062e6269/href</a></iframe><p>In the <em>production-is-exploration</em> approach, we used that <strong>what constitutes an implementation detail lies in the eye of the beholder</strong>, and leverage this concept to allow flexibility in the user experience by <strong>allowing the application code to speak the language of the developer</strong>. We came to terms with the idea that abstractions will leak and, instead of fighting it, we channel it and used it to our advantage. While we are aware of some of the challenges that come with this solution, in some cases the benefits might outweigh them: the removal of code duplication and rewriting and the ease of exploring and modifying based on well-known and maintained production code relieves a lot of the “maintenance” pressure that developers typically have in the “deploy as a service” and in the “exploration is production” setting.</p><p>¹: Basic types in this context include pandas dataframes and alike</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7d8d4733aba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software engineering for Machine Learning — Part II: An overeager implementation]]></title>
            <link>https://medium.com/@pabloalcain/software-engineering-for-machine-learning-part-ii-an-overeager-implementation-54d84a36333b?source=rss-822ce1efe96e------2</link>
            <guid isPermaLink="false">https://medium.com/p/54d84a36333b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Pablo Alcain]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 12:01:47 GMT</pubDate>
            <atom:updated>2022-10-17T12:01:47.274Z</atom:updated>
            <content:encoded><![CDATA[<h3>Software engineering for Machine Learning — Part II: An overeager implementation</h3><p>This is part of a series of posts in which we discuss the challenges and strategies for the productionization of machine learning code. In our <a href="https://medium.com/@pabloalcain/software-engineering-for-machine-learning-part-i-motivation-e23b87285279">previous post</a> we introduced the problem and arrived at the four pillars that the production ML code should have:</p><p>1. <strong>Fast</strong> and <strong>easy</strong> exploration<br>2. <strong>Declarative</strong> and <strong>Intention revealing</strong><br>3. Useful <strong>checkpoints</strong><br>4. <strong>Seamless</strong> tracking and monitoring</p><p>We will do an attempt to productionize the playground code we wrote earlier and show <em>step by step</em> the rationale behind each of our decisions. We will see how some attempts to implement a *production-is-exploration* approach eventually fall back to *deploy as a service* when we disregard the typical exploration workflow. To follow the evolution of the code, you can check the <a href="https://github.com/pabloalcain/software-design-for-lm">repository</a>. Remember that we began with the <a href="https://github.com/pabloalcain/software-design-for-ml/tree/e17264e310d8b82e0e79a469a4b3ad05ff136efa">original playground file</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/251dc07bc03dec924f45060692e9ddec/href">https://medium.com/media/251dc07bc03dec924f45060692e9ddec/href</a></iframe><p>The first thing we realize with this code is that there is no way in which we can put it into production: the model only leaves within this python file scope. We need to persist it somehow, and for that we choose <a href="https://docs.python.org/3/library/pickle.html">pickle</a>. Instead of calculating the accuracy score, once we train the model we save it (check the code at <a href="https://github.com/pabloalcain/software-design-for-ml/tree/592b342c84c83da090b3b27d6bebb4a0608e64c7">that commit in the repo</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f6d1a0307d61a2f5922e2d8d85aee5/href">https://medium.com/media/52f6d1a0307d61a2f5922e2d8d85aee5/href</a></iframe><p>We can then use this saved model to predict on a completely new dataset. In this scenario we will simplify this by reading the unseen dataset from disk, but keep in mind that we can use this to serve a model over any API with, for example, <a href="https://fastapi.tiangolo.com/">fastAPI</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/233984c1440278b5da19cce29f8c1406/href">https://medium.com/media/233984c1440278b5da19cce29f8c1406/href</a></iframe><p>From the _exploration-is-production_ perspective (see <a href="https://medium.com/@pabloalcain/software-engineering-for-machine-learning-part-i-motivation-e23b87285279">part I</a>) we could say our work is done: we have a model and it’s going into production. However, there are some things that can be improved in this code. Take for example the calls to pickle. If eventually we wanted to save it in any other format, we’d have to manually change all these files. And it’s something that Data Scientists are usually not interested in. Essentially we are saying that there are <em>implementation details</em> being exposed in the code. We know how to solve it — we abstract the implementation details away into functions! So we create the module model.py that will be in charge of knowing how to persist and load the model (check the diff from the previous step in the <a href="https://github.com/pabloalcain/software-design-for-ml/commit/c581cb699db6931a56497d4c6c938dc089a95aa8">repo</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/047169aca2352b529cd7eb7dcca01bd1/href">https://medium.com/media/047169aca2352b529cd7eb7dcca01bd1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28fe19317e3f9b52ad7cdb0de39d370e/href">https://medium.com/media/28fe19317e3f9b52ad7cdb0de39d370e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8271c87f141d02bfa6e3615907b670/href">https://medium.com/media/3d8271c87f141d02bfa6e3615907b670/href</a></iframe><p>See that, when creating this new file we have also split the code in two spaces: the file model.py is part of a “library” code, while predict.py and train.py are “application” code. See that now if, for some reason, we decided to change the tool we use to save the model (for example using joblib instead of pickle), we’d have to change only the library code and the user of the application code would not be impacted by this at all. This difference is important in order to understand how and when we are going to abstract implementation details, and we’ll use this distinction throughout this post.</p><p>Now we turn our attention to the model fitting itself, this section of the train.py file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87aacb1431f86cce50df6e6163aaa038/href">https://medium.com/media/87aacb1431f86cce50df6e6163aaa038/href</a></iframe><p>In a similar fashion to what we’ve done before, we will abstract the fitting of the model into a function. And, spoiler alert: this will turn out badly right away. When we abstract the fit_model into a function, we end up with train.py file and the model.py file looking like this (<a href="https://github.com/pabloalcain/software-design-for-ml/commit/d31652dc81301b2776f3bf190c08d313ca8cb16b">diff</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e5fb7f3dc4fa7e7f5e5e28386c03e06/href">https://medium.com/media/8e5fb7f3dc4fa7e7f5e5e28386c03e06/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25c06bf9ab254b1ded9c7eb18c4ec693/href">https://medium.com/media/25c06bf9ab254b1ded9c7eb18c4ec693/href</a></iframe><p>See that we have the _model as a repeating suffix in all of the functions. As Sandi Metz put it in her wonderful talk <a href="https://www.youtube.com/watch?v=8bZh5LMaSmE">All the Little Things</a>, when we see functions that have a repeating prefix or a repeating suffix, there’s a tortured object there that’s screaming trying to get out. So we do a very quick code refactor and “upgrade” the collection of functions with _model to a wellformed Model object, which you can also <a href="https://github.com/pabloalcain/software-design-for-ml/tree/604bff99265be6c98d9ebf2fab89bc006c6f6d5e">check in the repo</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad5953d5d2f629580d7dfc57b54d03c0/href">https://medium.com/media/ad5953d5d2f629580d7dfc57b54d03c0/href</a></iframe><p>Emboldened by the success and how clean the Model object looks like, we now turn our attention to the dataset loading in the train.py file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03f73c1d63f1f1f1f21f3247d6ea84ac/href">https://medium.com/media/03f73c1d63f1f1f1f21f3247d6ea84ac/href</a></iframe><p>Similarly, we can build the Dataset object that abstracts the information about the features and the target:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e534c53d81b5897ed565a345619d153b/href">https://medium.com/media/e534c53d81b5897ed565a345619d153b/href</a></iframe><p>We can also leverage this new object to modify slightly the signature of the fit method in Model and use this new structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f1d673fc8016202698cfa13d172c34a/href">https://medium.com/media/7f1d673fc8016202698cfa13d172c34a/href</a></iframe><p>With these small changes, the `train.py` file now is much more concise (check the full code in the <a href="https://github.com/pabloalcain/software-design-for-ml/tree/e9a12a8efee1ab6cc3f05ce01757c4919e557444">repo</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a87a587b9b1ec0dc2c76d41e7a08f0b0/href">https://medium.com/media/a87a587b9b1ec0dc2c76d41e7a08f0b0/href</a></iframe><p>It is now only a handful of lines, and it is intention-revealing: each of the lines in the application code is clear about what it’s doing. But, as we said earlier, this story doesn’t end well: immersed in our search for abstracting implementation details, we simply <strong>went too far</strong>.</p><p>Remember that one of our goals is to have fast and easy exploration. Suppose that a data scientist in our team wants to try out (even completely offline!) how the model would perform if we select 3 instead of 2 features in the SelectKBest. It’s OK, we know how to solve it: we get the hardcoded 2 in the __init__ method and parametrize it away! (<a href="https://github.com/pabloalcain/software-design-for-ml/commit/4a28fd4e9d2373bcb5a2b16c089ccad5b9e75f43">diff</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01f4a6a22a98c5bcac9f02bd0a4cf280/href">https://medium.com/media/01f4a6a22a98c5bcac9f02bd0a4cf280/href</a></iframe><p>Done! We live to see another day. But that “another day”, the data scientists that are exploring the model realize that sometimes they don’t want to pick anything, just want to go directly to the logistic regression step. Rushed by the needs of the data scientist to be able to explore this quickly, then, we come up with a maybe questionable (but very widespread in Python) design decision: we will use None as a special value in number_of_selected so that, in this case, we will skip the selection step (<a href="https://github.com/pabloalcain/software-design-for-ml/commit/3c71fde369a349a49740f3e543b15c11fa458bdf">diff</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f479701d7d253a2f009caec37b5abcca/href">https://medium.com/media/f479701d7d253a2f009caec37b5abcca/href</a></iframe><p>Phew! Bullet dodged, we are not super happy with the solution but it works. But right away (remember, the Data Science job here is to explore different solutions) people want to try out what would happen if we don’t use a logistic regression as the classifier, and they want to try out a fancy multilayer perceptron. Reluctantly, we do whatever-gets-this-thing-solved, and we come up with this idea (<a href="https://github.com/pabloalcain/software-design-for-ml/commit/14ea162f1ce222b412dfc7e96cd41dd9258f1bd8">diff</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18d63b4715d3fedf586dbac4d0605f80/href">https://medium.com/media/18d63b4715d3fedf586dbac4d0605f80/href</a></iframe><p>This was super fast to implement, but it’s clearly not good code: we are comparing with a string, raising an error that can be hard to understand, and the user needs to remember what are possible values for the classifier_type parameter, among other problems. We can see how this is a slippery slope: we did a lot of modifications to our production code for things that are only going to be part of the exploration step, they might never get into production. The price that we have to pay is both degradation of the quality of production code and also an exploration workflow with a lot of friction. At this point, we are extremely tempted to tell the data scientist to try whatever modification they want on their own and, if it turns out to be production-worthy, we will code it in production, falling back to the <em>deploy as a service</em> approach.</p><p>We finish this post on a sad note, but the solution is right around the corner. As some tips about how to solve it: see that we are extremely coupled with the original solution and that we actually don’t know what model we want. In the following posts, we will provide an alternative path to solve this problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54d84a36333b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software engineering for Machine Learning — Part I: Motivation]]></title>
            <link>https://medium.com/@pabloalcain/software-engineering-for-machine-learning-part-i-motivation-e23b87285279?source=rss-822ce1efe96e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23b87285279</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pablo Alcain]]></dc:creator>
            <pubDate>Mon, 03 Oct 2022 12:02:40 GMT</pubDate>
            <atom:updated>2022-10-08T15:17:10.488Z</atom:updated>
            <content:encoded><![CDATA[<h3>Software engineering for Machine Learning — Part I: Motivation</h3><p>Machine Learning and Data Science code has its own set of challenges and peculiarities. When we write code to be used by Data Scientists or Machine Learning Developers we have to keep in mind constantly that every abstraction we use has to a) be compatible with a fast and easy exploration playground; b) allow for sensible checkpoints and optimizations; c) implement in a declarative fashion repeated queries and functions; and d) provide an abstraction level over all of the production code so it can be tracked and monitored seamlessly.</p><p>In this series of blog posts we will provide general guidelines to approach this problem from a software design perspective, defining what should our entities be, how deep should our abstraction go, and how to avoid some usual design pitfalls.</p><p>We will study specifically a very well-known problem from multilabel classification: the <a href="https://www.kaggle.com/datasets/uciml/iris">iris species problem</a>. Our goal is to be able to classify different species of iris flowers (versicolor, setosa, and virginica) from the length and width of both the sepal and the petal. So let’s assume we begin with a dataset saved as a CSV file and we want to use <a href="https://scikit-learn.org/">scikit learn</a> and <a href="https://pandas.pydata.org/">pandas</a> to classify the flowers. The first approach to this problem could be to analyze the data in what we will call a <em>playground</em>, an offline analysis of the dataset. This is, for example, a solution to the classification problem through a pipeline: we first select the 2 best features (according to the f-value, as is the default behavior in scikit learn) and then we use a logistic regression as the classifier step. We fit this pipeline to the target and calculate the accuracy of the predictions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfGC84vJ90vCq2mQMJ-MIQ.png" /><figcaption>Iris features distribution</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b587a672fdf2e6c5c2d2ee6e588957d2/href">https://medium.com/media/b587a672fdf2e6c5c2d2ee6e588957d2/href</a></iframe><p>Eventually, we will want to put this model into production. This involves a lot of different stuff, among them: data preparation, model deployment, serving capabilities, infrastructure provisioning, monitoring, and model tracking. There is a very interesting and well-known paper (although maybe a bit dated now) from 2015 about different challenges in all of these,<a href="https://proceedings.neurips.cc/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf"> Hidden Technical Debt in Machine Learning Systems</a>. The main thesis of the paper is that the Machine Learning code itself, although fundamental, is a very small part of a robust ML system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*OiKnHVAcuPnKLUkiH8be7Q.png" /><figcaption>Hidden Technical Debt in Machine Learning Systems</figcaption></figure><p>Keeping this general landscape in mind, we will focus now on what happens with the machine learning code itself. In our case, the playground code we wrote earlier. How does it go into production?</p><h3>Exploration-is-production</h3><p>One very extended approach is what we will call <em>exploration-is-production</em>. In this approach, the Data Scientist has direct access to production code, and she usually moves the exploration code to the production environment. If a next data scientist comes, he will have to read the production code and understand it in order to do some changes. This scenario is fast for exploration and productionization, but it’s extremely fragile: naturally production and exploration are different tasks and have different requirements.</p><p>Suppose, for example, we wanted to log things on production: all of the logging will end up polluting the exploration code as well. Code quality can also suffer a lot since usually exploration is done without readability and modularity in mind. Therefore the production space very quickly ends up having hard-to-understand, duplicated, and non-informative code. This, as we said, makes total sense: it’s not the task of the DS to write <em>good</em> code (for whatever that means) and they are not trained to do that (and it’s OK; probably they shouldn’t).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bD8j8FoH1RsM0fgn6MFf7A.png" /><figcaption>Exploration-is-Production</figcaption></figure><h3>Deploy as a Service</h3><p>On the other extreme, we attempt to solve the shortcomings of this approach by putting a barrier between the Data Scientists and production code, the <em>Machine Learning Engineering</em> team. The data scientist focuses on the exploration and development of models conceptually and we remove the burden of code quality and deploy to the MLE. The cost of this approach is having more people on the team and exposing the solution to “translation” bugs, in which the production code doesn’t do exactly what the exploration code does. This makes the production code fundamentally <strong>unreliable</strong>. On the bright side, (at first at least) it makes it easier for the DS to develop code, and apparently decouples them from production.</p><p>However, keep in mind that the moment a new DS (or even the same one) wants to modify or even analyze production code, they will have to understand code that was written by an engineer, focusing on the code and not on the model. It also isolates knowledge: some implementation details done by the engineers will not mimic completely the intention in the production code. Very quickly we end up having (at least) two code bases being developed in parallel, and no reliable source of truth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXI5uweZxtn5d-_WpBIsPw.png" /><figcaption>Deploy as a Service</figcaption></figure><h3>What do we want from our solution?</h3><p>The attempt to decouple data scientists from production code generates a lot of problems that can be solved in many different ways (having engineers more familiar with the models themselves, helping data scientists understand production code, etc). We will propose here a solution in the realm of Software Design techniques that attempts to simplify this productionization. For it, we will focus on four pillars:</p><p>1. <strong>Fast</strong> and <strong>easy</strong> exploration: the nature of the machine learning models is speculative and they change way too often. We need to be sure that data scientists are able to work with new ideas starting from 100% reliable production code.</p><p>2. <strong>Declarative</strong> and <strong>Intention revealing</strong>: as Martin Fowler put it in<strong> </strong><a href="https://martinfowler.com/bliki/CodeAsDocumentation.html">CodeAsDocumentation</a>, the code is the only source of documentation that is “sufficiently detailed and precise to act in that role”. This, of course, doesn’t mean that we don’t have to write any documentation, rather that we have to seize the opportunity of the production code to act as documentation.</p><p>3. Useful <strong>checkpoints</strong>: if we have a workflow with many different steps in production (like feature extraction, transformation, model training), we want to be able to hook into and out of this workflow in a way in which we can reuse previous or future steps. Sometimes this reutilization is fundamental for fast exploration since the steps can take a very long time to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RnY5iUkLKNANZfCsFFErcA.png" /><figcaption>Hooking into and out of the production process in specific checkpoints</figcaption></figure><p>4. <strong>Seamless</strong> tracking and monitoring: we have to track the goal, but we should not track it in a way that pollutes the declarative and intention revealing code we have just described. Suppose, for example, we take the playground code we wrote in the beginning and add to it tens of lines that call functions that are pure logging: it will be very hard for us to find, among all of these lines, where is actually the <strong>model</strong>. And in the playground, we are usually not interested in the same loggings we want in production.</p><p>With these four pillars, we will see in the following posts how to write production code that also serves as exploration, subverting the <em>exploration-is-production</em> idea into what we will call <em>production-is-exploration</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23b87285279" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>