How to Develop Your First XGBoost Model in Python with scikit-learn

XGBoost is an implementation of gradient boosted decision trees designed for speed and performance that is dominative competitive machine learning.

In this post you will discover how you can install and create your first XGBoost model in Python.

After reading this post you will know:

  • How to install XGBoost on your system for use in Python.
  • How to prepare data and train your first XGBoost model.
  • How to make predictions using your XGBoost model.

Let’s get started.

  • Update Jan/2017: Updated to reflect changes in scikit-learn API version 0.18.1.
  • Update Mar/2017: Adding missing import, made imports clearer.
How to Develop Your First XGBoost Model in Python with scikit-learn

How to Develop Your First XGBoost Model in Python with scikit-learn
Photo by Justin Henry, some rights reserved.

Tutorial Overview

This tutorial is broken down into the following 6 sections:

  1. Install XGBoost for use with Python.
  2. Problem definition and download dataset.
  3. Load and prepare data.
  4. Train XGBoost model.
  5. Make predictions and evaluate model.
  6. Tie it all together and run the example.

Need help with XGBoost in Python?

Take my free 7-day email course and discover configuration, tuning and more (with sample code).

Click to sign-up now and also get a free PDF Ebook version of the course.

Start Your FREE Mini-Course Now!

1. Install XGBoost for Use in Python

Assuming you have a working SciPy environment, XGBoost can be installed easily using pip.

For example:

To update your installation of XGBoost you can type:

An alternate way to install XGBoost if you cannot use pip or you want to run the latest code from GitHub requires that you make a clone of the XGBoost project and perform a manual build and installation.

For example to build XGBoost without multithreading on Mac OS X (with GCC already installed via macports or homebrew), you can type:

You can learn more about how to install XGBoost for different platforms on the XGBoost Installation Guide. For up-to-date instructions for installing XGBoost for Python see the XGBoost Python Package.

For reference, you can review the XGBoost Python API reference.

2. Problem Description: Predict Onset of Diabetes

In this tutorial we are going to use the Pima Indians onset of diabetes dataset.

This dataset is comprised of 8 input variables that describe medical details of patients and one output variable to indicate whether the patient will have an onset of diabetes within 5 years.

You can learn more about this dataset on the UCI Machine Learning Repository website.

This is a good dataset for a first XGBoost model because all of the input variables are numeric and the problem is a simple binary classification problem. It is not necessarily a good problem for the XGBoost algorithm because it is a relatively small dataset and an easy problem to model.

Download this dataset and place it into your current working directory with the file name “pima-indians-diabetes.csv“.

3. Load and Prepare Data

In this section we will load the data from file and prepare it for use for training and evaluating an XGBoost model.

We will start off by importing the classes and functions we intend to use in this tutorial.

Next, we can load the CSV file as a NumPy array using the NumPy function loadtext().

We must separate the columns (attributes or features) of the dataset into input patterns (X) and output patterns (Y). We can do this easily by specifying the column indices in the NumPy array format.

Finally, we must split the X and Y data into a training and test dataset. The training set will be used to prepare the XGBoost model and the test set will be used to make new predictions, from which we can evaluate the performance of the model.

For this we will use the train_test_split() function from the scikit-learn library. We also specify a seed for the random number generator so that we always get the same split of data each time this example is executed.

We are now ready to train our model.

4. Train the XGBoost Model

XGBoost provides a wrapper class to allow models to be treated like classifiers or regressors in the scikit-learn framework.

This means we can use the full scikit-learn library with XGBoost models.

The XGBoost model for classification is called XGBClassifier. We can create and and fit it to our training dataset. Models are fit using the scikit-learn API and the model.fit() function.

Parameters for training the model can be passed to the model in the constructor. Here, we use the sensible defaults.

You can see the parameters used in a trained model by printing the model, for example:

You can learn more about the defaults for the XGBClassifier and XGBRegressor classes in the XGBoost Python scikit-learn API.

You can learn more about the meaning of each parameter and how to configure them on the XGBoost parameters page.

We are now ready to use the trained model to make predictions.

5. Make Predictions with XGBoost Model

We can make predictions using the fit model on the test dataset.

To make predictions we use the scikit-learn function model.predict().

By default, the predictions made by XGBoost are probabilities. Because this is a binary classification problem, each prediction is the probability of the input pattern belonging to the first class. We can easily convert them to binary class values by rounding them to 0 or 1.

Now that we have used the fit model to make predictions on new data, we can evaluate the performance of the predictions by comparing them to the expected values. For this we will use the built in accuracy_score() function in scikit-learn.

6. Tie it All Together

We can tie all of these pieces together, below is the full code listing.

Running this example produces the following output.

This is a good accuracy score on this problem, which we would expect, given the capabilities of the model and the modest complexity of the problem.

Summary

In this post you discovered how to develop your first XGBoost model in Python.

Specifically, you learned:

  • How to install XGBoost on your system ready for use with Python.
  • How to prepare data and train your first XGBoost model on a standard machine learning dataset.
  • How to make predictions and evaluate the performance of a trained XGBoost model using scikit-learn.

Do you have any questions about XGBoost or about this post? Ask your questions in the comments and I will do my best to answer.


Want To Learn The Algorithm Winning Competitions?

XGBoost With Python

Develop Your Own XGBoost Models in Minutes

…with just a few lines of Python

Discover how in my new Ebook:
XGBoost With Python

It covers self-study tutorials like:
Algorithm Fundamentals, Scaling, Hyperparameters, and much more…

Bring The Power of XGBoost To
Your Own Projects

Skip the Academics. Just Results.

Click to learn more.


35 Responses to How to Develop Your First XGBoost Model in Python with scikit-learn

  1. Qichang Feng August 26, 2016 at 8:21 pm #

    Hi Jason,

    First of all thanks for all your great posts. I have learned a lot from them.

    I have a question regarding the code seperating input features X and response variable Y. It seems you include the last column in the features as well which should not be the case.

    X = dataset[:,0:8]

    The correct one should be X = dataset[:, 0:7] to match 8 input variables for the medical details of patients.

    The error happened in your mini-course handbook as well.

    • Jason Brownlee August 27, 2016 at 11:32 am #

      You’re welcome Qichang.

      Perhaps you are getting different results based on the version of Python or Numpy you are using.

      I can confirm that the code in the post is correct:

      There are 9 columns, only the first 8 are stored in X with the 9th stored in Y. The above snippet produces:

      Does that help?

      Tested on Python 2.7.11 and numpy 1.11.1.

      • Qichang August 28, 2016 at 10:27 am #

        Hi Jason,

        Thanks a lot for your quick reply. It is my mistake as I am confused with 0:8 because I am also learning R recently. In R, the last number of 0:8 is included while it is excluded in Python. I should have checked the shape.

        Thanks again.

  2. Joao Pires September 21, 2016 at 6:42 am #

    Hi
    I run the code and I get this error:
    model = xgboost.XGBClassifier()
    AttributeError: ‘module’ object has no attribute ‘XGBClassifier’

    Do you know why?

    Thks

  3. SG Huang September 29, 2016 at 7:40 pm #

    Thanks Jason for the clear guide.

    What is the normal ways to improve the accuracy in practice? Shall we do some featuring engineering, or change to a different model?

    I have learned the basics of machine learning through online courses, but there is still a gap between what I learned in the courses and the practical problems such as the competitions on Kaggle. Can you share some insights?

    • Jason Brownlee September 30, 2016 at 7:51 am #

      I would recommend trying some feature engineering first.

      Try some new framings of the problem.

      Then later try algorithm tuning and ensemble methods.

      I have a list of things to try in the following post, it talks about deep learning but the techniques are general enough for most methods:
      http://machinelearningmastery.com/improve-deep-learning-performance/

      I hope that helps as a start.

  4. Jessica November 11, 2016 at 4:39 am #

    Thank you for this, it’s extremely helpful.

    I wrote a model for my data last night, and it performed very well.
    I tried to re-run it today, and it gave me an error trying to import xgboost.

    I typed in “import xgboost”
    And I got: “ImportError: No module named xgboost”

    • Jason Brownlee November 11, 2016 at 10:06 am #

      Sorry to hear that Jessica.

      I wonder if something changed with your environment.

      Perhaps try running everything from the command line.
      Confirm you’re using the same user.
      Confirm xgboost is still installed on the system (pip show or something…)

  5. Trupti November 21, 2016 at 5:26 pm #

    hello, thanks for the fantastic explanation!!
    I have a query. Can we get the list of significant variables that entered in the model? How do we read the “feature_importances_”?
    Also, how to fin-tune the xgboost model?
    Thanks again!

  6. Trupti November 21, 2016 at 7:55 pm #

    Hello. Thanks for the explanation!
    Can you tell me if I can see the list of variables entering in the model. Also, how do we fine tune the model further??
    Once we have the xgboost model..how do we productionise it? In logistic regression we get an equation which can be automated to run in real time production, what do we get in xgboost?

  7. Peter Tan December 8, 2016 at 8:26 am #

    Hi Jason, I am running into the same issue as some of the readers here:

    AttributeError: ‘module’ object has no attribute ‘XGBClassifier’

    To ensure I did not have any typo, I have created a complete copy of your sample code and I still get the same issue.

    (I do have import xgboost in my code).

    I am using xgboost 0.6a2 with anaconda2-4.2.0. Just wondering if you have run into similar issues.

  8. Hector December 30, 2016 at 1:29 pm #

    Hello Jason, I ran the example code here and one error returned as:

    File “./test.py”, line 21
    model = xgboost.XGBClassifier()
    ^
    SyntaxError: invalid syntax

    Can you tell me what I did wrong? I can successfully import the packages.

    I am using python 3.5 and xgboost 0.6.

    • Jason Brownlee December 31, 2016 at 7:02 am #

      Perhaps a copy paste error? Check for extra white space in your copy of the code.

  9. Trupti January 7, 2017 at 5:31 pm #

    I am using predict_proba to create predicted probabilities by xgboost model. Can I save these probs in the same train data on which model is built so that I can further create reports to show management about validations of the scorecard.

    • Jason Brownlee January 8, 2017 at 5:20 am #

      Sorry, I don’t think I understand.

      Predicted probabilities on the training dataset will be biased. You may want to report on the probabilities for a hold-out dataset.

  10. Niranjan March 14, 2017 at 3:23 am #

    Hi, It was a very nice intro to xgboost. Please add a import for train_test_split function

  11. Keren March 27, 2017 at 12:15 am #

    Hi Jason,
    I didn’t manage to find a clear explanation for the way the probabilities given as output by predict_proba() are computed.

    In random forest for example, I understand it reflects the mean of proportions of the samples belonging to the class among the relevant leaves of all the trees.

    However in XGBoost I couldn’t understand the computation from the documentation or the code. Shouldn’t it give different weights for each tree?

    • Jason Brownlee March 27, 2017 at 7:56 am #

      Good question Keren, I’m not sure off hand.

      You could check some of the original stochastic gradient boosting papers or even reach out to the xgboost authors.

  12. Niranjan April 20, 2017 at 8:31 pm #

    Hi, Jason, Thank you for such a nice explaination, would you help me out regarding how to print the training accuracy while we call the fit function in xgboost?

  13. sumi May 25, 2017 at 3:52 pm #

    Hi,

    Thankyou for your post. It was really helpful.But can you tell me why do I get ‘ImportError: cannot import name XGBClassifier’ when I run this code?i have installed XG Boost successfully and I still have this error. Please help me.

  14. vishwas May 25, 2017 at 10:20 pm #

    how to combine Xgboost classifier and Deep learning and create ensemble(voting classifier)…can you please elaborate more on ensemble techniques

  15. joao June 10, 2017 at 6:29 pm #

    In your step by step explanation you have: “from xgboost import XGBClassifier” and then you use: “model = xgboost.XGBClassifier()”. This will give an error.
    In the full code you have it right though.

  16. Mahmoud July 18, 2017 at 6:56 pm #

    Hello Dr Jason, thanks for the quick cool tutorial. It is fundamental and very beneficial.
    one question, how do I use GPU for training and prediction purposes in XGBoost? I am working on large dataset. thanks a lot in advance.

Leave a Reply