How to build Ensemble Models in machine learning? (with code in R)

Introduction

Over the last 12 months, I have been participating in a number of machine learning hackathons on Analytics Vidhya and Kaggle competitions. After the competition, I always make sure to go through winner’s solution. The winner’s solution usually provide me critical insights, which have helped me immensely in future competitions.

Most of the winners rely on an ensemble of well-tuned individual models along with feature engineering. If you are starting with machine learning, I would advise you to lay emphasis on these two areas as I have found them equally important to do well in a machine learning.

Most of the time, I was able to crack the feature engineering part but probably didn’t use the ensemble of multiple models. If you are a beginner, it’s even better to get familiar with ensembling as early as possible. Chances are that you are already applying it without knowing!

In this article, I’ll take you through the basics of ensemble modeling. Then I will walk you through the advantages of ensembling. Also, to provide you hands-on experience on ensemble modeling, we will use ensembling on a hackathon problem using R.

Table of Content

What is ensembling?

Types of ensembling

Advantages and disadvantages of ensembling

Practical guide to implementing ensembling in R

Additional resources

P.S. For this article, we will assume that you can build individual models in R / Python. If not, you can start your journey with our learning path.

1.What is ensembling?

In general, ensembling is a technique of combining two or more algorithms of similar or dissimilar types called base learners. This is done to make a more robust system which incorporates the predictions from all the base learners. It can be understood as conference room meeting between multiple traders to make a decision on whether the price of a stock will go up or not.

Since all of them have a different understanding of the stock market and thus a different mapping function from the problem statement to the desired outcome. Therefore, they are supposed to make varied predictions on the stock price based on their own understandings of the market.

Now we can take all of these predictions into account while making the final decision. This will make our final decision more robust, accurate and less likely to be biased. The final decision would have been opposite if one of these traders would have made this decision alone.

You can consider another example of a candidate going through multiple rounds of job interviews. The final decision of candidate’s ability is generally taken based on the feedback of all the interviewers. Although a single interviewer might not be able to test the candidate for each required skill and trait. But the combined feedback of multiple interviewers usually helps in better assessment of the candidate.

2. Types of ensembling

Some of the basic concepts which you should be aware of before we go into further detail are:

Averaging: It’s defined as taking the average ofpredictions from models in case of regression problem or while predicting probabilities for the classification problem.

Majority vote: It’sdefined astaking the prediction with maximum vote / recommendation from multiple models predictions while predicting the outcomes of a classification problem.

Weighted average: In this, different weights are applied to predictions from multiple models then taking the average which means giving high or low importance to specific model output.

Practically speaking, there can be a countless number of ways in which you can ensemble different models. But these are some techniques that are mostly used:

Bagging: Bagging is also referred to as bootstrap aggregation. To understand bagging, we first need to understand bootstrapping. Bootstrapping is a sampling technique in which we choose ‘n’ observations or rows out of the original dataset of ‘n’ rows as well. But the key is that each row is selected with replacement from the original dataset so that each row is equally likely to be selected in each iteration. Let’s say we have 3 rows numbered 1, 2 and 3.

For bootstrapped sample, we choose one out of these three randomly. Say we chose Row 2.

You see that even though Row 2 is chosen from the data to the bootstrap sample, it’s still present in the data. Now, each of the three:

Rows have the same probability of being selected again. Let’s say we choose Row 1 this time.

Again, each row in the data has the same probability to be chosen for Bootstrapped sample. Let’s say we randomly choose Row 1 again.

Thus, we can have multiple bootstrapped samples from the same data. Once we have these multiple bootstrapped samples, we can grow trees for each of these bootstrapped samples and use the majority vote or averaging concepts to get the final prediction. This is how bagging works.

One important thing to note here is that it’s done mainly to reduce the variance. Now, random forest actually uses this concept but it goes a step ahead to further reduce the variance by randomly choosing a subset of features as well for each bootstrapped sample to make the splits while training.

Boosting: Boosting is a sequential technique in which, the first algorithm is trained on the entire dataset and the subsequent algorithms are built by fitting the residuals of the first algorithm, thus giving higher weight to those observations that were poorly predicted by the previous model.

It relies on creating a series of weak learners each of which might not be good for the entire dataset but is good for some part of the dataset. Thus, each model actually boosts the performance of the ensemble.

It’s really important to note that boosting is focused on reducing the bias. This makes the boosting algorithms prone to overfitting. Thus, parameter tuning becomes a crucial part of boosting algorithms to make them avoid overfitting.

Some examples of boosting are XGBoost, GBM, ADABOOST, etc.

Stacking: In stacking multiple layers of machine learning models are placed one over another where each of the models passes their predictions to the model in the layer above it and the top layer model takes decisions based on the outputs of the models in layers below it.

Let’s understand it with an example:

Here, we have two layers of machine learning models:

Bottom layer models (d1, d2, d3 ) which receive the original input features(x) from the dataset.

Top layer model, f() which takes the output of the bottom layer models (d1, d2, d3 ) as its input and predicts the final output.

One key thing to note here is that out of fold predictions are used while predicting for the training data.

Here, we have used only two layers but it can be any number of layers and any number of models in each layer. Two of the key principles for selecting the models:

The individual models fulfill particular accuracy criteria.

The model predictions of various individual models are not highly correlated with the predictions of other models.

One thing that you might have realized is that we have used the top layer model which takes as input the predictions of the bottom layer models. This top layer model can also be replaced by many other simpler formulas like:

Averaging

Majority vote

Weighted average

3. Advantages and Disadvantages of ensembling

3.1 Advantages

Ensembling is a proven method for improving the accuracy of the model and works in most of the cases.

It is the key ingredient for winning almost all of the machine learning hackathons.

Ensembling makes the model more robust and stable thus ensuring decent performance on the test cases in most scenarios.

You can use ensembling to capture linear and simple as well non-linear complex relationships in the data. This can be done by using two different models and forming an ensemble of two.

3.2 Disadvantages

Ensembling reduces the model interpretability and makes it very difficult to draw any crucial business insights at the end.

It is time-consuming and thus might not be the best idea for real-time applications.

The selection of models for creating an ensemble is an art which is really hard to master.

4. Practical guide to implementing ensembling in R

I believe you would have a good grasp on ensembling concepts by now. Well, enough of theory now, let’s get down to implementing ensembling and see whether it can help us improve our accuracy for a real machine learning challenge. If you wish to read more about the basics of ensembling, then you can refer to this resource.

For the purpose of implementing ensembling, I have chosen Loan Prediction problem. We have to predict whether the bank should approve the loan based on the applicant profile or not. It’s a binary classification problem. You can read more about the problem here.

I’ll be using caret package in R for training various individual models. It’s the goto package for modeling in R. Don’t worry if you are not familiar with the caret package, you can get through this article to get the comprehensive knowledge of caret package. Let’s get done with getting the data and data cleaning part.

Now, let’s try out different ways of forming an ensemble with these models as we have discussed:

Averaging: In this, we’ll average the predictions from the three models. Since the predictions are either ‘Y’ or ‘N’, averaging doesn’t make much sense for this binary classification. However, we can do averaging on the probabilities of observations to be in wither of these binary classes.

Majority Voting: In majority voting, we’ll assign the prediction for the observation as predicted by the majority of models. Since we have three models for a binary classification task, a tie is not possible.

Weighted Average: Instead of taking simple average, we can take weighted average. Generally, the weights of predictions are high for more accurate models. Let’s assign 0.5 to logistic regression and 0.25 to KNN and random forest each.

#Taking weighted average of predictions
testSet$pred_weighted_avg<-(testSet$pred_rf_prob$Y*0.25)+(testSet$pred_knn_prob$Y*0.25)+(testSet$pred_lr_prob$Y*0.5)
#Splitting into binary classes at 0.5
testSet$pred_weighted_avg<-as.factor(ifelse(testSet$pred_weighted_avg>0.5,'Y','N'))

Before proceeding further, I would like you to recall about two important criteria that we previously discussed on individual model accuracy and inter-model prediction correlation which must be fulfilled. In the above ensembles, I have skipped checking for the correlation between the predictions of the three models. I have randomly chosen these three models for a demonstration of the concepts. If the predictions are highly correlated, then using these three might not give better results than individual models. But you got the point. Right?

So far, we have used simple formulas at the top layer. Instead, we can use another machine learning model which is essentially what stacking is. We can use linear regression for making a linear formula for making the predictions in regression problem for mapping bottom layer model predictions to the outcome or logistic regression similarly in case of classification problem.

Moreover, we don’t need to restrict ourselves here, we can also use more complex models like GBM, neural nets to develop a non-linear mapping from the predictions of bottom layer models to the outcome.

On the same example let’s try applying logistic regression and GBM as top layer models. Remember, the following steps that we’ll take:

Train the individual base layer models on training data.

Predict using each base layer model for training data and test data.

Now train the top layer model again on the predictions of the bottom layer models that has been made on the training data.

Finally, predict using the top layer model with the predictions of bottom layer models that has been made for testing data.

One extremely important thing to note in step 2 is that you should always make out of bag predictions for the training data, otherwise the importance of the base layer models will only be a function of how well a base layer model can recall the training data.

Even, most of the steps have been already done previously, but I’ll walk you through the steps one by one again.

Note it’s really important to choose the models for the ensemble wisely to get the best out of the ensemble. The two thumb rules that we discussed will greatly help you in that.

5. Additional resources

By now, you might have developed an in-depth conceptual as well as practical knowledge of ensembling. I would like to encourage you to practice this on machine learning hackathons on Analytics Vidhya, which you can find here.

You’ll probably find this article on top five questions related to ensembling helpful.

Also, if you missed out on the skilltest on ensembling, you can check your understanding of ensembling concepts here.

End Notes

Ensembling is a very popular and effective technique that is very frequently used by data scientists for beating the accuracy benchmark of even the best of individual algorithms. More often than not it’s the winning recipe in hackathons. The more you’ll use ensembling, the more you’ll admire its beauty.

Did you enjoy reading this article? Do share your views in the comment section below. If you have any doubts / questions feel free to drop them in the comments below.

I’m glad you found it helpful. Yes, I didn’t shared the results of the ensemble as I wanted to encourage readers to try it out and find it themselves. Whether it gave better performance than any individual model. If it did, great. But if it didn’t, then you’ll need to think about why it didn’t and what could be done to overcome it by thinking on the lines of the important criterias for ensembling that I have mentioned.

I’m glad you found it helpful. Yes, I didn’t shared the results of the ensemble as I wanted to encourage readers to try it out and find it themselves. Whether it gave better performance than any individual model. If it did, great. But if it didn’t, then you’ll need to think about why it didn’t and what could be done to overcome it by thinking on the lines of the important criterias for ensembling that I have mentioned.

I really wanted to compliment in being so transparent in sharing this knowledge and learning platform. You are strengthening the often overlooked notion when in reality sharing knowledge makes us better.

I am an avid reader of your posts as it helps me understand the changing world of advanced analytics and have informed discussions with data scientists.

Thanks Saurav. This article came at the right time. I was looking for stacking and blending example and read many article on the subject but didn’t find complete hands on example on R. So struggling thru but this article initialized me with the basic.That’s why I love this site!!!!.

See these are the practical challenges that you’re bound to face when you use ensembling. It is definitely more time consuming than using a single model.

They way I see it is as a trade-off between accuracy and the training time. You can optimise the parameter search, use higher computation power, etc to reduce the time if ensembling is giving you really good results than any single model. This always boils down to what is the threshold time you want to generate the response within for your real time application.

I completely agree with you. There are more possibility to improve the accuracy using Ensemble modelling.

We are building model only to draw crucial business insights.

But as you mentioned in the disadvantages of ensemble modelling “It very difficult to draw any crucial business insights at the end.” then how ensemble modelling will benefits us,even have higher accuracy.

For the part : model_rf<-train(trainset[, predictors],trainset[,outcomeName],method='rf',trControl=fitControl,tuneLength=3)
I am getting error msg as :
Error in trainset[, predictors] : incorrect number of dimensions

I am starting to get a Machine Learning overdose here..! As a newbie to Data Science I initially thought that a simple regression model, a decision tree or a knn setting would do the job. And I just found out the reason that I cannot reach the highest positions in the leaderboard by using only them! Now I have to study some more I guess….Anyway, thank you very much for your wonderful presentation and explanation of the topic, you have pointed me the way ahead!

Fantastic tutorial. Explained with such ace. Thank you very much. Things are starting to make sense now. Thank you again. I really liked the way you distinguished the Base models and Top model in the diagram and accordingly did the code. Cheers!