Extreme Gradient Boosting with XGBoost - Part 1 (DataCamp interactive course)
Chapter 1 - Classification with XGBoost
Do you know the basics of supervised learning and want to use state-of-the-art models on real-world datasets? Gradient boosting is currently one of the most popular techniques for efficient modeling of tabular datasets of all sizes. XGboost is a very fast, scalable implementation of gradient boosting, with models using XGBoost regularly winning online data science competitions and being used at scale across different industries.
This chapter will introduce you to the fundamental idea behind XGBoost—boosted learners. Once you understand how XGBoost works, you'll apply it to solve a common classification problem found in industry:predicting whether a customer will stop being a customer at some point in the future. PREREQUISITES: Supervised Learning with scikit-learn, Case Study: School Budgeting with Machine Learning in Python.
Introduction
- Supervised Learning
- Relies on labeled data
- Have some understanding of past behavior
- AUC: Metric for binary classification models
- Area Under the ROC Curve (AUC). Larger area under the ROC curve = better model
- Other supervised learning considerations:
- Features can be either numeric or categorical
- Numeric features should be scaled (Z-scored)
- Categorical features should be encoded (one-hot)
Introducing XGBosst
What is XGBoost? (Extreme Gradient Boosting)
- Optimized gradient-boosting machine learning library
- Originally written in C++
- Has APIs in several languages: Python, R, Scala, Julia, Java
What makes XGBoost so popular?
- Speed and performance
- Core algorithm is parallelizable
- Consistently outperforms single-algorithm methods
- State-of-the-art performance in many ML tasks
XGBoost: Fit/Predict
It's time to create your first XGBoost model! As Sergey showed you in the video, you can use the scikit-learn .fit() / .predict() paradigm that you are already familiar to build your XGBoost models, as the xgboost library has a scikit-learn compatible API!
Here, you'll be working with churn data. This dataset contains imaginary data from a ride-sharing app with user behaviors over their first month of app usage in a set of imaginary cities as well as whether they used the service 5 months after sign-up.
Your goal is to use the first month's worth of data to predict whether the app's users will remain users of the service at the 5 month mark. This is a typical setup for a churn prediction problem. To do this, you'll split the data into training and test sets, fit a small xgboost model on the training set, and evaluate its performance on the test set by computing its accuracy.
Instructions:
- Import xgboost as xgb.
- Create training and test sets such that 20% of the data is used for testing. Use a random_state of 123.
- Instantiate an XGBoostClassifier as xg_cl using xgb.XGBClassifier(). Specify n_estimators to be 10 estimators and an objective of 'binary:logistic'. Do not worry about what this means just yet, you will learn about these parameters later in this course.
- Fit xg_cl to the training set (X_train, y_train) using the .fit() method.
- Predict the labels of the test set (X_test) using the .predict() method and hit 'Submit Answer' to print the accuracy.
import xgboost as xgb
xgb.__version__
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
# churn_data = pd.read_csv("datasets/churn.csv") # This dataset is not the one that was used in the course.
churn_data = pd.read_csv("datasets/churn_data.csv")
print(churn_data.info())
churn_data.head()
import xgboost as xgb
# Create arrays for the features and the target: X, y
X, y = churn_data.iloc[:,:-1], churn_data.iloc[:,-1]
# Create the training and test sets
X_train, X_test, y_train, y_test= train_test_split(X, y, test_size=0.2, random_state=123)
# Instantiate the XGBClassifier: xg_cl
xg_cl = xgb.XGBClassifier(objective='binary:logistic', eval_metric ="error", n_estimators=10, seed=123, use_label_encoder=False)
# Fit the classifier to the training set
xg_cl.fit(X_train, y_train)
# Predict the labels of the test set: preds
preds = xg_cl.predict(X_test)
# Compute the accuracy: accuracy
accuracy = float(np.sum(preds==y_test))/y_test.shape[0]
print("accuracy: %f" % (accuracy))
What is a decision tree?
Decision trees as base learners
- Base learner : Individual learning algorithm in an ensemble algorithm
- Composed of a series of binary questions
- Predictions happen at the "leaves" of the tree
CART: Classification And Regression Trees:
- Each leaf always contains a real-valued score
- Can later be converted into categories
- Decision trees
Decision Tree (Exercise)
Our task in this exercise is to make a simple decision tree using scikit-learn's DecisionTreeClassifier on the breast cancer dataset that comes pre-loaded with scikit-learn.
This dataset contains numeric measurements of various dimensions of individual tumors (such as perimeter and texture) from breast biopsies and a single outcome value (the tumor is either malignant, or benign).
We've preloaded the dataset of samples (measurements) into X and the target values per tumor into y. Now, you have to split the complete dataset into training and testing sets, and then train a DecisionTreeClassifier. You'll specify a parameter called max_depth.
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# load the breast cancer dataset
df = pd.read_csv("datasets/breast_cancer_classification_data.csv", index_col=0)
diagnosis_type = {'M': 1, 'B': 0}
df.diagnosis = [diagnosis_type[item] for item in df.diagnosis]
# Droping the column has NaN
for col in df.columns:
null_num = df[col].isnull().values.any()
if null_num:
print(f"col {col} has {null_num} null values")
print(f"Droping {col}")
df = df.drop(col, axis=1)
X, y = df.drop("diagnosis", axis=1), df.diagnosis
print("X.shape: {}, y.shape: {}".format(X.shape, y.shape))
# Create the training and test sets
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=123)
# Instantiate the classifier: dt_clf_4
dt_clf_4 = DecisionTreeClassifier(max_depth = 4)
# Fit the classifier to the training set
dt_clf_4.fit(X_train, y_train)
# Predict the labels of the test set: y_pred_4
y_pred_4 = dt_clf_4.predict(X_test)
# Compute the accuracy of the predictions: accuracy
accuracy = float(np.sum(y_pred_4==y_test))/y_test.shape[0]
print("accuracy:", accuracy)
What is Boosting
Boosting overview
- Not a specific machine learning algorithm
- Concept that can be applied to a set of machine learning models "Meta-algorithm"
- Ensemble meta-algorithm used to convert many weak learners into a strong learner
Weak learners and strong learners
- Weak learner: ML algorithm that is slightly better than chance
- Boosting converts a collection of weak learners into a strong learner
- Strong learner: Any algorithm that can be tuned to achieve good performance.
How boosting is accomplished?
- Iteratively learning a set of week models on subsets of the data
- Weighting each weak prediction according to each weak learner's performance
- Combine the weighted predictions to obtain a single weighted prediction that is much better than the individual predictions themselves!
Model evaluation through cross-validation
- Cross-validation: Robust method for estimating the performance of a model on unseen data
- Generates many non-overlapping train/test splits on training data
- Reports the average test set performance across all data splits
Accuracy
You'll now practice using XGBoost's learning API through its baked in cross-validation capabilities. As Sergey discussed in the previous video, XGBoost gets its lauded performance and efficiency gains by utilizing its own optimized data structure for datasets called a DMatrix.
In the previous exercise, the input datasets were converted into DMatrix data on the fly, but when you use the xgboost cv object, you have to first explicitly convert your data into a DMatrix. So, that's what you will do here before running cross-validation on churn_data.
X, y = churn_data.iloc[:,:-1], churn_data.iloc[:,-1]
print(type(X))
# Create the DMatrix from X and y: churn_dmatrix
churn_dmatrix = xgb.DMatrix(data=X, label=y)
# Create the parameter dictionary: params
params = {"objective":"reg:logistic", "max_depth":3}
# Perform cross-validation: cv_results
cv_results = xgb.cv(dtrain=churn_dmatrix, params=params,
nfold=3, num_boost_round=5,
metrics="error", as_pandas=True, seed=123)
# Print cv_results
display(cv_results)
# Print the accuracy
print(((1-cv_results["test-error-mean"]).iloc[-1]))
cv_results stores the training and test mean and standard deviation of the error per boosting round (tree built) as a DataFrame. From cv_results, the final round 'test-error-mean' is extracted and converted into an accuracy, where accuracy is 1-error. The final accuracy of around 75% is an improvement from earlier!
Measuring AUC
Now that you've used cross-validation to compute average out-of-sample accuracy (after converting from an error), it's very easy to compute any other metric you might be interested in. All you have to do is pass it (or a list of metrics) in as an argument to the metrics parameter of xgb.cv().
Your job in this exercise is to compute another common metric used in binary classification - the area under the curve ("auc").
cv_results = xgb.cv(dtrain=churn_dmatrix, params=params,
nfold=3, num_boost_round=5,
metrics="auc", as_pandas=True, seed=123)
# Print cv_results
display(cv_results)
# Print the AUC
print((cv_results["test-auc-mean"]).iloc[-1])
Fantastic! An AUC of 0.84 is quite strong. As you have seen, XGBoost's learning API makes it very easy to compute any metric you may be interested in. In Chapter 3, you'll learn about techniques to fine-tune your XGBoost models to improve their performance even further. For now, it's time to learn a little about exactly when to use XGBoost.
When should I use XGBoost?
When to use XGBoost
- You have a large number of training samples
- Greater than 1000 training samples and less 100 features
- The number of features < number of training samples
- You have a mixture of categorical and numeric features
- Or just numeric features
When to NOT use XGBoost
- Image recognition
- Computer vision
- Natural language processing and understanding problems
- When the number of training samples is significantly smaller than the number of features