<?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[Lumiata - Medium]]></title>
        <description><![CDATA[Making Healthcare Smarter - Medium]]></description>
        <link>https://medium.com/lumiata?source=rss----322e223ce83c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Lumiata - Medium</title>
            <link>https://medium.com/lumiata?source=rss----322e223ce83c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:40:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/lumiata" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimizing Individual-Level Models for Group-Level Predictions]]></title>
            <link>https://medium.com/lumiata/optimizing-individual-level-models-for-group-level-predictions-aaef1b061223?source=rss----322e223ce83c---4</link>
            <guid isPermaLink="false">https://medium.com/p/aaef1b061223</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Hilaf Hasson]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 17:57:40 GMT</pubDate>
            <atom:updated>2019-06-24T16:19:50.015Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2 — The Median of a Sum of Independent Identically Distributed Variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WenpGVJS_k_Q8x3AwgF2hg.png" /></figure><h3>Introduction</h3><p>In <a href="https://medium.com/lumiata/optimizing-individual-level-models-for-group-level-predictions-655243e88344">Part 1 </a>— An Analysis of Bias I explored bias in group-level predictions coming from individual-level models. There I used the following theorem by Peter Hall (“On the Limiting Behaviour of the Mode and Median of a Sum of Independent Variables”¹):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*lqScU3u939Ahy1tezIVcpg.png" /></figure><p>But why is that true? I found Hall’s paper to be somewhat difficult to penetrate, but very interesting. As a service to the community, in this post I will introduce the tools used in proving this result in as motivated and detailed a fashion as I can manage, and supply a variant of Hall’s proof in full. I’ve changed some of the steps in the proof to make the proof more natural, removing his reliance on a theorem of Esseen, and instead proving his result using a mathematical tool called Edgeworth expansions (which I introduce) directly. I have also filled in some of the crucial details missing from the original proof. The basic outline of the proof is very appealing: use an estimate of the error of the Central Limit Theorem to prove the result.</p><h3>Edgeworth Expansions — Estimating the error of the Central Limit Theorem</h3><p>The easiest way to prove the <a href="https://en.wikipedia.org/wiki/Central_limit_theorem">Central Limit Theorem</a> (CLT) and many of its variants is by looking at the “<a href="https://en.wikipedia.org/wiki/Characteristic_function_(probability_theory)">characteristic function</a>” of random variables. The characteristic function of a random variable <strong><em>X</em></strong> is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*b6CmSEo0HdNeKxBKeUF5Wg.png" /></figure><p>The reason that characteristic functions are helpful is three-fold:</p><ol><li>The characteristic function of a sum of independent variables is the product of their respective characteristic functions:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*VlJgI4YXJRU6FIJThAzccQ.png" /></figure><p>so that makes computations easy.</p><p>2. Knowing the characteristic function of a random variable determines its distribution. In fact, the characteristic function of <strong><em>X</em></strong> is nothing other than the <a href="https://en.wikipedia.org/wiki/Fourier_transform">Fourier transform</a> of the probability density function of <strong><em>X</em></strong> (if one exists), and so this is just Fourier duality — the reverse Fourier transform of the Fourier transform is the original function! (Caveat: Fourier duality suffers from a plurality of conventions due to the identification of the <a href="https://en.wikipedia.org/wiki/Group_(mathematics)">group</a> of real numbers with its <a href="https://en.wikipedia.org/wiki/Pontryagin_duality#The_dual_group">dual group</a> being “<a href="https://en.wikipedia.org/wiki/Natural_transformation#Unnatural_isomorphism">unnatural</a>”, in the <a href="https://en.wikipedia.org/wiki/Category_theory">Category Theory</a> sense of that word. We will follow the convention that the Fourier transform of a function <strong><em>f(t)</em></strong> is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*bxlPg26L1QxRo3Je_3v4Ig.png" /></figure><p>and the reverse transform of a function <strong><em>f(t)</em></strong> is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*04vdSgLfsZF7fC_HeA4qkg.png" /></figure><p>With this convention, the reverse transform of the characteristic function of <strong><em>X </em></strong>is the pdf of <strong><em>X</em></strong>, if one exists.)</p><p>3. Finally,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*gNVOHviuBx2z-O4g3ziMfg.png" /></figure><p>this is <a href="https://en.wikipedia.org/wiki/L%C3%A9vy%27s_continuity_theorem">Levy’s Continuity Theorem</a>.<br> <br>The standard proof of the CLT follows exactly this approach. By normalizing first, you can reduce CLT to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*traUmDcBN3iqLOJw1SnySg.png" /></figure><p>One proves this by showing that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*up1yDTjIQA9UxgUhbc05AQ.png" /></figure><p>point-wise. <br> <br> The crucial step is that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*p8kbfEx2rKS7hpIpVwmz-Q.png" /></figure><p>and therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*bIYztdCtjhSUd4oTzpg8hg.png" /></figure><p>, where the last step is because the <strong><em>X_i</em></strong>’s are all identically distributed. To simplify notation let <strong><em>X:=X_1</em></strong>.<br> <br>Showing that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*qSnrAYCToReotAzK3sAY0w.png" /></figure><p>pointwise is relatively easy, though the details are irrelevant to the rest of the discussion.<br> <br>The idea behind Edgeworth expansions, which is the mathematical tool that Hall uses as motivation (albeit just stops short of using directly), is similar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*MmhJRwGrISLTnj8gpyZvPg.png" /></figure><p>To be more specific, what one does is write a <a href="https://en.wikipedia.org/wiki/Taylor_series">Maclaurin expansion</a> of <strong><em>Log</em></strong> of the characteristic function of <strong><em>X</em></strong>, where <strong><em>Log</em></strong> is the <a href="https://en.wikipedia.org/wiki/Principal_branch#Complex_logarithms">principal branch</a> of <strong><em>log</em></strong>, as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*t7_aJN3EhGPtNkpqd0m2KA.png" /></figure><p>For those of you who like naming things, these <strong><em>κ_j</em></strong>’s are usually called the “<a href="https://en.wikipedia.org/wiki/Cumulant">cumulants</a>” of <strong><em>X</em></strong>. Generally speaking, cumulants don’t have an intuitive interpretation, but the first three do: <strong><em>κ_1 = E(X)</em></strong>, <strong><em>κ_2= V(X)</em></strong>, and <strong><em>κ_3 = E((X — E(X))³)</em></strong>. In particular, for us: <strong><em>κ_1 = 0 </em></strong>and <strong><em>κ_2 = 1</em></strong>. <br> <br> Thus the chosen expansion of the characteristic function of <strong><em>X </em></strong>is then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*KLRx1SQ2OdbLzFGclpKlFQ.png" /></figure><p>Plug that into</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*Z7WO7RO8MsN9ZyNox_oJ0g.png" /></figure><p>and get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*i0qfn1NtCoj51_JRc1hJ5g.png" /></figure><p>This last equality is simply using the Maclaurin expansion of <strong><em>eˣ</em></strong>; each <strong><em>r_j</em></strong> is a polynomial with real coefficients of degree <strong><em>3j</em></strong>, and can be computed if need be.<br> <br>It now just remains to apply a reverse Fourier transform to get an expansion of the probability density of <strong><em>S_n.</em></strong> This is relatively easy — there’s a trick:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*-f4iuPM9ksO3ddBFNWCeyg.png" /></figure><p>(Why? The degree <strong><em>0</em></strong> case is standard, and the monomial case follows by repeatedly deriving the degree <strong><em>0</em></strong> case; the general case follows the monomial case trivially.) The trick continues: deriving the probability density function of the standard normal distribution <strong><em>j</em></strong> times is actually easy to compute (by commuting the derivative and the integral), and for any <strong><em>j</em></strong> it’s always some polynomial times the pdf of the standard normal. (The polynomials arising in this way are called <a href="https://en.wikipedia.org/wiki/Hermite_polynomials">Hermite polynomials</a>, but it is not crucial to determine their properties for our purposes.)<br> <br> The bottom line of all of this is that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*yTQEic4e2zBC1ism111OYg.png" /></figure><p>So we just got an estimate of the error of the Central Limit Theorem! <br> <br>Weeeellll…. It turns out Edgeworth expansions almost never converge… So the above is more of the motivational bedtime-story we tell about Edgeworth expansion. But as it turns out, under extremely mild conditions, Edgeworth expansions are “asymptotic expansions”, which is to say that for every k:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_-TvHa8JeILkzaTppX0dWA.png" /></figure><p>uniformly in <strong><em>x</em></strong> so long as <strong><em>E(|X|^(k+2))&lt;∞</em></strong> and <strong><em>X</em></strong> satisfies a condition called “Cramer’s Condition”, which is a weaker condition than having a continuous pdf. <br> <br>Proving this requires a bit of heavy lifting, and I refer to Peter Hall’s book “The Bootstrap and Edgeworth Expansion”², Section 2.4 and Chapter 5, for details.</p><h3>From Edgeworth expansions to an approximation of the median</h3><p>In Hall’s paper the equivalent of this entire section is the phrase “it follows that”, with no explanation given. As you will see, the argument requires some nuance. But the details do work out…!<br> <br>Let:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*oD-udQbRNA_JaZRI_CQD4g.png" /></figure><p>Since</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*oEIQJXs3vxfdgjm8yxN8kw.png" /></figure><p>it follows that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*xIe-VGS3H7MqMS0E8779QA.png" /></figure><p>Let’s plug that into the Edgeworth expansion above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*XxQrdvmxk4vGw-ebL1kAEg.png" /></figure><p>Note that since pdf of the standard normal is exponential, the numerator of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*GbDDCOaKyevOewyYpppx5w.png" /></figure><p>is bounded, and therefore this fraction converges to 0. This implies that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*L6LuBSrxewtZECsHK_oRTw.png" /></figure><p>and therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*VlIX2bez2tGsI8c9f39idA.png" /></figure><p>(We ultimately want to show that <strong><em>m_n</em></strong> converges, but this is a first step that is required for the remainder of the proof.)<br> <br> Let’s now use the Maclaurin expansion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1VDwG7LEaxaRDBpEESXbxw.png" /></figure><p>Its radius of convergence is infinity. It follows that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*zBF05ymTg9D2T5dv5uf-dQ.png" /></figure><p>It can be shown that the <strong><em>p_1(x)</em></strong> term in the Edgeworth expansion is equal <strong><em>-κ_3(x²-1)/6</em></strong>, hence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*U_xeeNp2jkTB8YTpT6kHiQ.png" /></figure><p>In particular:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*ogfPMLGPeNFP3-t1CRzFUA.png" /></figure><p>Therefore we have that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*h0LzJruTBHKp4isaoOjYEg.png" /></figure><p>Which, after multiplying by the square root of <strong><em>n</em></strong> implies that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*iSxTJOsbK3T-Q67MpXV6MQ.png" /></figure><p>We’re ready for the kill now. Using the Maclaurin expansion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*wNjEJEn-RIFMxrx6o05FTw.png" /></figure><p>We can see that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*Y9NriMpeT0FzwzFdQmECRg.png" /></figure><p>Which in particular is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*nNkOyNdu1o2treQV7hMczg.png" /></figure><p>Therefore as <strong><em>n</em></strong> approaches infinity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*4x-RD2xm5_YsdJV9_Un3VQ.png" /></figure><p>and we’re done!</p><h3>Final note on a Hall-like result for non-i.i.d</h3><p>Somewhat understandably, there are no asymptotic results about the median of a sum of independent but not identically distributed random variables. However, surprisingly, there does exist a variant of Edgeworth expansions that is available for non-i.i.d random variables that is ideal under some rather complex definition of being ideal. (See “Edgeworth Expansions of Distribution Functions of Independent Random Variables” by Bai Zhidong and Zhao Lincheng³.) It is conceivable that one can follow the recipe above to go from the Edgeworth expansion to an estimate of the median.</p><p>If this post got your interest and you would like to challenge yourself with similar problems, we are hiring! Please check our <a href="https://www.lumiata.com/careers.html">open positions</a>.</p><p>GitHub: <a href="https://github.com/lumiata/tech_blog">https://github.com/lumiata/tech_blog</a></p><p>Visit Lumiata at <a href="http://www.lumiata.com/">www.lumiata.com</a> and follow on Twitter via <a href="http://www.twitter.com/lumiata">@lumiata</a>.</p><p>Find us on LinkedIn: <a href="https://www.linkedin.com/company/lumiata/">www.linkedin.com/company/lumiata</a></p><p><strong><em>Citations</em></strong><em>:</em></p><p><em>1.Hall, P. (1980) On the limiting behaviour of the mode and median of a sum of independent random variables. Ann. Probability 8 419–430.</em></p><p><em>2. Hall, P. (1992) The Bootstrap and Edgeworth Expansion. Springer-Verlag,<br>New York.</em></p><p><em>3. Bai, Z. and Zhao, L. (1984) Edgeworth Expansions of Distribution Functions of Independent Random Variables. Scientia Sinica 29 1–22.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaef1b061223" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lumiata/optimizing-individual-level-models-for-group-level-predictions-aaef1b061223">Optimizing Individual-Level Models for Group-Level Predictions</a> was originally published in <a href="https://medium.com/lumiata">Lumiata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Individual-Level Models for Group-Level Predictions]]></title>
            <link>https://medium.com/lumiata/optimizing-individual-level-models-for-group-level-predictions-655243e88344?source=rss----322e223ce83c---4</link>
            <guid isPermaLink="false">https://medium.com/p/655243e88344</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Hilaf Hasson]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 17:54:51 GMT</pubDate>
            <atom:updated>2019-06-26T21:54:34.135Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1 — An Analysis of Bias</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPQIGBvWkeeqfeWAIa5vag.png" /></figure><h3>Introduction</h3><p>The goal of this post is to present some of my thoughts about a very common, yet scantily addressed, problem in machine learning at large (and healthcare in particular): how do you construct group-level predictions given only individual-level data in a way that optimizes a pre-determined loss function (e.g., MAE or MSE)?<br> <br>If you first create an individual-level model optimizing for some loss function and then take the average of the predictions, do you automatically optimize for the same loss function at the group level? As it turns out, while the answer happens to be “yes” in the case of MSE, the answer is a resounding “NO” in the case of MAE!<br> <br>In this post I explain why the knee-jerk method of using the same loss function at the individual level is The Wrong Thing To Do.<br> <br>This is a story about uncovering the real nature of this problem.<br> <br>As part of this exploration I use an interesting theorem by Peter Hall whose proof I found to be somewhat difficult to penetrate. As a service to the community, in <a href="https://medium.com/lumiata/optimizing-individual-level-models-for-group-level-predictions-aaef1b061223">Part 2</a> I will present the backstory for the theorem, and provide a slightly more natural proof than the one he provided in his paper, with all of the crucial details that were left out of the original paper filled in.</p><p>All code for plots seen in this post can be found in <a href="https://github.com/lumiata/tech_blog/blob/master/Individual_Model_Optimization/Individual_Model_Blog_Code.ipynb">this GitHub repo</a>.</p><h3>Example and Assumptions</h3><p>In order to make this exploration easier to follow, I will use a concrete example and fix my assumptions.</p><ul><li><em>Example</em>: A health insurance company wants to estimate the per-person cost of employer groups (i.e., the total cost of the group divided by the number of members) over the span of the next year, where each employer group consists of some number of individual members.</li><li><em>Base Assumptions</em>: You are given training and test data that consist of individual-level data as well as a member-to-group map. The training data has target values represented by each individual’s incurred cost in the next year, while the test data has no target values. The test data and the training data potentially have different groups.</li></ul><p>It only remains to specify what “true values” to compare against at the group level. In order to show why optimizing for the same loss function at the individual level that you do at the group level is misguided, it would be easiest using the following assumption:</p><ul><li><em>Assumption A</em>: For each group, set its true value to be the average target value of its members.</li></ul><p>We will later also consider another assumption that arises more naturally if you allow for membership to vary.</p><h3>Why have an individual model at all?</h3><p>One way to optimize a particular loss function at the group level is simply to create a group-level model that optimizes this loss function, whose features are engineered aggregated individual-level features. But the number of groups is presumably much smaller than the number of individuals, so one would expect that such a model would suffer from high variance. A combined individual-level and group-level approach would be wisest.<br> <br>“Why not use <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">Recurrent Neural Networks</a>? That way you can make a group-level model that uses all the data!”, I hear you cry. Well… That would be using all the individual-level features, but not the unaggregated target values, unless a special loss function is employed. And even then, RNN’s are order-dependent, and group membership is not! So let’s go ahead and call that “experimental”.<br> <br>Either way, your group-level predictions can only gain from doing an individual-level model well. So let’s get to it!</p><h3>Intuition about optimizing for MAE/MSE</h3><p>The bottom line is: optimizing for MSE means you are estimating the mean; optimizing for MAE means you are estimating the median.<br> <br>What does that actually mean? Let <strong><em>Y</em></strong> be the target value, and let <strong><em>X_1,…,X_n </em></strong>be the features. If your feature values are <strong><em>X_1=x_1,…,X_n=x_n</em></strong>, then the target value given those features <strong><em>Y|X_1=x_1,…,X_n=x_n</em></strong> is a random variable, not a constant. In other words, your feature values don’t determine the target. For example, if you are predicting cost, then it is perfectly conceivable that two individuals with the same feature values have different costs; though knowing these feature values does change the distribution of cost.</p><p>If you are optimizing for MSE, then plugging in <strong><em>(x_1,…,x_n)</em></strong> into your model will attempt to predict <strong><em>E(Y|X_1=x_1,…,X_n=x_n)</em></strong>; whereas if you are optimizing for MAE your model will attempt to predict <strong><em>median(Y|X_1=x_1,…,X_n=x_n)</em></strong>.</p><p>Indeed, if <strong><em>f(x_1,…,x_n) </em></strong>is the model’s prediction at these feature values for a machine learning model whose loss function is MSE, then it would attempt to approximate the <strong><em>a</em></strong> that minimizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*uxVAl_7cedK7TKINMt-GcA.png" /></figure><p>This last expression is a parabola in <strong><em>a</em></strong> with global minimum <strong><em>E(Y|X_1=x_1,…,X_n=x_n)</em></strong>.</p><p>Similarly, if <strong><em>f(x_1,…,x_n) </em></strong>is the model’s prediction at these feature values for a machine learning model whose loss function is MAE, then it would attempt to approximate the <strong><em>a</em></strong> that minimizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*UnjgWAnoNwb3jEXqfNhDcw.png" /></figure><p>The <strong><em>a</em></strong> that minimizes this expression is <strong><em>median(Y|X_1=x_1,…,X_n=x_n)</em></strong>. (To see this you have to play around with integrals; it’s an easy but annoying exercise.)</p><p>Technical note: Conditional probability of a random variable given an event only makes sense if the event that you’re conditioning on has positive probability. Attempts to extend the definition to events with zero probability are doomed to be ill-defined unless we specify a limiting procedure; see the <a href="https://en.wikipedia.org/wiki/Borel%E2%80%93Kolmogorov_paradox">Borel–Kolmogorov paradox</a>. If at least one of the <strong><em>X_i</em></strong>’s is continuous, then <strong><em>P(X_1=x_1,…,X_n=x_n)=0</em></strong>, which would imply that <strong><em>Y|X_1=x_1,…,X_n=x_n</em></strong> doesn’t make any sense. (The definition commonly found in undergraduate textbooks for <strong><em>Y|X_1=x_1,…,X_n=x_n</em></strong> is not coordinate invariant. For the more advanced readers: conditioning on sub-sigma-algebras rather than events yields the same issue, since the resulting random variable is unique up to “almost sure equality”, which means probability zero events can be exceptions.) We can and will elegantly avoid this issue by restricting the values of the features to values that a computer can represent. In this way, even “continuous” variables are actually discrete, and everything is well-defined.</p><h3>The problem</h3><p>Fix a group of size <strong><em>m</em></strong>, and let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*iKNWPrA3Y7SEZTxMlwMA4w.png" /></figure><p>be the features of the <strong><em>i</em></strong>-th person. If we are creating an individual-level model that optimizes MSE, then the average of the results is an estimate of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*r234M_QAsBTnOd71PiE1mQ.png" /></figure><p>By the linearity of expectation, this is equal to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*99brRrWLfKhLvyeZ887fPw.png" /></figure><p>Great! In other words, by optimizing MSE at the individual level, you’re optimizing MSE at the group level! <br> <br>Now let’s do the same analysis for MAE. If we are creating an individual-level model that optimizes MAE, then the aggregation of the results is an estimate of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*Halc8LkVhTlQOGDjn3KxrQ.png" /></figure><p>But that is very, very, veeeery far from being</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*oJ4ehRqMWcyqsRQnaYx7iA.png" /></figure><p>Here’s a quick illustration that the median of the sum is very far from being the sum of the medians, even if the random variables are all i.i.d’s:</p><p>In order to set up this example, I will be using a Gamma distribution with scale <strong><em>200</em></strong> and shape <strong><em>1</em></strong>. This is what this distribution looks like:</p><p>(Code for plots seen in this post can be found in <a href="https://github.com/lumiata/tech_blog/blob/master/Individual_Model_Optimization/Individual_Model_Blog_Code.ipynb">this GitHub repo</a>.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0Chxz5HvPsIkQDo0hk0EQ.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p>Now take <strong><em>X_i</em></strong>’s to be i.i.d’s following this distribution. Then here is a comparison of the average of their medians versus the median of their average:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMSkEedlffsXw55v8-xMBA.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p>As you can see, this gap is quite large!</p><h3>Optimizing MSE at the individual level is superior to optimizing MAE at the individual level for group-level MAE</h3><p>If a group is large then it is somewhat reasonable to assume that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*p9wCJirewUjIRPm2l-BCyA.png" /></figure><p>is approximately normal; and the median of a normal distribution is its mean. So if you optimize for MSE at the individual level and then take the average of the predictions, you’ll be approximately estimating the median for large groups! This might seem counter-intuitive at first: optimizing MSE at the individual level is superior to optimizing MAE at the individual level not only for group-level MSE, but also for group-level MAE.</p><p>But how bad should we expect the bias to be for small groups? (As it will turn out, secretly the key is to use estimates of the error of the Central Limit Theorem.)</p><h3>A result by Peter Hall</h3><p>This piqued my interest. So I started looking for results about the median of a sum of i.i.d’s. I found “On the Limiting Behaviour of the Mode and Median of a Sum of Independent Variables” by Peter Hall¹, where he proved the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*2er_PCMOnS8mUX3I4Rd6Uw.png" /></figure><p>(See <a href="https://medium.com/lumiata/optimizing-individual-level-models-for-group-level-predictions-aaef1b061223">Part 2</a> of this post for a deeper understanding of why this theorem is true.) Since the <strong><em>X_i</em></strong>’s are all identically distributed, let’s simply let <strong><em>X := X_1 </em></strong>for notational ease. If we do not assume that the <strong><em>X_i</em></strong>’s have mean <strong><em>0</em></strong> and variance <strong><em>1</em></strong>, a quick back of the envelope computation, reducing to the normalized case, shows that this reduces to the following approximation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*VNuKZvTxYVFF_6BGhpzbug.png" /></figure><p>Notice that this is an asymptotic result! For us to be able to use it in the machine learning context discussed above, we must first make sure that this approximation is reasonable for small <strong><em>n</em></strong>. So let’s do a quick proof-of-concept:</p><p>(Code for plots seen in this post can be found in <a href="https://github.com/lumiata/tech_blog/blob/master/Individual_Model_Optimization/Individual_Model_Blog_Code.ipynb">this GitHub repo</a>.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*6oLh8YJ8asaolI55cTWzxA.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>That’s pretty accurate!</p><h3>Bias estimation in the machine learning setting</h3><p>For each group we would be attempting to estimate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*kgKiCtZub7kf8Hr3BCgovA.png" /></figure><p>for that group. The summands are not i.i.d’s, and so Hall’s result is not directly applicable. To that end, we can try to replace Assumption A with:</p><ul><li><em>Assumption B: </em>For each group, assume that its “true value” is the expected value of the mean of <strong>m</strong> samples, with repetition, of the true values of its members<em>.</em></li></ul><p>(Arguably, Assumption B comes up more often in real life. Often in group level predictions the members don’t stay fixed, but the current members’ target values are indicative of the distribution target values of future members.)<br> <br>Now that the target value is the mean of i.i.d’s (because the sampling is done with repetition), we may employ Hall’s approximation. Fix a group, and let <strong><em>T_1, …, T_m</em></strong> be the sampling, with repetition, mentioned in Assumption B. The <strong><em>T_i</em></strong>’s are now i.i.d’s, and so for the sake of clarity let <strong><em>T:=T_1</em></strong>. We are now faced with the challenge of approximating <strong><em>V(T)</em></strong> and <strong><em>E((T-μ)³)</em></strong> for each group. This can be difficult, given that the groups that we want the most to bias-correct are small groups. <br> <br>One simplistic approach is to estimate <strong><em>V(T)</em></strong> as <strong><em>V(Y)</em></strong>, and estimate <strong><em>E((T-μ)³)</em></strong> as <strong><em>E((Y-E(Y))³)</em></strong>. In turn, estimate <strong><em>V(Y)</em></strong> and <strong><em>E((Y-E(Y))³)</em></strong> by taking the average values over the target values in our data, and denote these estimates as <strong><em>Vˆ </em></strong>and <strong><em>κˆ_3</em></strong> respectively. Whether these estimates work well or not depends on how different the groups are from one another — the more similar they are, the better this bias correction will be. Either way, these approximations are good enough to get a relatively clear picture of how small a group needs to be so that the bias is beyond your level of comfort. Namely, a rough estimate is that if the size of a group is <strong><em>m</em></strong>, then averaging an individual model trained using MSE should have a bias of about</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/56/1*WjQIV8hlvOQlWiXGTDivPA.png" /></figure><p>For groups for which this number is intolerably big, I would suggest extra care: <strong><em>Vˆ </em></strong>and <strong><em>κˆ_3</em></strong> may not be good enough estimates, and may lead to a bad bias correction. I would simply suggest to flag groups of this size as requiring a bias correction, and do more research on the bias correction needed that is informed by the data and the particular application you have in mind. <br> <br>(Notice that while it is tempting to use Bayesian approaches that will allow you to sample from the distributions of the <strong><em>Y|X_1=x_{i, 1},…,X_n=x_{i, n}</em></strong>’s, the vanilla version of these approaches assumes that the <strong><em>Y|X_1=x_{i, 1},…,X_n=x_{i, n}</em></strong>’s are normally distributed. If that were the case, there wouldn’t be any bias to correct for… This holds also for using dropout at prediction time in a neural network, which, <a href="http://proceedings.mlr.press/v48/gal16.pdf">by the work of Yarin Gal and Zoubin Ghahramani</a>², is roughly equivalent to sampling the posterior in an appropriately defined Gaussian process setting — but that setting also assumes normally distributed error.)</p><p>If this post got your interest and you would like to challenge yourself with similar problems, we are hiring! Please check our <a href="https://www.lumiata.com/careers.html">open positions</a>.</p><p>GitHub: <a href="https://github.com/lumiata/tech_blog">https://github.com/lumiata/tech_blog</a></p><p>Visit Lumiata at <a href="http://www.lumiata.com/">www.lumiata.com</a> and follow on Twitter via <a href="http://www.twitter.com/lumiata">@lumiata</a>.</p><p>Find us on LinkedIn: <a href="https://www.linkedin.com/company/lumiata/">www.linkedin.com/company/lumiata</a></p><p><strong><em>Citations</em></strong><em>:</em></p><p><em>1. Hall, P. (1980) On the limiting behaviour of the mode and median of a sum of independent random variables. Ann. Probability 8 419–430.</em></p><p><em>2. Gal, Y. and Ghahramani, Z. (2016) Dropout as a Bayesian approximation: Representing model uncertainty in deep learning.<br>ICML.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=655243e88344" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lumiata/optimizing-individual-level-models-for-group-level-predictions-655243e88344">Optimizing Individual-Level Models for Group-Level Predictions</a> was originally published in <a href="https://medium.com/lumiata">Lumiata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dependency Inversion Principle: an Application in Airflow Pipelines]]></title>
            <link>https://medium.com/lumiata/the-dependency-inversion-principle-an-application-in-airflow-pipelines-8f8ffbd2d274?source=rss----322e223ce83c---4</link>
            <guid isPermaLink="false">https://medium.com/p/8f8ffbd2d274</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Lumiata]]></dc:creator>
            <pubDate>Thu, 25 Apr 2019 19:41:07 GMT</pubDate>
            <atom:updated>2019-04-25T19:50:24.267Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Renzo Frigato, Data Engineer</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZzdXDM2oMzcA2GUNZBlPA.png" /></figure><p>Pipeline jungles are a common source of technical debt in advanced Machine Learning systems, and at Lumiata, with our fast iterations on model evolution, we were not exempt from this curse.</p><p>In this blog post, I want to share what we did at Lumiata and why it is important in this relatively new field to try to follow good engineering design principles. Our example will focus on how the Dependency Inversion Principle could be applied to ML Pipelines to control technical debt. If you want to go right into the code, this is the <a href="https://github.com/lumiata/tech_blog/tree/master/Airflow_DIP">Github repository</a> we created to show a simplified version of our Airflow infrastructure.</p><p><strong>Fast Iterations</strong></p><p>The Lumiata pipeline that creates features and generates predictions is for the most part owned and managed independently by the Data Science team. This allows them to quickly experiment and iterate over parameter tuning, new features and new models.</p><p>This supports the principle that Lumiata’s researchers should have a high degree of freedom. However, when experimenting and iterating, many problems could occur: experiments might not be reproducible, code is untested and has bugs when it is not run by the person who developed it, and so on.</p><p>In particular, as the Lumiata Data Science team was growing fast, it was hard to unify contributions from multiple people and run the full prediction pipeline in an automated and reproducible way. There were remarkable efforts in the Data Science team to have a unique configuration that would handle data and model management within the pipeline. But was that enough to get out of the pipeline jungle debt?</p><p><strong>Welcome Airflow</strong></p><p>Very early, when the Data Science team was still relatively small, we chose Airflow as the tool to orchestrate our pipelines. With its Sensors, Actions, Tasks, Schedulers, it looked like the Swiss Army Knife we were looking for. We compared it to other pipeline orchestration tools, but we found Airflow superior:</p><ul><li>Operators, the Airflow work unit, are very extensible</li><li>DAG are easy to build and define</li><li>the UI helps in visualizing and debugging jobs</li><li>the open source community and user base is very rich and active</li></ul><p>However, any tool, especially if it looks like an Army Knife, can get you in trouble if used incorrectly: you don’t want to use the bottle opener for cutting!</p><p>With Airflow, it’s very easy to add any type of computational job to your pipeline: a simple bash script, a spark job on your local machine or on your cloud provider, a data transfer and many more. We realized that this could lead to having a very wild pipeline, and even if Airflow helps in visualizing how the different pieces are connected together, that is not enough to maintain strict engineering principles.</p><p>As stated in <a href="https://storage.googleapis.com/pub-tools-public-publication-data/pdf/43146.pdf">this Google paper</a>¹: “Managing these pipelines, detecting errors and recovering from failures are all difficult and costly. Testing such pipelines often requires expensive end-to-end integration tests.” As described <a href="https://www.oreilly.com/library/view/thoughtful-machine-learning/9781491924129/ch01.html">here</a>², pipeline jungles could be due to a violation of one of the SOLID Engineering principles, Dependency Inversion.</p><p><strong>The Dependency Inversion Principle (DIP)</strong></p><p>The definition of the DIP from its <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">Wikipedia page</a> could look quite obscure:<br>A. High-level modules should not depend on low-level modules. Both should depend on abstractions.<br>B. Abstractions should not depend on details. Details should depend on abstractions.</p><p>A simple real life example could be one in which the high-level module is a car and the low-level module its engine. The DIP says that the car shouldn’t depend on a particular engine model. There should be an abstract definition or agreement of how an engine would be plugged into the car. This way there is no need to change the design of a car to add a particular engine or vice versa to change the internal details of an engine to fit some car model.</p><p>Implementing the DIP allows the development of a new car or engine without having to think about the integration with the other. As long as the engine-car abstract requirements are respected, the two components can be developed independently.</p><p><strong>Inverting the Dependency in ML Pipelines</strong></p><p>In object-oriented programming, the DIP could have multiple <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle#Implementations">implementations</a>: for example, It is possible to abstract the low-level module into an interface to define how the high-level module should interact with the low-level module. The low-level module will need to respect this interface to be called successfully by the high-level module.</p><p>Our ML pipelines infrastructure, of which you can find a simplified version in this <a href="https://github.com/lumiata/tech_blog/tree/master/Airflow_DIP">Github repository</a>, follows a similar approach: pipelines, the high-level modules, would depend on abstractions of the steps, the low-level modules, that need to get executed.</p><p>In more details we have that:</p><ul><li>Each step is abstracted as a script reading one or more input datasets and writing to one or more output datasets. To generate a representation of this abstraction, each step has a “dry-run” mode that returns input and output storage paths.</li><li>Each pipeline is a DAG (Directed Acyclic Graph) of low-level steps in which links correspond to the step direct dependencies.</li></ul><p>In this way the details of each step are independent of the full pipeline, as long as the step receives its inputs and produces its outputs. Abstracting each step allows us, as a bonus, to compute the DAG dependencies and generate the pipeline automatically, as each step depends directly only on the steps that produce its required inputs as shown in the Airflow diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2VLeEXYon81GqwCh" /></figure><p><strong>Three Easy Pieces</strong></p><p>In the Github repository, we created three examples to demonstrate the DIP Airflow implementation.</p><p>The first one is just a <a href="https://github.com/lumiata/tech_blog/blob/master/Airflow_DIP/dags/test_pipeline.py">toy example</a> with two scripts: one creating a file (“create”) and another copying it (“copy”). The only dependency we have is from the “create” to the “copy” step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xHSGyHHn1JyPxhli" /></figure><p><a href="https://github.com/lumiata/tech_blog/blob/master/Airflow_DIP/dags/embedding_dag.py">The second example</a> shows how we can leverage the infrastructure in a more sophisticated way: a sentiment analysis model using word embeddings, derived from this <a href="https://developers.google.com/machine-learning/crash-course/embeddings/programming-exercise">Google tutorial</a>.</p><p>There are 4 tasks in the basic DAG:</p><ul><li>Load training and test data</li><li>Get informative terms for sentiment analysis</li><li>Train the embedding on sentiment analysis</li><li>Evaluate the performance of the embedding</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*24SuGBlCcv_738ZN" /></figure><p><a href="https://github.com/lumiata/tech_blog/blob/master/Airflow_DIP/dags/embedding_dag_extended.py">The third example</a> extends the previous one, comparing the performance of multiple embeddings with different hyperparameters and informative term sets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z7zU4m9l0wnrQvhx" /></figure><p>We have trained 4 different models, tuning on embedding dimension and the informative terms (default has 50 terms, all_informative_terms is the full vocabulary of the documents with 30,716 terms).</p><p>A final task compares the 4 models on the test set and returns the model with the best accuracy.</p><p><strong>Summary</strong></p><p>A couple of takeaways we can get from this are the following:</p><ul><li>Machine learning pipelines are hard to maintain. This is well known and documented in <a href="https://storage.googleapis.com/pub-tools-public-publication-data/pdf/43146.pdf">this paper</a>¹.</li><li>Design principles look very abstract, but are very powerful when applied concretely to Software Systems. A simple example we made is on how the DIP applies to adapting engines to cars, but it does have countless other applications.</li><li>The DIP could also be used in Machine Learning Systems to avoid pipeline jungle issues. Check our <a href="https://github.com/lumiata/tech_blog/tree/master/Airflow_DIP">Github repo</a> to have a concrete example, inspired by our Airflow infrastructure.</li></ul><p>If this post got your interest and you would like to challenge yourself with similar problems, we are hiring! Please check our <a href="https://www.lumiata.com/careers.html">open positions</a>.</p><p>GitHub: <a href="https://github.com/lumiata/tech_blog">https://github.com/lumiata/tech_blog</a></p><p>Visit Lumiata at <a href="http://www.lumiata.com/">www.lumiata.com</a> and follow on Twitter via <a href="http://www.twitter.com/lumiata">@lumiata</a>.</p><p>Find us on LinkedIn: <a href="https://www.linkedin.com/company/lumiata/">www.linkedin.com/company/lumiata</a></p><p><strong><em>Citations</em></strong><em>:</em></p><p><em>1. D. Sculley, Gary Holt, Daniel Golovin, Eugene Davydov, Todd Phillips, Dietmar Ebner, Vinay Chaudhary and Michael Young: “Machine Learning: The High Interest Credit Card of Technical Debt”, SE4ML: Software Engineering for Machine Learning (NIPS 2014 Workshop)</em></p><p><em>2. Matthew Kirk: “Probably Approximately Correct Software”, Thoughtful Machine Learning with Python, Chapter 1</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8ffbd2d274" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lumiata/the-dependency-inversion-principle-an-application-in-airflow-pipelines-8f8ffbd2d274">The Dependency Inversion Principle: an Application in Airflow Pipelines</a> was originally published in <a href="https://medium.com/lumiata">Lumiata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-Validation for Imbalanced Datasets]]></title>
            <link>https://medium.com/lumiata/cross-validation-for-imbalanced-datasets-9d203ba47e8?source=rss----322e223ce83c---4</link>
            <guid isPermaLink="false">https://medium.com/p/9d203ba47e8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[healthcare-technology]]></category>
            <dc:creator><![CDATA[Lumiata]]></dc:creator>
            <pubDate>Tue, 05 Mar 2019 15:59:04 GMT</pubDate>
            <atom:updated>2019-03-05T17:21:53.909Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Anusha Mohan, Data Scientist</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UaXqpaTjTncyKd-rk7eAGw.png" /></figure><p>Cross-validation is like a sharp knife. It cuts great, more can be done with less effort, but if one is not careful, it could injure the user. This blog post details a common mistake which data scientists could make while leveraging cross-validation to improve the performance of a model trained on an imbalanced dataset.</p><p><strong>Why Use Cross-Validation?<br></strong>Cross-validation is a popular technique that data scientists use to validate the stability and generalizability of a machine learning model. In <em>K</em>-fold cross-validation, the data is partitioned into <em>K</em> subsets. We then iteratively train on each set of (<em>K-1</em>) subsets and validate on the remaining subset, allowing each data point to be used as training data (<em>K-1</em>) times and validation data 1 time. The model score is then computed as the average validation score across all <em>K</em> trials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3w1w9p5U14300MqK" /></figure><p>This helps a data scientist validate that their model is not overfitting and will generalize to unseen data, as the model score is an average across multiple validation scores, not just a single iteration. A data scientist must ensure that the model is learning the patterns in the data and not fitting to the noise. In other words, the model should be low on bias and variance.</p><p><strong>Imbalanced Datasets</strong><br>An imbalanced dataset is one where a positive signal occurs in only a small proportion of the total dataset. Often, the minority class in such a dataset will carry an extreme risk if it is not properly detected. For example, fraudulent credit card transactions account for only 1–2% of all transactions, but the risk associated with not catching fraudulent activity is very high.</p><p>There are several disadvantages when building a model with imbalanced data:</p><ul><li><strong>Bias </strong>— The classification output is biased as the classifiers are more sensitive to detecting the majority class and less sensitive to the minority class.</li><li><strong>Optimization Metrics </strong>— Normal optimization metrics, such as accuracy, may not be indicative of true performance, especially when there is increased risk associated with false-negative or false-positive predictions.</li><li><strong>Difficulty Getting More Data </strong>— Datasets are often imbalanced because of real world factors, as with the credit card example mentioned above. Namely, the minority class is simply a rare event, which makes finding data that would hopefully balance the class distribution of the dataset very difficult.</li></ul><p>Because of these disadvantages, there can be caveats when trying to leverage cross-validation with an imbalanced dataset. These caveats are perhaps best illustrated with an example.</p><p><strong>An Illustrated Example<br></strong>The dataset I have picked is a breast cancer prediction dataset from the <a href="https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Original%29">UCI machine learning repository</a>. This dataset consists of a sample of patients who have been diagnosed with either a malignant tumor or a benign tumor, and 9 features that each contain information on the detected tumor.</p><p>Further, I made this dataset severely imbalanced by keeping only a sample of positive instances (malignant tumor) from the original dataset. This pre-processed dataset contains 456 patients, where 2.6% have a malignant tumor (12 patients) and 97.3% have a benign tumor (444 patients). Finally, I randomly sampled 30% of the pre-processed dataset to be held out as a pure test set so that I could evaluate the model against truly unseen data.</p><p>All code and data can be found at <a href="https://github.com/lumiata/tech_blog/tree/master/Cross_Validation_Imbalanced_Datasets">this GitHub repository</a>.</p><p><strong>Model Optimization Metrics</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qp1wvrLiNHxqwOMu" /></figure><p>When choosing the correct optimization metric, we must consider the risks associated with the results of our predictions. For example, accuracy would not be the right metric to evaluate a model trained on this dataset. A naive model would classify all data in a test set with the majority class label, which in our case would be label 0 — benign tumor. The accuracy of this naive model would be very high, but every patient with a malignant tumor would be incorrectly diagnosed. In healthcare, the worst case scenario is a false-negative diagnosis. We want to identify as many breast cancer patients as possible to provide the care and treatment they deserve. Therefore this naive implementation would be unacceptable.</p><p>Since we want to penalize our model as much as possible for false-negative predictions, recall is the right metric to evaluate our model.</p><p><strong>Baseline Model<br></strong>When a random forest model was trained on this imbalanced dataset and applied to the test set, the accuracy obtained was 97%, with precision and recall scores 0%. We would like to improve upon this baseline test-set recall score, as our objective is to identify as many patients with malignant tumors as possible.</p><p><strong>How Do We Improve Performance?<br></strong>The recall and precision scores were low as there was not enough data for the model to pick up the signal for malignant tumors. No observations in the test set were classified as 1’s, which resulted in 0 overall positives (true and false positives) and 4 false-negatives.</p><p>One thing we can do to improve our performance is to balance the dataset. We have two options to do this:</p><ul><li><strong>Undersampling the majority class </strong>— Undersampling involves reducing the number of samples from the majority class by randomly selecting a subset of data points from that class to use for training. One of the major disadvantages of performing undersampling is that useful data or information might be thrown away.</li><li><strong>Oversampling the minority class </strong>— Oversampling involves increasing the number of the samples from the minority class in the training dataset. The common method is to add copies of data points from the minority class, which amplifies the decision region resulting in the improvement of evaluation metrics. The main disadvantage of this method is that it might result in overfitting. Another method to oversample, which reduces this issue, is SMOTE (Synthetic Minority Oversampling Technique). SMOTE is an enhanced sampling method that creates synthetic samples based on the nearest neighbors of feature values in the minority class.</li></ul><p>Since our sample size is already small, we will use oversampling to try to improve test set performance.</p><p><strong>Cross-Validation on Oversampled Data (using SMOTE)<br></strong>The minority class in the training set was oversampled to a class ratio of 1 to improve the quality of model predictions by enhancing the decision boundary. 5-fold cross-validation was then performed using this balanced training set in order to get an estimate of test set performance. Taking the average recall score across all 5 iterations, we get a model score of 100%!</p><p>100% cross-validated recall score looks pretty great without any feature engineering or hyper-parameter tuning. The only difference was the minority class in the dataset was oversampled to a ratio of 1. It is almost too good to be true…</p><p>And we are right. When a model trained with the balanced training set is applied to the test set, the test recall score is only 50%.</p><p>So what happened? Cross-validation was supposed to represent test set performance, but it didn’t work in this case. Did my model overfit?</p><p>First we can check the feature distributions in the training set. When we plot the kernel densities, we see that only 2 out of 9 features show high discriminative power between class 0 and class 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*GckbMTrTQDznyngaARtU2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*FSgCMimLsiLbCIJsTbmBDQ.png" /></figure><p>This makes us even more suspicious of our cross-validation process, as it is hard to overfit as heavily as indicated when only two features have high predictive power.</p><p>The real reason our test recall score was far less than the cross-validated score was because of information bleed from the validation set to the training set in each iteration. Let’s think for a moment about how the oversampling was done. I split the data first into training and test, followed by oversampling the minority class in the training data using SMOTE, then passing that balanced dataset through cross-validation. During cross-validation, the already oversampled training data was further divided into train and validation sets. This causes two problems:</p><ol><li>Synthetic observations could end up in both the training and validation sets during the same iteration. A sophisticated model architecture like Random Forest will be able to recognize these feature values are from the same distribution and predict accurately on validation, thereby inflating recall scores.</li><li>The model training and application process are not representative of the testing environment. In each iteration of cross-validation, the model is both trained and applied on balanced datasets, while in reality it will be trained on a balanced dataset and applied on an imbalanced dataset.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3mKCvNHrp_EcGCWp1tqXg.png" /></figure><p>The ideal way to conduct this experiment would be to perform oversampling of the training set in each cross-validation iteration, not before beginning the process. This prevents the data leakage from the validation set to the training set during cross-validation, and reflects how the model trained on a balanced training set would perform when applied to an imbalanced, unseen test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Owas_uyBN9U7C6UOk9xulg.png" /></figure><p>Now that we can rely on our cross-validation process to be indicative of test set performance, we can continue to try to improve model performance by feature engineering and hyper-parameter tuning.</p><p><strong>Conclusion<br></strong>One of the main challenges data scientists face is working with imbalanced datasets, where predicting the minority class is often difficult. Techniques like oversampling/SMOTE help to improve model performance trained on these datasets, but in order to ensure cross-validation is helping us produce the best model that will generalize to unseen data, it is essential to follow these guidelines:</p><ul><li>In each iteration exclude some data for validation. The excluded data should not be used for feature selection, oversampling and model building.</li><li>Oversample the minority class only in the training set without the data already excluded for validation.</li><li>Repeat <em>K</em> times, where <em>K </em>is number of folds.</li></ul><p>This will make sure each iteration of cross-validation is representative of the real-world environment, in both training a model on balanced data and applying to an imbalanced validation set.</p><p>GitHub: <a href="https://github.com/lumiata/tech_blog">https://github.com/lumiata/tech_blog</a></p><p>Visit Lumiata at <a href="http://www.lumiata.com/">www.lumiata.com</a> and follow on Twitter via <a href="http://www.twitter.com/lumiata">@lumiata</a>.<br>Find us on LinkedIn: <a href="https://www.linkedin.com/company/lumiata/">www.linkedin.com/company/lumiata</a></p><p><strong><em>Citations</em></strong><em>:<br>1. O. L. Mangasarian and W. H. Wolberg: “Cancer diagnosis via linear programming”, SIAM News, Volume 23, Number 5, September 1990, pp 1 &amp; 18.</em></p><p><em>2. William H. Wolberg and O.L. Mangasarian: “Multisurface method of pattern separation for medical diagnosis applied to breast cytology”, Proceedings of the National Academy of Sciences, U.S.A., Volume 87, December 1990, pp 9193–9196.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d203ba47e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lumiata/cross-validation-for-imbalanced-datasets-9d203ba47e8">Cross-Validation for Imbalanced Datasets</a> was originally published in <a href="https://medium.com/lumiata">Lumiata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Data Science Advantage for Healthcare]]></title>
            <link>https://medium.com/lumiata/the-data-science-advantage-for-healthcare-1679907f26f1?source=rss----322e223ce83c---4</link>
            <guid isPermaLink="false">https://medium.com/p/1679907f26f1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[healthcare]]></category>
            <dc:creator><![CDATA[Lumiata]]></dc:creator>
            <pubDate>Wed, 13 Feb 2019 15:23:27 GMT</pubDate>
            <atom:updated>2019-04-25T13:56:59.878Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Charles Greenberg, Senior Data Scientist</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLRqyZlQdu_kkyoQolWB7A.png" /></figure><p>A number of industries are effectively leveraging data science to realize greater efficiency and gain a number of benefits. When it comes to the healthcare industry, here are three advantages of using data science approaches:</p><p><strong>1. Reliability, Verifiability, and Openness to Experiments</strong><br>Much of the healthcare industry relies on the knowledge and experience of clinicians, administrators, and underwriters. Along with the insights and creativity of people, there is also the possibility of human error and inconsistency. Data-based approaches can be built to produce similar results under similar conditions, reliably, and importantly can be tested on millions of patients to verify performance — this also allows a fast cycle of experimenting with new methods.</p><p><strong>2. Models Reveal Biases</strong><br>Data science models are designed to identify complex patterns that can predict health outcomes or cost with minimal human intervention. In addition to improving predictions, such models can illuminate how traditional approaches might be biased. Are care programs selectively benefitting certain population groups better than others? Are certain patients not being reached? These questions can be as important as overall program effectiveness.</p><p><strong>3. Predictions Often Improve with More Data</strong><br>Perhaps the most exciting benefit of using machine learning-based models is that they can improve with more data, assuming the model has enough free parameters to discover new patterns and that the new data is sufficiently different from previous datasets. Much of the work in data science is in tuning models such that the number of features is high enough to capture important effects in the data, without introducing so many that the model overfits to the training set. In our experience, after model tuning, adding millions of new medical health records has significantly improved our predictive performance.</p><p>Stay tuned, as we take a closer look at each of these advantages and explore how healthcare can benefit from data science.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1679907f26f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lumiata/the-data-science-advantage-for-healthcare-1679907f26f1">The Data Science Advantage for Healthcare</a> was originally published in <a href="https://medium.com/lumiata">Lumiata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lumiata’s Tech Blog: A CTO’s First 30 Days (1 of 3)]]></title>
            <link>https://medium.com/lumiata/lumiatas-tech-blog-a-cto-s-first-30-days-1-of-3-391f583e607a?source=rss----322e223ce83c---4</link>
            <guid isPermaLink="false">https://medium.com/p/391f583e607a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Lumiata]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 20:02:28 GMT</pubDate>
            <atom:updated>2019-04-25T13:53:00.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tech Blog: A CTO’s First 30 Days</h3><p><em>Miguel Alvarado, Chief Technology Officer</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPC_Hlt53hfq2OT6_phgaw.png" /></figure><h3>My name is Miguel Alvarado; I’m Lumiata’s new CTO. I joined Lumiata on October 1st, only a little over 35 days ago. It has only been just over a month and Lumiata already feels like a second home.</h3><p>This is my first blog post, and with this post, I would like to introduce the tech side of the Lumiata blog. From this post on, our data science (machine learning) and engineering teams will be posting every 2 to 3 weeks on various topics related to the work we’re doing. Things are very action packed here at Lumiata. Some of the things we’re doing are very challenging and interesting. We’re hoping to engage with the community at many different levels by regularly presenting what goes on here. The goal is to inform and inspire, as well as being informed and getting inspired ourselves.</p><p>​Moving on to my blog post topic — “CTO’s First 30 Days.” This is the first part of a three-part series. I will be posting again after 60 and 90 days. The series will attempt to depict my experience in a way that is hopefully informative to others going through similar experiences.</p><h3><strong>Why Lumiata?</strong></h3><p>Before diving deep into my first 30 days, I would like to describe why I joined Lumiata, to set better context around my entire experience. In short, I wanted to be part of a technology organization that had big ambitions and was trying to change the world for the better. Prior to Lumiata, I had been in entertainment for some time, and while every single experience I had was interesting, challenging and exciting, I wanted to be part of something that was attempting to change fundamental aspects of our society. I also wanted to be part of something that was building software where Big Data and Machine Learning were at the heart of the product.</p><p>I’ve long thought that two of the most important pillars of society are education and healthcare. Recently, I realized that I wanted to be at a company helping to advance the needs within those pillars. Lumiata’s mission to “make healthcare smarter” resonated incredibly well with my ambitions. Often, companies with big missions like that have short term goals that are scattered and unrealistic — that was not the case with Lumiata. I found that Dilawar Syed (CEO) had done a great job in the last 6 months to focus the company. Further, the mid-term goals were attainable while still pursuing the long-term ambitions that could change health care in fundamental ways.</p><p>Lumiata’s initial goal is to provide risk and cost predictions for patients and populations to help optimize major health plans. Between reading academic papers on the topics that Lumiata shared with me and learning about the projects that Lumiata has been working on over the last few months, the team gave me very strong evidence that there is something special here. They showed me that there is a true problem area to pursue, but also that Lumiata has already been laying the groundwork in terms of providing robust Predictive Analytics solutions, built with Machine Learning.</p><p>What I saw was an organization that had found a very specific set of problems to solve, and had a proven way to do so with Machine Learning. I saw an organization ready to build software that would “industrialize” the proven predictive analytics capabilities it already had found a market-fit for. The Machine Learning knowhow was there; it was now a matter of applying industry software development “know-how” to scale it and industrialize it. This latter part is something that I felt I could personally help with.</p><p>This seemed like an ideal opportunity for me. An opportunity where I could combine software, big data and machine learning “know-how,” for a space that represents one of the core pillars in any society, that space being healthcare. Not to mention that the company already has a particular edge that customers are willing to pay for. That is ultimately why I joined Lumiata, and now my mission is that of the company — “make healthcare smarter.”</p><h3>What did I learn in that first week?</h3><p>First of all, it took me over a week to talk to everyone. I scheduled meetings very tight next to each other so that I could get this done in the shortest amount of time possible, and it was very energy consuming.</p><p>One of the most important things I got from the meetings is that the morale is very high, everyone is incredibly smart, highly educated (many PhDs), and incredibly passionate about what we’re doing. Everyone really wants to make a dent in the world of healthcare. I did not hear unproductive complaints, nobody talked negatively about anybody that works currently at Lumiata, and everyone had a legitimate willingness to making things better. I was pleasantly surprised by how positive everyone was. I say that I was surprised, just because the status quo is that most organizations have issues here and there, especially when it comes to morale, and I did not find any red or even orange flags!</p><p>I did find that there is a lot of room for “better,” and these were my biggest takeaways:</p><p>1. Lumiata’s world (healthcare) is complex. So, better documentation is needed.<br>2. The ML side could inherit some aspects from the software world while keeping its highly experimental nature.<br>3. Too much time is spent with datacenter matters. Yes, Lumiata is not in a cloud provider (yet).<br>4. I got reminded that Security and Privacy are hard if you’re in healthcare, and we can’t miss a beat.<br>5. For every project, there is a heavy “integration” step at the end of it, bringing together the effort of many scientists and engineers.<br>6. We could use more test automation, and there are recent advances here that we can adopt.<br>7. There are times where there are data bugs, not just code bugs.<br>8. It is hard to understand the lineage from data sources to models to predictions.<br>9. Inconsistency with development process and people sometimes not knowing what is going on and when to expect things.<br>10. Lead time is currently very long.</p><h3>What to do? Project Carabela.</h3><p>One of the most important things I have learned in my career is to not overthink things or else you can fall into “analysis paralysis.” I realized that it was going to be key to make some decisions so that we can start making progress as soon as possible in some of the identified areas. There were some ‘low hanging fruit’ things that I made decisions on very fast… Visit our blog to read about the major refactor of our environment (codenamed ‘Project Carabela’): <a href="https://www.lumiata.com/news/introducing-lumiatas-tech-blog-ctos-first-30-days">https://www.lumiata.com/news/introducing-lumiatas-tech-blog-ctos-first-30-days</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=391f583e607a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lumiata/lumiatas-tech-blog-a-cto-s-first-30-days-1-of-3-391f583e607a">Lumiata’s Tech Blog: A CTO’s First 30 Days (1 of 3)</a> was originally published in <a href="https://medium.com/lumiata">Lumiata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Healthcare Costs: Avoiding Pitfalls with Patient Cost Predictions]]></title>
            <link>https://medium.com/lumiata/healthcare-costs-avoiding-pitfalls-with-patient-cost-predictions-87d849eee9d5?source=rss----322e223ce83c---4</link>
            <guid isPermaLink="false">https://medium.com/p/87d849eee9d5</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Lumiata]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 20:01:51 GMT</pubDate>
            <atom:updated>2019-04-25T13:46:34.008Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Matt McClelland, Data Scientist</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUnRkJ_rA0RDKSQN-5Q1Xg.png" /></figure><p>Plans in healthcare have historically been priced in bulk, which is done to alleviate risk to individuals by putting money into pools. When predicting for this cost, it is typical to use aggregated features such as historical account cost and account demographics. <br>​<br>Growing capabilities to handle big and unstructured data as well as advances in modeling make individual-level predictions increasingly feasible and an attractive alternative to modeling at the aggregate level. Individual-level models can utilize medical data including lab values, diagnoses, prescriptions, or even doctors’ notes to predict the cost of a single patient. However, there are risks in naively aggregating individual-level predictions to account-level predictions without due considerations to potentially exaggerating model error.</p><p><strong>​Advantages of Individual Predictions</strong><br>An account-level view is an extreme simplification of a very complex cost relationship between patient health, hospitals, and providers. A more detailed look at patient medical claims, for example, could provide more accurate predictions of cost. Claims data consist of thousands of possible medical codes, each of which represents an event in a patient’s medical history. Patient-level models can discover complex interactions between these codes which are predictive of cost. For this purpose, Lumiata has built a robust patient tagging process capable of translating claims data into ingestible patient timelines. We leverage this in three ways:</p><ul><li><strong>Depth</strong> — Patient timelines are often independent of group timelines. A patient-level view allows for flexible aggregation, which is not restricted by the lifetime of the group. This helps with the cold start problem (what to predict for new groups) and enables us to use the full patient timeline.</li><li><strong>Reactivity</strong> — It is known that patients with specific diseases can represent a disproportionate cost of medical care, but these patients are obscured at the group level. Identifying high cost disease states before they drive up costs can be a huge advantage.</li><li><strong>Data, Data, Data</strong> — A patient-level view allows use of more features, more complex models (e.g., deep learning and boosted trees), and more training examples. Due to aggregation group-level models are limited to only a few thousand training examples, reducing the ability to detect complex patterns.</li></ul><p><strong>​Concerns with Individual Predictions</strong><br>But with great power comes great responsibility. Approaching cost prediction at the patient-level introduces complexity that must be tightly controlled. There are several characteristics of healthcare cost that makes this especially relevant:</p><ul><li><strong>Extreme Outliers</strong> — High cost patients can exert disproportionate weight in cost functions.</li><li><strong>Sparse Data</strong> — The high dimensionality of the feature space implies that most features are null most of the time.</li><li><strong>Noisy Signals</strong> — Even for routine medical practice, diagnosis, treatment, and cost can vary from doctor to doctor and patient to patient.</li></ul><p>More complex models (with low bias, see below) can adapt to these characteristics, but risk over-fitting (high variance). Below I’ll review the bias-variance tradeoff and how to use hyperparameters to control model complexity.</p><p><strong>​Bias-Variance Review</strong><br>For a more in-depth review of the bias-variance trade-off, I would suggest David Dalpiaz’s great online resource, <a href="https://daviddalpiaz.github.io/r4sl/biasvariance-tradeoff.html">R for Statistical Learning</a>. The examples I am providing here are adapted from this resource.</p><p>Assume some random vector (<strong>X,Y</strong>) with values in <strong>ℝᵖ×ℝ </strong>and define <strong>f(x)</strong> for <strong>E(Y|X=x)</strong>. Notice that this form of <strong>f(x) </strong>minimizes the expected squared error, representing the best possible prediction we can make. Since <strong>f(x) </strong>is unknown, we approximate it with <strong>f̂(x)</strong> using some training data <strong>D</strong>, and our favorite machine learning algorithm. Note that when I refer to “algorithm”, I am referencing the method used to learn a specific model.</p><p>Using these definitions and conditioning on <strong>X</strong>, observe that the expected value of prediction can be expanded into two separate components <strong>reducible error</strong> and <strong>irreducible error</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*kAJqNOaE5OJ1AlM-.png" /></figure><p>Reducible error is what we strive to *<em>drumroll</em>* reduce as it is a measure of our approximation of <strong>f(x) </strong>with <strong>f̂(x)</strong>. Irreducible error, which is equal to <strong>V(Y|X=x)</strong>, on the other hand, is simply not a learnable function of <strong>X</strong> and should be recognized as noise. From reducible error, we can further derive <strong>bias</strong> and <strong>variance</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*ZnvlNET_3_Ug42i3.png" /></figure><p>Bias is a measure of the deviation of the expected form of our models and <strong>f(x)</strong>. The word “expected” means that the model is a function of the underlying data that an algorithm is trained on, which is it itself a random variable. Variance on the other hand measures the expected deviance of <strong>f̂(x)</strong> from the expected fit of <strong>f̂(x)</strong>.<br>​<br>It is always possible to have completely unbiased models with high variance by perfectly fitting the training data — but it would change significantly depending on the input, and so would generalize poorly (i.e., overfit). In order to lower the variance, the model must make certain generalizing <em>assumptions</em>. The more such assumptions it makes, the lower the variance — but at the cost of bias, if our assumptions turn out to be incorrect. For example, if we fit linear regression for expected true values that are not linear in the features, then that’s a bad assumption that leads to bias; it does, however, decrease variance.</p><p><strong>​Visualizing Bias and Variance</strong><br>To demonstrate the bias-variance tradeoff, I repeatedly fit polynomial models to simulated data (normally distributed random points with mean <strong>x²</strong>) as defined in the following code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*zZ6gMH4OM12UmRsg.png" /></figure><p>Below I used 3 algorithms representing a biased algorithm (<strong>k=1</strong>), an unbiased and low variance algorithm (<strong>k=2</strong>), and an unbiased high-variance algorithm (<strong>k=10</strong>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*Xd69lt6SzvbCmdAj.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/0*v2APT3dB6y_SIbQH" /></figure><p>In the above plot <strong>f̂₁</strong> seems quite consistent with varying training data, even if it is missing the true form of <strong>f</strong> (defined above as <strong>x²</strong>). In contrast observe that <strong>f̂₁₀</strong>, while following the trend of the data, seems to vary a large deal from simulation to simulation.</p><p>​Below I repeat the above simulations 100 times, and for each model calculate <strong>f(x)−f̂k(x)</strong>, where <strong>x=0.8</strong>. Notice that the center of each resulting distribution indicates the bias introduced by the algorithm and the width of distribution indicates the variance of the fit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w7BsLwgM4DIXJjft.png" /></figure><p>There are several things to notice here: for the algorithm with bias, <strong>f̂₁</strong>, we see that the distribution of fit is not centered around <strong>0</strong>; however, it is relatively tight. As <strong>k</strong> increases, bias is reduced but the dispersion of fit also increases. Additionally, notice that even for the well-conditioned algorithm, there is inherent randomness in the fitting process.</p><p><strong>​<br>​The Risks of Aggregation</strong><br>What happens to error with aggregated models? A naive approach to predictions at the group level is to train a patient-level model, and then for each group set the aggregate prediction to the sum of patient predictions for every group member. The question then arises: does this procedure optimize for the group level error? As it turns out, the answer is no!</p><p>To see this, consider the following heuristic. Let a group of size N consist of individuals with feature values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*10-rC8jxtTXfAuAfxu-AdQ.png" /></figure><p>and true costs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*A1-MlGTD_zm-fl0UEeG7oA.png" /></figure><p>Furthermore, we assume that costs are independent across patients and all 𝑥 are equal (If naive aggregation fails with even this assumption, there is no hope in general.) Then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*-Xm9hGFft8R8AU0mOLoirw.png" /></figure><p>where ​<strong>f(x):=E(Y|X=x),</strong> and the <strong>εᵢ</strong>’s are independent identically distributed variables with mean <strong>0</strong>.</p><p>​As before, the patient-level error for <strong>X=x</strong> has a decomposition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*d4Xq1HaAB0_t9_DQvONLCg.png" /></figure><p>where <strong>V(εᵢ) = σ²</strong> for all <strong>i</strong>.</p><p>Let’s look now at the group-level error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*51u9mlctM_5rTY9h.png" /></figure><p>because of the linearity of expectation, and that fact that variance of a sum of independent variables is the sum of the variances of those variables.<br>​<br>Thus the error of the aggregation is <em>not</em> a linear multiple of the sum of the errors of the individual predictions! At the aggregated level, reducible error is multiplied by the square of <strong>N</strong> (in fact, both bias and variance are multiplied by the square of <strong>N</strong>), but the irreducible error is multiplied only by <strong>N</strong>.</p><p><strong>​Discussion</strong><br>​In the above analysis we can notice, somewhat trivially, that bias compounds. Someone without much experience in data science might think that we may underpredict a little here and overpredict a little there…but hey! it all adds up to a null sum! This brings to mind the old joke “We lose money on every sale, but make it up on volume!” That is, when you add up many small losses you get a big loss!<br>​<br>In healthcare, we are even more likely to compound our model error because accounts tend to be more homogenous than the general population; that is, members within accounts are more similar to one another than they are to members in the general population. For example, consider a logging company (the most accident prone job in America). In this case members have higher expected cost than the general population. Since our predicted cost <strong>f̂(x)</strong> is less than the expected cost <strong>f(x)</strong>, we have introduced bias. Furthermore, since we are predicting in aggregate for every member of that account, we will be compounding our bias for each prediction! We can generalize this to any account that has characteristics that are not reflected in the general population.</p><p><strong>​Making Healthcare Smarter</strong><br>Optimizing patient predictions for aggregate performance is an area of active research at Lumiata. Below are some strategies we employ when predicting at the group-level:</p><ul><li>Optimize patient predictions for group level performance.</li><li>Evaluate group predictions for signs of aggregated error.</li><li>Build additional corrective models on aggregated predictions using group-level features.</li></ul><p>​<br>​Following this roadmap we can leverage patient-level data while avoiding the pitfalls that would accompany naive aggregation. If you are interested in building and scaling cool models with healthcare data, <a href="https://www.lumiata.com/careers.html">Lumiata is hiring</a>!</p><p>Visit Lumiata at <a href="http://www.lumiata.com/">www.lumiata.com</a> and follow on Twitter via <a href="http://www.twitter.com/lumiata">@lumiata</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87d849eee9d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lumiata/healthcare-costs-avoiding-pitfalls-with-patient-cost-predictions-87d849eee9d5">Healthcare Costs: Avoiding Pitfalls with Patient Cost Predictions</a> was originally published in <a href="https://medium.com/lumiata">Lumiata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>