<?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 Eoghan Keany on Medium]]></title>
        <description><![CDATA[Stories by Eoghan Keany on Medium]]></description>
        <link>https://medium.com/@egnkeany?source=rss-1bc545e83cfe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*58nTy5HsShF0oryWxrYN5g.jpeg</url>
            <title>Stories by Eoghan Keany on Medium</title>
            <link>https://medium.com/@egnkeany?source=rss-1bc545e83cfe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:48:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@egnkeany/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[The Ultimate Guide for Clustering Mixed Data]]></title>
            <link>https://medium.com/analytics-vidhya/the-ultimate-guide-for-clustering-mixed-data-1eefa0b4743b?source=rss-1bc545e83cfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eefa0b4743b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mixed-data-types]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Eoghan Keany]]></dc:creator>
            <pubDate>Mon, 01 Nov 2021 16:21:27 GMT</pubDate>
            <atom:updated>2021-11-30T06:15:36.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S8VFig_fR8XE4rhS" /><figcaption>Photo by <a href="https://unsplash.com/@live_for_photo?utm_source=medium&amp;utm_medium=referral">Teng Yuhong</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Clustering is an unsupervised machine learning technique used to group unlabeled data into clusters. These clusters are constructed to contain data points that are ‘similar’ to each other, and ‘dissimilar’ from data points assigned to other clusters. Every clustering algorithm works by organizing data points into clusters using some sort of ‘similarity’ measure. This similarity measure is typically calculated using Euclidean distance for numerical based data, whereas the Jaccard distance is used for categorical data.</p><p>Unfortunately, the majority of clustering algorithms can only work with data that exclusively contains either numeric or categorical features. This is a huge problem, as most real world datasets will contain multiple types of features. This article provides pythonic implementations of different methods that can be used for distance-based clustering with mixed data. The workflow for this article has been inspired by a paper titled “<em>Distance-based clustering of mixed data</em>” by M Van de Velden .et al, that can be found <a href="https://www.researchgate.net/publication/327832223_Distance-based_clustering_of_mixed_data"><strong>here</strong></a>. These methods are as follows:</p><ol><li>Gower Distance.</li><li>Dimensionality Reduction Techniques.</li><li>Recode Categorical Variables.</li><li>Recode Continuous Variables.</li><li>K-prototypes.</li></ol><p>“All of the code used to create this article can be found at <a href="https://github.com/Ekeany/Clustering-Mixed-Data/tree/main/Notebooks"><strong><em>GitHub</em></strong></a><strong><em>”</em></strong></p><h3>Datasets</h3><p>All of the methods below were applied to the three open sourced datasets. These datasets varied by the proportion of numeric &amp; categorical variables that they contain. This variation provides a more rigorous evaluation process, for all of the distance based clustering methods.</p><p>The <a href="https://github.com/Ekeany/Clustering-Mixed-Data/blob/main/data/heart.csv"><strong>Cleveland Heart Disease</strong></a> data set from the UCI machine learning repository contains 13 variables in total, 5 numeric and 8 categorical. These 13 medical variables were gathered on 303 patients in order to diagnose if the patient does or does not have Heart Disease. For this analysis, any patient with missing records was removed from the dataset, leaving 297 patients for the actual analysis. The heart disease diagnoses was also used as our target variable to evaluate the performance of the clustering algorithms. Thus the number of clusters for this dataset was set to 2.</p><p>The <a href="https://github.com/Ekeany/Clustering-Mixed-Data/blob/main/data/fifa_data_2019.csv"><strong>Kaggle FIFA 19 Complete Player</strong></a> data set, is publicly available and contains information on approximately 7,000 players from 42 different soccer leagues. In order to speed up computation time, a random subset of 2,500 players were taken along with 43 continuous variables &amp; 4 categorical variables that contain information about an individual player’s style of play. The player’s position (goalkeeper, striker, midfielder or defender), was used as a target variable to validate the performance of the clustering algorithms.</p><p>The <a href="https://www.kaggle.com/prakharrathi25/banking-dataset-marketing-targets"><strong>Banking-Marketing</strong></a><strong> </strong>dataset includes information relating to the direct marketing campaigns of a Portuguese banking institution. The dataset contains approximately 50,000 rows and 18 columns, due the class imbalance the dataset was randomly under-sampled to leaving 8,512 rows for the actual analysis. From a preliminary analysis 3 redundant columns were dropped due to their lack of correlation with the target variable. The external variable used to validate the clustering solution was if a client had subscribed to a term deposit or not. For this dataset the number of clusters was set to 2.</p><h3>Evaluation Metrics</h3><p>Evaluating any clustering algorithm is a complex task, as deciding on a definition of success, is completely context and problem specific. This is because the goal of your unsupervised analysis will vary based on your problem requirements. Despite this ambiguity, the ‘Adjusted Rand Index’ was used to measure the similarity between the obtained clusters and our ground truth values. The similarity of the clusters produced by the different algorithms was also measured using the ‘Adjusted Rand Index’. For fairness of evaluation all of the methods applied use a version of the K-Means ++ algorithm to create their optimal clustering solutions, the number of clusters (k) is also prior knowledge and was held constant for each method.</p><h3>1. Gower Distance</h3><p>Gower’s distance is a metric used to measure the similarity between two data points that contain both numeric and categorical variables. It simply works by applying different measures of similarity for the each data type. The similarity scores for each data type are then combined to create an overall similarity score. The measures used for each data type are as follows:</p><ul><li><strong>Numerical Variables:</strong> a normalized <a href="https://en.wikipedia.org/wiki/Taxicab_geometry">Manhattan distance</a></li><li><strong>Categorical Variables:</strong> the variables are first one hot encoded and and then the Jaccard distance is applied.</li><li><strong>Ordinal Variables: </strong>the variables are first sorted, then the Manhattan distance is applied with an adjustment for ties.</li></ul><p>The gist below includes a toy python function that will create a Gower distance matrix from a pandas dataframe. This code will hopefully help you understand what is happening under the hood.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/481b201b89c010feea78cfa1f88072a8/href">https://medium.com/media/481b201b89c010feea78cfa1f88072a8/href</a></iframe><p>However, I would recommend using the <em>“gower”</em> python package if you actually intend to use this method on your own data. The package can simply be installed using the “pip” framework and then the following code can be executed to calculate your distance matrix.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d738955b38e92f27bf0d3a3564b2454/href">https://medium.com/media/1d738955b38e92f27bf0d3a3564b2454/href</a></iframe><p>For all three datasets we computed their corresponding Gower distance matrices using the above function. From a geometric stand point one should not compute Euclidean distances from the resultant Gower matrices. Therefore, this method cannot be combined with the <strong>Kmeans</strong> algorithm. Instead the <strong>KMedoids</strong> algorithm provided by the <em>“sklearn_extra”</em> package in python was used to determine the optimal clustering solution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d6dc17750af31b5b324e7f4d0d5eb99/href">https://medium.com/media/0d6dc17750af31b5b324e7f4d0d5eb99/href</a></iframe><h4>2D Visualization of Gower Clustering Solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*uRaxR2k9Iln4aNNSQ7D3yg.png" /></figure><h3>2. Dimensionality Reduction</h3><p>Dimensionality reduction is a common technique used to cluster high dimensional data. This technique attempts to transform the data into a lower dimensional space while retaining as much information about the original data. For our purposes we are not interested in converting our data into a lower dimensional space. Instead we want to utilize the technique to homogenize our mixed dataset, by converting all of our variables into a normalized numeric values. For this article we leveraged two different dimensionality reduction techniques <strong>Factorial Analysis of Mixed Data (FAMD) </strong>and<strong> Uniform Manifold Approximation and Projection for Dimension Reduction (UMAP).</strong></p><p><strong>a. Factorial Analysis of Mixed Data (FAMD)</strong></p><p>This algorithm generalizes the Principal Component Analysis (PCA) algorithm to mixed datasets. This method, operates by first one hot encoding the categorical variables. Each numerical variable is then standardized, by subtracting the mean and dividing by the standard deviation. The one hot encoded variables are treated slightly different as they are divided by the squared root of the proportion of objects in the column (the number of 1s over the number of observations in the column) and then centered (subtract the mean). Finally the PCA algorithm is executed on the resulting matrix to obtain the final output. The following code snippet shows a pythonic implementation of the procedure of the FAMD algorithm described above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f9290da85faf752ab3064eaeb762042/href">https://medium.com/media/6f9290da85faf752ab3064eaeb762042/href</a></iframe><p>The code above is more of a demonstration to visualize the procedure of how the algorithm works. I would not advise using this code for your own analysis . Instead I would use the python implementation from the “prince” package that can easily be “pip” installed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9f01324fe00948ac71c93dfaf68ea51/href">https://medium.com/media/e9f01324fe00948ac71c93dfaf68ea51/href</a></iframe><h4>2D Visualization of FAMD Clustering Solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*vxh5qIHNnSBYl9gDjXIlPg.png" /></figure><p><strong>b.</strong> <strong>Uniform Manifold Approximation and Projection for Dimension Reduction (UMAP)</strong></p><p>UMAP is a dimensionality reduction technique predicated upon manifold learning &amp; ideas from topological data analysis. It provides a general framework for applying dimensionality reduction and is an incredibly powerful tool in any data scientist’s arsenal. In order to apply UMAP to mixed data we must create two separate manifolds one for each data type, as UMAP still needs to compute distances between points. These two manifolds are then combined either by computing the Union which preserves the categorical embedding more, or by calculating the intersection which will cause the embedding to more closely resemble the numerical manifold.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31fdac4e7ef425181b3f39040b010877/href">https://medium.com/media/31fdac4e7ef425181b3f39040b010877/href</a></iframe><h4>2D Visualization of the UMAP Clustering Solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*Xco1VhiqxM45mT4xvoH32g.png" /></figure><h3>Recode Categorical Variables</h3><p>The general pre-processing workflow for recoding categorical variables is to first one hot encode the variables. This means that for each unique category a new new binary variable is added appended to the dataset. Each one hot encoded variable is then standardized by subtracting the column mean and dividing it by the standard deviation. The approach is implemented in the Python code snippet below.</p><p>One thing to note is that Distance-based clustering methods, such as K-means, are not invariant against affine transformations. Also the choice standardizing the one hot variables has an effect on clustering performance. However an optimal choice that applies to various different data sets or clustering techniques does not exist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77193d939a52438a98d3ee05fa9d1637/href">https://medium.com/media/77193d939a52438a98d3ee05fa9d1637/href</a></iframe><h4>2D Visualization of the Clustering Solution from the Recoding the Categorical Variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*bLkm9h--DME6sDoPFILKyg.png" /></figure><h3>Recode Numerical Variables</h3><p>Numerical variables can be converted into categories by a process called discretization. Discretization splits the numerical variable into N number of intervals, the categories are then labelled according to the interval that the values fall between. Apart from the obvious lose of information another challenge with this approach, is choosing the correct method of discretization. Some variables will have a natural intervals that lend themselves to a meaningful discretization ie. breaking down age into natural age groups such as children, teenagers, adults and elderly. Unfortunately, in many cases these natural groupings do not exist or can not be applied without expert knowledge. This ambiguity on choosing the appropriate discretization method for each variable poses a problem. As the choice of discretization has a direct impact on the performance of the clustering algorithms.</p><p>For this article all of the numerical variables were discretized using the same method, by applying the KMeans algorithm (k=5) to each variable individually. This method is very simplistic &amp; can definitely be improved upon, even by simply selecting the optimal number of k individually would improve the results. The following function applies the simple method described above by discretizing every numerical feature in a dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ccfaf155c85b077c204b73c44805e03/href">https://medium.com/media/7ccfaf155c85b077c204b73c44805e03/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*6tTx_J-vryc11m7e-z1kng.png" /><figcaption>The distributions of Footballers Age before and after discretization</figcaption></figure><p>After all the numerical data was converted into categories three different clustering techniques were applied and there performance measured. These methods were:</p><ol><li><strong><em>KModes</em></strong></li><li><strong><em>Categorical Embedding + KMeans</em></strong></li><li><strong><em>Graph Analysis Community detection</em></strong></li></ol><h4>a. KModes</h4><p>The K-Modes algorithm modifies the standard K-Means process for clustering categorical data by replacing the notion of distances with dissimilarities. That means instead of measuring distances, it counts the total number of mismatches between two observations the smaller the count the more similar two observations are. Also instead of using the mean to find the centroid of the cluster it uses the mode. These changes allow the algorithm to converge to a local minimal for categorical datasets. For more information please check out this<strong> </strong><a href="https://ai.plainenglish.io/k-means-and-k-modes-clustering-algorithm-4ff51395fa8d"><strong>blog post</strong></a><strong>.</strong></p><p>Unfortunately as of yet the <strong>KModes</strong> algorithm is not implemented as part of the sklearn.cluster module. Therefore, the “kmodes” package from the PYPI antifactory is needed in order to cluster the categorical data. The code below demonstrates how to use the <strong>KModes</strong> function from “kmodes”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22e3ae17210001ae3762688999af6983/href">https://medium.com/media/22e3ae17210001ae3762688999af6983/href</a></iframe><h4>2D Visualization of KModes Clustering Solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*_-JEIRNId2Nnbq95eB-rnw.png" /></figure><h4>b. Categorical Embedding + KMeans</h4><p>As our data is now homogenous (containing only one data type) we can apply certain dimensionality reduction techniques that specialize in categorical data. The thought process here is to apply dimensionality reduction in order to create a standardized numeric representation of the data for the KMeans algorithm to cluster. In this article we chose the UMAP algorithm with the “Dice” distance metric, although any dimensionality reduction technique that can handle categorical data, could have been applied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e278e49bbb4aadc119a034f773371c7/href">https://medium.com/media/5e278e49bbb4aadc119a034f773371c7/href</a></iframe><h4>2D Visualization of the Clustering Solution from Categorical UMAP Embedding + KMeans</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*yHfW9TK98GnrtZq7kJYVKA.png" /></figure><h4>c. Graph Analysis Community Detection</h4><p>We can transform our recoded (only containing categorical data) tabular data into a Graph structure by creating an edge list. To create an edge list we can consider each row to be a node in the graph, this row will be connected to it’s categorical values or associated metadata, as these categories will also be nodes in the graph.</p><p>Modelling the data in this way allows us to witness all of the different non linear interactions between the categorical variables and our observations. Below is the code necessary to convert your tabular data into an edge list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*VRoRwgSBSYYZcWHvHr3Hrw.png" /><figcaption>An example of the the edge list created for the Heart Dataset each row is only connected to it’s categorical values. All edges have a weight of one.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e5b22a006af54dab977fab2c4b71b11/href">https://medium.com/media/6e5b22a006af54dab977fab2c4b71b11/href</a></iframe><p>Once we have a Graph, it is now time to analyze it. As this article is concerned with clustering we will perform community detection on the Graph. Community detection essentially finds subsets of nodes that are densely connected to each other and sparsely connected to the other nodes in the graph. This is pretty much the graph analytics equivalent of clustering. In this article we used the “community” python package to perform the <a href="https://neo4j.com/docs/graph-data-science/current/algorithms/louvain/"><strong>Louvain method</strong></a><strong> </strong>for community detection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba163c354a45565e29c143ebde873353/href">https://medium.com/media/ba163c354a45565e29c143ebde873353/href</a></iframe><h4>Visualizations of the Resultant Graphs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIRknwqoGpcI4GZcGaaFog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNgqETNakadNOhliC9UaPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcjBb2MPreVsyCP6U__IwQ.png" /><figcaption>The resultant Graphs produced by the code above on each of our three datasets (left to right Banking Dataset Marketing Targets, Kaggle FIFA 19 Complete Player and Cleveland Heart Disease), the colors in each graph highlight the communities that the nodes belong to. The visualizations were created using the Gephi software.</figcaption></figure><h3>K-prototypes</h3><p><strong>K-Prototypes</strong> is an adaptation of the <strong>KMeans</strong> algorithm that offers the ability to cluster mixed data. Just like <strong>KMeans</strong>, <strong>K-Prototypes</strong> measures the distance between numerical variables using ‘Euclidean’ distance. However, unlike the <strong>KMeans </strong>algorithm it measures the distance between categorical variables using the number of matching categories. The algorithm combines both of these distance metrics to compute the actual distance between samples.</p><p>Unfortunately, as of yet the <strong>K-Prototypes</strong> algorithm is not implemented as part of the sklearn.cluster module. Therefore, the “kmodes” package from the PYPI antifactory is needed. The code below demonstrates how to use the <strong>KPrototypes</strong> function from “kmodes”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/637d05338fc1dbdf9306e240d172e10b/href">https://medium.com/media/637d05338fc1dbdf9306e240d172e10b/href</a></iframe><h4>2D Visualization of the K-Prototypes Clustering Solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*vPMVAtLMsvcnDezRaBT0bQ.png" /></figure><h3>Results</h3><p>This article has demonstrated several pythonic implementations of distance-based clustering algorithms for mixed data. Regardless of the ubiquitous nature of mixed data in the wild, there is still no agreement on the best approach to cluster such data. The primary reason for this ambiguity, lies with the issue of assessing the quality or success of the clusters produced.</p><p>As illustrated by the results below, the applied methods can produce very unique outputs despite achieving similar ‘Adjusted Rand Index’ scores with the target label. This makes it a challenge, to compare the performances of our algorithms. Moreover, in a real world setting the clustering analysis will primarily be unsupervised so alternative methods must be applied to select the best algorithm. For this reason alone, some mockingly call unsupervised learning more of an art form than a science. Despite this, some performances stand out from the rest of our results.</p><p>First off, the UMAP 2D approach produces clusters that are almost completely different from the other algorithms. Also the resultant clusters perform significantly worse when evaluated against the target variables. In contrast, the clusters produced by the Recoded Categorical Variables method achieved the highest average Adjusted Rand Index value (0.26) with the target variables. Followed closely by the solutions provided by the UMAP Recode Numerical Variables method which achieved an average score of (0.25). Interestingly, the similarity between these two clustering solutions changes drastically from dataset to dataset. The novel community detection approach worked well, on real problems this method has the benefit of automatically choosing the number of clusters. However, for this analysis it hindered it’s performance as we could not pre-select the already known number of clusters. The performance of every clustering algorithm with respect to the target variable drops for the Banking dataset. These low scores can be attributed to the poor separation boundary between the classes. Clearly the chosen variables are not able to predict if a client had subscribed to a term deposit or not.</p><p>In conclusion, this article provides a variety of different distance based clustering methods to choose from. Unfortunately, there is “No Free Lunch” when it comes to clustering mixed data, as each clustering solution depends entirely upon your own success criterion. Although combining a plethora of different clustering techniques that will produce uncorrelated clustering solutions, with various evaluation metrics such as “Silhouette Score”, “Davies &amp; Bouldin” and human evaluation to asses the quality of your clustering solutions. Will allow you to discover the optimal solution to your problem.</p><p>“All of the code used to create this article can be found at <a href="https://github.com/Ekeany/Clustering-Mixed-Data/tree/main/Notebooks"><strong><em>GitHub</em></strong></a><strong><em>”</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPHMbkppwRBVnQziVPtxSQ.png" /><figcaption>This matrix shows the Adjusted Rand Index scores between each method and the label when present for our three datasets. The table also shows the Adjusted Rand Index scores between the methods themselves the columns are labeled #1–#9, these numbers represent each method and the corresponding number can be seen in the Method column</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eefa0b4743b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/the-ultimate-guide-for-clustering-mixed-data-1eefa0b4743b">The Ultimate Guide for Clustering Mixed Data</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is this the Best Feature Selection Algorithm “BorutaShap”?]]></title>
            <link>https://medium.com/analytics-vidhya/is-this-the-best-feature-selection-algorithm-borutashap-8bc238aa1677?source=rss-1bc545e83cfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bc238aa1677</guid>
            <category><![CDATA[feature-importance]]></category>
            <category><![CDATA[pypi]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[feature-selection]]></category>
            <dc:creator><![CDATA[Eoghan Keany]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 13:55:28 GMT</pubDate>
            <atom:updated>2020-06-01T13:55:28.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3yXAnbYlRKtQIZa2" /><figcaption>Photo by <a href="https://unsplash.com/@amartino20?utm_source=medium&amp;utm_medium=referral">Anthony Martino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Feature Selection ?</h3><p>Feature selection is an important but often forgotten step in the machine learning pipeline. The process involves reducing the dimension of the input space by selecting a relevant subset of the input features. <strong>But why should we care ?</strong></p><ol><li>Firstly, the reduction in model size and complexity makes it easier to interpret.</li><li>The smaller model is now faster and easier to train. Also with less features to create the feature engineering pipeline can also be simplified not to mention data collection.</li><li>Feature selection can also reduce over fitting by removing noisy features. Thus increasing the models ability to generalize to new unseen data and increasing accuracy.</li></ol><p>The central idea behind using a feature selection algorithm is that modern datasets will contain a certain amount of <em>redundant</em> or <em>irrelevant </em>features, that can be removed without causing a significant loss in information.</p><p>A feature selection algorithm can be broken down into two components a search technique, which proposes new subsets along with an evaluation metric to score these new subsets. The simplest feature selection algorithm would therefore ideally test every possible subset of the input features and select the one which minimizes the error rate of the model. However, this is an exhaustive search and is not computationally feasible for any large data set as the number of subsets is exponential. With the number of subsets defined as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*_WYl63n3gHWjV-bjk-JFBg.png" /><figcaption>where n is the number of features in the data set</figcaption></figure><h3>What’s out there ?</h3><p>Well feature selection methods are typically presented in three classes based on how they combine the selection algorithm and the model building. These three methods include<strong> filter</strong>, <strong>wrapper</strong> and <strong>embedded</strong> methods.</p><h4>Filter Methods</h4><p>Filter methods select the subset of features independently from the model. Their main premise is that they use some sort of correlation metric with the variable to predict. Common metrics used include, <em>“Mutual Information”</em> , <em>“Point-wise Mutual Information”</em> or even simply <em>“Pearson Coefficient”. </em>As filter methods are based on these statistical metrics they<em> </em>usually less computationally intensive than wrapper methods. However the subset of features selected is not tuned to our model nor has it considered the relationships or interactions between variables themselves.</p><h4>Wrapper Methods</h4><p>Wrapper methods use a predictive model to score feature subsets, where each new subset is used to train a model which is then tested on a hold out set. The prediction error is computed and used as a representative score for that subset. As you can imagine training a new model on each subset is very computationally expensive, but this method usually provides the best performing feature set for that particular type of model or typical problem. A example of this type of method would be <em>“Step Wise Regression”</em>.</p><h4>Embedded Methods</h4><p>Embedded methods try to combine the advantages of the previous two methods by incorporating feature selection as part of model construction. The text book example of this is the “<em>LASSO Regression</em>”, which penalizes the regression coefficients with an L1 penalty. Any features which have non-zero regression coefficients are essentially <em>“Selected”</em> by the LASSO algorithm.</p><h3>What is Boruta ?</h3><p>“<a href="https://www.jstatsoft.org/article/view/v036i11/v36i11.pdf"><strong>Boruta</strong></a>” is an elegant wrapper method built around the <a href="https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf"><strong>Random Forest</strong></a> model. The algorithm is an extension of the idea introduced by the “<a href="https://journal.r-project.org/archive/2009-2/RJournal_2009-2_Strobl~et~al.pdf"><strong>Party On</strong></a>” paper which determines feature importance by comparing the relevance of the real features to that of the random probes. In short the algorithm operates as follows; if you would like a more detailed step by step breakdown of the algorithm I would suggest this medium <a href="https://towardsdatascience.com/boruta-explained-the-way-i-wish-someone-explained-it-to-me-4489d70e154a"><strong>article</strong></a>.</p><ol><li>Start by creating new copies of all the features in the data set and name them shadow + feature_name, shuffle these newly added features to remove their correlations with the response variable.</li><li>Run a random forest classifier on the extended data with the random shadow features included. Then rank the features using a feature importance metric the original algorithm used permutation importance as it’s metric of choice.</li><li>Create a threshold using the maximum importance score from the shadow features. Then assign a hit to any feature that had exceeded this threshold.</li><li>For every unassigned feature preform a two sided T-test of equality.</li><li>Attributes which have an importance significantly lower than the threshold are deemed ‘unimportant’ and are removed them from process. Deem the attributes which have importance significantly higher than than the threshold as ‘important’.</li><li>Remove all shadow attributes and repeat the procedure until an importance has been assigned for each feature, or the algorithm has reached the previously set limit of the random forest runs.</li></ol><p>In my opinion “Boruta” is one of the best automated feature selection algorithms available, as it provides accurate and stable results. However, it can be improved in two domains especially with regards to computational complexity and the metric that it uses to rank a feature’s importance. Thus, introducing SHAP</p><h3>SHAP (SHapley Additive exPlanations)</h3><p><a href="https://github.com/slundberg/shap">SHAP</a> is a unified approach to explain the output of any machine learning model. SHAP connects game theory with local explanations to create the only consistent and accurate explainer. From a <strong>very</strong> high level, SHAP essentially calculates the average marginal contributions for each feature across all permutations at a local level. As this method is additive the mean value of these marginal contributions can be then used to achieve a global feature importance.</p><p>SHAP truly has unified the field of model interoperability, and in my eyes is one of the most impactful recent additions to the machine learning community. If you haven&#39;t already, I would highly recommend delving more into the field of<strong> </strong>interpretable machine learning and there is no better place to start then with <em>Christoph Molnar’s “</em><a href="https://christophm.github.io/interpretable-ml-book/shap.html">A Guide for Making Black Box Models Explainable</a><em>” .</em></p><p>However, one flaw is that SHAP’s kernel explainer which evidently has to create and measure the marginal contribution of every coalition in the dateset is a computationally expensive process. Luckily as the “Boruta” algorithm is based on a Random Forest, there is a solution TreeSHAP, which provides an efficient estimation approach for tree-based models reducing the time complexity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*W6wiJ8Da7kNt7ubQoXFNcA.png" /><figcaption>Where T is the number of trees, L is the maximum number of leaves in any tree and D the maximal depth of any tree.</figcaption></figure><h3>The Problem with Boruta/ Boruta+Shap</h3><p>Previously we outlined two major problems with the original implementation of the “Boruta” algorithm the first being computational complexity with the second being the consistency/accuracy of the feature rankings themselves. However, both of these problems can be simply resolved by switching the feature importance algorithm (permutation importance) with the TreeSHAP explainer.</p><p>Just to re-iterate the “Boruta” algorithm adds noise to our data set by creating these random permutations of the original features. The algorithm then fits a Random Forest to this noisy data and uses a feature importance ranking to decide whether or not a feature should be kept or not.</p><p>Traditionally, global feature importance values of tree ensemble methods are calculated in three primary ways:</p><ol><li>Gain: Gain is a classic approach and is calculated as the the total reduction of loss or impurity contributed by all splits for a given feature. This is the default feature importance method implemented in Scikit-learn’s tree ensemble methods.</li><li>Split Count: A second common approach is simply to count how many times a feature is used to make a split inside the tree structure.</li><li>Permutation: A third common approach is to randomly permute the values of a feature in the test set and then observe the change in the model’s error. If a feature’s value is important then permuting it should create a large increase in the model’s error.</li></ol><p>The original implementation of “Boruta” package in R uses the Permutation based approach this is the definitely the most consistent method of the three however, it scales badly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*IAhtUqz88zFEd5043NE_ig.png" /><figcaption>n is the number of features</figcaption></figure><p>Surprisingly there is no Python implementation of the original “Boruta” package. Although there is a implementation “<a href="https://github.com/scikit-learn-contrib/boruta_py">Boruta_py</a>” that uses the Mean Decrease in Impurity as it feature importance score despite its speed <strong>neither this or split count are reliable measures of global feature importance</strong>, despite there wide spread use.</p><h3>Comparison</h3><p>To test the benefits of “BorutaShap” I created a Python implementation that included all three metrics (Gain, Shap and Permutation). I then compared the various methods on three test datasets to evaluate their performance respectively.</p><p>In each iteration of the test a default Scikit-learn Random Forest was used as the base model. However, it should be noted that both the Shap and Permutation importance metrics are model agnostic .Whereas, in contrast the Gain importance can only work for tree based models.</p><p><strong>Gain Importance: </strong>To compute the gain metric the base “<a href="https://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html"><em>feature_importances_</em></a><em>”</em><strong><em> </em></strong>method implemented in Scikit-learn was used. This approach is also sometimes called “gini importance” or “mean decrease impurity” and is defined as the total decrease in node impurity weighted by the probability of reaching that node averaged over all trees of the ensemble.</p><p><strong>Permutation Importance:</strong> Whereas, for the Permutation Importance, “<em>sklearn.inspection’s”</em> implementation of “<a href="https://scikit-learn.org/stable/modules/permutation_importance.html">permutation_importance</a><strong>” </strong>was used. This method calculates the mean decrease in accuracy of the model by randomly shuffling a feature in dateset. This procedure of shuffling the feature breaks it’s relationship with the target, thus the drop in the model accuracy is indicative of how much the model depends on the feature.</p><p><strong>SHAP Importance</strong>: As seen above the SHAP python package created by “slundberg” was used to calculated the importance values. Within this package their are numerous different explainers which are optimized for different model structures. Therefore for the TreeExplainer is used to explain the behavior of the Random Forest model. which is a fast, model-specific alternative to KernelSHAP for tree based models.</p><h4>Ozone Dataset</h4><p>The Los Angeles ozone pollution dataset contains 366 daily observations on 13 variables from 1976. This is a regression problem where the goal is to predict the daily maximum one-hour-average ozone reading (‘V4’) using the other variables. The correct names of all the variables are as follows</p><ul><li>“V1” Month: 1 = January, …, 12 = December</li><li>“V2” Day of month</li><li>“V3” Day of week: 1 = Monday, …, 7 = Sunday</li><li>“V4” Daily maximum one-hour-average ozone reading</li><li>“V5” 500 millibar pressure height (m) measured at Vandenberg AFB</li><li>“V6” Wind speed (mph) at Los Angeles International Airport (LAX)</li><li>“V7” Humidity (%) at LAX</li><li>“V8” Temperature (degrees F) measured at Sandburg, CA</li><li>“V9” Temperature (degrees F) measured at El Monte, CA</li><li>“V10” Inversion base height (feet) at LAX</li><li>“V11” Pressure gradient (mm Hg) from LAX to Daggett, CA</li><li>“V12” Inversion base temperature (degrees F) at LAX</li><li>“V13” Visibility (miles) measured at LAX</li></ul><p>As seen below in all three variants of the “Boruta” algorithm were used to subset the Ozone dataset. With each variant achieving different results. Both “Shap” and “Gain” achieved similar subsets although “Shap” interpreted “V1” or the Month of year to be a significant feature. In contrast the “Permutation” variant was much more lenient and considered both “V1” and “V5” to be significant features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jv-kq_kiiRmU6wrgsHQrPA.png" /><figcaption>Each feature, for each “Boruta” variant is represented as a boxplot. The green values are those features which have been accepted, red rejected and blue represent metrics of the shadow features. The y axis has been scaled using a log transform, also as each of the variants return a different metric all of the values have been normalized for comparison.</figcaption></figure><h4>Breast Cancer Dataset</h4><p>The Wisconsin breast cancer data set contains 569 instances with 32 features. Each observation relates to a single patient and the challenge is to classify whether the scan is benign or malignant. The features from this data set describe characteristics of the cell nuclei and are computed from a digitized image of a fine needle aspirate (FNA) of a breast mass. As described in <a href="https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Diagnostic%29">UCI Machine Learning Repository</a>, the attribute information&#39;s are:</p><ul><li>a) radius (mean of distances from center to points on the perimeter)</li><li>b) texture (standard deviation of gray-scale values)</li><li>c) perimeter</li><li>d) area</li><li>e) smoothness (local variation in radius lengths)</li><li>f) compactness (perimeter² / area — 1.0)</li><li>g) concavity (severity of concave portions of the contour)</li><li>h) concave points (number of concave portions of the contour)</li><li>i) symmetry</li><li>j) fractal dimension (“coastline approximation” — 1)</li></ul><p>The mean, standard error and “worst” or largest (mean of the three largest values) of these features were computed for each image, resulting in 30 features.</p><p>From the figure below we can observe a difference not only between the feature subsets produced but also the ranking of the individual features. The fact that “Shap” provides the only consistent interpretation means that these outputs can also be used for inference about the models behavior on a global level. To test the quality of the subsets produced by the three variants I preformed a 5 fold cross validation on each of the three subsets produced the results of which are tabulated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*daSTvNs-HCCAJOBlNnMIVQ.png" /><figcaption>Table of Results from Cross Fold Validation</figcaption></figure><p>Here we can see that the subset produced by the “Shap” variant actually increases the accuracy of our “Random Forest” classifier by one percent. Although this may not sound all to impressive it reduced the feature subspace from 32 features to 21 that is a reduction of approximately 28 % thus we now have a more accurate and simpler model than before. One thing to note is that the Gain variant also achieved the same accuracy as the “Shap” variant however choose a larger and different subset of features. Also the last column considers the time taken for each variant we can see that the Gain variant is significantly faster than the others as it is independent of the number of observations as it uses the structure of the model itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHzrzHeuu6hZWw-jumXS4g.png" /><figcaption>Again the green values are those features which have been accepted, red rejected and blue represent metrics of the shadow features. The y axis has been scaled using a log transform, also as each of the variants return a different metric all of the values have been normalized for comparison.</figcaption></figure><h4>Madelon Dataset</h4><p>According to the <a href="https://archive.ics.uci.edu/ml/datasets/Madelon">UCI Machine Learning Repository</a> the Madelon is an artificial data set containing data points grouped in 32 clusters placed on the vertices of a five dimensional hypercube and randomly labeled +1 or -1. The five dimensions constitute 5 informative features. 15 linear combinations of those features were added to form a set of 20 (redundant) informative features. 480 redundant randomized features have then been added to create a data set containing 4400 observations and 500 columns.</p><p>Again the subsets produced are also quite different with “Shap” choosing 15 features to be statistically significantly , whereas botht the “Gain” and “Permutation” variants choose 19 and 20 features respectively . Surprisingly , all three variants achieved similar accuracy levels however the model produced from the “Shap” subset is a much similar with almost 25% less features than the other two models. One comparison to note is the linear dependence of both “Shap” and “Permutation” to the number of observations in the data set with both algorithms having a much longer run time relative to the “Gain” variant. Also another interesting aspect, is how different individual feature rankings are. With each variant essentially producing their own interpretation of the random forest model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIDGmvwDeLg3oaF4Qj3-Sg.png" /><figcaption>Table of Results from Cross Fold Validation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7x4YdxT_fQLeabHnMGs8sg.png" /><figcaption>As the dataset was so large only the accepted variables could be shown in a clear visualization, The green values are those features which have been accepted, red rejected and blue represent metrics of the shadow features. The y axis has been scaled using a log transform, also as each of the variants return a different metric all of the values have been normalized for comparison.</figcaption></figure><h4>Time Complexity</h4><p>When running the above analysis it was hard not to notice the differences between the run times for each of the variants. So I decided investigate it further by creating two experiments which highlight the dependency of each variant on the number of rows and observations. As we can see below the Gain/Gini method is independent from the size of the data set as it uses the internal structure of the tree to interpret the model, this allows it’s runtime to stay consistent across various data sizes. Whereas, both the “Shap” and “Permutation” algorithms are dependent on the input data to create their interpretations meaning the have scaling issues. However, “Permutation” importance is linearly dependent on both the number of observations and columns, while “Shap’s” TreeExplainer is linearly dependent on the number of observations it is not dependent on the number of columns but rather the complexity of the Tree as seen above O(TLD²).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeBKkBfblEZDenQ4I-69sw.png" /></figure><p>This creates a dilemma, despite the “Shap” implementation’s relative successes in both accuracy and time complexity, this algorithm will struggle on huge data sets from a time perspective. Furthermore, the “Boruta” algorithm cannot be parallelized as it is computed sequentially. Instead I propose to reduce the runtime by sampling a proportion of your data, at the expense of some estimation variance.</p><p>Rather than simply taking a random sample at each iteration, I created a method to find the smallest representative sample at each iteration. To do this I represented the data as an anomaly distribution by scoring every instance with an <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html">Isolation Forest</a> which returns a score between -1 and 1. Then starting at a sample size of 5% of the original data, I take a random sample where the probability of selection is weighted by how weird/strange this data point is using the Isolation Forest. This sample is then compared to the original distribution using a Ks-test and only samples with a score above 0.95 confidence level are accepted. If no samples are found within a set number of sampling tries then the size of the sample is increased by 5% and so on. In testing this method preformed really well reducing the time on some problems by up to 70%. However, this method does add more variance to the “Shap ”values themselves. Despite this the overall ranking and feature subset produced remains an accurate representation of the entire data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Kcit8o7KzyG6FLwS1_q7HQ.png" /><figcaption>The Random Distribution on the left is not an accurate representation of the underlying distribution in blue therefore it is rejected. Whereas, the sample on the right is accepted as it fits the underlying distribution quite well.</figcaption></figure><p>Before settling on this approach I did implement another sampling technique inspired by the K-means sampling approach provided by the “Shap” Kernel Explainer. This method clusters the data and uses the centroids of the clusters found from the K-means algorithm as the sample points. These samples are then weighted by the number of points in the cluster they represent. This method is nice as the number of samples is very low providing excellent improvements in speed. However, the overall feature ranking and feature subset left a lot to be desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*x-Hu7AEz-_GvQkJVi0AG-w.png" /><figcaption>Three clusters with the centroids marked with red crosses</figcaption></figure><h3>BorutaShap</h3><p>After all that I decided to package this code up and store it on the PYPI artifactory for anyone to use. This package can easily be installed using the pip install command as follows .</p><pre>pip install BorutaShap</pre><p>This package has a few nice features that would certainly stand out to me as potential user.</p><ol><li>It is the only implementation I know of that combines the “Boruta” Algorithm with Shapley values.</li><li>Second it can be used with any tree based learner of your choice. (In the future this may be expanded depending on demand)</li><li>Despite “Shap’s” lack of speed a unique sampling method has been implemented to speed up the process, also a gain importance metric can also be used to speed things up if desired.</li><li>The results can also be easily visualized and if the data set is too large to visualize, the results can be simply exported to a csv.</li></ol><h4>Example</h4><p>In my opinion the API has a very accessible and user friendly. To demonstrate this to you I will go through a simple feature selection process on the Boston House Pricing data set. This is a staple data set in the machine learning community where the challenge is to use 13 real valued features to predict the median house value. More information on this data set can be found <a href="https://www.kaggle.com/c/boston-housing">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17eec441790b04a0cc15cfad771f3a06/href">https://medium.com/media/17eec441790b04a0cc15cfad771f3a06/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*jQhJ-Bu71b-CfbW71_yZpg.png" /></figure><p>In order to use the “BorutaShap” feature selection tool we simply have to initialize it by creating an instance. This initialization takes a maximum of 5 parameters including a tree based model of your choice example a “Decision Tree ”or “XGBoost” default is a “Random Forest”. Which importance metric you would like to evaluate the features importance with either Shapley values (default) or Gini importance, A flag to specify if the problem is either classification or regression, a percentile parameter which will take a percentage of the max shadow feature thus making the selector less strict and finally a p-value or significance level which a after a feature will be either rejected or accepted. In this example we will use the all the default Parameters.</p><p>After the instance has been created we simply need to call the fit function which takes 5 Parameters also. X &amp; y are self explanatory and the random state has been added for reproducibility. The n_trials refers to the number of trials or iterations of the algorithm that you wish to run. Also there is a boolean sample parameter that when <strong>True </strong>will use the sampling technique mentioned above to speed up the process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a99fa636ba7e958da17b245946e7b83/href">https://medium.com/media/0a99fa636ba7e958da17b245946e7b83/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9fxfClRUiY9YzkVrLdtQQ.png" /></figure><p>As we can see the algorithm has confirmed 9 out of the 13 features to important predictors of our target variables. Whereas, 4 out of the 13 features have been rejected as they consistently preformed worse than the random variables.</p><p>In this case zero attributes were tentative, a tentative feature is one produced when the algorithm is unsure whether to reject or accept a feature. When this case arises you have three solutions. You can either run the algorithm for more iterations, look at the visual graph and decide whether it is important or not. Or you can use the TenativeRoughFix() function which will compare the median importance value of the tentative features with the median importance from the maximum random variable to decide to accept or reject the feature.</p><p>To visualize the results you can simply call the plot function which has a few parameters the the log of the y axis is chosen at default as it leads to a better visualization as without it the boxes are hard to see with the difference in scale. The <em>which_features</em> parameter has four different modes, ‘all’, ‘accepted’, ‘rejected’ and ‘tentative’ as sometimes the plot becomes overcrowded . If this is still the case there is a function to save your results to a csv to make it easier to understand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebed9dd2883ec796f2b87ae09ec97807/href">https://medium.com/media/ebed9dd2883ec796f2b87ae09ec97807/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*v1gJ_31Szp165kMzeAhLXQ.png" /></figure><p>We can then simply call the subset function to return the optimal feature subset of the original data frame to either save or use for modelling purposes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5ad0408725ff455f1433d4866d7914e/href">https://medium.com/media/a5ad0408725ff455f1433d4866d7914e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*fnqRWcUlCLRcsCyF4brF2A.png" /></figure><p>For more examples on how to use this package please look at these <a href="https://github.com/Ekeany/Boruta-Shap/tree/master/Examples">notebooks</a>. The following embedded notebook shows you how to use “BorutaShap” with various different Tree Based models. I thought the results were interesting as each model returns its own optimal subset of the data. Which truly shows the importance of using your selected model for the feature selection process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55b40d3d9fe42861c4897af0c828105f/href">https://medium.com/media/55b40d3d9fe42861c4897af0c828105f/href</a></iframe><h3>Conclusion</h3><p>“BorutaShap” definitely provides the most accurate subset of features when compared to both the “Gain” and “Permutation” methods. Although, I know “there is no free lunch” the “BorutaShap” algorithm is a great choice for any automatic feature selection task. Not only does this algorithm provide the best subset of features but in theory it is model agnostic, allowing you to replace the “Random Forest” with your intended model. Also, the “Shapley” values provide the most accurate and consistent global ranking results, this combined with the variance from each iteration is an excellent model inference tool giving the user a true insight into the inner workings of their black box model.</p><h3>References</h3><ol><li><a href="https://www.kdnuggets.com/2019/12/interpretability-part-3-lime-shap.html">https://www.kdnuggets.com/2019/12/interpretability-part-3-lime-shap.html</a></li><li><a href="https://www.jstatsoft.org/article/view/v036i11/v36i11.pdf">https://www.jstatsoft.org/article/view/v036i11/v36i11.pdf</a></li><li><a href="https://arxiv.org/pdf/1802.03888.pdf">https://arxiv.org/pdf/1802.03888.pdf</a></li><li><a href="https://christophm.github.io/interpretable-ml-book/shap.html">https://christophm.github.io/interpretable-ml-book/shap.html</a></li><li><a href="https://archive.ics.uci.edu/ml/index.php">https://archive.ics.uci.edu/ml/index.php</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bc238aa1677" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/is-this-the-best-feature-selection-algorithm-borutashap-8bc238aa1677">Is this the Best Feature Selection Algorithm “BorutaShap”?</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes “XGBoost” so Extreme ?]]></title>
            <link>https://medium.com/analytics-vidhya/what-makes-xgboost-so-extreme-e1544a4433bb?source=rss-1bc545e83cfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1544a4433bb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[from-scratch]]></category>
            <dc:creator><![CDATA[Eoghan Keany]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 18:17:37 GMT</pubDate>
            <atom:updated>2020-02-03T19:04:55.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>What makes “XGBoost” so Extreme?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*EJzzS8zqWL8VBN7rLr-xGg.png" /></figure><h3>Introduction</h3><p>Have you ever asked how “XGBoost” works ?, or how “XGBoost “differs from gradient boosting ?, or even a simple example in python. If you have then your in the right place. “Xgboost” is one of the most powerful machine learning tools available for tabulated data. It’s efficiency and performance in learning non linear decision boundaries have made it a staple in both industry and academia alike.<strong> So what makes this algorithm so special</strong> <strong>?</strong>.</p><p>This article was written in response to the frustration I encountered when trying to answer this question. Don’t get me wrong there are numerous resources online about the topic but none simply explain why “XGBoost” is so special and how it differs from gradient boosting.</p><p>In order to fully test my understanding of the algorithm, I decided to implement “XGBoost” from scratch in Python. Thus this article will try to explain the learning process and the knowledge gained in replicating the core components of “XGBoost”. Including external material that I found helpful and a simple numerical example that show how the algorithm works.</p><p>In essence “XGBoost” builds upon the foundations of gradient boosting by introducing regularization to combat over fitting along with numerous other additions. One could even argue the case that it would be more appropriate to name “XGBoost”, as <strong>regularized gradient boosting</strong> as this is one of the most crucial aspects to its success. In order to understand “XGBoost” fully it is necessary to first grasp the ideas behind it. Therefore, this article will begin with an explanation about Regression Trees, Gradient Boosting and then “XGBoost” itself.</p><ul><li>Regression Trees</li><li>Gradient Boosting</li><li>XGBoost</li></ul><h3>Regression Trees</h3><p>The regression tree is a simple machine learning model that can be used for regression tasks. Unlike linear models, decision trees have the ability to capture the non-linear interactions between the features and the target variable. Tree based models also have the added benefit of being highly interpretable as the model is constructed by the <strong>recursive partitioning </strong>of the data by using simple <strong>Yes/No</strong> logic conditions on the feature values. However, they do have some downsides, regression trees are notoriously unstable, meaning if you perturb your data in the slightest way you might get a completely different tree structure. Regression trees are also prone to over fit data and lack a solid principled probabilistic framework preventing them from having useful features such as confidence intervals, posterior probabilities etc.</p><p>The basic pseudo code of an <strong>exact greedy (</strong>calculates every split point value<strong>) </strong>regression tree model is as follows:</p><ol><li>Create the root node.</li><li>Iterate through every feature and find the best split value that maximizes some splitting criteria.</li><li>Check if any stopping criteria have been met if so stop building the tree otherwise continue with another node.</li></ol><p>I am linking a brilliant video made by Josh Starmer who clearly explains the process better than I ever could so if you don’t understand how a regression tree works under the hood I really suggest that you watch this video. As understanding these base algorithms really translates to the more complicated ones.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fg9c66TUylZ4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dg9c66TUylZ4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fg9c66TUylZ4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b4a9c995b08122082384d8104189879/href">https://medium.com/media/4b4a9c995b08122082384d8104189879/href</a></iframe><p>This video perfectly illustrates the split finding procedure of a regression tree. However, it does not really cover the tree constraints used to combat over fitting. A regression tree has four main criteria that it uses to influence the tree structure while training these include, Tree Depth, The number of nodes or number of leaves, Number of observations per split and minimum improvement an explanation of which is given below.</p><ol><li><strong>Tree depth</strong>, depth of tree refers to the number of layers in the tree as a deeper tree will more likely over fit the data therefore people usually set a depth constraint. Deeper trees are more complex thus shorter trees are preferred. Generally, the best results are seen with 4–8 layers.</li><li><strong>The number of nodes or leaves</strong> this is pretty self explanatory, very similar to the depth parameter but as depth is layer wise it is symmetric whilst this constraint is asymmetric can lead to unbalanced tree structures.</li><li><strong>Number of observations per split</strong> imposes a minimum constraint on the amount of training data at a training node before a split can be considered.</li><li><strong>Minimum improvement to gain</strong> is a constraint that requires a threshold improvement value for any new split to be added to the tree.</li></ol><p><strong>Tree Pruning</strong> is also a technique used to mitigate the effects of over fitting. However, it is applied post training and uses a metric such as <strong>cost complexity pruning. </strong>This method iterates over the tree removing leaf nodes until only the root remains. For each tree structure it defines a score which considers not only the accuracy of the tree’s predictions but also the complexity of its structure.</p><h3>Classical Gradient Boosting</h3><p>Gradient Boosting is a machine learning algorithm that can be used for both classification and regression problems. It creates an ensemble model from numerous weak predictors usually “<strong>Regression Trees</strong>” which are added in a stage wise fashion with each new tree focusing on the errors of the previous tree. This additive approach with a focus on previous mistakes essentially converts these weak learners into a single strong predictor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*aYfBx8vI7v-sdOhHPe-VQw.png" /><figcaption>The final prediction is the sum of all (M) trees which are weighted by a shrinkage factor lambda</figcaption></figure><p>One concept that I found really helpful to get an intuition for gradient boosting is to think of the problem in terms of gradient descent. I am essentially summarizing a fantastic blog post written by Nicholas Hug which will be linked <a href="http://nicolas-hug.com/blog/gradient_boosting_descent">here</a>.</p><p>Just to quickly recap how gradient descent is applied to a simple Ordinary Least Squares estimator. If we take the negative of the gradient of the loss function this will essentially guide us to the minimum of the function aka our best model. Most models such as OLS use gradient descent on the models hyperparamteters such as the slope/intercept to find the optimal solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsBakfF2Geh1zgY4HJbwFQ.gif" /><figcaption>Image shows gradient descent for linear regression. Image sourced from http://alykhantejani.github.io</figcaption></figure><p>This can be expressed mathematically as follows our loss function is defined as the sum of the squared residuals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*9zJb3bnGfVSWBV3MZHAySA.png" /><figcaption>Sum of the squared residuals</figcaption></figure><p>In order to minimize the loss function we take the derivative of the loss function with respect to the slope and the intercept and add the negative of this value to the slope weight scaled by some learning rate to achieve a more accurate model this is process is repeated until convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*Y6SQ4FsHE54QmY6esHtDjw.png" /><figcaption>Updated slope and equivalent equation is used to calculate the new intercept too except the derivative of the loss function is with respect to the intercept.</figcaption></figure><p>So why do we care ?, and what has this got to do with gradient boosting ?. Well if you notice that the sum of the squared residuals is written in terms of the predictions themselves (y hat). What would happen if we took the derivative with respect to predictions themselves and iteratively updated the predictions themselves ?.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*WxTFNDyIy-Z_0AaOk7ZH0w.png" /><figcaption>Updating the predictions using gradient descent</figcaption></figure><p>This is genius but there is one <strong>vital flaw</strong> we can’t make any predictions with this method as we need the true value Y in order to calculate the loss and update our predictions. Don’t worry this is where the sequential regression trees (weak learners) come into place. So instead of updating our predictions with the real value of the gradient, we will train a regression tree to predict these gradients, at each iteration. Thus, allowing us to make predictions on unseen data points.</p><p>Unfortunately we are not finished as the negative gradient only gives the direction of the step. Further effort is necessary to determine the step length (pm) that the will be taken in the direction. The most popular way to do this is a line search I will not go through all the math as someone already has <a href="https://towardsdatascience.com/boosting-algorithm-gbm-97737c63daa3">here</a>. Briefly we can write the loss function in terms of a tree do some math and we essentially end up with an equation to measure the quality of a tree structure with respect to the minimizing the loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*Rsb4lHdAl6eQVqtrXhrx_Q.png" /><figcaption>Gj is the sumof the gradients in a leaf and nj is the number of samples in that leaf node and T is the number of leaf nodes in the tree</figcaption></figure><p>As it is impractical to create every tree structure we can re-arrange this function to minimize the loss at every layer of the tree. This is a much better method than just using the internal mechanism of the regression tree to fit the residuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*8FVCeAVP0VbwkXa3NunU8w.png" /><figcaption>GL and nl are the sum of the gradients andd the number of samples on the left hand side of the split respectivly and GR and nR are the same but for the right hand side.</figcaption></figure><p>This is the core idea behind gradient boosting and the pseudo code for such an algorithm is as follows:</p><p><strong>Gradient Boosting Pseudo Code</strong></p><p>1.The algorithm begins by making an initial prediction that minimizes this equation below. If the task is regression then this equation boils down to using the average value of our target column as our initial prediction. Whereas, if we are concerned with classification then our initial prediction will use the log odds of our target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*uyc5xPC-SWC-m1euVTbjWA.png" /></figure><p>2. Next we need to compute the negative gradient of the loss function with respect to our predictions. A regression tree is then trained to estimate this gradient in order to predict unseen values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*6kDAwgdM2Q7j5C6FkDEGcQ.png" /></figure><p>3. Now that we have our regression tree structure we still need to find a single value for each leaf node that will minimizes this summation below. Again this looks complicated and the math is ! but when you take the derivative with respect to gamma and set this equation to zero to find optimal leaf value.<br>It essentially tells us that the average value in a leaf node is the optimal value for regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*P-Q5mkmiUgNSvoNxpiSP9Q.png" /></figure><p>4. This new regression tree is now added to the initial prediction, scaled by some shrinkage factor (learning rate). The negative gradient of this new model is then calculated and the entire process is repeated for a specific number of Boosting Rounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*dg0plQUZet9PApg9x-IHyg.png" /></figure><p>All of this may seem quite complicated but in practice it is actually surprisingly manageable. I will not do an example of gradient boosting by hand as there are many resources available online. Such as this video series by Statquest which I highly recommend watching to gain an intuition how this algorithm works in practice.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjxuNLH5dXCs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjxuNLH5dXCs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjxuNLH5dXCs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8dc6490b590efbb5535c1a6e2c4ed04/href">https://medium.com/media/c8dc6490b590efbb5535c1a6e2c4ed04/href</a></iframe><p>Although this series of videos eloquently describes the process of gradient boosting. If you were paying attention above you will notice that nearly all of the online resources use a naive approach to boosting. That is they use just a simple regression tree with its own internal split metric to fit the residuals.</p><p>So instead of using the defined loss function to construct the tree they simply grow the tree using some standard metric which has no direct link to problem at hand. However this is only a trivial fix as we simply replace the gain metric and sum up the leaf values in a different way but the process itself remains unchanged. On my GitHub repository I implement both a naive approach and on that follows Friedman’s model named “Gradient Boosting Machine”.</p><h3>Gradient Boosting in Python from Scratch</h3><p>For my own understanding I have implemented both gradient boosting for classification and regression in python only using Numpy and Pandas. I would not advice anyone to use this algorithm seriously. Rather it is a demonstration of the application of all the math from above. Hopefully if you are more comfortable with code might help you understand the material a bit better. As you can deconstruct the parts of the algorithm mess around with it and figure out how exactly everything works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b5310193a7b608ad2f77b6599a98c74/href">https://medium.com/media/0b5310193a7b608ad2f77b6599a98c74/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54bf17ae1f637dc5c1543a3e938469dd/href">https://medium.com/media/54bf17ae1f637dc5c1543a3e938469dd/href</a></iframe><h3>XGBoost</h3><p>XGBoost was developed by T. Chen &amp; C. Guestrin in 2016 and is described as an “optimized distributed gradient boosting library designed to be highly efficient, flexible and portable”. This algorithm has several noticeable improvements over classical gradient boosting notably:</p><ul><li>Newton Boosting</li><li>Regularization</li><li>Handling Missing Values</li><li>Weighted Quantile Sketch</li><li>Custom loss function</li><li>Parallel Processing</li></ul><p><strong>Newton Boosting</strong></p><p>As you already know by now it implements a gradient boosting framework that uses regression trees as weak learners plus some extra innovations. As we have seen above the classical implementation of gradient boosting can be viewed in terms of gradient descent, where the direction of travel is provided <br>by the negative gradient of the cost function and the step size is provided by the line search. This is the first major difference between “XGBoost” and the classical boosting algorithms as “XGBoost” is built upon the “<a href="https://en.wikipedia.org/wiki/Newton&#39;s_method_in_optimization">Netwon Rhapson Method</a>”. So instead of just computing the gradient and following it, it uses the second order derivative to gather more information to make a better approximation about the direction of the maximum decrease (in the loss function) and the step size . If we use gradient descent, we update our point x(i), at every iteration as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*Uk8oN_vxsaz0ch7Fi_ol8w.png" /><figcaption>Upside down triangle is the gradient and pm is the step size</figcaption></figure><p>Whereas, when using “Newton’s Method” x(i) is updated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*UN5ng_XqWWg6oZOGrYeSoQ.png" /></figure><p>Where “Hess” refers to the Hessian or the second order derivative of the loss function. This new update takes into account second order information<br>which will give a more precise estimate of the direction of highest decrease which should allow the model to converge at a much faster rate, also as the hessian is a constant value in many loss functions such as the mean squared error it is computationally inexpensive. This is the first major change that you will notice in my code as the regression trees now are not trying to simply fit the negative gradient of the loss function with respect to the predictions but both the negative gradient and the hessian.</p><p><strong>Taylor Expansion of Loss Function</strong></p><p>In order to use newton boosting, we use the Taylor expansion to rewrite the loss function around the current estimate in terms of the gradient and hessian. As we are using a tree to fit the data, this can then be further simplified into the summation of the leaf values of the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*kVlkM5J3cfo_RN-lynrUSA.png" /><figcaption>Tm is the number of leaves in the tree and Gjm and Hjm are the sum of the gradient and hessian in the region aka leaf and Wjm is the sum of the leaf weights. The right hand side refers to the regularization term</figcaption></figure><p>This becomes our optimization goal for the new tree. One important advantage of this definition is that the value of the loss function only depends on Gi and Hi. This is how XGBoost can support custom loss functions.</p><p><strong>Model Complexity</strong></p><p>A large proportion of “XGBoost’s” versatility and accuracy can be attributed to it’s focus on model complexity. Whereas, previously gradient boosting models only focused on improving impurity/gain. “XGBoost” applies a variety of regurlaization techniques to avoid overfitting. XGBoost defines the complexity of a tree as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*kCeF4UKHZKWv5BkzRp-MvA.png" /><figcaption>Where T is the number of leaves, <strong>γ</strong> is the penalization term on the number of terminal nodes, <strong>α</strong> and <strong>λ </strong>are for <strong>L1</strong> and <strong>L2</strong> regularization respectively. Wj is the sum of all the weights of the leaves.</figcaption></figure><p>Finally, since L1 regularization in trees is applied to <em>leaf scores</em> rather than directly to features as in regression, it actually serves to reduce the depth of trees. This <em>will</em> reduce the impact of less-predictive features, but it isn’t as severe as in regression where L1 regularization (Lasso) can set the contribution of features to zero. Both L1 and L2 are used together in XGBoost similarly to Elasticnet. The L1 regularization will punish the less-predictive features and L2 (Ridge) is used to further punish large leaf scores without having a huge impact on the less-predictive features.</p><p><strong>Structure Score</strong></p><p>After re-formulating the tree model using the Taylor expansion, we can write the loss function with respect to the Tth tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*UChi0uvc5bugSy3oFsRboA.png" /></figure><p>As the tree structure is fixed we can take the derivative with respect to a leaf weight to find the optimal leaf weight value exactly like we did for gradient boosting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*UtvUe0N877Gd5vNVJY7WcQ.png" /></figure><p>If we then plug this optimal value back into the equation before we have now approximated the loss function in terms of the next tree structure. This can also be viewed as metric for the quality of the structure of the new tree similar to the cost complexity tree pruning that we seen before with the regression trees. Where the smaller the value the better the tree structure is at minimizing the loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*UiH_l4PHV6w1MtwZbAxW4A.png" /></figure><p><strong>Learn the Tree Structure</strong></p><p>Now that we have a way to measure how good a tree is, we could build every possible tree structure but this is highly inefficient and impractical. Instead XGBoost optimizes one level at a time. This can be done by expressing the gain of a potential split in terms of the equation above. Thus we are using the loss function to construct the tree controlled by the model complexity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*ymMtvsqG1uuZqJ4UALAvTQ.png" /><figcaption>GL and HL are the sum of the gradient and the hessian values on the leaf values on the left hand side of the split and GR and HR are the sum of the gradient and the hessian values on the leaf values on the right hand side of the split.</figcaption></figure><p>This formula can be decomposed as 1) the score on the new left leaf 2) the score on the new right leaf 3) The score on the original leaf 4) regularization on the additional leaf. We can see an important fact here: if the gain is smaller than γ, we would do better not to add that branch. The role of the hessian in the denominator of the optimal leaf value equation is a bit ambiguous. However if we are using the RMSE loss function it’s second order derivative is essentially the number of samples. Thus normalizing by the hessian is giving us the average leaf weight. Where as in the case of logloss for classification it is a bit more intricate. The optimal leaf value essentially translates to the Z-score of the leaf for more info look <a href="https://github.com/dmlc/xgboost/issues/2483">here</a>. Also this derivation is in line with the actaul paper written with Tianqi Chen and corresponds to equation seven. However for simplicity he removes the alpha term corresponding to L1 regularization term for a full derivation I would recommend visiting this <a href="https://towardsdatascience.com/boosting-algorithm-xgboost-4d9ec0207d">article</a>.</p><p><strong>Weighted Quantile Sketch</strong></p><p>To find the best split over a continuous feature, data needs to be sorted and stored in memory this is an issue when dealing with large data sets. To solve this issue a novel method for finding approximate split points is used.</p><p>Candidate split points are proposed based on the percentiles of feature distribution. The continuous features are binned into buckets that are split based on the candidate split points. For example if you had a feature with 100 values sorted {1,2,3,….100} we can calculate the gain at each of the 10 10-quantiles split points {10,20,30⋯,90} and have a good approximation of the distribution. This is what the eps value in “XGBoost” is doing. “XGBoost” only considers a split point when the split has ∼eps*<em>N</em> more points under it than the last split point. If eps=0.01 on the example above then you will end up with ∼100 split points, being larger than {1%,2%,…,99%} of the other points. “Xgboost” does not consider a new split when “the sum changes more than eps but when the number of points under the current point is larger by eps than the last one.</p><p>If your feature values are similar than there is no real point splitting between them instead you want to split the parts of your data set that are very wrong. This is where the weights play a role we use the hessian to act as weight that represents how wrong the prediction is. So now the first 10-quantile will not be the first point that is larger than 10% of the points, but the first point that is larger than 10% of the hessian values.</p><p><strong>Handling Missing Values (Sparsity Aware)</strong></p><p>Unlike previous algorithms each node not only has a split point that determines whether samples are filtered to the left or to the right but it also has a base general direction. This direction is pre defined in XGBoost to the left meaning that any Missing Values (NAs) are filtered to the left, as a logical statement cannot be applied to a missing value.</p><p>However if you train your XGBoost with NAs included in the dataset then the model will automatically learn the best direction to send them either to the left or to the right. It does this by calculating the gain at the each split point point with all the NA values on the left hand side first and then computes the gain with the NA values on the right had side. Which ever split point minimizes maximizes the gain is chosen and the direction is set. Any unknown values will then be passed through this direction at that particular node upon prediction. We can do this as even though the feature value is missing we don’t use it to compute the gain all we need is the gradient and the hessian values. This calculation looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*CvHjpO-l5eRItOmxDCMRYw.png" /><figcaption>So the gain is calculated with the sum of the gradients and the hessian of the nas on the left and on the right hand side</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*Lp1CMO6wIPcNOkC96j2Fcw.png" /><figcaption>This is it in code</figcaption></figure><h3>Parameters</h3><p>XGBoost contains a wide variety of hyper-parameters some of these are quite cryptic relative to a standard regression tree thus I will try my best explain them.</p><p><strong>Scale_Pos_Weight</strong></p><p>This is a super useful parameter when dealing with an unbalanced data set. I have personally used it on a real life application with great success. Typically this parameter should be set as the ratio of the Majority Class to the Minority Class I usually use this function to calculate the scale pos weight factor, although like any other parameter for maximum accuracy some sort of optimization/tuning is advised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*17Idx26rtkkP1rC0a1_gNA.png" /></figure><p>I can only assume how this parameter effects the model as there is no mention of it within the actual paper or the documentation. Assuming that we have an imbalanced data set where we have 90% negative samples and Positive samples only account for 10%. The algorithm can either up sample meaning that it will repeat the positive examples 9 times to make it a balanced problem. However, I believe that the model instead builds a collection of models trained on 1/9th of the negative samples as it allows for easier cross validation of results. The outputs from each model are then ensembled together to create a more accurate result.</p><p><strong>Min_Child_Weight</strong></p><p>This parameter controls the model complexity. It is described as the “Minimum sum of instance weight (hessian) needed in a child. If the tree partition step results in a leaf node with the sum of instance weight less than min_child_weight, then the building process will give up further partitioning.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*m77CdlhC1CT1qdH6zkq4hA.png" /><figcaption>Mean Squared Error</figcaption></figure><p>For regression using the mean squared error the second derivative with respect to the predictions is simply 1. So when you get the sum of the hessian in a node it essentially equals the number of samples in that node. Whereas for binary logistic the Hessain for each point looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*tcLn1M0wAOZUw5jKBLuYow.png" /><figcaption>Hessian of logloss the sigma character represents the sigmoid function</figcaption></figure><p>Lets get an intuition for this equation so if we have a pure node (either we have only ones or zeros) with all ones then all the predictions will be large so all the hessian terms will be near zero. Similar logic holds if the node only contains zeros. So essentially the min_child_weight is stopping the tree from making further splits once a certain degree of purity has been reached to avoid over fitting.</p><p><strong>Eta</strong></p><p>Step size shrinkage is used to prevent over fitting. After each boosting step, we will scale the contribution of the new base learner on the prediction with eta. More or less this parameter is equivalent to the learning rate.</p><p><strong>Gamma</strong></p><p>This parameter also prevents over fitting and is present in the the calculation of the gain (structure score). As this is subtracted from the gain it essentially sets a minimum gain amount to make a split in a node.</p><p><strong>Subsample</strong></p><p>“XGBoost” will subsample the ratio of the training instances used to train a single tree at a particular boosting step. Setting it to 0.5 means that XGBoost would randomly sample half of the training data prior to growing its trees. This will happen for every tree so every tree will be trained on a different sample of the data which reduces variance as it reduces the dependence on certain values in the training sample. Both colsample and subsample are predicated upon the idea of a Random Forest.</p><p><strong>Colsample</strong></p><p>This parameter is based on the same idea as Subsample basically reduce the variance of the models by training on different parts of the data. Unlike row sampling there are three ways in which the XGBoost samples columns</p><p><em>Colsample_bytree:</em> For this we construct the entire tree on the same sub sample of the data</p><p><em>Colsample_bylevel:</em> At each tree level/depth we will only consider a sub sample of the columns to use. This sub sample will thus change for each level of the constructed tree.</p><p><em>Colsample_bynode:</em> This is at the most granular level as each node would be constrained to use a different sub set of the data.</p><p><em>Colsample_by:</em> all you to use a combination of all of the above sample methods. For instance, the combination {‘colsample_bytree’:0.5, ‘colsample_bylevel’:0.5, ‘colsample_bynode’:0.5} with 64 features will leave 8 features to choose from at each split.</p><p><strong>Lambda</strong></p><p>L2 regularization term on weights. Increasing this value will make model more conservative.</p><p><strong>Alpha</strong></p><p>L1 regularization term on weights. Increasing this value will make model more conservative.</p><p><strong>Sketch_eps</strong></p><p>This parameter is used in the quantile weighted skecth or ‘approx’ tree method roughly translates to (1 / sketch_eps) number of bins. If it was 0.1 and we had 100 examples then we would only calculate the gain for ten points.</p><p><strong>Tree Method</strong></p><p>Refers to algorithm used to construct the tree at a layerwise approach.</p><p><em>Exact: </em>refers to exact greedy where the gain will be calculated for every split point for every column. Thus giving the most accurate result.</p><p><em>Approx:</em> this equates to the weighted quantile sketch algorithm described above.</p><p><em>Hist: </em>Is a super fast histogram optimized approximate greedy algorithm inspired by the approach used in lightgbm.</p><p><strong>Max delta step</strong></p><p>This parameter can be used for extremely unbalanced class problems. As we seen above for the min_child_weight, if the leaf node is almost pure which will happen (when we have very unbalanced classes) the leaf weights value become very large as the hessian will tend to zero and as it is on the denominator of the weight equation will approach infinity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*qTaBc7iEcdL_yPPMnPMEnA.png" /></figure><p>So despite multiplying the weight values by eta/learning rate to stop over fitting in the case of severe class imbalances this will not be enough. What max_delta_step does is to introduce an ‘absolute’ regularization capping the weight before apply eta correction. Personally I have never had great success with this parameter and have found from experience that the scale_pos_weight factor gives better results.</p><h3><strong>“XGBoost” By Hand</strong></h3><p>Apologies that was a lot of complicated maths, but I think it is beneficial to include it and to have some sort of knowledge about the theory behind the algorithm rather then leave it out. I know that all that math looks scary but it really isn’t that complicated to apply. To prove this to you I am going to show exactly how “XGBoost” works under the hood by doing all the calculations by hand on a toy data set.</p><p>First we will start of with our toy data our goal is to predict if someone plays video games based on two features age and gender. The data looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*_chDNPzwoRUrTKgWbuw4bA.png" /></figure><p>“XGBoost” starts by making an initial prediction of 1 for each of the sample data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*1yWhz4_a8J4BQ_SR8iDNWw.png" /></figure><p>This is used as the starting point for the algorithm in theory we could start with any value here and in fact gradient boosting begins with the log odds of the target variable as its initial prediction. Which in my opinion is a better initial prediction. Using this prediction can now calculate the negative gradient and hessian of our loss function with respect to our predictions in order to construct our first tree. But first we need to convert our initial prediction of 1 into a probability value using the sigmoid function as inside the tree as we are using the logistic loss function all our values are in log odds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*iLt4cxtoF75dEW9SqJYGvg.png" /></figure><p>To use the sigmoid function we simply pass our initial prediction for each row through the function. Using these newly calculated probabilities we can now calculate the negative gradient and the hessian for each row in our data set. Again this is a simple procedure we just replace the p in our equations with our row probability and yi with the target variable in this case if a person plays video games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*URiQVnc5FE6wa4Xg_lzGnQ.png" /></figure><p>Now we can start constructing our tree for the purpose of this example I have chosen a gamma,lambda and learning rate value of 0, 1 and 0.4 respectively. The tree will be constructed using the exact greedy method where the gain is calculated at every split point. So for every value in a feature we will split the data filtering values below or equal to itself to the left and any values greater than itself to right. If you are unsure about the procedure of creating a regression tree I highly suggest going back to the start and watching the regression trees video provided. Anyways we will start with the root node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9DxbfHkZNl2ShuFe1_BAA.png" /></figure><p>Above we can see that the second table stores all the gain values for every split point across both features. In order to calculate the gain at a specific split point we use the equation on the right hand side of the table lets do an example for a potential split at say age 24 then the math would look like this. We will take the sum of the hessian and gradient of all the values less than or equal to 24 (in green) on the left hand side and calculate the sum of the hessian and gradient for all the values greater than 24 (in red)on the right. Below is the calculations required to calculate the gain for this particular split point the equation essentially compares the benefit of the splitting the node or not splitting the node the subtraction part, also gamma is there to set a minimum threshold we wish to allow a split to happen. In this case the gain is negative so we would not make a split at this value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*aCx0iC3LdVgZPS4WVVSVbw.png" /></figure><p>So after repeating this calculation for every split possible we can see that our first split point will be at 16 years of age as this value has the largest gain value. The node is split in two, creating two new nodes the people who are 16 or younger and those who are older than 16. We can see that the split on the left or those people who are 16 or younger all play video games. This means that this is a pure node and there is no point make any further splits here as they will all have negative gain values. So instead we will focus on making further splits to the right hand side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vAe4_jZqpIeiKxmPufMsw.png" /></figure><p>Now calculate the gain for every split inside are new node the maximum gain is given by a gender thus we will apply another split based on gender to the people who are older than 16. Again the left hand node is pure and will require no further splits whereas the right hand side can be split one more time from the look of things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgU2KdCTWjh-AOan2C52VQ.png" /></figure><p>So now we have exhausted our splits and our tree is constructed if you notice we have also calculated our leaf values. Using the equation provided we essentially just sum up the gradient in the leaf node and divide by the sum of the hessian plus a constant lambda. This table format looks a bit messy in my opinion so I am going to clean it up and show it the form of a tree structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*PuUefHpSh2LHnBDMguvxzg.png" /></figure><p>So now this is our first tree which we will now use to update our initial predictions the values in the leaf nodes are again in the log odds form and we will multiply there values by a learning rate of 0.4. Which ever leaf our samples fall into that will be their update value. Our new predictions will now look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*sNQvIM8upk956SBSQys5Qw.png" /></figure><p>So we have finished our first boosting round and now have our new predictions. To continue we will do the exact same process again by converting our newest predictions to probabilities and calculating the new negative gradient and hessian values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3cNsyZxOmTkXZForGEUWg.png" /></figure><p><strong>Second Tree</strong></p><p>Now that we have our new updated values for our Gradient and Hessian we can again fit a tree structure using the exact same procedure as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpDbXWrxH4P00901qEHvvA.png" /></figure><p>Again this looks messy so I will represent our new tree like this instead. Where the red represents a split node and green is a leaf node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*dYrga4VpfiCzu7c3z4D3Hg.png" /></figure><p>We now use this tree to make predictions and add this to our previous prediction.Which ever leaf our samples fall into that will be their update value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obuU3uIABjHHzZ7_WIIVpg.png" /></figure><p>That’s it we have completed two boosting rounds by hand. In summary, this what we have done. First we made an initial log odds prediction of 1 for our entire data set. By converting this prediction into a probability using the sigmoid function we were able to calculate the negative gradient and hessian with respect to our initial prediction. Then we constructed a regression tree from both these quantities and calculated our leaf node values from the equations above. This tree was then used to update our initial log odds prediction. The process was then repeated for our new updated log odds prediction for two boosting rounds. This simple example hopefully was helpful in demonstrating the main mechanism behind “XGBoost” just to point out this example was missing weighted quantile sketch and sparsity aware fitting to make the example more coherent.</p><h3>Implementation in Python from Scratch</h3><p>This is python implementation of “XGBoost” written using Numpy and Pandas it was developed for my understanding aka I would not recommend using it but feel free to deconstruct it and hopefully it can make some of the concepts more tangible. This example does not include the sparsity aware fitting (the ability to handle NA’s) as I think this is a more novel aspect of the algorithm and any good pipeline should be handling missing data before it reaches the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c795d0845687b96af27b7b9d64bb9634/href">https://medium.com/media/c795d0845687b96af27b7b9d64bb9634/href</a></iframe><h3>Conclusion</h3><p>I hope you enjoyed this post and it answered some of the questions that you had about “XGBoost”. If this post receives positive feedback then I might even consider creating something similar for Catboost. Also feel free to ask any questions if you have any doubts or if anything is unclear. This <a href="https://github.com/Ekeany/XGBoost-From-Scratch">link</a> will take you to the Github repository where the code lives.</p><h3>Reference Material</h3><ol><li><a href="https://arxiv.org/pdf/1603.02754.pdf">https://arxiv.org/pdf/1603.02754.pdf</a></li><li><a href="https://xgboost.readthedocs.io/en/latest/tutorials/model.html">https://xgboost.readthedocs.io/en/latest/tutorials/model.html</a></li><li><a href="https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/">https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/</a></li><li><a href="https://www.youtube.com/user/joshstarmer/videos">https://www.youtube.com/user/joshstarmer/videos</a></li><li><a href="https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/">https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/</a></li><li><a href="http://cican17.com/an-overview-of-boosted-trees/">http://cican17.com/an-overview-of-boosted-trees/</a></li><li><a href="https://towardsdatascience.com/boosting-algorithm-gbm-97737c63daa3">https://towardsdatascience.com/boosting-algorithm-gbm-97737c63daa3</a></li><li><a href="https://towardsdatascience.com/boosting-algorithm-xgboost-4d9ec0207d">https://towardsdatascience.com/boosting-algorithm-xgboost-4d9ec0207d</a></li><li><a href="http://nicolas-hug.com/blog/gradient_boosting_descent">http://nicolas-hug.com/blog/gradient_boosting_descent</a></li><li><a href="https://cengiz.me/posts/extreme-gradient-boosting/">https://cengiz.me/posts/extreme-gradient-boosting/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1544a4433bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/what-makes-xgboost-so-extreme-e1544a4433bb">What makes “XGBoost” so Extreme ?</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>