Automate Stacking In Python: How to Boost Your Performance While Saving Time
Utilizing stacking (stacked generalizations) is a very hot topic when it comes to pushing your machine learning algorithm to new heights. For instance, most if not all winning Kaggle submissions nowadays make use of some form of stacking or a variation of it.
By Lukas Frei, PwC
Utilizing stacking (stacked generalizations) is a very hot topic when it comes to pushing your machine learning algorithm to new heights. For instance, most if not all winning Kaggle submissions nowadays make use of some form of stacking or a variation of it. First introduced in the 1992 paper Stacked Generalization by David Wolpert, their main purpose is to reduce the generalization error. According to Wolpert, they can be understood “as a more sophisticated version of cross-validation”. While Wolpert himself noted at the time that large parts of stacked generalizations are “black art”, it seems that building larger and larger stacked generalizations win over smaller stacked generalizations. However, as these models keep increasing in size, they also increase in complexity. Automating the process of building different architectures would significantly simplify this process. The remainder of this article will deal with the package vecstack I recently came across that is attempting just this.
What Does a Stacked Generalization Look like?
The main idea behind the structure of a stacked generalization is to use one or more first level models, make predictions using these models and then use these predictions as features to fit one or more second level models on top. To avoid overfitting, cross-validation is usually used to predict the OOF (out-of-fold) part of the training set. There are two different variants available in this package but I’m going to describe ‘Variant A’ in this paragraph. To get the final predictions in this variant, we take the mean or mode of all of our predictions. The whole process can be visualized using this GIF from vecstacks’ documentation:
Use Case: Building a Stacked Generalization for Classification
After having taken a look at the documentation, it was time to try using the package myself and see how it works. To do so, I decided to use the wine data set available on the UCI Machine Learning Repository. The problem statement for this data set is to use the 13 features, which all represent different aspects of the wine, to predict from which of three cultivars in Italy the wine was derived.
To get started, let’s first import the packages we are going to need for our project:
Now we are ready to import our data and take a look at it to gain a better understanding of what it looks like:
Running the code chunk above gives us:
Note that I used .sample() instead if .head() to avoid being potentially misled by assuming the entire data set has the structure of the first five rows. Luckily, this data set does not have any missing values, so we can easily use it to test our package right away without any of the usually required data cleaning and preparation.
Following this, we are going to separate the response from the input variables and perform an 80:20 train-test-split following the example on vecstacks’ documentation.
We are getting closer to the interesting part. Remember the GIF from earlier? It is time now to define a few first level models for our stacked generalization. This step definitely deserves its own article but for purposes of simplicity, we are going to use three models: A KNN-Classifier, a Random Forest Classifier and an XGBoost Classifier.
These parameters were not tuned prior to setting them as the purpose of this article is testing the package. If you were to optimize performance, you should not just copy and paste these.
Taking the next part of code from the documentation, we are essentially performing the GIF’s first part using first level models to make predictions:
The stacking function takes several inputs:
- models: the first level models we defined earlier
- X_train, y_train, X_test: our data
- regression: Boolean indicating whether we want to use the function for regression. In our case set to False since this is a classification
- mode: using the earlier describe out-of-fold during cross-validation
- needs_proba: Boolean indicating whether you need the probabilities of class labels
- save_dir: save the result to directory Boolean
- metric: what evaluation metric to use (we imported the accuracy_score in the beginning)
- n_folds: how many folds to use for cross-validation
- stratified: whether to use stratified cross-validation
- shuffle: whether to shuffle the data
- random_state: setting a random state for reproducibility
- verbose: 2 here refers to printing all info
Doing so, we get the following output:
Again, referring to the GIF, all that’s left to do now is fit the second level model(s) of our choice on our predictions to make our final predictions. In our case, we are going to use an XGBoost Classifier. This step is not significantly different from a regular fit-and-predict in sklearn except for the fact that instead of using X_train to train our model, we are using our predictions S_train.
Using vecstacks’ stacking automation, we’ve managed to predict the correct wine cultivar with an accuracy of approximately 97.2%! As you can see, the API does not collide with the sklearn API and could, therefore, provide a helpful tool when trying to speed up your stacking workflow.
As always, if you have any feedback or found mistakes, please don’t hesitate to reach out to me.
Bio: Lukas Frei is a Data Science Consultant at PwC.
Original. Reposted with permission.
- Here’s how you can accelerate your Data Science on GPU
- One Simple Trick for Speeding up your Python Code with Numpy
- GPU Accelerated Data Analytics & Machine Learning
Top Stories Past 30 Days