<?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 Tom Blanke on Medium]]></title>
        <description><![CDATA[Stories by Tom Blanke on Medium]]></description>
        <link>https://medium.com/@Tom_Blanke?source=rss-8ae63257dadd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MrkM2kgXvEaczGqtKf7Z2g.jpeg</url>
            <title>Stories by Tom Blanke on Medium</title>
            <link>https://medium.com/@Tom_Blanke?source=rss-8ae63257dadd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:56:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Tom_Blanke/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[Hyperparameter tuning for hyperaccurate XGBoost model]]></title>
            <link>https://medium.com/cmotions/hyperparameter-tuning-for-hyperaccurate-xgboost-model-d6e6b8650a11?source=rss-8ae63257dadd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e6b8650a11</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hyper-parameter-tuning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[grid-search]]></category>
            <category><![CDATA[gridsearchcv]]></category>
            <dc:creator><![CDATA[Tom Blanke]]></dc:creator>
            <pubDate>Sun, 27 Feb 2022 19:49:29 GMT</pubDate>
            <atom:updated>2022-03-06T15:55:42.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xOtvl1mo99TqzHPvTDrDrg.jpeg" /></figure><h4>No Data Scientist is the Same — part 4</h4><p><em>This article is part of our series about how different types of data scientists build similar models differently. No human is the same and therefore also no data scientist is the same. And the circumstances under which a data challenge needs to be handled changes constantly. For these reasons, different approaches can and will be used to complete the task at hand. In our series we will explore the four different approaches of our data scientists — Meta Oric, Aki Razzi, Andy Stand, and Eqaan Librium. They are presented with the task to build a model to predict whether employees of a company — STARDATAPEPS — will look for a new job or not. Based on their distinct profiles discussed in the </em><a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-introducing-our-data-science-rock-stars"><em>first blog</em></a><em> you can already imagine that their approaches will be quite different.</em></p><p>In the <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-good-model-by-default-using-xgboost">previous article</a> Meta Oric’s aim was to quickly create a default XGBoost and therefore she sticked with the default settings. In this article Aki Razi is going to search for a better model performance and tries to tune the hyperparameters. Before we start with discussing how she tries to do that, let me first remind you of who Aki Razzi is:</p><h3>Aki Razzi: ‘Accuracy is what truly matters’</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*afyOev6Lg6jKr1l0.png" /></figure><p>Aki has won multiple Kaggle competitions, since her models achieve the highest possible performance. Time and resources do not matter that much to her. Hail the almighty accuracy, precision and recall. She does not care whether a technique is easy to explain or not. Similarly, she is no stranger to using ensemble models to achieve the near-perfect performance as well as very convoluted feature engineering techniques.</p><h3>Using XGBoost to predict which Data Scientists are likely to change jobs</h3><p>First of all, Aki imports the necessary packages, among which ‘xgboost’ enabling her to create a XGBoost:</p><pre>pip install xgboost</pre><pre><em># Importing packages and settings: </em><br><strong>import</strong> warnings <br>warnings<strong>.</strong>filterwarnings(action<strong>=</strong> &#39;ignore&#39;)<br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np<br><strong>from</strong> sklearn.impute <strong>import</strong> SimpleImputer<br><strong>from</strong> sklearn.pipeline <strong>import</strong> Pipeline<br><strong>from</strong> sklearn.preprocessing <strong>import</strong> StandardScaler, OneHotEncoder<br><strong>from</strong> sklearn.compose <strong>import</strong> ColumnTransformer<br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br><strong>import</strong> xgboost <strong>as</strong> xgb<br><strong>from</strong> sklearn.model_selection <strong>import</strong> StratifiedKFold<br><strong>from</strong> sklearn.model_selection <strong>import</strong> cross_val_score<br><strong>from</strong> sklearn <strong>import</strong> metrics<br><strong>from</strong> sklearn.model_selection <strong>import</strong> GridSearchCV<br><strong>from</strong> sklearn.metrics <strong>import</strong> roc_curve<br><strong>import</strong> joblib</pre><p>Second, Aki loads the dataset. A bit of preparation on this data was done, as described <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-data-to-predict-which-employees-are-likely-to-leave">here</a>. The target variable ‘target’ indicates whether a data scientist in this historic dataset has left the company. All other columns in the dataset are possible predictors of whether a data scientist is likely to leave the company soon.</p><pre>df_prep <strong>=</strong> pd<strong>.</strong>read_csv(&#39;https://bhciaaablob.blob.core.windows.net/featurenegineeringfiles/df_prepared.csv&#39;)</pre><pre>df <strong>=</strong> df_prep<strong>.</strong>drop(columns<strong>=</strong>[&#39;Unnamed: 0&#39;,&#39;city&#39;, &#39;experience&#39;, &#39;enrollee_id&#39;])  </pre><pre>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*iT9uoitIixpX9oksK9Ty0Q.png" /></figure><p>Aki’s aim is to assess if she can improve Meta’s default XGBoost by tuning the hyperparameters. To make a fair comparison she performs the same data preparation steps as Meta did. She imputes the missing values, converts the categorical variables into dummies and standardizes the numerical variables. In addition, just like Meta did, Aki also uses <a href="https://towardsdatascience.com/how-to-use-sklearn-pipelines-for-ridiculously-neat-code-a61ab66ca90d">pipelines</a> to prep the data, to train her XGBoost, and to make predictions.</p><p>In the code below Aki separates the target from the features, creates a train and test dataset, and creates the pipelines to prep the features:</p><pre><em># Define the target vector y</em><br>y <strong>=</strong> df[&#39;target&#39;]  </pre><pre><em># Creating a dataset without the DV:</em><br>X <strong>=</strong> df<strong>.</strong>drop(&#39;target&#39;, axis <strong>=</strong> 1)</pre><pre><em># Split X and y into training and testing sets</em><br>X_train, X_test, y_train, y_test <strong>=</strong> train_test_split(<br>  X, y, test_size<strong>=</strong>0.25, stratify<strong>=</strong>y, random_state<strong>=</strong>1121218 <br>)</pre><pre><em># Creating an object with the column labels of only the categorical features and one with only the numeric features:</em><br>categorical_features <strong>=</strong> X<strong>.</strong>select_dtypes(exclude<strong>=</strong>&quot;number&quot;)<strong>.</strong>columns<strong>.</strong>tolist()<br>numeric_features <strong>=</strong> X<strong>.</strong>select_dtypes(include<strong>=</strong>&quot;number&quot;)<strong>.</strong>columns<strong>.</strong>tolist()</pre><pre><em># Create the categorical pipeline, for the categorical variables Aki imputes the missing values with a constant value and we encode them with One-Hot encoding:</em><br>categorical_pipeline <strong>=</strong> Pipeline(<br>    steps<strong>=</strong>[<br>        (&quot;impute&quot;, SimpleImputer(strategy<strong>=</strong> &#39;constant&#39;, fill_value<strong>=</strong> &#39;unknown&#39;)), <br>        (&quot;one-hot&quot;, OneHotEncoder(handle_unknown<strong>=</strong>&quot;ignore&quot;, sparse<strong>=False</strong>)) <br>    ]<br>)</pre><pre><em># Create the numeric pipeline, for the numeric variables Aki imputes the missings with the mean of the column and standardize them, so that the features have a mean of 0 and a variance of 1: </em><br>numeric_pipeline <strong>=</strong> Pipeline(<br>    steps<strong>=</strong>[(&quot;impute&quot;, SimpleImputer(strategy<strong>=</strong>&quot;mean&quot;)), <br>           (&quot;scale&quot;, StandardScaler())]<br>)</pre><pre><em># Combining the two pipelines with a column transformer:</em><br>full_processor <strong>=</strong> ColumnTransformer(transformers<strong>=</strong>[<br>        (&quot;numeric&quot;, numeric_pipeline, numeric_features),<br>        (&quot;categorical&quot;, categorical_pipeline, categorical_features),<br>    ]<br>)</pre><p>Next, Aki recreates Meta’s default XGBoost:</p><pre><em># Instantiate the XGBClassifier:</em><br>xgb_cl <strong>=</strong> xgb<strong>.</strong>XGBClassifier(eval_metric<strong>=</strong>&#39;logloss&#39;, seed<strong>=</strong>7) </pre><pre><em># Create XGBoost pipeline:</em><br>xgb_pipeline <strong>=</strong> Pipeline(steps<strong>=</strong>[<br>    (&#39;preprocess&#39;, full_processor),<br>    (&#39;model&#39;, xgb_cl)<br>])</pre><pre><em># Evaluate the model with the use of cv:</em><br>cv <strong>=</strong> StratifiedKFold(n_splits<strong>=</strong>5, shuffle<strong>=True</strong>, random_state<strong>=</strong>7)  <em>#, shuffle=True with or without shuffle??</em><br>scores <strong>=</strong> cross_val_score(xgb_pipeline, X_train, y_train, cv<strong>=</strong>cv, scoring <strong>=</strong> &#39;roc_auc&#39;)<br>print(&quot;roc_auc = %f (%f)&quot; <strong>%</strong> (scores<strong>.</strong>mean(), scores<strong>.</strong>std()))</pre><p>Output:</p><pre>roc_auc = 0.791519 (0.004802)</pre><p>With only default parameters without hyperparameter tuning, Meta’s XGBoost got a <a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">ROC AUC score</a> of 0.7915. As you can see below XGBoost has quite a lot of hyperparameters that Aki can tune to try to improve Meta’s default XGBoost.</p><pre><em># The default hyperparameters of the XGBoost:</em><br>xgb_cl</pre><p>Output:</p><pre>XGBClassifier(base_score=None, booster=None, colsample_bylevel=None, colsample_bynode=None, colsample_bytree=None, enable_categorical=False, eval_metric=’logloss’, gamma=None, gpu_id=None, importance_type=None, interaction_constraints=None, learning_rate=None, max_delta_step=None, max_depth=None, min_child_weight=None, missing=nan, monotone_constraints=None, n_estimators=100, n_jobs=None, num_parallel_tree=None, predictor=None, random_state=None, reg_alpha=None, reg_lambda=None, scale_pos_weight=None, seed=7, subsample=None, tree_method=None, validate_parameters=None, verbosity=None)</pre><p>After introducing you to Aki Razzi you can image that Aki is not yet satisfied with a XGBoost with only the default parameters. Aki attempts to improve Meta’s default XGBoost with the use of the GridSearchCV function from the scikit-learn package to optimize the model. GridSearchCV accepts possible values for the provided hyperparameters and fits separate models on the given data for each combination of hyperparameters. The performance of each combination of hyperparameters is evaluated and afterwards the best performing model can easily be selected. Thus, GridSearchCV enables Aki to tune multiple hyperparameters at once. It is not feasible to tune all hyperparameters at once, because this will result in way too many models. Aki optimizes seven hyperparameters with the use of 5-fold cross validation, meaning that if she tries to tune all parameters with just one gridsearch and with e.g. five different values for each parameter a total of 5x5x5x5x5x5x5x5 = 390.625 trees (seven times 5 for each parameter and one time 5 for the 5-fold cross validation) would be trained. Hence, Aki tunes the model in multiple steps.</p><p>As Meta did in the previous article, Aki evaluates each model created in the grid search based on ROC AUC score. She does so with the use of this function:</p><pre><strong>def</strong> print_results_gridsearch(gridsearch, list_param1, list_param2, name_param1, name_param2):<br>  <br>  <em># Checking the results from each run in the gridsearch: </em><br>  means <strong>=</strong> gridsearch<strong>.</strong>cv_results_[&#39;mean_test_score&#39;]<br>  stds <strong>=</strong> gridsearch<strong>.</strong>cv_results_[&#39;std_test_score&#39;]<br>  params <strong>=</strong> gridsearch<strong>.</strong>cv_results_[&#39;params&#39;]<br>  print(&quot;The results from each run in the gridsearch:&quot;)<br>  <strong>for</strong> mean, stdev, param <strong>in</strong> zip(means, stds, params):<br>    print(&quot;roc_auc = %f (%f) with: %r&quot; <strong>%</strong> (mean, stdev, param))<br>  <br>  <em>#Visualizing the results from each run in the gridsearch: </em><br>  scores <strong>=</strong> np<strong>.</strong>array(means)<strong>.</strong>reshape(len(list_param1), len(list_param2))<br>  <strong>for</strong> i, value <strong>in</strong> enumerate(list_param1):<br>    plt<strong>.</strong>plot(list_param2, scores[i], label<strong>=</strong> str(name_param1) <strong>+</strong> &#39;: &#39; <strong>+</strong> str(value))<br>  plt<strong>.</strong>legend()<br>  plt<strong>.</strong>xlabel(str(name_param2))<br>  plt<strong>.</strong>ylabel(&#39;ROC AUC&#39;)  <br>  plt<strong>.</strong>show()<br>    <br>  <em># Checking the best performing model:</em><br>  print(&quot;\n&quot;)<br>  print(&quot;Best model: roc_auc = %f using %s&quot; <strong>%</strong> (gridsearch<strong>.</strong>best_score_, gridsearch<strong>.</strong>best_params_))</pre><p>Aki starts with searching for the optimum parameters for the learning rate and the number of estimators (n_estimators). She begins her search with the commonly used starting value of 0.8 for subsample and colsample_bytree and keeps all other parameters at its default.</p><ul><li><strong>Learning_rate (eta):</strong> determines how fast the XGBoost model learns. In the boosting process, each additional tree modifies the overall model. The magnitude of the modification is controlled by the learning rate. A low learning rate makes computation slower, and requires more trees to achieve the same reduction in residual error as a model with a high learning rate. But, it optimizes the chances to reach the best optimum (optimum = perfect bias/variance tradeoff = no underfitting and no overfitting). Typically used values are 0.01–0.3 and its default value is 0.3.</li><li><strong>N_estimators:</strong> determines how many decisions trees will be built and boosted. If n_estimator is set equal to n_estimators=1, just a single decision tree will be created and thereby there is no boosting happening. This would make the result similar to training just a standard decision tree. The default XGBoost above (xgb_cl: Meta’s XGBoost) shows that the default value for n_estmators is 100 and it must be an integer greater than 0. The larger value you take for n_estimators, the more accurate the model performs on the trainset due to the Gradient Boosting algorithm. But it takes a longer time to train the model and it might overfit the model on your trainset.</li></ul><p>In the code below you see that the GridsearchCV contains a couple of parameters. First of all, it uses the created XGBoost pipeline: ‘xgb_pipeline’. Second, it uses a specified grid that will be tested in the gridsearch: ‘param_grid’. A third parameter that is specified for the gridsearch is n_jobs. N_jobs is the number of jobs to run in parallel. Aki has set it equal to -1, meaning that the grid search will use all available processors. Fourth, Aki uses 5-fold cross validation to tune the hyperparameters. Finally, the performance evaluation metric is set equal to the ROC AUC score for the cross-validation with the scoring parameter.</p><pre><em># Step 1: Searching for the optimum parameters for the learning rate and the number of estimators:</em></pre><pre><em># Defining the parameter grid to be used in GridSearch:</em><br>param_grid <strong>=</strong> {&quot;model__subsample&quot;: [0.8], &quot;model__colsample_bytree&quot;: [0.8]<br>              , &quot;model__learning_rate&quot;: [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3]<br>              , &quot;model__n_estimators&quot;: range(50,500,50)<br>              }</pre><pre><em>#instantiate the Grid Search:</em><br>cv <strong>=</strong> StratifiedKFold(n_splits<strong>=</strong>5, shuffle<strong>=True</strong>, random_state<strong>=</strong>7) <br>grid_cv1 <strong>=</strong> GridSearchCV(xgb_pipeline<br>                        , param_grid<br>                        , n_jobs<strong>=</strong> <strong>-</strong>1 <br>                        , cv <strong>=</strong> cv<br>                        , scoring<strong>=</strong>&quot;roc_auc&quot;) </pre><pre><em># Fit</em><br>_ <strong>=</strong> grid_cv1<strong>.</strong>fit(X_train, y_train) </pre><pre><em># Checking the results from each run in the gridsearch:  </em><br>print_results_gridsearch(gridsearch<strong>=</strong>grid_cv1, list_param1 <strong>=</strong> param_grid[&quot;model__learning_rate&quot;], list_param2 <strong>=</strong> param_grid[&quot;model__n_estimators&quot;]<br>                         , name_param1 <strong>=</strong> &#39;learning_rate&#39; , name_param2 <strong>=</strong> &#39;n_estimators&#39;)</pre><p>Output:</p><pre>The results from each run in the gridsearch (2 out of 54 displayed): <br>roc_auc = 0.799438 (0.004784) with: {‘model__colsample_bytree’: 0.8, ‘model__learning_rate’: 0.0001, ‘model__n_estimators’: 50, ‘model__subsample’: 0.8} <br>roc_auc = 0.799471 (0.004625) with: {‘model__colsample_bytree’: 0.8, ‘model__learning_rate’: 0.0001, ‘model__n_estimators’: 100, ‘model__subsample’: 0.8} <br>&quot;...&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*Z87CU5NgaKP2TRePgTbW0Q.png" /></figure><pre>Best model: roc_auc = 0.803714 using {‘model__colsample_bytree’: 0.8, ‘model__learning_rate’: 0.01, ‘model__n_estimators’: 250, ‘model__subsample’: 0.8}</pre><p>So, with only changing the number of estimators and the learning rate, Aki already improves the ROC AUC score from 0.7915 to 0.8037 compared to Meta’s XGBoost with default settings.</p><p>Next up, with the best values identified for the number of estimators and the learning rate, Aki continues with optimizing the parameters: max_depth and min_child_weight.</p><ul><li><strong>Max_depth:</strong> the maximum depth of a tree. It is used to control for overfitting. Increasing this value will make the model more complex, allowing the model to learn relations very specific to the sample at hand and making it more likely to overfit. In addition, XGBoost aggressively consumes memory when training a deep tree. Typically used values are 3–10 and as its default value is 6.</li><li><strong>Min_child_weight:</strong> the minimum sum of weights of all observations needed in a child node. So, if the tree partition step results in a leaf node with the sum of instance weight less than the min_child_weight, the building process will give up further partitioning. This parameter is also used to control for overfitting. Higher values prevent a model from learning relations which might be highly specific to the particular sample selected for a tree. But, too high values can lead to underfitting. Hence, it should be tuned using CV. The min_child_weight can be any number and the default is 1.</li></ul><pre><em># Step 2: Searching for the optimum parameters for max_depth and min_child_weight:</em></pre><pre><em># Defining the parameter grid to be used in GridSearch:</em><br>param_grid <strong>=</strong> {&quot;model__subsample&quot;: [0.8], &quot;model__colsample_bytree&quot;: [0.8], &quot;model__learning_rate&quot;: [0.01], &quot;model__n_estimators&quot;: [250]<br>              , &#39;model__max_depth&#39;: range(3,10,2)<br>              , &#39;model__min_child_weight&#39;: range(1,6,2)<br>             }</pre><pre><em>#instantiate the Grid Search:</em><br>cv <strong>=</strong> StratifiedKFold(n_splits<strong>=</strong>5, shuffle<strong>=True</strong>, random_state<strong>=</strong>7)<br>grid_cv2 <strong>=</strong> GridSearchCV(xgb_pipeline<br>                        , param_grid<br>                        , n_jobs<strong>=-</strong>1<br>                        , cv<strong>=</strong>cv<br>                        , scoring<strong>=</strong>&quot;roc_auc&quot;) </pre><pre><em># Fit</em><br>_ <strong>=</strong> grid_cv2<strong>.</strong>fit(X_train, y_train) </pre><pre><em># Checking the results from each run in the gridsearch:  </em><br>print_results_gridsearch(gridsearch<strong>=</strong>grid_cv2, list_param1 <strong>=</strong> param_grid[&quot;model__max_depth&quot;], list_param2 <strong>=</strong> param_grid[&quot;model__min_child_weight&quot;]<br>                         , name_param1 <strong>=</strong> &#39;max_depth&#39; , name_param2 <strong>=</strong> &#39;min_child_weight&#39;)</pre><p>Output:</p><pre>The results from each run in the gridsearch (2 out of 12 displayed): <br>roc_auc = 0.797348 (0.004734) with: {‘model__colsample_bytree’: 0.8, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 3, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__subsample’: 0.8} <br>roc_auc = 0.797315 (0.004521) with: {‘model__colsample_bytree’: 0.8, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 3, ‘model__min_child_weight’: 3, ‘model__n_estimators’: 250, ‘model__subsample’: 0.8} <br>&quot;...&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*kglm-FI1mNTAfBEiLToRlw.png" /></figure><pre>Best model: roc_auc = 0.803552 using {‘model__colsample_bytree’: 0.8, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 5, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__subsample’: 0.8}</pre><p>The search for optimal values for the maximum depth of a tree and the minimum child weight resulted in only changing the maximum depth from six to five and keeping the minimum child weight at the default of 1. Due to only a small change to the parameters, the performance of the new best performing model is comparable to the previous one. The mean ROC AUC from the cross validation in this gridsearch is even slightly lower, it decreased from 0.8037 to 0.8036.</p><p>Third, Aki tries to improve the parameters: subsample and colsample_bytree.</p><ul><li><strong>Subsample:</strong> the fraction of observations XGBoost will randomly take for constructing each tree. If you set this value to 0.5, XGBoost will randomly collect half of the records to grow trees. This can be used to prevent overfitting. A lower value prevents overfitting and makes the algorithm more conservative, but too small values might lead to underfitting. Typically used values are 0.4–1 and its default value is 1.</li><li><strong>Colsample_bytree:</strong> the fraction of columns XGBoost will randomly take for constructing each tree. This parameter can also be used to control for overfitting. Typically used values are 0.4–1 and as its default value is 1.</li></ul><pre><em># Step 3: Searching for the optimum parameters for subsample and colsample_bytree:</em></pre><pre><em># Defining the parameter grid to be used in GridSearch:</em><br>param_grid <strong>=</strong> {&quot;model__learning_rate&quot;: [0.01], &quot;model__n_estimators&quot;: [250], &#39;model__max_depth&#39;: [5], &#39;model__min_child_weight&#39;: [1]<br>              , &#39;model__subsample&#39;:[i<strong>/</strong>10.0 <strong>for</strong> i <strong>in</strong> range(4,10)]<br>              , &#39;model__colsample_bytree&#39;:[i<strong>/</strong>10.0 <strong>for</strong> i <strong>in</strong> range(4,10)] <br>             }</pre><pre><em>#instantiate the Grid Search:</em><br>cv <strong>=</strong> StratifiedKFold(n_splits<strong>=</strong>5, shuffle<strong>=True</strong>, random_state<strong>=</strong>7)<br>grid_cv3 <strong>=</strong> GridSearchCV(xgb_pipeline<br>                        , param_grid<br>                        , n_jobs<strong>=-</strong>1<br>                        , cv<strong>=</strong>cv<br>                        , scoring<strong>=</strong>&quot;roc_auc&quot;) </pre><pre><em># Fit</em><br>_ <strong>=</strong> grid_cv3<strong>.</strong>fit(X_train, y_train) </pre><pre><em># Checking the results from each run in the gridsearch:  </em><br>print_results_gridsearch(gridsearch<strong>=</strong>grid_cv3, list_param1 <strong>=</strong> param_grid[&quot;model__subsample&quot;], list_param2 <strong>=</strong> param_grid[&quot;model__colsample_bytree&quot;]<br>                         , name_param1 <strong>=</strong> &#39;subsample&#39; , name_param2 <strong>=</strong> &#39;colsample_bytree&#39;)</pre><p>Output:</p><pre>The results from each run in the gridsearch (2 out of 36 displayed): <br>roc_auc = 0.801835 (0.004100) with: {‘model__colsample_bytree’: 0.4, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 5, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__subsample’: 0.4} <br>roc_auc = 0.801859 (0.004040) with: {‘model__colsample_bytree’: 0.4, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 5, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__subsample’: 0.5}<br>&quot;...&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*DVfWb5-JYajq0FhTT_Aobg.png" /></figure><pre>Best model: roc_auc = 0.803887 using {‘model__colsample_bytree’: 0.9, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 5, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__subsample’: 0.5}</pre><p>The grid search above resulted in the optimum values: 0.5 for the subsample and 0.9 for the colsample_bytree. In other words, the grid search shows that the best model performance is achieved by constructing each tree based on half of the records and 90% of the features. Tuning these parameters improve the model performance from an AUC ROC score of 0.8036 to 0.8039.</p><p>Finally, Aki tries to improve the model even further by tuning the gamma and the lambda.</p><ul><li><strong>Gamma (min_split_loss):</strong> specifies the minimum loss reduction required to make a split. A node only splits when the resulting split gives a positive reduction in the loss function above the gamma threshold. It is a pseudo-regularization hyperparameter in gradient boosting. The higher the Gamma, the higher the regularization, and the more conservative the algorithm. Gamma depends on both the training set and the other parameters you use. Gamma can be any integer and its default value is 0.</li><li><strong>Lambda:</strong> the L2 regularization term on weights (analogous to Ridge regression). This term is a constant that is added to the second derivative (Hessian) of the loss function during gain and weight (prediction) calculations. Lambda effects the choice of split points as well as the weight size. Although many data scientists don’t tune this parameter, it should be explored to reduce overfitting. Increasing this value will make the model more conservative. Lambda can be any integer and its default value is 1. XGBoost is also known as a ‘regularized boosting’ technique, due to its regularization terms.</li></ul><pre><em># Step 4: Searching for the optimum parameters for gamma and lambda: </em></pre><pre><em># Defining the parameter grid to be used in GridSearch:</em><br>param_grid <strong>=</strong> {&quot;model__learning_rate&quot;: [0.01], &quot;model__n_estimators&quot;: [250], &#39;model__max_depth&#39;: [5], &#39;model__min_child_weight&#39;: [1], &#39;model__subsample&#39;:[0.5], &#39;model__colsample_bytree&#39;:[0.9] <br>              , &quot;model__gamma&quot;: [i<strong>/</strong>10.0 <strong>for</strong> i <strong>in</strong> range(0,6)]<br>              , &quot;model__reg_lambda&quot;: [0, 0.5, 1, 1.5, 2, 3, 4.5]<br>             }<br>              <br><em>#instantiate the Grid Search:</em><br>cv <strong>=</strong> StratifiedKFold(n_splits<strong>=</strong>5, shuffle<strong>=True</strong>, random_state<strong>=</strong>7)<br>grid_cv4 <strong>=</strong> GridSearchCV(xgb_pipeline<br>                        , param_grid<br>                        , n_jobs<strong>=-</strong>1<br>                        , cv<strong>=</strong>cv<br>                        , scoring<strong>=</strong>&quot;roc_auc&quot;) <br></pre><pre><em># Fit</em><br>_ <strong>=</strong> grid_cv4<strong>.</strong>fit(X_train, y_train) </pre><pre><em># Checking the results from each run in the gridsearch:  </em><br>print_results_gridsearch(gridsearch<strong>=</strong>grid_cv4, list_param1 <strong>=</strong> param_grid[&quot;model__gamma&quot;], list_param2 <strong>=</strong> param_grid[&quot;model__reg_lambda&quot;]<br>                         , name_param1 <strong>=</strong> &#39;Gamma&#39; , name_param2 <strong>=</strong> &#39;Lambda&#39;)</pre><p>Output:</p><pre>The results from each run in the gridsearch (2 out of 42 displayed): <br>roc_auc = 0.803624 (0.004730) with: {‘model__colsample_bytree’: 0.9, ‘model__gamma’: 0.0, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 5, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__reg_lambda’: 0, ‘model__subsample’: 0.5} <br>roc_auc = 0.803668 (0.004591) with: {‘model__colsample_bytree’: 0.9, ‘model__gamma’: 0.0, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 5, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__reg_lambda’: 0.5, ‘model__subsample’: 0.5}<br>&quot;...&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*pVFIn8b1oDZQ42rESHdxNg.png" /></figure><pre>Best model: roc_auc = 0.803887 using {‘model__colsample_bytree’: 0.9, ‘model__gamma’: 0.0, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 5, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__reg_lambda’: 1, ‘model__subsample’: 0.5}</pre><p>This final grid search shows that the default values should not be changed. Therefore, Aki keeps Gamma equal to 0 and Lamda equal to 1, resulting in the same and final AUC ROC score of 0.8039. By tuning the model in four steps and searching for the optimal values for eight different hyperparameters, Aki manages to improve Meta’s default XGBoost from a ROC AUC score of 0.791519 to 0.8039. This results in the best set of hyperparameters, which are shown below.</p><pre>grid_cv4<strong>.</strong>best_params_</pre><p>Output:</p><pre>{‘model__colsample_bytree’: 0.9, ‘model__gamma’: 0.0, ‘model__learning_rate’: 0.01, ‘model__max_depth’: 5, ‘model__min_child_weight’: 1, ‘model__n_estimators’: 250, ‘model__reg_lambda’: 1, ‘model__subsample’: 0.5}</pre><p>Now both Meta and Aki found their final parameters for their XGBoost algorithms we can evaluate their models on the testset:</p><pre><em># Predict with Aki&#39;s final XGBoost with the best parameters resulting from the GridSearch: </em><br>y_pred_aki <strong>=</strong> grid_cv4<strong>.</strong>predict(X_test)<br>y_pred_prob_aki <strong>=</strong> grid_cv4<strong>.</strong>predict_proba(X_test)[::,1]</pre><pre><em># Evaluate:</em><br>print(&quot;roc_auc_score:&quot;,metrics<strong>.</strong>roc_auc_score(y_test, y_pred_aki))</pre><p>Output:</p><pre>roc_auc_score: 0.7149328865312845</pre><p>Code:</p><pre><em># Fit Meta&#39;s default XGBoost pipeline:</em><br>xgb_pipeline<strong>.</strong>fit(X_train, y_train)</pre><pre><em># Predict:</em><br>y_pred_meta <strong>=</strong> xgb_pipeline<strong>.</strong>predict(X_test)<br>y_pred_prob_meta <strong>=</strong> xgb_pipeline<strong>.</strong>predict_proba(X_test)[::,1]</pre><pre><em># Evaluate:</em><br>print(&quot;roc_auc_score:&quot;,metrics<strong>.</strong>roc_auc_score(y_test, y_pred_meta))</pre><p>Output:</p><pre>roc_auc_score: 0.6993045967695355</pre><p>Code:</p><pre><em># Compute False postive rate, and True positive rate</em><br>fpr1 , tpr1, thresholds1 <strong>=</strong> roc_curve(y_test, y_pred_prob_aki)<br>fpr2 , tpr2, thresholds2 <strong>=</strong> roc_curve(y_test, y_pred_prob_meta)</pre><pre><em># Calculate Area under the curve to display on the plot</em><br>roc_auc_aki <strong>=</strong> metrics<strong>.</strong>roc_auc_score(y_test, y_pred_aki)<br>roc_auc_meta <strong>=</strong> metrics<strong>.</strong>roc_auc_score(y_test, y_pred_meta)</pre><pre><em># Now, plot the computed values</em><br>plt<strong>.</strong>plot([0,1],[0,1], &#39;k--&#39;)<br>plt<strong>.</strong>plot(fpr1, tpr1, label<strong>=</strong> &#39;%s ROC (area = %0.2f)&#39; <strong>%</strong> (&quot;XGBoost Aki&quot;, roc_auc_aki)) <em>#&quot;XGBoost Aki&quot;)</em><br>plt<strong>.</strong>plot(fpr2, tpr2, label<strong>=</strong> &#39;%s ROC (area = %0.2f)&#39; <strong>%</strong> (&quot;XGBoost Meta&quot;, roc_auc_meta)) <em>#label= &quot;XGBoost Meta&quot;)</em><br>plt<strong>.</strong>legend()<br>plt<strong>.</strong>xlabel(&#39;False Positive Rate&#39;)<br>plt<strong>.</strong>ylabel(&#39;True Positive Rate&#39;)<br>plt<strong>.</strong>title(&#39;Receiver Operating Characteristic&#39;)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*I3Os8QSoXDSHPE2JsixddQ.png" /></figure><p>As on the trainset, Aki’s tuned XGBoost outperforms Meta’s default XGBoost. Aki’s tuning resulted in an improved ROC AUC score of 0.7149 compared to Meta’s ROC AUC score of 0.6993. As we did for Meta in the previous article, we also save Aki’s model to be able to compare results later on. Just to be sure, we quickly test if her model is saved correctly.</p><pre><em>#Saving Aki&#39;s final XGBoost pipeline:</em><br>best_pipe_aki <strong>=</strong> grid_cv4<strong>.</strong>best_estimator_<br>joblib<strong>.</strong>dump(best_pipe_aki, &#39;best_pipe_aki.joblib&#39;)</pre><p>Output:</p><pre>[‘best_pipe_aki.joblib’]</pre><p>Code:</p><pre><em>#Testing if Aki&#39;s model is correctly saved:</em></pre><pre><em># Load the models:  </em><br>upload_pipe_aki <strong>=</strong> joblib<strong>.</strong>load(&#39;best_pipe_aki.joblib&#39;)</pre><pre><em># Use it to make the same predictions:</em><br>print(upload_pipe_aki<strong>.</strong>predict(X_test))</pre><p>Output:</p><pre>[0 1 0 … 0 1 0]</pre><p>I hope you enjoyed reading this article and getting to know Aki. Her approach didn’t really focus on prepping the features, she focused on improving Meta’s XGBoost by tuning the hyperparameters. In the upcoming articles we investigate if we can improve her data preparations. Topics that we will look into are <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-beat-dirty-data">common data problems</a>, <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-the-case-of-high-cardinality-kerfuffles">dealing with high cardinality</a>, and <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-guide-to-manage-missing-data">dealing with missing data</a>. We will not only focus on improving model performance, but also how to improve the interpretability and explainability of the models. This is something both Andy Stand and Eqaan Librium value very much when practicing data science.</p><p>This article is part of our <strong>No Data Scientist Is The Same </strong>series. The full series is written by <a href="https://medium.com/@anya.tonne">Anya Tonne</a>, <a href="https://medium.com/@jurriaan.nagelkerke">Jurriaan Nagelkerke</a>, <a href="https://medium.com/@karingruijs">Karin Gruijs-Vodde</a> and <a href="https://medium.com/@Tom_Blanke">Tom Blanke</a>. The series is also available on <a href="https://www.theanalyticslab.nl/blogs/">theanalyticslab.nl</a>.</p><p>An overview of all articles on Medium within the series:</p><ol><li><a href="https://medium.com/@anya.tonne/introducing-our-data-science-rock-stars-19ef8d9131a6">Introducing our data science rock stars</a></li><li><a href="https://medium.com/@jurriaan.nagelkerke/data-to-predict-which-employees-are-likely-to-leave-4fe1c64b1af4">Data to predict which employees are likely to leave</a></li><li><a href="https://medium.com/@Tom_Blanke/good-model-by-default-using-xgboost-ab14f26f7f6a">Good model by default using XGBoost</a></li><li><a href="https://medium.com/@Tom_Blanke/hyperparameter-tuning-for-hyperaccurate-xgboost-model-d6e6b8650a11">Hyperparameter tuning for hyperaccurate XGBoost model</a></li><li><a href="https://medium.com/@karingruijs/beat-dirty-data-5d9a6254c2f9">Beat dirty data</a></li><li><a href="https://medium.com/@anya.tonne/the-case-of-high-cardinality-kerfuffles-d9b7fccc6570">The case of high cardinality kerfuffles</a></li><li><a href="https://medium.com/@karingruijs/guide-to-manage-missing-data-961bee610ef9">Guide to manage missing data</a></li><li><a href="https://medium.com/@jurriaan.nagelkerke/visualise-the-business-value-of-predictive-models-21c6bc8132c">Visualise the business value of predictive models</a></li><li><a href="https://medium.com/@jurriaan.nagelkerke/no-data-scientist-is-the-same-42a5bfdf7ed6">No data scientist is the same!</a></li></ol><p>Do you want to do this yourself? Please feel free to download the Notebook on our <a href="https://gitlab.com/cmotions/publications/-/tree/master/NoDataScientistIsTheSameNotebooks">gitlab page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e6b8650a11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/hyperparameter-tuning-for-hyperaccurate-xgboost-model-d6e6b8650a11">Hyperparameter tuning for hyperaccurate XGBoost model</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Good model by default using XGBoost]]></title>
            <link>https://medium.com/cmotions/good-model-by-default-using-xgboost-ab14f26f7f6a?source=rss-8ae63257dadd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab14f26f7f6a</guid>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Tom Blanke]]></dc:creator>
            <pubDate>Sat, 26 Feb 2022 17:43:00 GMT</pubDate>
            <atom:updated>2022-03-06T15:44:32.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*r6RjKtbN9Nda-4VqVhbObw.jpeg" /></figure><h4>No Data Scientist is the Same — part 3</h4><p><em>This article is part of our series about how different types of data scientists build similar models differently. No human is the same and therefore also no data scientist is the same. And the circumstances under which a data challenge needs to be handled changes constantly. For these reasons, different approaches can and will be used to complete the task at hand. In our series we will explore the four different approaches of our data scientists — Meta Oric, Aki Razzi, Andy Stand, and Eqaan Librium. They are presented with the task to build a model to predict whether employees of a company — STARDATAPEPS — will look for a new job or not. Based on their distinct profiles discussed in the </em><a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-introducing-our-data-science-rock-stars"><em>first blog</em></a><em> you can already imagine that their approaches will be quite different.</em></p><p><em>In this article we will discuss Meta Oric’s approach. Let me first remind you of who Meta oric is:</em></p><h3>Meta Oric: “It’s all about Meteoric speed”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*i8eJF0EtJd36HoeR.png" /></figure><p>Meta Oric is always very busy. She works on a lot of different projects and as a result she does not have much time to spend on each individual model that she has to build. This also applies when she is presented with the challenge to predict whether employees will look for a new job or not. She is very excited that her company is starting with HR analytics and therefore does not want to miss out on this opportunity. But she is already struggling with how to finish her current projects. Therefore, she decides to get a piece of the action by trusting the power of XGBoost. In previous projects, she had great experiences with the use of XGBoost and with little dataprep and reusing an old notebook she can quickly produce a model.</p><h3>Why is Meta so excited about XGBoost?</h3><p>One of the most popular algorithms for both regression and classification tasks nowadays, is <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a>. But what makes XGBoost so special and why is Meta so excited about it?</p><p>The two main reasons why XGBoost is so popular are:</p><ul><li><em>Execution speed</em>: The core XGBoost algorithm is parallelizable and can thereby use all of the processing power of your machine or it can be run in parallel on multiple machines. This makes XGBoost fast and makes it possible to train the algoritmn on very large sets of data.</li><li><em>Model performance</em>: Its outstanding model performance on structured or tabular datasets is the main reason why XGBoost is so popular. Many challenges and competitions (Kaggle and others) have been won by using XGBoost (<a href="https://github.com/dmlc/xgboost/tree/master/demo#machine-learning-challenge-winning-solutions">see here a list of machine learning winning solutions with XGBoost</a>)</li></ul><p>There are a lot of good introductions to XGBoost available, a very nice introduction to the model can be found <a href="https://xgboost.readthedocs.io/en/latest/tutorials/model.html">here</a>. In short, eXtreme Gradient Boosting (XGBoost) is an ensemble learning method constructed from decision tree algorithms. XGBoost is an ensemble method, which means that it is a combination of multiple base models (multiple decision trees) in order to produce one optimal predictive model. There are different kinds of ensemble methods, among which bagging and boosting. XGBoost uses a <strong>gradient boosting</strong> framework. Meaning, the decision trees in XGBoost are grown in a sequential manner, as an iterative learning process: A first tree is trained and evaluated, after that the incorrect predicted data points are given more weightage in the next iteration. Then a next tree is trained and evaluated and the wrong predictions are given more weightage in the following iteration etc.</p><p><strong>Boosting visualized</strong> (<a href="https://www.datacamp.com/community/tutorials/xgboost-in-python">source</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*0EWtb6atLBAy-ai5.png" /></figure><p>By giving wrongly predicted data points more weightage, these data points have a higher probability to appear in the next trained tree. XGBoost uses a <a href="https://arxiv.org/pdf/1603.02754.pdf">weighted quantile sketch algorithm</a> to effectively find the splitting points in weighted data. This boosting ensemble method is the main difference between XGBoost and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">Random Forest</a>. With Random Forest, new training datasets are formed by random sampling with replacement from the original dataset, where each observation has the same probability to appear in a new dataset (also referred to as <strong>Bagging</strong>). Thus, Random Forest and boosted trees are both tree-based ensemble algorithms and the difference between them arises from how the models are trained.</p><h3>What makes Extreme Gradient Boosting ‘Extreme’?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*-gt7u0pNwLJNXULA.jpg" /></figure><p>XGBoost wasn’t the first algorithm to use a boosting strategy in predictions. Earlier on, Gradient Boosting models were popular but they were surpassed when XGBoost was introduced. Why? The <a href="https://www.educba.com/xgboost-algorithm/">picture</a> above shows the improvements that make XGBoost an advanced version of Gradient Boosting (GBM).</p><p><em>First of all, system improvements:</em></p><ul><li>Parallelization: Making use of all available CPU cores.</li><li>Tree Pruning: A gradient boosting model stops splitting when it encounters a negative loss in the split, making it a more greedier algorithm. However, XGBoost makes splits until the provided max_dept is reached and then starts pruning the tree backwards and remove splits beyond which there is no positive gain.</li><li>Cache awareness and out-of-core computing: XGboost has been designed to make efficient use of hardware resources.</li></ul><p><em>Second, algorithmic improvements:</em></p><ul><li>Regularization: A general principle of model building is that we would like to have a simple and predictive model. The tradeoff between the two is also referred to as bias-variance tradeoff in machine learning. As Tiangi Chen, one of the builders of XGBoost, <a href="https://www.quora.com/What-is-the-difference-between-the-R-gbm-gradient-boosting-machine-and-xgboost-extreme-gradient-boosting/answer/Tianqi-Chen-1">emphasizes</a> a difference between GBM and XGBoost is that XGBoost controls for the complexity of the model through both LASSO (L1) and Ridge (L2) regularization, which helps us to avoid overfitting. Therefore XGBoost is also known as a ´regularized boosting´ technique.</li><li>Handling of missing/Sparsity-aware: XGBoost contains a sparsity-aware split finding algorithm and handles different types of sparsity patterns in the data. Thereby it handles missing data (which most other algorithms can’t) and also sparsity that could occur due to one-hot encoding, zero entries etc.</li><li>Built-in cross-validation: The algorithm has a built-in cross-validation method at each iteration which removes the need to explicitly program this search and to specify the exact number of boosting iterations required in a single run.</li></ul><h3>Disadvantages of XGBoost:</h3><p>There are a few reasons why some of our data scientists will consider other algorithms in our series of articles:</p><ul><li>The biggest disadvantage of XGBoost is that it is a black box in nature. XGBoost does not provide you with effect sizes. You need to program this part yourself.</li><li>XGBoost performs less on unstructured data.</li><li>It has many hyperparameters and is thereby harder to tune.</li><li>Although XGBoost is less sensitive to overfitting than GBM, it is still sensitive to overfitting if parameters aren’t tuned properly.</li><li>Like every boosting ensemble method XGBoost is sensitive to outliers, since every classifier tries to fix the errors in the predecessors.</li></ul><h3>Using XGBoost to predict which Data Scientists are likely to change jobs</h3><p>Meta Oric wants to get good predictions with minimal time spent and for that reason she has a strong preference for XGBoost. First, Meta imports the necessary packages, among which the package that enables her to use XGBoost: ‘xgboost’. This package offers a wraper class which enables Meta to use XGBoost in a scikit-learn framework.</p><pre>pip install xgboost</pre><pre><em># Importing packages and settings: </em><br><strong>import</strong> warnings <br>warnings<strong>.</strong>filterwarnings(action<strong>=</strong> &#39;ignore&#39;)<br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np<br><strong>from</strong> sklearn.impute <strong>import</strong> SimpleImputer<br><strong>from</strong> sklearn.pipeline <strong>import</strong> Pipeline<br><strong>from</strong> sklearn.preprocessing <strong>import</strong> StandardScaler, OneHotEncoder<br><strong>from</strong> sklearn.compose <strong>import</strong> ColumnTransformer<br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br><strong>import</strong> xgboost <strong>as</strong> xgb<br><strong>from</strong> sklearn.model_selection <strong>import</strong> StratifiedKFold<br><strong>from</strong> sklearn.model_selection <strong>import</strong> cross_val_score<br><strong>import</strong> joblib</pre><p>Second, Meta loads the dataset. A bit of preparation on this data was done, as described <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-data-to-predict-which-employees-are-likely-to-leave">here</a>. The target variable is conveniently named <em>target</em> and indicates whether a data scientist in this historic dataset has left the company. All other columns in the dataset are the features that might help to predict which data scientists are likely to leave the company soon.</p><pre>df_prep <strong>= </strong>pd<strong>.</strong>read_csv(&#39;https://bhciaaablob.blob.core.windows.net/featurenegineeringfiles/df_prepared.csv&#39;)</pre><pre>df <strong>=</strong> df_prep<strong>.</strong>drop(columns<strong>=</strong>[&#39;Unnamed: 0&#39;,&#39;city&#39;, &#39;experience&#39;, &#39;enrollee_id&#39;])  </pre><pre>df<strong>.</strong>head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*zpmtffKNq4z70aJr9ThtWg.png" /></figure><p>Because Meto Oric is very busy, she doesn’t have a lot of time to prepare the data. However, some dataprep is required to be able to train the XGBoost. She imputes the missing values, converts the categorical variables into dummies, and standardizes the numerical variables. Why does Meta impute the missing values herself while we just discussed that XGBoost is able to do this by itself? Meta prefers to impute the missings herself to have maximum control. And letting XGBoost handle the missings by itself does not appear to lead to better results compared to standard imputation (<a href="https://link.springer.com/article/10.1007/s42452-020-3128-y">source</a>). Other strategies for dealing with missings are discussed in more detail in <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-guide-to-manage-missing-data">this article</a> of our series.</p><p>To save time and to re-use a lot of code from previous projects, Meta makes use of pipelines to prep the data, to conduct cross-validation and to train the XGBoost. If you want to read more about scikit-learn pipelines, <a href="https://towardsdatascience.com/how-to-use-sklearn-pipelines-for-ridiculously-neat-code-a61ab66ca90d">this</a> is one of the many available sources.</p><p>In the code below Meta separates the target and the features, creates train and test sets, and creates the pipelines to prep the features:</p><pre><em># Define the target vector y</em><br>y <strong>=</strong> df[&#39;target&#39;]  </pre><pre><em># Creating a dataset without the DV:</em><br>X <strong>=</strong> df<strong>.</strong>drop(&#39;target&#39;, axis <strong>=</strong> 1)</pre><pre><em># Split X and y into training and testing sets</em><br>X_train, X_test, y_train, y_test <strong>=</strong> train_test_split(<br>  X, y, test_size<strong>=</strong>0.25, stratify<strong>=</strong>y, random_state<strong>=</strong>1121218 <br>)</pre><pre><em># Creating an object with the column labels of only the categorical features and one with only the numeric features:</em><br>categorical_features <strong>=</strong> X<strong>.</strong>select_dtypes(exclude<strong>=</strong>&quot;number&quot;)<strong>.</strong>columns<strong>.</strong>tolist()<br>numeric_features <strong>=</strong> X<strong>.</strong>select_dtypes(include<strong>=</strong>&quot;number&quot;)<strong>.</strong>columns<strong>.</strong>tolist()</pre><pre><em># Create the categorical pipeline, for the categorical variables Meta imputes the missing values with a constant value and we encode them with One-Hot encoding:</em><br>categorical_pipeline <strong>=</strong> Pipeline(<br>    steps<strong>=</strong>[<br>        (&quot;impute&quot;, SimpleImputer(strategy<strong>=</strong> &#39;constant&#39;, fill_value<strong>=</strong> &#39;unknown&#39;)), <br>        (&quot;one-hot&quot;, OneHotEncoder(handle_unknown<strong>=</strong>&quot;ignore&quot;, sparse<strong>=False</strong>)) <br>    ]<br>)</pre><pre><em># Create the numeric pipeline, for the numeric variables Meta imputes the missings with the mean of the column and standardize them, so that the features have a mean of 0 and a variance of 1: </em><br>numeric_pipeline <strong>=</strong> Pipeline(<br>    steps<strong>=</strong>[(&quot;impute&quot;, SimpleImputer(strategy<strong>=</strong>&quot;mean&quot;)), <br>           (&quot;scale&quot;, StandardScaler())]<br>)</pre><pre><em># Combining the two pipelines with a column transformer:</em><br>full_processor <strong>=</strong> ColumnTransformer(transformers<strong>=</strong>[<br>        (&quot;numeric&quot;, numeric_pipeline, numeric_features),<br>        (&quot;categorical&quot;, categorical_pipeline, categorical_features),<br>    ]<br>)</pre><p>Now that everything is ready to prep the data, Meta quickly creates a XGBoost classifier with default parameters and evaluates its performance. Meta uses the logloss as evaluation metric, which is the default for classification. Meta also sets a random seed to be able to reproduce her results. Meta evaluates the model performance initially only on the trainset with the use of stratified 5-folds cross-validation. <a href="https://scikitlearn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html">Stratified cross-validation</a> is a variation of KFold cross-validation that returns stratified folds. The folds are made by preserving the percentage of samples for each class. Stratified cross-validation is recommended to use if the classes are imbalanced. Our target is imbalanced, 25% of the employees are looking for a new job. If you are not familiar with <a href="https://towardsdatascience.com/5-reasons-why-you-should-use-cross-validation-in-your-data-science-project-8163311a1e79">cross-validation</a> this is a good source where you can read more about it.</p><pre><em># Meta instantiates the XGBClassifier, since we are dealing with a classification task:</em><br>xgb_cl <strong>=</strong> xgb<strong>.</strong>XGBClassifier(eval_metric<strong>=</strong>&#39;logloss&#39;, seed<strong>=</strong>7) </pre><pre><em># Create XGBoost pipeline:</em><br>xgb_pipeline <strong>=</strong> Pipeline(steps<strong>=</strong>[<br>    (&#39;preprocess&#39;, full_processor),<br>    (&#39;model&#39;, xgb_cl)<br>])</pre><pre><em># Evaluate the model with the use of cv:</em><br>cv <strong>=</strong> StratifiedKFold(n_splits<strong>=</strong>5, shuffle<strong>=True</strong>, random_state<strong>=</strong>7)  <em>#, shuffle=True with or without shuffle??</em><br>scores <strong>=</strong> cross_val_score(xgb_pipeline, X_train, y_train, cv<strong>=</strong>cv, scoring <strong>=</strong> &#39;roc_auc&#39;)<br>print(&quot;roc_auc = %f (%f)&quot; <strong>%</strong> (scores<strong>.</strong>mean(), scores<strong>.</strong>std()))</pre><p>Output:</p><pre>roc_auc = 0.791519 (0.004802)</pre><p>With only default parameters without hyperparameter tuning, Meta’s XGBoost gets a <a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">ROC AUC score</a> of 0.7915. As you can see below XGBoost has quite a lot of hyperparameters that can be tweaked, to create the optimal model for the provided dataset.</p><pre><em># The default hyperparameters of the XGBoost:</em><br>xgb_cl </pre><p>Output:</p><pre>XGBClassifier(base_score=None, booster=None, colsample_bylevel=None, colsample_bynode=None, colsample_bytree=None, enable_categorical=False, eval_metric=’logloss’, gamma=None, gpu_id=None, importance_type=None, interaction_constraints=None, learning_rate=None, max_delta_step=None, max_depth=None, min_child_weight=None, missing=nan, monotone_constraints=None, n_estimators=100, n_jobs=None, num_parallel_tree=None, predictor=None, random_state=None, reg_alpha=None, reg_lambda=None, scale_pos_weight=None, seed=7, subsample=None, tree_method=None, validate_parameters=None, verbosity=None)</pre><p>Meta does not have time to try to tune and optimize the model, so she sticks with the default XGBoost parameters. To be able to compare Meta’s approach with the approaches of Aki Razzi, Andy Stand, and Eqaan Librium later on, we’ll fit her model on the trainset and save it. Just to be sure, we quickly test if her model is saved correctly.</p><pre><em># Fit Meta&#39;s default XGBoost pipeline:</em><br>xgb_pipeline<strong>.</strong>fit(X_train, y_train)</pre><pre><em>#Saving Meta&#39;s final XGBoost pipeline:</em><br>joblib<strong>.</strong>dump(xgb_pipeline, &#39;pipe_meta.joblib&#39;)</pre><p>Output:</p><pre>[‘pipe_meta.joblib’]</pre><p>Code:</p><pre><em>#Testing if Meta&#39;s model is correctly saved:</em></pre><pre><em># Load the models:  </em><br>upload_pipe_meta <strong>=</strong> joblib<strong>.</strong>load(&#39;pipe_meta.joblib&#39;)</pre><pre><em># Use it to make the same predictions:</em><br>print(upload_pipe_meta<strong>.</strong>predict(X_train))</pre><p>Output:</p><pre>[0 0 1 … 0 0 1]</pre><p>I hope you enjoyed reading this article and getting to know Meta. Meta’s aim was to quickly produce a XGBoost. In the next article <a href="https://www.theanalyticslab.nl/no-data-scientist-is-the-same-hyperparameter-tuning-for-hyperaccurate-xgboost-model">Aki Razzi</a> will try to improve Meta’s default XGBoost by tuning the hyperparameters. Additionally, in the next article the performance of the XGBoost models of Meta and Aki will be evaluated on the testset.</p><p>This article is part of our <strong>No Data Scientist Is The Same </strong>series. The full series is written by <a href="https://medium.com/@anya.tonne">Anya Tonne</a>, <a href="https://medium.com/@jurriaan.nagelkerke">Jurriaan Nagelkerke</a>, <a href="https://medium.com/@karingruijs">Karin Gruijs-Vodde</a> and <a href="https://medium.com/@Tom_Blanke">Tom Blanke</a>. The series is also available on <a href="https://www.theanalyticslab.nl/blogs/">theanalyticslab.nl</a>.</p><p>An overview of all articles on Medium within the series:</p><ol><li><a href="https://medium.com/@anya.tonne/introducing-our-data-science-rock-stars-19ef8d9131a6">Introducing our data science rock stars</a></li><li><a href="https://medium.com/@jurriaan.nagelkerke/data-to-predict-which-employees-are-likely-to-leave-4fe1c64b1af4">Data to predict which employees are likely to leave</a></li><li><a href="https://medium.com/@Tom_Blanke/good-model-by-default-using-xgboost-ab14f26f7f6a">Good model by default using XGBoost</a></li><li><a href="https://medium.com/@Tom_Blanke/hyperparameter-tuning-for-hyperaccurate-xgboost-model-d6e6b8650a11">Hyperparameter tuning for hyperaccurate XGBoost model</a></li><li><a href="https://medium.com/@karingruijs/beat-dirty-data-5d9a6254c2f9">Beat dirty data</a></li><li><a href="https://medium.com/@anya.tonne/the-case-of-high-cardinality-kerfuffles-d9b7fccc6570">The case of high cardinality kerfuffles</a></li><li><a href="https://medium.com/@karingruijs/guide-to-manage-missing-data-961bee610ef9">Guide to manage missing data</a></li><li><a href="https://medium.com/@jurriaan.nagelkerke/visualise-the-business-value-of-predictive-models-21c6bc8132c">Visualise the business value of predictive models</a></li><li><a href="https://medium.com/@jurriaan.nagelkerke/no-data-scientist-is-the-same-42a5bfdf7ed6">No data scientist is the same!</a></li></ol><p>Do you want to do this yourself? Please feel free to download the Notebook on our <a href="https://gitlab.com/cmotions/publications/-/tree/master/NoDataScientistIsTheSameNotebooks">gitlab page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab14f26f7f6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cmotions/good-model-by-default-using-xgboost-ab14f26f7f6a">Good model by default using XGBoost</a> was originally published in <a href="https://medium.com/cmotions">Cmotions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>