<?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 Edden Gerber on Medium]]></title>
        <description><![CDATA[Stories by Edden Gerber on Medium]]></description>
        <link>https://medium.com/@edden.gerber?source=rss-a0c252a1bf6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*RmOsoIep11oSg7qXDiJ7wA.jpeg</url>
            <title>Stories by Edden Gerber on Medium</title>
            <link>https://medium.com/@edden.gerber?source=rss-a0c252a1bf6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:11:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edden.gerber/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[A new perspective on Shapley values: the Radical Shapley method]]></title>
            <link>https://medium.com/data-science/a-new-perspective-on-shapley-values-the-radical-shapley-method-6c2f4af7f922?source=rss-a0c252a1bf6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c2f4af7f922</guid>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[shapley-values]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Edden Gerber]]></dc:creator>
            <pubDate>Sun, 01 Dec 2019 00:00:00 GMT</pubDate>
            <atom:updated>2020-01-02T21:04:14.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwJ4VHpdxoE5NOEx8hNZzQ.png" /><figcaption>Image adapted from <a href="https://shap.readthedocs.io/">shap.readthedocs.io</a></figcaption></figure><h3>A new perspective on Shapley values: the Naïve Shapley method</h3><h4>Getting smarter about SHAP by exploring a conceptual alternative.</h4><p>** <strong>EDIT, Jan 2020:</strong> I renamed the method presented here <em>Naive Shapley</em> from the less intuitive <em>Radical Shapley</em>. This was changed throughout the post but the code snippets and git repository may still reflect the old name. **</p><h3>Why should you read this post?</h3><ul><li><strong>For insight into Shapley values and the SHAP tool</strong>. Most other sources on these topics are explanations ased on existing primary sources (e.g. academic papers and the SHAP documentation). This post is an attempt to gain some understanding through an empirical approach.</li><li><strong>To learn about an alternative approach to computing Shapley values</strong>, that under some (limited) circumstances may be preferable to SHAP (or wait for the next post for a more broadly-applicable idea).</li></ul><p><strong>If you are unfamiliar with Shaply values or SHAP</strong>, or want a short recap of how the SHAP explainers work, <a href="https://medium.com/@edden.gerber/a-new-perspective-on-shapley-values-an-intro-to-shapley-and-shap-6f1c70161e8d">check out this post</a>.</p><p><strong>In a hurry?</strong> I’ve emphasized key sentences to assist your speed-reading.</p><h3>A more wordy introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*YR1NvVEjKnAVjWG4.jpg" /></figure><p>My interest in Shapley values was sparked when I was using the SHAP library during a <a href="https://medium.com/@edden.gerber/datahack-2019-2nd-place-on-the-armis-challenge-and-fun-with-anomaly-detection-65cf1a3df595">recent hackathon</a> to explain the predictions of an Isolation Forest model. I noticed that for our model, the SHAP computation seemed to be quite inefficient, taking far too long to run on the entire dataset. So long, in fact, that I wondered whether in this case the “brute force”, exponentially-complex approach to Shapley values was actually a better option. This led me to write a function that computes Shapley values using an approach that seemed intuitive to me: <strong>instead of simulating missing features by integrating over their possible values (as in the SHAP method), they can be removed altogether from the model during training</strong>. For lack of an existing term in the literature I decided to refer to these as <strong>Naive Shapley values</strong>, in the sense that they are based only on the dataset (plus a model class) and not on a trained model.</p><p><strong>One thing I learned as a neuroscience graduate student is that if you want to understand — and trust — your analysis tools, you need to subject them to careful empirical study </strong>as if they were your actual object of research. Reading the existing literature is important, as is getting hands-on experience yourself, but I find that real insight comes from not taking a tool’s results for granted but testing it in relation to artificial edge cases or other methods. <strong>The main idea of this post is then to better understand the advantages and limits of the SHAP explainers, by examining them in comparison to the Naive Shapley approach.</strong></p><p><strong>Code for the Shapley function</strong> and the examples used in this post is available <a href="https://github.com/edden-gerber/radical-shapley-values">here</a>.</p><h3>Outline (not quite a tl;dr)</h3><p>In this post I will try to show the following:</p><ul><li><strong>Naive Shapley values can be computed for a low number of features</strong> by retraining the model for each of 2ᴹ feature subsets (where <em>M</em> is the number of features).</li><li><strong>The SHAP library explainers and the Naive Shapley method provide two different interpretations to Shapley values.</strong> The former is best suited for explaining individual predictions for a given (trained) model, and the latter better suited for explaining feature importance for a dataset and model <em>class </em>(e.g., a random forest initialized with certain parameters, but not a trained random forest).</li><li><strong>Under some (limited) circumstances, the Naive Shapley computation can be faster than the SHAP method.</strong> These circumstances are broadly when all of the following are true: <strong>a.</strong> a low number of features (&lt;~15), <strong>b. </strong>using a model that is not supported by the efficient SHAP explainers, and <strong>c.</strong> Shapley values are wanted for a large number of samples (e.g., the entire dataset).</li></ul><p>In a future post I hope to discuss a more practical, polynomially-complex alternative of estimating Naive Shapley values with sampling.</p><h3>So what are “<strong>Naive</strong>” Shapley values?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*x_LtoyIAF_fbQkuw.jpg" /></figure><p><strong>First, what is a Shapley value? </strong>If you have a team of people each contributing toward a total gain, but whose contributions are not necessarily independent (like a team manager’s contribution is dependent on also having contributing workers), then a Shapley value quantifies each one’s contribution to the total gain as the weighted average of their marginal contribution across all possible teams (so our team manager’s contribution might be 0 with no additional workers, 100 with at least one worker etc., and this is averaged across all possible permutations of the team). In more technical terms, a Shapley value reflects the expected value of the surplus payoff generated by adding a player to a coalition, across all possible coalitions that don’t include the player.</p><p>In the realm of statistical models, Shapley values quantify the difference in the model’s prediction driven by adding each feature in the model. However, since such models typically cannot handle incomplete inputs, it’s not possible to simply remove a feature from the dataset in order to calculate its marginal contribution. Therefore, <strong>implementing the concept of Shapley values for explaining predictive models is matter of some interpretation</strong>. Specifically,</p><ul><li><strong>the SHAP explainers interpret “adding a feature” in terms of it having a specific value vs. its value being unknown, for a given sample, during the prediction phase</strong>. For example, the marginal contribution of the “Age=30” to the output of a model predicting individuals’ income level can be computed relative to the mean predicted income level when substituting other possible values for “Age” from the dataset. On the other hand,</li><li><strong>the Naive Shapley method is based on the alternative intuition of measuring a feature’s impact in relation to it being absent from the model altogether during training</strong>. And so the contribution of “Age=30” in our example would be relative to the case of the model being initially trained with no Age feature at all.</li></ul><p><strong>Both interpretations are consistent with the mathematical notion of Shapley values, but they measure slightly different things.</strong></p><h3>Computing Naive Shapley values</h3><p><strong>The function for computing Naive Shapley values </strong>(code <a href="https://github.com/edden-gerber/radical-shapley-values">here</a>)<strong> takes a dataset and a payoff function, and computes the payoff for each possible feature combination (or, “player coalition”). </strong>Shapley values are then computed with the standard Shapley formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*KWgr8OkooalNU6N0.png" /><figcaption><em>φi</em> is the Shapley value for feature <em>i</em>, <em>S</em> is a coalition of features, <em>v(S)</em> is the payoff for this coalition, and N is the total number of features. <em>N\{i}</em> is all the possible feature coalitions not containing <em>i</em>. The first term within the sum corresponds to the fraction of times <em>S</em> appears within the possible feature permutations; intuitively, this gives the highest weight to the most informative contributions of a feature, i.e. when it is isolated or when it is added to a full set of features.</figcaption></figure><p>The output is the same format as that of the SHAP library explainers, and so all the SHAP plotting tools can be used to visualize it.</p><p><strong>The payoff function can be any function that takes a dataset and returns a score</strong> (for instance, the profit generated by our team of workers, for any team makeup). It is thus a general function that can be used for any kind of Shapley computation, but for the purpose of generating Naive Shapley values it will always be a function that trains a particular type of model on the dataset, and returns a prediction for each row.</p><p><strong>For example</strong>: Let’s say we want to compute Naive Shapley values for an XGBoost model. We will write a custom payoff function that initializes an xgb model, trains it and returns a prediction for each sample (or perhaps only for a validation set). The Shapley function will feed the payoff function each possible combination of input features, and use the resulting outputs to compute a Shapley value for each sample and feature (you will see a living example for this soon enough).</p><p><strong>The main disadvantage of this algorithm is its computational complexity</strong> — it needs to run 2ᴹ times (where <em>M</em> is the number of features), re-training the model each time. This complexity is of course the main reason the SHAP library was needed; on the other hand, under some limited circumstances this may be a faster option than using the SHAP Kernel explainer. <strong>The issue of comparative run time is covered at the end of this post</strong>.</p><h3>How is this different from SHAP, and why should we care?</h3><p><strong>I compared results from the Naive Shapley method to both the SHAP KernelExplainer and TreeExplainer.</strong> I didn’t go into a comparison with the DeepExplainer, since neural network models rarely have the low number of input variables which would make the comparison relevant. As a quick summary, the Naive Shapley method differs conceptually from all SHAP explainers by representing features’ contribution to the <em>model itself </em>rather than to <em>individual predictions</em>; at the same time, it is generally slower (and impractical for more than a low number of features), although in some cases in may be more efficient than KernelExplainer. Once again, <a href="https://medium.com/@edden.gerber/a-new-perspective-on-shapley-values-an-intro-to-shapley-and-shap-6f1c70161e8d">this post</a> can help you if you’re not sure about what the SHAP explainers do.</p><h4>Naive Shapley values vs. TreeExplainer</h4><p>TreeExplainer is a good first candidate for the comparison with the Naive Shapley approach because unlike KernelExplainer they are both deterministic (not relying on sampling-based estimation) and insensitive to dependence between features (at least in TreeExplainer’s default implementation). This allows us to focus on the implications of the conceptual difference in how they treat missing features, namely, by re-training the model vs. integrating over feature values.</p><p><strong>We can demonstrate the significance of this difference with a simple artificial example</strong>. Let’s generate a 3-feature linear regression model, with one feature <em>x1</em> which is a strong predictor of <em>y</em>, a second feature <em>x2</em> which is strongly correlated with it (and so slightly less predictive of <em>y</em>), and a third non-predictor feature <em>x3</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9524e15c7f21681e8e089f7f225ec158/href">https://medium.com/media/9524e15c7f21681e8e089f7f225ec158/href</a></iframe><p>To get Naive Shapley values, we need to first define the payoff function, which simply trains the model and returns its predictions (for simplicity I’m not including any training-validation split etc.).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f54d0b97116aaa165a3d90f6c7ee823/href">https://medium.com/media/9f54d0b97116aaa165a3d90f6c7ee823/href</a></iframe><p>And now run the Shapley function itself (<em>reshape_shapley_output</em> just re-arranges the original output, since <em>compute_shapley_values</em> returns a dictionary that does not assume a particular payoff format. An explanation of the function inputs and output is provided on <a href="https://github.com/edden-gerber/radical-shapley-values">github</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f412c8eaaa6f903a7c6c58ab2a013e2e/href">https://medium.com/media/f412c8eaaa6f903a7c6c58ab2a013e2e/href</a></iframe><p>To get SHAP values, we’ll define the XGB regressor model, train it, and compute SHAP values with TreeExplainer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1601feb0bd402f1d75f63fb593be0bb4/href">https://medium.com/media/1601feb0bd402f1d75f63fb593be0bb4/href</a></iframe><p>Now let’s see how SHAP values and Naive Shapley values compare with each other. We’ll use the SHAP library’s neat <em>summary_plot</em> visualization tool, which plots the distribution of Shapley values for each feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2LtVRlZMBPhkJG5UrGxyw.png" /></figure><p>Let’s break this down:</p><ul><li>With the TreeExplainer, the model has already been trained with all 3 features, so <strong>SHAP values reflect the fact that <em>x1</em> has the highest impact within the trained model</strong>, while <em>x2</em> has a much smaller role as it is mostly redundant.</li><li>With the Naive Shapley method on the other hand, x2’s impact on <em>y</em> is almost as large as x1’s because <strong>when the model is trained without <em>x1</em>, <em>x2</em> is nearly just as informative</strong>.</li><li>At the same time, the non-predictive <em>x3</em> is credited with a higher impact using the Naive Shapley method — simply because, especially as we did not do a training/validation split, it can over-fitted to the data in the absence of better predictors.</li></ul><p><strong>Now let’s try a real-world example</strong>. We will look at Shapley values for one of the datasets included in the SHAP library — the adult census database, with 12 demographic features that are used to predict whether an individual’s income is &gt;50K$ (load with <em>shap.datasets.adult()</em>). For clarity and reduced computation runtime, we’ll include only 6 of the 12 features in our model (<em>Age, Hours per week, Education, Marital status, Capital gain, and Sex</em>). Our model will be an XGBoost classifier. How do the TreeExplainer SHAP values and Naive Shapley values compare with each other in this case? A scatter plot gives us a quick first impression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*ZXOAEuEZezdgGvNxniyPWQ.png" /></figure><p>The results seem to be highly correlated, and this should already give us an indication that despite their conceptual differences, the two approach probably don’t diverge too drastically in their results. Now with <em>summary_plot</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCJW-WvNoai5fkTqJay0Tw.png" /></figure><p>Here too the results seem similar enough (although different enough that the order of global feature importance is changed a bit). But let’s zoom in on the differences in how Shapley values for the <em>Sex</em> variable are distributed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-oanlleLDb1cxkTFzb8SFQ.png" /></figure><p>What’s going on here?</p><ul><li>The Naive Shapley results show us that <strong>averaged all possible feature combinations, adding this variable will have a consistent impact on prediction for this dataset</strong> (hello gender wage gap).</li><li>The TreeExplainer results show us that <strong>in our trained model, this variable has a smaller and less consistent impact on prediction across our samples</strong>, most likely because it is used to explain smaller residual variance after most of the information it conveys was provided by other, more predictive features.</li></ul><blockquote><strong>Note: </strong>A benefit of implementing our own custom Shapley function is that we have easy access to a wealth of intermediate results — for example, the payoff margins that we calculated for each possible feature combination with vs. without a given feature (and whose weighted average is the Shapley value for each sample). Just for fun, I extracted it from the <em>compute_shapley_values</em> function so we can have a look at how the final Shapley values arise from these individual payoff margins. These are the distributions of payoff margins for the <em>Sex</em> variable, plotted against the number of features to which it is added:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ckRyRal_oeYSr4AB.png" /></figure><blockquote>We can see how the more features are already in the model, the marginal impact of this feature becomes smaller and less bimodal. Contrast this to the distribution of margins for <em>Education_Num</em> for example, whose contribution remains pretty much fixed no matter how many other features make up the model — indicating that its contribution to the model is largely independent of them:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oissMiyJxaqpl8x8.png" /></figure><p><strong>So — which method should we use</strong> to explain the role of the <em>Sex</em> variable in our data and model? I think the best way to put this is:</p><ul><li><strong>Naive Shapley values better represent the global impact of the features in our dataset</strong>, while</li><li><strong>SHAP values better explain specific predictions given our existing trained model</strong>.</li></ul><p>Two additional notes before moving on:</p><blockquote><strong>A practical note</strong>: I am not suggesting that if you care about global feature impact in your dataset you should necessarily use the Naive Shapley method — mainly because in most cases that would be computationally intractable (although see the final sections for when it might not be). It is also apparent from my examples that the SHAP explainers’ results are typically not so different that they should not be used for this purpose. My main motivation here is to get a better understanding of SHAP results and their limitations.</blockquote><blockquote><strong>A technical note</strong>: If you are familiar with TreeExplainer, you may know that since in the case of binary classification the weights of the tree nodes hold not probabilities but log-odd values (which are transformed into probabilities with the logistic function as a final step) — the default optimization approach utilized by TreeExplainer provides SHAP values that add up to these untransformed values (and not the final probabilities). Simply applying the logistic function to the SHAP values themselves wouldn’t work, since the sum of the transformed values != the transformed value of the sum. To produce SHAP values that correspond directly to probability outputs, the TreeExplainer has to sacrifice some of its efficiency and use an approach similar to the KernelExplainer of simulating missing features by replacement with a background dataset — naturally a slower and less exact method. On the other hand, to directly explain probability outputs with the Naive Shapley method all that we need to do is choose the output of the payoff function to be the probability. <strong>Since with the Naive Shapley method we always pay the maximum computation cost, we might as well use a payoff function that gives us exactly what we want our Shapley values to explain</strong>.</blockquote><h4>Naive Shapley values vs. KernelExplainer</h4><p>KernelExplainer is a model-blind method for computing SHAP values. As a very quick summary, it works by:</p><ol><li>Sampling only a small subset of the possible feature permutations.</li><li>For each such permutation, simulating “missing features” by generating many bootstrapped samples where values of these features are replaced with values from a small “background dataset”, and averaging these samples’ predictions.</li></ol><p>This means that <strong>in comparison to TreeExplainer, KernelExplainer is</strong>:</p><ol><li><strong>Slower</strong> — a large number of predictions needs to be computed for each explained instance in the dataset (since missing values are simulated by averaging over many possible values of the feature).</li><li><strong>Non-deterministic</strong> — KernelExplainer’s SHAP values are estimated, with variance introduced both by the coalition sampling method and the background dataset selection.</li></ol><p><strong>How does this add up when comparing KernelExplainer SHAP values to Naive Shapley values?</strong> Let’s use the same 6-feature census dataset predicting a &gt;500K$ income as a test case. This time, Following the <a href="https://slundberg.github.io/shap/notebooks/Census%20income%20classification%20with%20scikit-learn.html">example of this SHAP library notebook</a>, we will use a KNN model to make this prediction and the KernelExplainer to provide Shapley values, which we can compare to Naive Shapley values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d78eaa0af5127b3a54a2897f2559588/href">https://medium.com/media/0d78eaa0af5127b3a54a2897f2559588/href</a></iframe><p>Comparing the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*GI1Jcc7YjQqYS-dGUUiIOg.png" /></figure><p>The two methods produce different but correlated results. If we sort and rank the Shapley values of each sample (from 1 to 6), the order would be different by about 0.75 ranks on average (e.g., in about 75% of the samples two adjacent features’ order is switched). Let’s remember that we are not looking at the relation between exact values and their noisy estimation: rather, <strong>Naive <em>Shapley values are a deterministic measure of one thing, and the kernel SHAP values are an estimation of another (related) thing</em></strong>.</p><p>A final point to stress here, I think, is that despite all the sources of variance between the two methods, the results are still very similar overall, telling us that <strong>in many cases these methods can probably be used interchangeably </strong>assuming that the differences are not crucial for us.</p><h3>Can Naive Shapley be faster than KernelExplainer?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*H0R2uX2I3evhT5VR.jpg" /></figure><p>As we’ve established, the Naive Shapely method needs to re-train the model and produce predictions 2ᴹ times. This makes it impractical whenever the number of features is not low (let’s say, more than 15–20). But is it comparable to the SHAP explainers for a low number of features?</p><p>One thing to get out of the way is that <strong>the optimized SHAP explainers will always be faster than the Naive Shapley method, but the model-blind KernelExplainer can be very slow when explaining a large dataset</strong>. To get a better idea, let’s see what goes into the run time of the KernelExplainer vs the Naive Shapley method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMHGsXc_CO-rwpRHRyitsw.png" /></figure><p><strong>The bold entries emphasize the weaknesses of each method</strong>. The Naive Shapley method is of course most vulnerable to increasing the number of features, and is also dependent on model training time, whereas KernelExplainer is not affected by these factors (although its prediction becomes more variable with increased number of features). The disadvantages of the KernelExplainer in terms of run time is that while it does not need to spend time re-training the model, it runs separately for each explained prediction (while Naive Shapley runs for all predictions at once), each time having to produce predictions for ~200K samples (<em>nsamples</em> X <em>num. background samples</em>, which by default are 2048+2M and 100, respectively).</p><p><strong>A good example for a model for which the Naive Shapley method can potentially perform faster than KernelExplainer, for a low number of features, is an <em>Isolation Forest</em> model</strong>, a popular tool for anomaly detection, as despite being a tree-based model it is not supported by TreeExplainer and its training time (compared to prediction) is relatively fast. To demonstrate this, I am using the <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud">Credit Card Fraud Detection dataset from Kaggle</a>, a ~285K sample, 30 features dataset used to predict anomalous credit card transaction. For our demonstration let’s use 100K samples and reduce the 30 features down to 15. On my old laptop I get the following approximate run times:</p><p><em>- Train the model</em>: <strong>8 sec </strong><br>- <em>Make predictions for all 100K samples</em>: <strong>8 sec</strong> <br>- <em>Compute SHAP values for a single prediction</em>: <strong>18 sec</strong> (which is, unsurprisingly, about the time it takes to compute predictions for ~200K bootstrapped samples)</p><p>Based on this we can make a rough estimate of how long it would take to compute Shapley values for the entire dataset. The KernelExplainer should simply take 100,000 x 18 seconds, or <strong>about 500 hours</strong>. The Naive Shapley function will run for up to 2¹⁵*(15+13) seconds, or <strong>about 150 hours</strong> (actually, a better estimate may be about 50 hours since the bootstrapped datasets used for training in each iteration of the algorithm will have between 1 to 15 features, or 7–8 on average, making training typically faster). Both methods are slow (though both could benefit from parallelization), but what’s important here is not the specific example but understanding where the computation time comes from in each case. To summarize:</p><ul><li><strong>If you need to explain only a small group of “important” predictions, KernelExplainer should be fast enough.</strong></li><li><strong>If you need to explain a million predictions and you have less than 10–15 features, the Naive Shapley method should be much faster.</strong></li></ul><h3>A practical compromise? Estimating Naive Shapley values with sampling</h3><p><strong>What if our model is only supported by KernelExplainer, and we really need Shapley values for our entire huge dataset — but there are too many features to compute Naive Shapley values?</strong></p><p>Well, why not try to <strong>estimate Naive Shapley values using coalition sampling</strong>?<strong> </strong>Using random sampling to estimate Shapley values for a high number of players (as is done e.g. by the KernelExplainer) has been thoroughly discussed in the literature and improved methods are still being developed (see for example <a href="https://www.sciencedirect.com/science/article/pii/S0305054808000804">Castro et al. 2009</a>, <a href="https://www.sciencedirect.com/science/article/pii/S030505481730028X">Castro et al. 2017</a> or <a href="https://www.sciencedirect.com/science/article/abs/pii/S0377221719304448">Benati et al. 2019</a>). I would suggest that sampling can work well in combination with the Naive Shapley approach — that is, to sample the space of feature combinations on which the model is trained (thus not needing to simulate missing features by averaging over bootstrapped samples).</p><p><strong>Getting rid of the exponential component in the algorithm would drastically reduce run time and make the approach feasible for a high number of features</strong> (at the expense of some estimation variance), while keeping the re-training approach would still ensure a short run time when computing Shapley values for large datasets.</p><p>This is only a theoretical idea at this point, and this post is long enough without developing it here. I would be happy to get any comments you may have about this idea (maybe you’ve already encountered it somewhere else?), and I hope to develop and discuss it in a future post.</p><p><em>Originally published at </em><a href="https://edden-gerber.github.io/shapley-part-2/"><em>https://edden-gerber.github.io</em></a><em> on December 8, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c2f4af7f922" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-new-perspective-on-shapley-values-the-radical-shapley-method-6c2f4af7f922">A new perspective on Shapley values: the Radical Shapley method</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A new perspective on Shapley values: an intro to Shapley and SHAP]]></title>
            <link>https://medium.com/data-science/a-new-perspective-on-shapley-values-an-intro-to-shapley-and-shap-6f1c70161e8d?source=rss-a0c252a1bf6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f1c70161e8d</guid>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[shapley-values]]></category>
            <dc:creator><![CDATA[Edden Gerber]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 00:00:00 GMT</pubDate>
            <atom:updated>2020-01-02T21:03:13.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*fZl0UC9OxZRCKKIjcZ_62w.png" /></figure><h4>A concise introduction to Shapley values and the SHAP python library</h4><h3>What is this post about?</h3><p>This post is the first in a series of two (for now) posts about explaining statistical models with Shapley values. I can think of two main reasons you might want to read it (apart from, you know, for fun):</p><ol><li><strong>To learn about Shapley values and the SHAP python library</strong>. This is what this post is about after all. The explanations it provides are far from exhaustive and contain nothing that cannot be gathered from other online sources, but it should still serve as a good quick intro or bonus reading on this subject.</li><li><strong>As an introduction or quick refresher before reading the next post about Naive Shapley values</strong>. The next post is my attempt at a novel contribution to the topic of Shapley values in machine learning. You may be already familiar with SHAP and Shapley and are just glancing over this post to make sure we’re on common ground, or you may be here to clear up something confusing from the next post.</li></ol><h3>What are Shapley Values?</h3><figure><img alt="Game theory meme" src="https://cdn-images-1.medium.com/max/623/0*t4ygas1dxpjpDFlB.jpg" /></figure><p>There are numerous online sources that explain this topic, so my explanation here will be brief. I specifically recommend <a href="https://christophm.github.io/interpretable-ml-book/shapley.html">this chapter</a> of <a href="https://christophm.github.io/interpretable-ml-book/">Interpretable Machine Learning</a> by Christoph Molnar for a more detailed explanation. I also found that staring at the mathematical formula (below or on <a href="https://en.wikipedia.org/wiki/Shapley_value">Wikipedia</a>) until I got it gave me the best intuition into this concept.</p><p>The Shapley value is a concept from game theory, describing how the contribution to a total payoff generated by a coalition of players can be distributed among the players. Its definition is quite straightforward: the contribution of any player is the expected value, across all possible coalition of players not containing this player, of the prediction change caused by adding this player to the coalition. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*YmaQiQ-vgh9PkMfp.png" /></figure><p><strong>Let’s look at an example</strong>: say we have a team that needs to perform a task. Each individual on the team contributes an additive 20% chance of success on the task, but one team member, <em>A</em>, has a special tool that guarantees a 90% chance of success, as long as there is at least one additional member on the team. If our team today is made up of three members, <em>A</em>, <em>B</em>, and <em>C</em> — having together a 90% chance of success — how much does each one contribute to this chance?</p><p>Let’s compute this for team member <em>C</em>, using all possible combinations not containing them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*coZU5-Bnn2kba27IZXbM2A.png" /></figure><p>Applying the formula (the first term of the sum in the Shapley formula is 1/3 for {} and {A,B} and 1/6 for {A} and {B}), we get a Shapley value of <strong>21.66%</strong> for team member <em>C</em>. Team member <em>B</em> will naturally have the same value, while repeating this procedure for <em>A</em> will give us <strong>46.66%</strong>. A crucial characteristic of Shapley values is that players’ contributions always add up to the final payoff: <strong>21.66% + 21.66% + 46.66% = 90%</strong>.</p><h3>Shapley values in machine learning</h3><p><strong>The relevance of this framework to machine learning is apparent if you translate <em>payoff</em> to <em>prediction</em> and <em>players</em> to <em>features</em>.</strong> But computing Shapley values for model features is not entirely straightforward, because features in a model do not behave the same way as workers in a team. Specifically, <strong>a predictive model cannot typically handle one of its input features being simply removed in order to test how its output changes as a result</strong>. Instead, ML implementations of Shapley values, and specifically the SHAP method, interpret <em>missing features</em> as <em>features whose value is unknown</em> and simulate this unknown state by averaging over possible values of the feature (the next post in this series proposes a different approach and compares it to the SHAP method).</p><figure><img alt="Exponential complexity meme" src="https://cdn-images-1.medium.com/max/899/0*JP0C2oDnxjbNQRCA.jpg" /></figure><p><strong>The main problem with deriving Shapley values is computational complexity</strong> — specifically, the fact that they require 2ᴹ (where M is the number of features) to compute. No matter how beefed-up your GPU is, exponential complexity is almost always a deal breaker (just think how many steps this is when your features are for instance 20x20 image pixels). In the theoretical literature, this problem is most commonly addressed by sampling methods — rather than going over all possible feature coalitions, estimate the Shapley value using a sub-sample of them (if you are interested in this see for example <a href="https://www.sciencedirect.com/science/article/pii/S0305054808000804">Castro et al. 2009</a>, <a href="https://www.sciencedirect.com/science/article/pii/S030505481730028X">Castro et al. 2017</a> or <a href="https://www.sciencedirect.com/science/article/abs/pii/S0377221719304448">Benati et al. 2019</a>).</p><h3>Enter the SHAP python library</h3><p>The <a href="https://shap.readthedocs.io/">SHAP library</a> is a recent and powerful addition to the data scientist’s toolkit. It provides three main “explainer” classes — TreeExplainer, DeepExplainer and KernelExplainer. The first two are specialized for computing Shapley values for tree-based models and neural networks, respectively, and implement optimizations that are based on the architecture of those models. The kernel explainer is a “blind” method that works with any model. I explain these classes below, but for a more in-depth explanation of how they work I recommend <a href="https://christophm.github.io/interpretable-ml-book/shap.html">this chapter</a>.</p><h4>KernelExplainer</h4><p>The KernelExplainer’s approach to computing Shapley values can be summed up in these two main points:</p><ol><li><strong>Instead of iterating over all 2</strong>ᴹ <strong>possible feature permutations, it samples a small subset</strong>. The default number of samples is <em>nsamples = 2*M+2048</em>. So if we have, for instance, 20 features, KernelExplainer will sample 2088/2²⁰ or about 0.2% of the possible coalitions. Coalitions are not selected completely randomly; rather, those with higher weight in the Shapley formula will be selected first (so, coalitions of 0 or M-1 features, which are most informative about the effect of adding another feature, will be included first).</li><li><strong>“Missing features” are simulated by averaging the model’s prediction over bootstrapped samples with values for these features taken from other entries in the data set.</strong> This “background” dataset has no default size but the algorithm suggests 100 samples. This means that for each sampled feature coalition, the algorithm will generate 100 predictions, each based on a bootstrapped sample, and average over them. Note that the fact that the KernelExplainer’s result is based solely on outputs of the model for different inputs, means that it will work for any kind of function without making any further assumptions about it.</li></ol><p><strong>The significance of (1)</strong> is that Shapley values are basically estimated using random sampling. Appropriately, increasing <em>nsamples</em> (or the size of the background dataset) leads to increased runtime (more or less linearly) and decreased variance in the estimation (meaning that when you run the explainer multiple times, the Shapley values will be more similar to each other and to the expected value). This is easily demonstrated by running the Kernel Explainer with different <em>nsamples</em> values:</p><figure><img alt="Plots of estimation variance and run time as a function of nsamples" src="https://cdn-images-1.medium.com/max/626/0*Hx4jLvWDkoIz8uCk.png" /><figcaption>Based on the Census Income database included in the SHAP library. There are 12 features in the dataset and so <em>nsamples</em> is effectively capped at 212=4096. Estimation variance and mean run time are computed across 30 iterations of running the SHAP explainer on a K-Nearest-Neighbors classification model.</figcaption></figure><p><strong>The significance of (2)</strong> — handling “missing” features by replacing their values with surrogate “background” data — is more complex:</p><ul><li>First and most simply, it is an <strong>additional source of variance</strong> to the Shapley value estimation, as the results are to at least some extent dependent on the selection of the background dataset.</li><li>Second, it makes an <strong>assumption about feature independence</strong>: if for example features <em>x1</em>, <em>x2</em> are highly correlated in our training data, replacing values of <em>x1</em> with random ones from the background dataset ignores this dependence and generates predictions based on {<em>x1</em>, <em>x2</em>} instances which are not likely to appear in the training set, making the SHAP value estimation less reliable.</li><li>And finally, it represents an <strong>interpretation of feature contribution to the prediction</strong> not as how they affect the prediction model itself, but rather how they affect the result of the already-trained model if the values of these features were unknown. Another great opportunity to remind you that this all leads to the next post where a different interpretation is explored.</li></ul><h4>TreeExplainer</h4><p>TreeExplainer is a class that computes SHAP values for tree-based models (Random Forest, XGBoost, LightGBM, etc.). Compared to KernelExplainer it’s:</p><ol><li><strong>Exact</strong>: Instead of simulating missing features by random sampling, it makes use of the tree structure by simply ignoring decision paths that rely on the missing features. The TreeExplainer output is, therefore, deterministic and does not vary based on the background dataset.</li><li><strong>Efficient</strong>: Instead of iterating over each possible feature combination (or a subset thereof), all combinations are pushed through the tree simultaneously, using a more complex algorithm to keep track of each combination’s result — reducing complexity from <em>O(TL2</em>ᴹ<em>)</em> for all possible coalitions to the polynomial <em>O(TLD</em>²<em>)</em> (where <em>M</em> is the number of features, <em>T</em> is number of trees, <em>L</em> is maximum number of leaves and <em>D</em> is maximum tree depth).</li></ol><p>What have we gained by using TreeExplainer? First, <strong>we got rid of all the sampling-based estimation variance</strong>, in that we don’t need to use a background dataset or select a subset of feature coalitions. Second, our results are <strong>no longer skewed due to dependencies between features</strong>, since these are contained in the tree structure (although under some circumstances, we may have to waive both of the previous benefits). Third, <strong>our run time is <em>significantly</em> faster</strong>, in some cases making the difference between <em>pretty fast</em> and <em>unacceptably slow</em>. Finally, note that there is no difference between the two explainers in terms of their interpretation of feature contributions being in respect to the predictions of a given trained model, rather than in respect to how they affect the model itself.</p><h4>Wait, what about DeepExplainer?</h4><p>DeepExplainer is a class specialized for computing SHAP values for neural network models. I am not including a detailed explanation of it here because <strong>1</strong>, I lack the hands-on-experience I have with the other explainers that allow me to vouch for my explanations of them, and <strong>2,</strong> this post is mainly a preamble to the next one where the SHAP explainers will be compared to the Naive Shapley values approach, and this comparison is largely irrelevant when it comes to explaining neural networks.</p><p>As a rough overview, the DeepExplainer is much faster for neural network models than the KernelExplainer, but similarly uses a background dataset and the trained model to estimate SHAP values, and so similar conclusions about the nature of the computed Shapley values can be drawn — they vary (though not to a large extent) based on the selection of background data, and they may not respect dependencies between features when generating the bootstrapped samples used for estimation.</p><h3>How can I use SHAP to explain my models?</h3><p>Oh, that’s really simple. Just import <a href="https://shap.readthedocs.io/">shap</a>, and do something like this (e.g. for the KernelExplainer):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc0f6c4018f644dae4385c127dbae851/href">https://medium.com/media/cc0f6c4018f644dae4385c127dbae851/href</a></iframe><p>And then use one of the SHAP library’s pretty visualization functions to look at the results — either for a single sample’s SHAP values or globally across the dataset.</p><figure><img alt="SHAP Force Plot for the probability that you will like this post" src="https://cdn-images-1.medium.com/max/741/0*CeBQkLjdEOldbdjm.png" /></figure><h3>Got it! What’s next?</h3><p>All this was just to get us in sync on Shapley values and the SHAP explainers. You can stop here and continue (or start) making use of this great tool in your own work. <strong>But if you want to go a bit deeper, get a better understanding of this topic and possibly another tool in your toolset, keep reading the </strong><a href="https://towardsdatascience.com/a-new-perspective-on-shapley-values-the-radical-shapley-method-6c2f4af7f922"><strong>next post</strong></a><strong>!</strong>.</p><p><em>Originally published at </em><a href="https://edden-gerber.github.io/shapley-part-1/"><em>https://edden-gerber.github.io</em></a><em> on November 28, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f1c70161e8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-new-perspective-on-shapley-values-an-intro-to-shapley-and-shap-6f1c70161e8d">A new perspective on Shapley values: an intro to Shapley and SHAP</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guessing Someone’s Location On Earth Based On Their Distance]]></title>
            <link>https://medium.com/@edden.gerber/guessing-someones-location-on-earth-based-on-their-distance-2d91b122f1ef?source=rss-a0c252a1bf6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d91b122f1ef</guid>
            <category><![CDATA[google-maps-api]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[geopy]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Edden Gerber]]></dc:creator>
            <pubDate>Fri, 11 Oct 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-11-27T16:52:34.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgL9xO3uzIcaAd-ZGKQ9eA.png" /></figure><p>If I say I’m 50 km from your location, would you be able to guess where I am?</p><p>This question came up as I was chatting with someone on a popular dating app. This app, like others of its kind, is based on users’ location, and so displays the distance of potential matches from your location. This particular person happened to be traveling for work about 2800 km away at the time, and as I tried to guess where they were visiting, I occurred to me that a bit of data and coding can make this game much easier.</p><p>This turned out to be a very entertaining one-day project, that had me looking into world population data, sphere geometry, google maps API, and even signal processing. This is the idea: given that a person is located in unknown coordinates on Earth <em>(lat2, long2)</em> but with known distance from a location <em>(lat1, long1)</em>, how can we best guess <em>(lat2, long2)</em>? My approach was to use world population density data, and assign probabilities to locations based on this density.</p><h3>First stop: NASA</h3><p>First we need some data. I ended up on <a href="https://sedac.ciesin.columbia.edu/">NASA’s Socioeconomic Data and Applications Center (SEDAC)</a> website, where I found the Gridded Population of the World (GPW) v4.11 data set ( <a href="https://sedac.ciesin.columbia.edu/data/set/gpw-v4-population-density-rev11/data-download">download here</a>, free registration required). Several resolutions are available — a 2.5 minute (about 5km; a minute is 1/60 of a degree) grid seemed good enough to me without having to deal with a heavy dataset.</p><p>It’s an ASCII file containing 4320 rows and 8640 columns of numbers, corresponding to population density estimates for a square grid covering the Earth’s surface (180° of latitude and 360° of longitude in steps of 2.5 Minutes, or 0.04167°). It also contains six header lines. Non-land locations are coded as -9999, which we’ll replace with NaN (I’m using Python; import commands are placed where they are first required for clarity).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9512119408faac4b53efd0f7cfa7cb9d/href">https://medium.com/media/9512119408faac4b53efd0f7cfa7cb9d/href</a></iframe><p>Our strategy will be to:</p><ol><li><strong>Choose a center location and distance</strong></li><li><strong>Retrieve all population density grid entries that fall on the corresponding circle on Earth</strong></li><li><strong>Compute probabilities for discrete location labels — using Google Maps’ API to translate numerical coordinates to rich location data.</strong></li></ol><h3>Doing the math</h3><p>This is where I ran into the first challenge: on a spherical coordinate system, how do we compute the set of coordinates that make up our circle of equidistant points? After a very short attempt with pen and paper and trying to recall some trigonometry, that most useless of high school subjects, I quickly realized that this is not a simple problem. Not simple, of course, only in the sense that it means I had to <a href="https://www.movable-type.co.uk/scripts/latlong.html">look up the formulas online</a> rather than figure it all out myself. So here is a function that translates a center point, distance and angle to the corresponding target coordinate on the circle circumference:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/713554fdfd0cfb381e2814b5b4532827/href">https://medium.com/media/713554fdfd0cfb381e2814b5b4532827/href</a></iframe><h3>Putting it together</h3><p>Next, let’s add a couple of utility functions to convert earth coordinates to row and column in our dataset and vice versa (actually we’ll never use <em>index_to_coord</em> — it’s here just for completeness):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/370e256330b221edef886a2d9985a64d/href">https://medium.com/media/370e256330b221edef886a2d9985a64d/href</a></iframe><p>Now we can define a center point and distance and sample our circle. But how many points to sample? Obviously, we gain nothing by sampling with higher resolution than that of the dataset, so my quick-and-dirty solution was to select the maximal resolution that samples each entry on the circle at least once, which is simply <em>np.max(data.shape)</em> (corresponding to the number of grid squares on the maximal circumference possible, e.g. the equator). Let’s use the parameters from the case I started with — a distance of 2850km from my (approximate) location in Jaffa, Israel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a803dd0c54bd42b38c9dce87e05d8090/href">https://medium.com/media/a803dd0c54bd42b38c9dce87e05d8090/href</a></iframe><h3>It’s map time</h3><p>With a set of coordinates and population density values, we are ready to plot our preliminary results on a map! We’ll handle this aspect using the <em>gmaps</em> and <em>geopy</em> libraries. Note that to access Gmap’s API, we need to generate an API key. I already had a Google Cloud account so doing this was simple using <a href="https://developers.google.com/maps/documentation/embed/get-api-key">these instructions</a>. Make sure you get your own key if you want to run this code yourself. This is what we need to set up:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baf91c681aa980735e506a9f2fba785d/href">https://medium.com/media/baf91c681aa980735e506a9f2fba785d/href</a></iframe><p>I also had to run this to enable the Google maps to display within my Jupyter Notebook (required a computer restart).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4a06e0b16dac55cdc09f2d991dd6490/href">https://medium.com/media/c4a06e0b16dac55cdc09f2d991dd6490/href</a></iframe><p>Okay, now for the actual plotting, using a heatmap layer to show the population density values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df64e0db0f75635537c7b6a6720bd2c1/href">https://medium.com/media/df64e0db0f75635537c7b6a6720bd2c1/href</a></iframe><p>…And here we are!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*Te_TY8tXTagyCCrbgGJbvQ.png" /></figure><h3>Smoothing out the details</h3><p>Our next task is to take this array and translate it into a list of probabilities for possible discrete locations. We need to define what we mean by “location”, so let’s say our desired resolution is city-level (which is suitable given our ~5km grid resolution). Ideally, we could extract (using the geopy library) the country/city label for each point on our circle, add up the population density values belonging to each unique location, and divide each by the total density across the array to get a probability between 0 and 1. This is because if a city is large enough to span several samples, the probability to be in this city should be the sum of the probabilities of being in each of its sampled points.</p><p>However, we run into a technical issue here — the Google Maps API doesn’t seem to to like it when we send thousands of location data requests at the same time. Despite some attempts to go around this, I just ended up getting a ‘Service timed out’ error each time. Instead then, let’s take another approach.</p><p>Rather than integrating across all locations along the circle, we can look just at peaks of population density. This of course changes what we are effectively looking for (e.g. we will not be sensitive to large but sparsely-populated locations), but it should be good enough. To start with, let’s look at what we are working with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88ac979ca2dcac26e53af7556108ab1c/href">https://medium.com/media/88ac979ca2dcac26e53af7556108ab1c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*K-BR4MK1gAFcY9qUSMH0tg.png" /></figure><p>So what we have here is a time series — or rather a space series if you will. We can see the peak clusters that correspond to the blobs in Russia, Ethiopia and Europe in the map above (angle 0 is right above the center). With my scientific background analyzing biological time series data, I feel right at home here… I also know that I can’t just run a peak-finding function on this series, since it is very non-smooth and so there are peaks everywhere — in the sense of samples that are simply higher than their immediate neighbors.</p><p>Let’s see this happening (and zoom in for clarity):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6be0cad208facb1be86bd164d9da7c2f/href">https://medium.com/media/6be0cad208facb1be86bd164d9da7c2f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*lsVfnwIBM934WMZLSHFnGg.png" /></figure><p><em>find_peaks</em> has parameters we can play with to narrow down the results, like minimal height, minimal distance from other peaks, and so on. Rather than get into that, I prefer to look at the problem from a signal processing perspective and simply apply a smoothing filter. This has the advantages of not only getting rid of this pesky quantization noise in the signal, but also introducing a bit of spatial integration — that is, the value at each point will reflect not only the density at this point but also a weighted sum of neighboring points (since any smoothing — i.e. “low pass” — filter is basically a moving weighted average). This works for us because by going with the “peaks” approach we’re basically ignoring the data around the peaks.</p><p>What kind of filter to use? Common filters used in signal processing such as the Butterworth or Chebychev filters are good if you care about the precise frequency spectrum of your output, but they pay for that by introducing some distortions (e.g. “ringing” around square waves) that we want to avoid (as they may create artificial peaks). A simple Gaussian filter is probably the best option in our case.</p><p>We need to select one parameter — the standard deviation (width) of our Gaussian, corresponding to the degree of smoothing. A width of 5km makes sense and seems to generate good results — let’s compare the signals and detected peaks before and after filtering (again zooming in, and let’s also add a minimal height criterion to find_peaks to get rid of very low peaks):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7416bcf94618fee0e2ab98c2386d532c/href">https://medium.com/media/7416bcf94618fee0e2ab98c2386d532c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*-jxr7W0DFSHmtxKuTYchOA.png" /></figure><p>Looking at the entire circle again, and with some nicer graphics:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71b8650eb2dc3f9615860c3ac4afedba/href">https://medium.com/media/71b8650eb2dc3f9615860c3ac4afedba/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*NHHAPqtoKwa5CQWoYxUbQw.png" /></figure><h3>Going local</h3><p>Okay, that was fun but we still have the main part of the algorithm ahead of us. Next we need to extract the location information from each peak’s coordinates. For this we’ll need the following functions that extract country and city (coded as by Google “locality” as not every place is within a city) from the gmap data structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc2f767e12373ef72d2c5da9b4d19eb5/href">https://medium.com/media/cc2f767e12373ef72d2c5da9b4d19eb5/href</a></iframe><p>We’ll store our results in a Pandas dataframe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e421254c9012e13523ce9e9702e81cf/href">https://medium.com/media/7e421254c9012e13523ce9e9702e81cf/href</a></iframe><p>This is now what our dataframe looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXGsr6k71PKNEuw64hfUsQ.png" /></figure><p>We could wrap up here and simply sort by <em>pop_density</em> to get our final suggestions. But we’ll go a bit further and handle the case of non-unique rows. That is, the case that there are multiple peaks within the same locality. Although it’s a bit problematic to do this after abandoning the idea of continuous integration in favor of focusing on peaks (as it unjustifiably biases our results toward localities that have multiple distinct density peaks), let’s just go ahead and sum these together, using of course the awesome power of groupby. At the same time, it makes sense to separate our results into multiplicative country and locality probabilities — such that the probability for a country is the sum of probabilities of locations within it, and probabilities for localities are computed within their respective countries. This is also easily accomplished with groupby.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb5972eaf01b106dbb4df7218d694adb/href">https://medium.com/media/bb5972eaf01b106dbb4df7218d694adb/href</a></iframe><p>Last thing before displaying the results — let’s get them sorted in descending order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f323614145b3e050edb36cc8fc879ef/href">https://medium.com/media/8f323614145b3e050edb36cc8fc879ef/href</a></iframe><h3>Drumroll please</h3><p>…Aaand print!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fa2508fb29a369ac3853ab36dd9c0b5/href">https://medium.com/media/9fa2508fb29a369ac3853ab36dd9c0b5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*Rs3jDPcjviEmbvviES0H8Q.png" /></figure><p>So our most likely result is Germany with 53.5%, with Berlin being the most likely location within this country. Incidentally, this is indeed where my conversation partner was at the time, so that’s nice and validating.</p><p>But what if they happened to be a bit further away, say in Brussels, Belgium (3245km)? Well, since our algorithm cares about nothing but population density, our answer would have been very different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*igdCh01E-oG-xzf828P1vw.png" /></figure><p>This would of course be wrong if the other person was an Israeli citizen like myself, implying a strong prior probability against Karachi. So on a final note, how could we take this little project further if we wanted it to take advantage of additional knowledge that we may have? One idea that comes up is to use international travel statistics — what is the volume of travel between pairs of countries — and generating from it a probability prior (assuming of course that we know the target individual’s nationality). Of course, having two or more sets of probabilities means that I need to decide how to weigh them. I could try to learn these weights or even use a more complex prediction model using each set as a feature — though this would make it a supervised learning problem requiring labeled data of people’s distances and locations. In other words, it’s doable but somebody will have to pay me for it :)</p><h3>To sum up</h3><p>This was a fun and educational little project. I enjoyed taking a simple idea and carrying it all the way to a working solution, discovering along the way how not so simple it actually is. As for the text conversation that sparked this idea, unfortunately it never became more than that. Oh well…</p><p><em>Originally published at </em><a href="https://edden-gerber.github.io/guessing-location-on-earth/"><em>https://edden-gerber.github.io</em></a><em> on October 11, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d91b122f1ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Datahack 2019: 2nd Place On The Armis Challenge And Fun With Anomaly Detection]]></title>
            <link>https://medium.com/@edden.gerber/datahack-2019-2nd-place-on-the-armis-challenge-and-fun-with-anomaly-detection-65cf1a3df595?source=rss-a0c252a1bf6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/65cf1a3df595</guid>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[isolation-forests]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Edden Gerber]]></dc:creator>
            <pubDate>Thu, 03 Oct 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-12-24T08:19:41.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeU8cPyB9k--RuHtJP8KVw.png" /></figure><h3>My first hackathon</h3><p>A few weeks ago I had a chance to participate in my first data science hackathon — <a href="https://www.datahack.org.il/">Datahack 2019</a>, which took place in Jerusalem. I joined a friend’s team (incidentally composed almost entirely of neuro/biology PhD graduates), and we signed up for the <a href="https://www.datahack.org.il/challenge/armis-devices-gone-rogue">“devices gone rogue” anomaly detection challenge</a> presented by <a href="https://www.armis.com/">Armis</a>.</p><p>With two free days before the event that I could spend studying ahead, I came very prepared having read anything that I could find about common approaches to anomaly detection problems and with a few ideas of my own. The event itself was a great deal of fun, I got to know some wonderful teammates and we eventually ended up on the 2nd place for this challenge.</p><h3>The devices-gone-rogue challenge</h3><p>Armis’s product is an IoT security platform, that identifies threats coming from any type of device in an organization’s network (phones, printers, smart televisions, vehicles, medical instruments, etc.). Appropriately, the <a href="https://github.com/armis-security/DataHack2019">challenge</a> presented in the Datahack was to determine, based on a large database of network traffic events, devices with suspicious (i.e., anomalous) behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYugD5L7L_chdpKWZJTTwQ.png" /><figcaption>Taken from <a href="https://github.com/armis-security/DataHack2019">https://github.com/armis-security/DataHack2019</a></figcaption></figure><p>Our team’s solution, along with explanation and even a PPT presentation, is available on <a href="https://github.com/YG15/DataHack2019">github</a>: (credit due to my team members Tali Shrem, Guy Sheffer, Yonathan Guttel, Inbal Meir and myself).</p><p>By the way, the 1st place solution can be found <a href="https://github.com/dmarcous/Self-Supervised-Network-Anomaly-Detection?fbclid=IwAR02I0JsfydDS1ud7uHezbw9CbwZWBNROpRTlmY54os0bEmDtV0daw2dfa0">here</a>. Achieving an area-under-the-ROC-curve of ~0.9 compared to our 0.87, it is a great deal more complex and incorporates domain-expertise-based feature engineering and model ensembling. Worth a look.</p><h3>Our solution</h3><p>Fairly quickly into the work we decided on a simple pipeline comprising of data exploration, feature engineering, and modeling with isolation forest (optionally ensembling other models later). By dividing ourselves among the different tasks, it was easy to start with some initial features and a simple model to establish the workflow, and then gradually add to it as each update is carried downstream along the already-established pipeline.</p><h3>Exploring the data</h3><p>The data included traffic from five consecutive days and four different networks. Our first priority was to understand how these time and space properties impact the data: is there a daily cyclic traffic pattern for some device types? should similar devices on different network be modeled separately or should their data be pooled together? The former question is particularly relevant for anomaly detection, since if different times of day correspond e.g. to different traffic volume baselines, this variance can be regressed out so that it would not mask local rather than global outliers.</p><p>Overall, traffic features tended to stay uniform across the day, with some notable exceptions. For example, packet loss for mobile phones was higher during peak traffic hours than during the night:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*BSA8_m6viBoumN_W6taO1A.png" /></figure><p>No differences were found between days or networks; we therefore handled this variance by subtracting from each traffic parameter its hour-specific mean, pooling data from all days and networks.</p><h3>Feature engineering and selection</h3><p>Each device that had to be assigned an anomaly score had data for multiple sessions each comprising summary data for a single hour-session (for example, a device’s outbound byte count was described using mean, median, std. deviation, min and max for a given hour). Multiple sessions meant that another layer of summary was required (for example, the outbound byte count mean could be again averaged across sessions). Aggregating data across sessions using mean, median, min and max, we naturally ended up with a lot of somewhat similar features (e.g. mean across sessions of inbound_packet_size_max, and max across sessions of inbound_packet_size_mean…). With some trial and error we found that our isolation forst model works better when we use only some of the features (by the time we aggregated session-based data into device-based data, we were down from million of rows of data to only about 70K, which apparently meant that the model did not have data to spare chasing down too many irrelevant paths along its trees).</p><p>How to select the best feature combination? Isolation Forest runs pretty fast, so under different circumstances even a brute force approach of trying out possible combinations could have worked, but we did not have that kind of time. Instead we used a mix of intuitive feature selection (for example, since we are looking for outliers, means, mins and medians were mostly discarded in favor of max values) and manual testing of different feature combinations.</p><p>Surprisingly, our final model made use of <em>only 7 features</em> (mostly having to do with outbound traffic volume, temporal range of activity across the week and number of unique protocols/port numbers). This feature combination outperformed similar selections with a larger number of features.</p><h3>The model</h3><p>Isolation Forest is a natural solution for this kind of problem. It works by generating trees whereby at each node the data is split along a random dimension and a random cutoff point between the min and max value. Since samples that are easily isolated (e.g. they lie far from most other samples along one or more dimensions) would become the only sample in the node after fewer splits, the average path length to isolation is used as an anomaly score (e.g. smaller values indicate higher probability of anomaly). The algorithm is quite fast since unlike for decision trees, no search is required to decide on each split, and the trees are developed only up to their expected mean path length of log 2 N as no anomalies are expected for longer paths.</p><p>One of the ideas I had preparing for the datahack was to try using an autoencoder model. An autoencoder is a neural network that learn an identity function (i.e. the output layer should be identical to the input layer) but with a hidden layer smaller than the input/output layers. This effectively accomplishes a compressed representation of the data in the hidden layer, which is then decoded back to the output layer as the input + some decoding error. The rationale of using this architecture for anomaly detection is that putting anomalies through the trained network would result in larger decoding errors, since their features behave in an unexpected way relative to each other.</p><p>The problem with this approach in the current case is that autoencoders require a supervised, anomaly-free dataset to train on, while our data was mixed and unlabeled. However, this problem can be partially overcome using the results of the isolation forest: since the isolation forest provides us with a continuous anomaly score, we could set the threshold arbitrarily low such that we can expect to capture the majority of anomalies (along with a large number of false positives). The remaining dataset can be then trusted to be relative anomaly-free, and used to train the autoencoder.</p><p>It’s a nice idea in theory, but the actual results were unfortunately quite poor. Looking across the dataset, there was definitely some correlation between the anomaly score provided by the isolation forest and the decoding error of the autoencoder (averaged across features) — but the latter performed very poorly against the leaderboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*tzLB2nxp3pvk-7BQoRM7OQ.png" /></figure><h3>Explaining the results</h3><p>One of the evaluation parameters of the challenge was explainability of the results. We used the shap library to easily compute SHAP values that portray the degree to which each feature moved the anomaly score of a device toward a positive or negative value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/0*MRxnHNw_sPlMvkY-.png" /></figure><p>Computing SHAP values using the shap library’s Kernel Explainer takes a few seconds for each sample, and provides an <em>approximation</em> of the real <a href="https://en.wikipedia.org/wiki/Shapley_value">Shapley values</a> that precisely reflect the contribution of each feature to the final result (averaged across all possible combination of features). This made me curious whether in this and other cases (when there are few features and model training is relatively fast) when it makes more sense to compute the exact Shapley values by actually re-training the model using every possible feature combination. I will expand on this topic in a future post.</p><p><em>Originally published at </em><a href="https://edden-gerber.github.io/datahack-2019/"><em>https://edden-gerber.github.io</em></a><em> on October 3, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65cf1a3df595" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>