#!/usr/bin/env python # coding: utf-8 # # Boosting # > A Summary of lecture "Machine Learning with Tree-Based Models in Python # ", via datacamp # # - toc: true # - badges: true # - comments: true # - author: Chanseok Kang # - categories: [Python, Datacamp, Machine Learning] # - image: images/sgb_train.png # In[59]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # ## Adaboost # - Boosting: Ensemble method combining several weak learners to form a strong learner. # - Weak learner: Model doing slightly better than random guessing # - E.g., Dicision stump (CART whose maximum depth is 1) # - Train an ensemble of predictors sequentially. # - Each predictor tries to correct its predecessor # - Most popular boosting methods: # - AdaBoost # - Gradient Boosting # - AdaBoost # - Stands for **Ada**ptive **Boost**ing # - Each predictor pays more attention to the instances wrongly predicted by its predecessor. # - Achieved by changing the weights of training instances. # - Each predictor is assigned a coefficient $\alpha$ that depends on the predictor's training error # - AdaBoost: Training # ![adaboost_train](https://github.com/goodboychan/chans_jupyter/blob/master/_notebooks/image/adaboost_train.png?raw=1) # - Learning rate: $0 < \eta < 1$ # ### Define the AdaBoost classifier # In the following exercises you'll revisit the [Indian Liver Patient](https://www.kaggle.com/uciml/indian-liver-patient-records) dataset which was introduced in a previous chapter. Your task is to predict whether a patient suffers from a liver disease using 10 features including Albumin, age and gender. However, this time, you'll be training an AdaBoost ensemble to perform the classification task. In addition, given that this dataset is imbalanced, you'll be using the ROC AUC score as a metric instead of accuracy. # # As a first step, you'll start by instantiating an AdaBoost classifier. # In[59]: # In[60]: from google.colab import drive drive.mount('/content/drive') # - Preprocess # In[61]: get_ipython().system('pwd') indian = pd.read_csv('/content/drive/MyDrive/colab-notebooks/indian_liver_preprocessed.csv', index_col=0) indian.head() # In[62]: X = indian.drop('Liver_disease', axis='columns') y = indian['Liver_disease'] # In[63]: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) # In[64]: from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier # Instantiate dt dt = DecisionTreeClassifier(max_depth=2, random_state=1) # Instantiate ada ada = AdaBoostClassifier(base_estimator=dt, n_estimators=180, random_state=1) # ### Train the AdaBoost classifier # Now that you've instantiated the AdaBoost classifier ada, it's time train it. You will also predict the probabilities of obtaining the positive class in the test set. This can be done as follows: # # Once the classifier ```ada``` is trained, call the ```.predict_proba()``` method by passing ```X_test``` as a parameter and extract these probabilities by slicing all the values in the second column as follows: # ```python # ada.predict_proba(X_test)[:,1] # ``` # # # In[65]: # Fit ada to the training set ada.fit(X_train, y_train) # Compute the probabilities of obtaining the positive class y_pred_proba = ada.predict_proba(X_test)[:, 1] # ### Evaluate the AdaBoost classifier # Now that you're done training ```ada``` and predicting the probabilities of obtaining the positive class in the test set, it's time to evaluate ```ada```'s ROC AUC score. Recall that the ROC AUC score of a binary classifier can be determined using the ```roc_auc_score()``` function from ```sklearn.metrics```. # In[66]: from sklearn.metrics import roc_auc_score # Evaluate test-set roc_auc_score ada_roc_auc = roc_auc_score(y_test, y_pred_proba) # Print roc_auc_score print('ROC AUC score: {:.2f}'.format(ada_roc_auc)) # ## Gradient Boosting (GB) # - Gradient Boosted Trees # - Sequential correction of predecessor's errors # - Does not tweak the weights of training instances # - Fit each predictor is trained using its predecessor's residual errors as labels # - Gradient Boosted Trees: a CART is used as a base learner. # - Gradient Boosted Trees for Regression: Training # ![gb_train](https://github.com/goodboychan/chans_jupyter/blob/master/_notebooks/image/gb_train.png?raw=1) # - $\eta$ (shrinkage) # - Ensemble is shrinked after it is multiplied by a learning rate # ### Define the GB regressor # You'll now revisit the [Bike Sharing Demand](https://www.kaggle.com/c/bike-sharing-demand) dataset that was introduced in the previous chapter. Recall that your task is to predict the bike rental demand using historical weather data from the Capital Bikeshare program in Washington, D.C.. For this purpose, you'll be using a gradient boosting regressor. # # As a first step, you'll start by instantiating a gradient boosting regressor which you will train in the next exercise. # - Preprocess # In[71]: bike = pd.read_csv('/content/drive/MyDrive/colab-notebooks/bikes.csv') bike.head() # In[72]: X = bike.drop('cnt', axis='columns') y = bike['cnt'] # In[73]: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2) # In[74]: from sklearn.ensemble import GradientBoostingRegressor # Instantiate gb gb = GradientBoostingRegressor(max_depth=4, n_estimators=200, random_state=2) # ### Train the GB regressor # You'll now train the gradient boosting regressor ```gb``` that you instantiated in the previous exercise and predict test set labels. # In[75]: # Fit gb to the training set gb.fit(X_train, y_train) # Predict test set labels y_pred = gb.predict(X_test) # ### Evaluate the GB regressor # Now that the test set predictions are available, you can use them to evaluate the test set Root Mean Squared Error (RMSE) of ```gb```. # In[76]: from sklearn.metrics import mean_squared_error as MSE # Compute MSE mse_test = MSE(y_test, y_pred) # Compute RMSE rmse_test = mse_test ** 0.5 # Print RMSE print("Test set RMSE of gb: {:.3f}".format(rmse_test)) # ## Stochastic Gradient Boosting (SGB) # - Gradient Boosting: Cons & Pros # - GB involves an exhaustive search procedure # - Each CART is trained to find the best split points and features. # - May lead to CARTs using the same split points and maybe the same features. # - Stochastic Gradient Boosting # - Each tree is trained on a random subset of rows of the training data. # - The sampled instances (40%-80% of the training set) are sampled without replacement. # - Features are sampled (without replacement) when choosing split points # - Result: further ensemble diversity. # - Effect: adding further variance to the ensemble of trees. # - Stochastic Gradient Boosting: Training # ![sgb_train](https://github.com/goodboychan/chans_jupyter/blob/master/_notebooks/image/sgb_train.png?raw=1) # - Residual errors are multiplied by the learning rate $\eta$ and are fed to the next tree in ensemble. # - Process is repeated sequentially until all the trees in the ensemble are trained. # ### Regression with SGB # As in the exercises from the previous lesson, you'll be working with the [Bike Sharing Demand](https://www.kaggle.com/c/bike-sharing-demand) dataset. In the following set of exercises, you'll solve this bike count regression problem using stochastic gradient boosting. # In[77]: from sklearn.ensemble import GradientBoostingRegressor # Instantiate sgbr sgbr = GradientBoostingRegressor(max_depth=4, n_estimators=200, subsample=0.9, max_features=0.75, random_state=2) # ### Train the SGB regressor # In this exercise, you'll train the SGBR ```sgbr``` instantiated in the previous exercise and predict the test set labels. # In[79]: # Fit sgbr to the training set sgbr.fit(X_train, y_train) # Predict test set labels y_pred = sgbr.predict(X_test) # ### Evaluate the SGB regressor # You have prepared the ground to determine the test set RMSE of ```sgbr``` which you shall evaluate in this exercise. # In[80]: from sklearn.metrics import mean_squared_error as MSE # Compute test set MSE mse_test = MSE(y_test, y_pred) # Compute test set RMSE rmse_test = mse_test ** 0.5 # Print rmse_test print('Test set RMSE of sgbr: {:.3f}'.format(rmse_test))