블로그 이미지
Flying Mr.Cheon youGom

Recent Comment»

Recent Post»

Recent Trackback»

« 2025/5 »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

 

'ensemble'에 해당되는 글 3

  1. 2020.04.23 Ensembling guide - kaggle
  2. 2020.04.23 Ensemble 2/2 (앙상블)
  3. 2020.04.23 Ensemble 1/2 (앙상블)
 

Ensembling guide - kaggle

카테고리 없음 | 2020. 4. 23. 18:04 | Posted by youGom

ref : https://mlwave.com/kaggle-ensembling-guide/

 

Model ensembling is a very powerful technique to increase accuracy on a variety of ML tasks. In this article I will share my ensembling approaches for Kaggle Competitions.

For the first part we look at creating ensembles from submission files. The second part will look at creating ensembles through stacked generalization/blending.

I answer why ensembling reduces the generalization error. Finally I show different methods of ensembling, together with their results and code to try it out for yourself.

This is how you win ML competitions: you take other peoples’ work and ensemble them together.”

Vitaly Kuznetsov NIPS2014

 

Creating ensembles from submission files

The most basic and convenient way to ensemble is to ensemble Kaggle submission CSV files. You only need the predictions on the test set for these methods — no need to retrain a model. This makes it a quick way to ensemble already existing model predictions, ideal when teaming up.

Voting ensembles.

We first take a look at a simple majority vote ensemble. Let’s see why model ensembling reduces error rate and why it works better to ensemble low-correlated model predictions.

Error correcting codes

During space missions it is very important that all signals are correctly relayed.

If we have a signal in the form of a binary string like:

1110110011101111011111011011

and somehow this signal is corrupted (a bit is flipped) to:

1010110011101111011111011011

then lives could be lost.

A coding solution was found in error correcting codes. The simplest error correcting code is a repetition-code: Relay the signal multiple times in equally sized chunks and have a majority vote.

Original signal:
1110110011

Encoded:
10,3 101011001111101100111110110011

Decoding:
1010110011
1110110011
1110110011

Majority vote:
1110110011

Signal corruption is a very rare occurrence and often occur in small bursts. So then it figures that it is even rarer to have a corrupted majority vote.

As long as the corruption is not completely unpredictable (has a 50% chance of occurring) then signals can be repaired.

A machine learning example

Suppose we have a test set of 10 samples. The ground truth is all positive (“1”):

1111111111

We furthermore have 3 binary classifiers (A,B,C) with a 70% accuracy. You can view these classifiers for now as pseudo-random number generators which output a “1” 70% of the time and a “0” 30% of the time.

We will now show how these pseudo-classifiers are able to obtain 78% accuracy through a voting ensemble.

A pinch of maths

For a majority vote with 3 members we can expect 4 outcomes:

All three are correct
  0.7 * 0.7 * 0.7
= 0.3429

Two are correct
  0.7 * 0.7 * 0.3
+ 0.7 * 0.3 * 0.7
+ 0.3 * 0.7 * 0.7
= 0.4409

Two are wrong
  0.3 * 0.3 * 0.7
+ 0.3 * 0.7 * 0.3
+ 0.7 * 0.3 * 0.3
= 0.189

All three are wrong
  0.3 * 0.3 * 0.3
= 0.027

We see that most of the times (~44%) the majority vote corrects an error. This majority vote ensemble will be correct an average of ~78% (0.3429 + 0.4409 = 0.7838).

Number of voters

Like repetition codes increase in their error-correcting capability when more codes are repeated, so do ensembles usually improve when adding more ensemble members.

Repetition codes performance on graph

Using the same pinch of maths as above: a voting ensemble of 5 pseudo-random classifiers with 70% accuracy would be correct ~83% of the time. One or two errors are being corrected during ~66% of the majority votes. (0.36015 + 0.3087)

Correlation

When I first joined the team for KDD-cup 2014, Marios Michailidis (KazAnova) proposed something peculiar. He calculated the Pearson correlation for all our submission files and gathered a few well-performing models which were less correlated.

Creating an averaging ensemble from these diverse submissions gave us the biggest 50-spot jump on the leaderboard. Uncorrelated submissions clearly do better when ensembled than correlated submissions. But why?

To see this, let us take 3 simple models again. The ground truth is still all 1’s:

1111111100 = 80% accuracy
1111111100 = 80% accuracy
1011111100 = 70% accuracy.

These models are highly correlated in their predictions. When we take a majority vote we see no improvement:

1111111100 = 80% accuracy

Now we compare to 3 less-performing, but highly uncorrelated models:

1111111100 = 80% accuracy
0111011101 = 70% accuracy
1000101111 = 60% accuracy

When we ensemble this with a majority vote we get:

1111111101 = 90% accuracy

Which is an improvement: A lower correlation between ensemble model members seems to result in an increase in the error-correcting capability.

Use for Kaggle: Forest Cover Type prediction

Forest

Majority votes make most sense when the evaluation metric requires hard predictions, for instance with (multiclass-) classification accuracy.

The forest cover type prediction challenge uses the UCI Forest CoverType dataset. The dataset has 54 attributes and there are 6 classes.

We create a simple starter model with a 500-tree Random Forest. We then create a few more models and pick the best performing one. For this task and our model selection an ExtraTreesClassifier works best.

Weighing

We then use a weighted majority vote. Why weighing? Usually we want to give a better model more weight in a vote. So in our case we count the vote by the best model 3 times. The other 4 models count for one vote each.

The reasoning is as follows: The only way for the inferior models to overrule the best model (expert) is for them to collectively (and confidently) agree on an alternative.

We can expect this ensemble to repair a few erroneous choices by the best model, leading to a small improvement only. That’s our punishment for forgoing a democracy and creating a Plato’s Republic.

“Every city encompasses two cities that are at war with each other.”

Plato in The Republic

Table 1. shows the result of training 5 models, and the resulting score when combining these with a weighted majority vote.

Model Public Accuracy Score
GradientBoostingMachine 0.65057
RandomForest Gini 0.75107
RandomForest Entropy 0.75222
ExtraTrees Entropy 0.75524
ExtraTrees Gini (Best) 0.75571
Voting Ensemble (Democracy) 0.75337
Voting Ensemble (3*Best vs. Rest) 0.75667

Use for Kaggle: CIFAR-10 Object detection in images

CIFAR-10

CIFAR-10 is another multi-class classification challenge where accuracy matters.

Our team leader for this challenge, Phil Culliton, first found the best setup to replicate a good model from dr. Graham.

Then he used a voting ensemble of around 30 convnets submissions (all scoring above 90% accuracy). The best single model of the ensemble scored 0.93170.

A voting ensemble of 30 models scored 0.94120. A ~0.01 reduction in error rate, pushing the resulting score beyond the estimated human classification accuracy.

Code

We have a sample voting script you could use at the MLWave Github repo. It operates on a directory of Kaggle submissions and creates a new submission. Update: Armando Segnini has added weighing.

Ensembling. Train 10 neural networks and average their predictions. It’s a fairly trivial technique that results in easy, sizeable performance improvements.

One may be mystified as to why averaging helps so much, but there is a simple reason for the effectiveness of averaging. Suppose that two classifiers have an error rate of 70%. Then, when they agree they are right. But when they disagree, one of them is often right, so now the average prediction will place much more weight on the correct answer.

The effect will be especially strong whenever the network is confident when it’s right and unconfident when it’s wrong.

Ilya Sutskever A brief overview of Deep Learning.

Averaging

Averaging works well for a wide range of problems (both classification and regression) and metrics (AUC, squared error or logaritmic loss).

There is not much more to averaging than taking the mean of individual model predictions. An often heard shorthand for this on Kaggle is “bagging submissions”.

Averaging predictions often reduces overfit. You ideally want a smooth separation between classes, and a single model’s predictions can be a little rough around the edges.

Learning from noise

The above image is from the Kaggle competition: Don’t Overfit!, the black line shows a better separation than the green line. The green line has learned from noisy datapoints. No worries! Averaging multiple different green lines should bring us closer to the black line.

Remember our goal is not to memorize the training data (there are far more efficient ways to store data than inside a random forest), but to generalize well to new unseen data.

Kaggle use: Bag of Words Meets Bags of Popcorn

Icons

This is a movie sentiment analysis contest. In a previous post we used an online perceptron script to get 95.2 AUC.

The perceptron is a decent linear classifier which is guaranteed to find a separation if the data is linearly separable. This is a welcome property to have, but you have to realize a perceptron stops learning once this separation is reached. It does not necessarily find the best separation for new data.

So what would happen if we initialize 5 perceptrons with random weights and combine their predictions through an average? Why, we get an improvement on the test set!

Model Public AUC Score
Perceptron 0.95288
Random Perceptron 0.95092
Random Perceptron 0.95128
Random Perceptron 0.95118
Random Perceptron 0.95072
Bagged Perceptrons 0.95427

Above results also illustrate that ensembling can (temporarily) save you from having to learn about the finer details and inner workings of a specific Machine Learning algorithm. If it works, great! If it doesn’t, not much harm done.

Perceptron bagging

You also won’t get a penalty for averaging 10 exactly the same linear regressions. Bagging a single poorly cross-validated and overfitted submission may even bring you some gain through adding diversity (thus less correlation).

Code

We have posted a simple averaging script on Github that takes as input a directory of .csv files and outputs an averaged submission. Update: Dat Le has added a geometric averaging script. Geometric mean can outperform a plain average.

Rank averaging

When averaging the outputs from multiple different models some problems can pop up. Not all predictors are perfectly calibrated: they may be over- or underconfident when predicting a low or high probability. Or the predictions clutter around a certain range.

In the extreme case you may have a submission which looks like this:

Id,Prediction
1,0.35000056
2,0.35000002
3,0.35000098
4,0.35000111

Such a prediction may do well on the leaderboard when the evaluation metric is ranking or threshold based like AUC. But when averaged with another model like:

Id,Prediction
1,0.57
2,0.04
3,0.96
4,0.99

it will not change the ensemble much at all.

Our solution is to first turn the predictions into ranks, then averaging these ranks.

Id,Rank,Prediction
1,1,0.35000056
2,0,0.35000002
3,2,0.35000098
4,3,0.35000111

After normalizing the averaged ranks between 0 and 1 you are sure to get an even distribution in your predictions. The resulting rank-averaged ensemble:

Id,Prediction
1,0.33
2,0.0
3,0.66
4,1.0

Historical ranks.

Ranking requires a test set. So what do you do when want predictions for a single new sample? You could rank it together with the old test set, but this will increase the complexity of your solution.

A solution is using historical ranks. Store the old test set predictions together with their rank. Now when you predict a new test sample like “0.35000110” you find the closest old prediction and take its historical rank (in this case rank “3” for “0.35000111”).

Kaggle use case: Acquire Valued Shoppers Challenge

Scissors

Ranking averages do well on ranking and threshold-based metrics (like AUC) and search-engine quality metrics (like average precision at k).

The goal of the shopper challenge was to rank the chance that a shopper would become a repeat customer.

Our team first took an average of multiple Vowpal Wabbit models together with an R GLMNet model. Then we used a ranking average to improve the exact same ensemble.

Model Public Private
Vowpal Wabbit A 0.60764 0.59962
Vowpal Wabbit B 0.60737 0.59957
Vowpal Wabbit C 0.60757 0.59954
GLMNet 0.60433 0.59665
Average Bag 0.60795 0.60031
Rank average Bag 0.61027 0.60187

I already wrote about the Avito challenge where rank averaging gave us a hefty increase.

Finally, when weighted rank averaging the bagged perceptrons from the previous chapter (1x) with the new bag-of-words tutorial (3x) on fastML.com we improve that model’s performance from 0.96328 AUC to 0.96461 AUC.

Code

A simple work-horse rank averaging script is added to the MLWave Github repo.

Competitions are effective because there are any number of techniques that can be applied to any modeling problem, but we can’t know in advance which will be most effective.

Anthony Goldbloom Data Prediction Competitions — Far More than Just a Bit of Fun
Whiskey blendingFrom ‘How Scotch Blended Whisky is Made’ on Youtube

Stacked Generalization & Blending

Averaging prediction files is nice and easy, but it’s not the only method that the top Kagglers are using. The serious gains start with stacking and blending. Hold on to your top-hats and petticoats: Here be dragons. With 7 heads. Standing on top of 30 other dragons.

Netflix

Netflix organized and popularized the first data science competitions. Competitors in the movie recommendation challenge really pushed the state of the art on ensemble creation, perhaps so much so that Netflix decided not to implement the winning solution in production. That one was simply too complex.

Nevertheless, a number of papers and novel methods resulted from this challenge:

All are interesting, accessible and relevant reads when you want to improve your Kaggle game.

Netflix Prize Leaderboard

This is a truly impressive compilation and culmination of years of work, blending hundreds of predictive models to finally cross the finish line. We evaluated some of the new methods offline but the additional accuracy gains that we measured did not seem to justify the engineering effort needed to bring them into a production environment.

Netflix Engineers

Stacked generalization

Stacked generalization was introduced by Wolpert in a 1992 paper, 2 years before the seminal Breiman paper “Bagging Predictors“. Wolpert is famous for another very popular machine learning theorem: “There is no free lunch in search and optimization“.

The basic idea behind stacked generalization is to use a pool of base classifiers, then using another classifier to combine their predictions, with the aim of reducing the generalization error.

Let’s say you want to do 2-fold stacking:

  • Split the train set in 2 parts: train_a and train_b
  • Fit a first-stage model on train_a and create predictions for train_b
  • Fit the same model on train_b and create predictions for train_a
  • Finally fit the model on the entire train set and create predictions for the test set.
  • Now train a second-stage stacker model on the probabilities from the first-stage model(s).

A stacker model gets more information on the problem space by using the first-stage predictions as features, than if it was trained in isolation.

It is usually desirable that the level 0 generalizers are of all “types”, and not just simple variations of one another (e.g., we want surface-fitters, Turing-machine builders, statistical extrapolators, etc., etc.). In this way all possible ways of examining the learning set and trying to extrapolate from it are being exploited. This is part of what is meant by saying that the level 0 generalizers should “span the space”.

[…] stacked generalization is a means of non-linearly combining generalizers to make a new generalizer, to try to optimally integrate what each of the original generalizers has to say about the learning set. The more each generalizer has to say (which isn’t duplicated in what the other generalizer’s have to say), the better the resultant stacked generalization.

Wolpert (1992) Stacked Generalization

Blending

Blending is a word introduced by the Netflix winners. It is very close to stacked generalization, but a bit simpler and less risk of an information leak. Some researchers use “stacked ensembling” and “blending” interchangeably.

With blending, instead of creating out-of-fold predictions for the train set, you create a small holdout set of say 10% of the train set. The stacker model then trains on this holdout set only.

Blending has a few benefits:

  • It is simpler than stacking.
  • It wards against an information leak: The generalizers and stackers use different data.
  • You do not need to share a seed for stratified folds with your teammates. Anyone can throw models in the ‘blender’ and the blender decides if it wants to keep that model or not.

The cons are:

  • You use less data overall
  • The final model may overfit to the holdout set.
  • Your CV is more solid with stacking (calculated over more folds) than using a single small holdout set.

As for performance, both techniques are able to give similar results, and it seems to be a matter of preference and skill which you prefer. I myself prefer stacking.

If you can not choose, you can always do both. Create stacked ensembles with stacked generalization and out-of-fold predictions. Then use a holdout set to further combine these models at a third stage.

Stacking with logistic regression

Stacking with logistic regression is one of the more basic and traditional ways of stacking. A script I found by Emanuele Olivetti helped me understand this.

When creating predictions for the test set, you can do that in one go, or take an average of the out-of-fold predictors. Though taking the average is the clean and more accurate way to do this, I still prefer to do it in one go as that slightly lowers both model and coding complexity.

Kaggle use: “Papirusy z Edhellond”

Gondor

I used the above blend.py script by Emanuele to compete in this inClass competition. Stacking 8 base models (diverse ET’s, RF’s and GBM’s) with Logistic Regression gave me my second best score of 0.99409 accuracy, good for first place.

Kaggle use: KDD-cup 2014

Using this script I was able to improve a model from Yan Xu. Her model before stacking scored ~0.605 AUC. With stacking this improved to ~0.625.

Stacking with non-linear algorithms

Popular non-linear algorithms for stacking are GBM, KNN, NN, RF and ET.

Non-linear stacking with the original features on multiclass problems gives surprising gains. Obviously the first-stage predictions are very informative and get the highest feature importance. Non-linear algorithms find useful interactions between the original features and the meta-model features.

Kaggle use: TUT Headpose Estimation Challenge

TUT headpose

 The TUT Headpose Estimation challenge can be treated as a multi-class multi-label classification challenge.

For every label a separate ensemble model was trained.

The following table shows the result of training individual models, and their improved scores when stacking the predicted class probabilities with an extremely randomized trees model.

Model Public MAE Private MAE
Random Forests 500 estimators 6.156 6.546
Extremely Randomized Trees 500 estimators 6.317 6.666
KNN-Classifier with 5 neighbors 6.828 7.460
Logistic Regression 6.694 6.949
Stacking with Extremely Randomized Trees 4.772 4.718

We see that stacked generalization with standard models is able to reduce the error by around 30%(!).

Read more about this result in the paper: Computer Vision for Head Pose Estimation: Review of a Competition.

Code

You can find a function to create out-of-fold probability predictions in the MLWave Github repo. You could use numpy horizontal stacking (hstack) to create blended datasets.

Feature weighted linear stacking

Feature-weighted linear stacking stacks engineered meta-features together with model predictions. The hope is that the stacking model learns which base model is the best predictor for samples with a certain feature value. Linear algorithms are used to keep the resulting model fast and simple to inspect.

Blended prediction

Vowpal Wabbit can implement a form of feature-weighted linear stacking out of the box. If we have a train set like:

1 |f f_1:0.55 f_2:0.78 f_3:7.9 |s RF:0.95 ET:0.97 GBM:0.92

We can add quadratic feature interactions between the s-featurespace and the f-featurespace by adding -q fs. The features in the f-namespace can be engineered meta-features like in the paper, or they can be the original features.

Quadratic linear stacking of models

This did not have a name so I made one up. It is very similar to feature-weighted linear stacking, but it creates combinations of model predictions. This improved the score on numerous experiments, most noticeably on the Modeling Women’s Healthcare Decision competition on DrivenData.

Using the same VW training set as before:

1 |f f_1:0.55 f_2:0.78 f_3:7.9 |s RF:0.95 ET:0.97 GBM:0.92

We can train with -q ss creating quadratic feature interactions (RF*GBM) between the model predictions.

This can easily be combined with feature-weighted linear stacking: -q fs -q ss, possibly improving on both.

So now you have a case where many base models should be created. You don’t know apriori which of these models are going to be helpful in the final meta model. In the case of two stage models, it is highly likely weak base models are preferred.

So why tune these base models very much at all? Perhaps tuning here is just obtaining model diversity. But at the end of the day you don’t know which base models will be helpful. And the final stage will likely be linear (which requires no tuning, or perhaps a single parameter to give some sparsity).  

Mike Kim Tuning doesn’t matter. Why are you doing it?

Stacking classifiers with regressors and vice versa

Stacking allows you to use classifiers for regression problems and vice versa. For instance, one may try a base model with quantile regression on a binary classification problem. A good stacker should be able to take information from the predictions, even though usually regression is not the best classifier.

Using classifiers for regression problems is a bit trickier. You use binning first: You turn the y-label into evenly spaced classes. A regression problem that requires you to predict wages can be turned into a multiclass classification problem like so:

  • Everything under 20k is class 1.
  • Everything between 20k and 40k is class 2.
  • Everything over 40k is class 3.

The predicted probabilities for these classes can help a stacking regressor make better predictions.

“I learned that you never, ever, EVER go anywhere without your out-of-fold predictions. If I go to Hawaii or to the bathroom I am bringing them with. Never know when I need to train a 2nd or 3rd level meta-classifier”

T. Sharf

Stacking unsupervised learned features

There is no reason we are restricted to using supervised learning techniques with stacking. You can also stack with unsupervised learning techniques.

K-Means clustering is a popular technique that makes sense here. Sofia-ML implements a fast online k-means algorithm suitable for this.

Another more recent interesting addition is to use t-SNE: Reduce the dataset to 2 or 3 dimensions and stack this with a non-linear stacker. Using a holdout set for stacking/blending feels like the safest choice here. See here for a solution by Mike Kim, using t-SNE vectors and boosting them with XGBoost: ‘0.41599 via t-SNE meta-bagging‘.

t-SNE

Piotr shows a nice visualization with t-SNE on the Otto Product Classification Challenge data set.

Online Stacking

I spend quit a lot of time working out an idea I had for online stacking: first create small fully random trees from the hashed binary representation. Substract profit or add profit when the tree makes a correct prediction. Now take the most profitable and least profitable trees and add them to the feature representation.

It worked, but only on artificial data. For instance, a linear perceptron with online random tree stacking was able to learn a non-linear XOR-problem. It did not work on any real-life data I tried it on, and believe me, I tried. So from now on I’ll be suspicious of papers which only feature artificial data sets to showcase their new algorithm.

A similar idea did work for the author of the paper: random bit regression. Here many random linear functions are created from the features, and the best are found through heavy regularization. This I was able to replicate with success on some datasets. This will the topic of a future post.

A more concrete example of (semi-) online stacking is with ad click prediction. Models trained on recent data perform better there. So when a dataset has a temporal effect, you could use Vowpal Wabbit to train on the entire dataset, and use a more complex and powerful tool like XGBoost to train on the last day of data. Then you stack the XGBoost predictions together with the samples and let Vowpal Wabbit do what it does best: optimizing loss functions.

The natural world is complex, so it figures that ensembling different models can capture more of this complexity.

Ben Hamner ‘Machine learning best practices we’ve learned from hundreds of competitions’ (video)

Everything is a hyper-parameter

When doing stacking/blending/meta-modeling it is healthy to think of every action as a hyper-parameter for the stacker model.

So for instance:

  • Not scaling the data
  • Standard-Scaling the data
  • Minmax scaling the data

are simply extra parameters to be tuned to improve the ensemble performance. Likewise, the number of base models to use can be seen as a parameter to optimize. Feature selection (top 70%) or imputation (impute missing features with a 0) are other examples of meta-parameters.

Like a random gridsearch is a good candidate for tuning algorithm parameters, so does it work for tuning these meta-parameters.

Sometimes it is useful to allow XGBoost to see what a KNN-classifier sees. –

Marios Michailidis

Model Selection

You can further optimize scores by combining multiple ensembled models.

  • There is the ad-hoc approach: Use averaging, voting or rank averaging on manually-selected well-performing ensembles.
  • Greedy forward model selection (Caruana et al.). Start with a base ensemble of 3 or so good models. Add a model when it increases the train set score the most. By allowing put-back of models, a single model may be picked multiple times (weighing).
  • Genetic model selection uses genetic algorithms and CV-scores as the fitness function. See for instance inversion‘s solution ‘Strategy for top 25 position‘.
  • I use a fully random method inspired by Caruana’s method: Create a 100 or so ensembles from randomly selected ensembles (without placeback). Then pick the highest scoring model.

Automation

Otto Group

When stacking for the Otto product classification competition I quickly got a good top 10 spot. Adding more and more base models and bagging multiple stacked ensembles I was able to keep improving my score.

Once I had reached 7 base models stacked by 6 stackers, a sense of panic and gloom started to set in. Would I be able to replicate all of this? These complex and slow unwieldy models were out of my comfort zone of fast and simple Machine Learning.

I spend the rest of the competition building a way to automate stacking. For base models pure random algorithms with pure random parameters are trained. Wrappers were written to make classifiers like VW, Sofia-ML, RGF, MLP and XGBoost play nicely with the Scikit-learn API.

Whiteboard automated stacking

 

The first whiteboard sketch for a parallelized automated stacker with 3 buckets

For stackers I let the script use SVM, random forests, extremely randomized trees, GBM and XGBoost with random parameters and a random subset of base models.

Finally the created stackers are averaged when their fold-predictions on the train set produced a lower loss.

This automated stacker was able to rank 57th spot a week before the competition ended. It contributed to my final ensemble. The only difference was I never spend time tuning or selecting: I started the script, went to bed, and awoke to a good solution.

Otto Leaderboard

The automated stacker is able to get a top 10% score without any tuning or manual model selection on a competitive task with over 3000 competitors.

Automatic stacking is one of my new big interests. Expect a few follow-up articles on this. The best result of automatic stacking was found on the TUT Headpose Estimation challenge. This black-box solution beats the current state-of-the-art set by domain experts who created special-purpose algorithms for this particular problem.

Tut headpose leaderboard

Noteworthy: This was a multi-label classification problem. Predictions for both “yaw” and “pitch” were required. Since the “yaw” and “pitch”-labels of a head pose are interrelated, stacking a model with predictions for “yaw” increased the accuracy for “pitch” predictions and vice versa. An interesting result.

Models visualized as a network can be trained used back-propagation: then stacker models learn which base models reduce the error the most.

Ensemble Network

Next to CV-scores one could take the standard deviation of the CV-scores into account (a smaller deviation is a safer choice). One could look at optimizing complexity/memory usage and running times. Finally one can look at adding correlation into the mix — make the script prefer uncorrelated model predictions when creating ensembles.

The entire automated stacking pipeline can be parallelized and distributed. This also brings speed improvements and faster good results on a single laptop.

Contextual bandit optimization seems like a good alternative to fully random gridsearch: We want our algorithm to start exploiting good parameters and models and remember that the random SVM it picked last time ran out of memory. These additions to stacking will be explored in greater detail soon.

In the meantime you can get a sneak preview on the MLWave Github repo: “Hodor-autoML“.

The #1 and #2 winners of the Otto product classification challenge used ensembles of over a 1000 different models. Read more about the first place and the second place.

Why create these Frankenstein ensembles?

You may wonder why this exercise in futility: stacking and combining 1000s of models and computational hours is insanity right? Well… yes. But these monster ensembles still have their uses:

  • You can win Kaggle competitions.
  • You can beat most state-of-the-art academic benchmarks with a single approach.
  • You can then compare your new-and-improved benchmark with the performance of a simpler, more production-friendly model
  • One day, today’s computers and clouds will seem weak. You’ll be ready.
  • It is possible to transfer knowledge from the ensemble back to a simpler shallow model (Hinton’s Dark Knowledge, Caruana’s Model Compression)
  • Not all base models necessarily need to finish in time. In that regard, ensembling introduces a form of graceful degradation: loss of one model is not fatal for creating good predictions.
  • Automated large ensembles ward against overfit and add a form of regularization, without requiring much tuning or selection. In principle stacking could be used by lay-people.
  • It is currently one of the best methods to improve machine learning algorithms, perhaps telling use something about efficient human ensemble learning.
  • A 1% increase in accuracy may push an investment fund from making a loss, into making a little less loss. More seriously: Improving healthcare screening methods helps save lives.

Update: Thanks a lot to Dat Le for documenting and refactoring the code accompanying this article. Thanks to Armando Segnini for adding weighted averaging. Thanks a lot everyone for the encouraging comments. My apologies if I have forgotten to link to your previous inspirational work. Further reading at “More is always better – The power of Simple Ensembles” by Carter Sibley, “Tradeshift Benchmark Tutorial with two-stage SKLearn models” by Dmitry Dryomov, “Stacking, Blending and Stacked Generalization” by Eric Chio, Ensemble Learning: The wisdom of the crowds (of machines) by Lior Rokach, and “Deep Support Vector Machines” by Marco Wiering.

Terminology: When I say ensembling I mean ‘model averaging’: combining multiple models. Algorithms like Random Forests use ensembling techniques like bagging internally. For this article we are not interested in that.The intro image came from WikiMedia Commons and is in the public domain, courtesy of Jesse Merz.

Cite

If you use significant portions or methods from this article in a scientific paper, report, or book, please consider attributing with:

  • Hendrik Jacob van Veen, Le Nguyen The Dat, Armando Segnini. 2015. Kaggle Ensembling Guide. [accessed 2018 Feb 6]. https://mlwave.com/kaggle-ensembling-guide/

or, if you prefer a more authoritative reference:

  • Michailidis, Marios. (2017). Investigating machine learning methods in recommender systems (Thesis). University College London.

For other, less formal, material, such as blogs or educational slides, a simple link will suffice to satisfy Creative Commons 3.0 attribution.

The resource URL will remain static and the page hosted on this site for the foreseeable future.

:

Ensemble 2/2 (앙상블)

데이터사이언스/MachineLearning | 2020. 4. 23. 17:59 | Posted by youGom

본 포스팅은 Boosting Algorithm에 관련된 내용입니다. 글에 적합한 이미지는 후에 차근차근 넣어보겠습니다.

Boosting Algorihtm

앙상블은 여러 모델을 사용하여 좋은 모델을 만드는 것을 목표로 하는 테크닉입니다. Kaggle 등의 DS Competition에서 높은 성적을 위해 많이 사용하는 방법이기도 합니다.

그중에서도 Boost 계열의 알고리즘은 약한(weak) 분류기를 많이 사용하여, 강한(Boost) 분류기를 만드는 것을 목표로 합니다. 이 중에서 흔히 사용하는 대표적인 알고리즘을 중심으로 하나씩 살펴보겠습니다.

간단한 모델인 앞의 두 모델은 매개변수까지 가볍게 살펴보고, 뒤의 알고리즘은 특징과 장/단점을 위주로 살펴보도록 하겠습니다.

  • AdaBoost
  • Gradient Boost Machine
  • XGBoost
  • LightGBM
  • CatBoost

AdaBoost

서론

Adaptive Boosting의 줄임말인 AdaBoost는 꽤 오래된 모델입니다. 1996년에 Freund와 Schapire이 제안한 알고리즘입니다. 2003년에는 괴델상을 수상한 알고리즘이기도 합니다.

이 모델은 다른 학습 알고리즘(weak learner)의 결과물들에 가중치를 두어 더하는 방법으로 최종 모델을 만듭니다. 여러 알고리즘을 사용하여 일반화 성능이 뛰어나며, 매우 간단한 구현으로 가능하기에 효율성이 뛰어난 알고리즘입니다.

보통 속도나 성능적인 측면에서 desision Tree를 weak learner로 사용합니다.

좀 더 이해하기

AdaBoost는 다음과 같은 단계로 진행하게 됩니다.

  1. 각 weak 모델에서 학습할 데이터 선택
  2. 모든 데이터의 가중치 초기화
  3. 한 번 학습 후, error(ϵϵ ) 계산, 모델 별 가중치(αα ) 계산, 데이터 가중치(DD )를 갱신
  4. 오류가 0이 되거나, 약한 분류기 수가 최대치에 도달할 때까지 반복
  5. 최종적으로 각 분류기의 가중치를 고려한 선형합산으로 예측값 계산

과정을 보면 알 수 있듯이, 학습에 있어 error값으로 가중치들을 갱신합니다. 이 과정을 통해 이전 모델이 틀린 데이터를 보다 잘 구분할 수 있도록 가중치를 갱신합니다.

하지만 그런 이유로 이 모델은 noisy한 데이터나 이상치(outlier)가 있을 때 취약(sensitive)합니다.

Code로 보는 AdaBoost

scikit-learn Documentation

from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_iris
from sklearn.ensemble import AdaBoostClassifier

# iris
X, y = # ~
clf = AdaBoostClassifier(n_estimators=100)
clf.fit(X, y)
clf.score(X, y)

기본적으로 base_estimatorDecisionTreeClassifier를 사용하고 있고, n_estimators로 수를 조정합니다. (default값은 50입니다.)

learning rate는 default값으로 1. 을 사용합니다. 그 외에 ‘random_state’로 시드를 조정할 수 있습니다.

여기서 혼동할 수 있는 부분 중 하나는 learning_rate입니다. 대부분의 AdaBoost 문서에는 learning rate가 포함될 부분이 없어보입니다.

저는 그 답을 StackExchange에서 찾았습니다. 구체적인 수식은 링크를 타고 보시면 될 것 같고, learning_raten_estimators에 대한 내용만 덧붙이자면

  • learning_rate L을 줄인다면
    • L은 가중치를 갱신하는 데 쓰이는 αα 값에 붙는 상수(1이하 양의 실수)입니다.
    • 이는 가중치 갱신의 크기/스케일을 줄입니다.
    • 그렇기에 weak classifier의 결정 경계들(decision boundaries)간의 차이가 적습니다. (모델의 단순화)
  • 반복 횟수 M을 늘린다면
    • 사용하는 weak classifier의 수를 늘고, 최종적으로 이를 선형으로 더해야합니다.
    • 그렇기에 분류기의 결정 경계가 더욱 다양해지고 복잡해집니다.

이런 이유로 L과 M은 trade-off 관계라고 생각할 수 있습니다. 그렇기에 둘을 잘 조정하여 사용하는 것이 이 알고리즘의 핵심입니다.

수 많은 변형

여기서 변형된 알고리즘으로는 다음과 같은 알고리즘이 있습니다. 더 많이 있지만, wiki의 상위 2항목만 소개하면 다음과 같습니다.

Algorithm Description
Real AdaBoost 기본적인 Adaboost는 분류기의 결과를 {1, -1}로 사용하는데 이를 실수로 표현하여 확률값으로 계산가능
LogitBoost Logistic Regression을 활용한 AdaBoost

이제 이런 AdaBoost를 시작으로 만들어진 알고리즘을 아래에서 보도록 합시다.

Gradient Boosting

서론

GBM(Gradient Boosting) 이라고도 부르며, Friedman이 2001년에 소개한 알고리즘입니다. 다른 명칭으로는 MART(Multiple Additive Regression Trees) 또는 GBRT (Gradient Boosted Regression Trees)이 있습니다.

좀 더 이해하기

AdaBoost와 같은 순서로 진행합니다. 단 모델의 가중치(DD )를 계산하는 방식에서 Gradient Descent를 이용하여 파라미터를 구합니다.

AdaBoost에서는 모델 가중치를 고려한 선형합으로 최종 predictions을 구합니다. 그렇다면 이 모델 가중치 선형 합 연산을 하나의 식으로 본다면 어떨까요? 모델에 따른 최적의 가중치를 Gradient decent로 구해서 보다 최적화된 결과를 얻고자 하는 것이 GBM의 특징입니다.

하지만 GBM은 greedy algorithm이고, 과적합(overfitting)이 빠르게 된다는 단점이 있습니다. 그렇기에 일부 사항에 제약을 두어 모델의 일반화 성능을 향상시킬 수 있습니다.

다음은 어떤 방식으로 일반화시킬 수 있는지 봅시다.

Code로 보는 GBM

scikit-learn Documentation

보다 나은 모델을 위한 방법을 코드와 함께 알아보도록 하겠습니다. GBM에 있어 매개변수는 크게 3개로 나눌 수 있습니다.

  1. Tree-Specific : 개별 트리 관련
  2. Boosting : boosting 연산 관련
  3. Other : 그 외

나눠서 봅시다. 아래 Reference에도 적어두었지만, 기본적으로 parameter를 어떤 식으로 튜닝할 수 있는지 좋은 이 있으니 함께 보면 좋을 것 같습니다. GBM 기반의 알고리즘에서 보통 공통적으로 사용하는 매개변수이므로 간단하게 정리해보았습니다.

Tree-Specific

parameter description
max_depth 트리의 최대 깊이입니다. decision tree가 깊어질 수록 모델은 복잡해지고, 모델은 과적합될 가능성이 큽니다. 그렇기에 깊이를 얕게 하는 것이 좋습니다. (제가 참고한 글에서는 4-8이라고 하네요.)
max_leaf_nodes 노드의 최대 개수입니다. 최종적으로 decision tree에서 만들어지는 노드들의 수를 한정합니다.
min_samples_split leaf의 분할 가능 최소 개수입니다. 분할 기준을 제한하여 모델의 복잡도를 줄입니다.
min_sample_leaf leaf 노드가 되기 위한 최소 개수입니다. 바로 위의 매개변수와 잘 조정하여 사용합니다.
min_weight_fraction_leaf 위와 유사하지만, 이는 전체 개수에서 비율로 조정합니다. 위의 매개변수와 동시 사용은 불가합니다.
max_features 나누는 기준이 되는 feature의 개수입니다. sqrt 정도 사용하라고 합니다. 값에 따라 과적합이 발생할 수 있습니다.

Boosting

parameter description
n_estimators 트리의 개수입니다. 모델에 트리가 너무 많게 되면 학습 속도가 너무 느리게 됩니다. 개수에 따른 성능 향상이 크게 없다면 수를 더 이상 늘릴 필요는 없습니다.
learning_rate 일반적으로 값이 낮을수록 좋지만, 낮은 만큼 많은 수의 트리가 필요하고, 계산 비용이 많이 드니 조정해야합니다.
subsample 개별 트리는 데이터를 부분적으로만 사용하여, 각 트리간의 상관도를 줄입니다. 랜덤하게 데이터를 선택하여 쓰고, 그렇기에 Stochastic Gradient Boost라는 명칭을 씁니다. ~0.8 정도에서 fine tuning을 하면 됩니다.

그 외의 변인은 따로 설명은 하지 않겠습니다. 궁금하신 분은 공식 문서를 확인하는 것을 추천합니다.


이제부터 본격적으로 Competition에서 많이 사용하는 3대 Boosting 알고리즘을 살펴봅시다. 구체적인 매개변수는 다루지 않을 예정입니다. (왜냐면 거의 100개에 가까운 매개변수를 정리하는 건 너무 비효율적이니까요.)

XGBoost

서론

2014년, Tianqi Chen이 GBM을 기반으로 만든 알고리즘입니다. 만들고 바로 유명해진 것은 아니고 2016년에 Kaggle에서 Higgs Machine Learning Challenge에서 본인이 만든 알고리즘을 사용하여 우승했고, 이후 친구의 제안을 받아 python으로 만들고 논문도 publish하였다고 합니다. 후기

로직 자체는 매우 복잡합니다. 그렇기에 구체적 알고리즘을 알기보다는 기존 GBM과의 차이나 장단점을 위주로 보도록 하겠습니다. 성능이 얼마나 뛰어나면 eXtream GBM일까요.

좀 더 이해하기

기존 GBM에서 시스템 최적화알고리즘 성능 향상은 다음과 같이 진행했습니다.

  • 시스템 최적화에는 병렬화(Parallerlization), 가지치기(Tree Prunning), 하드웨어 최적화(Hardware Optimization)이 있습니다.
  • 알고리즘 성능 향상에는
    • Lasso나 Ridge를 통한 정규화
    • missing value의 패턴을 찾아 효율적으로 처리 (결측값은 모두 제외하고 분할, 그 후에 loss가 제일 적은 곳에 할당)
    • weighted Quantile Sketch algorithm을 사용한 효율적인 분할
    • 교차 검증을 통한 일반화

위에서 언급한 방법 덕분에 기존 GBM에 비해 월등히 속도가 빠르고, 훈련시간을 줄였으며, 보다 일반화된 모델을 얻을 수 있게 되었습니다. 또한 위에서 언급한 바와 같이 missing value를 따로 처리하지 않아도 된다는 장점이 있습니다. 또한 병렬화를 덕분에 GPU를 사용할 수 있게 되었습니다.

XGBoost는 scikit-learn이 아닌 xgboost 패키지가 따로 존재합니다. 또한 조정가능한 매개변수가 지나치게 많기 때문에 공식 문서를 보며 차차 세부 튜닝하는 것을 추천합니다.

LightGBM

서론

2016년에 발표되어 XGBoost를 이은 GBM 기반의 모델입니다. 최근 Kaggle에서 가장 많이 우승한 알고리즘이기도 합니다. Microsoft에서 발표한 알고리즘입니다. 그렇기에 패키지도 따로 있습니다.

기존에 GBM이 DFS와 같이 leaf에서 더 깊은 leaf를 생성했다면(level wise/depth wise), LightGBM은 BFS와 같이 같은 level의 leaf를 추가적으로 생성합니다.(leaf-wise) 좀 더 쉽게 표현하면, 기존에는 세로로 자라는 나무였다면 LightGBM은 가로로 자라는 나무입니다.

좀 더 이해하기

LightGBM은 다음과 같은 장점이 있습니다.

  • 빠른 교육 속도 및 높은 효율성 : LightGBM은 히스토그램 기반 알고리즘을 사용합니다.
    • 기존에는 분할을 위해 모든 데이터를 확인했지만, LightGBM은 히스토그램으로 근사치를 측정
    • local voting과 global voting의 사용으로 병렬화에서 소모되는 communication 연산 축소
    • voting 결과로 분할할 수 있는 feature가 2개 선택 -> 매우 빠름
    • XGBoost와 같이 Missing Value 무시
  • 메모리 사용량 감소 : 기존 GBM보다 적은 메모리를 사용합니다.
  • 정확도 : leaf-wise 방식을 사용하여 복잡한 모델을 만들고, 더욱 높은 정확도를 만듭니다. 과적합될 가능성이 있지만 max_depth 등의 매개변수로 조정할 수 있습니다.
  • 대용량 데이터 세트와의 호환성 : XGBoost와 비교하여 속도가 빠르고(2~10배 정도), 유사한 성능을 냅니다.
  • GPU 사용 가능

물론 단점도 존재합니다. 과적합이 쉽게 되는 모델이기에 적은 데이터셋이 아닌 10000개 이상의 데이터셋이 있을 때 적합한 알고리즘입니다.

XGBoost와 다르게 범주형(Categorical)도 따로 처리할 수 있게 되어있습니다. int로 변환하여 제공해야하긴 하지만 one-hot encoding이 아닌 다른 방식으로 범주형 feature를 관리합니다. (코드에서 categorical_feature로 넘겨줄 수 있습니다.)

LightGBM에서 parameter tuning에 대한 좋은 이 있어 공유합니다.

CatBoost

제가 이전 앙상블 시리즈 글을 쓸 당시에는 자료가 논문 외에는 크게 없었는데, 이제는 좀 많네요!

서론

가장 최근(2017.06)에 발표되었고, 급부상중인 알고리즘인 CatBoost입니다. Categorical을 다루는 알고리즘이라 CatBoost입니다. 빠른 속도, 정확도 향상, 범주형 데이터 특화 등 여러 장점을 앞세운 알고리즘입니다.

대표적으로 ordered boosting의 구현, categorical feature 처리가 핵심인 알고리즘으로 좀 더 구체적으로 알아보겠습니다.

좀 더 이해하기

Categorical Feature Processing

  1. 기존의 GBM은 One-Hot 인코딩을 사용하여 범주형 특성을 다뤘습니다. 이런 One-Hot 인코딩은 전처리 단계에서 진행할 수도 있고, 훈련 중에서도 진행할 수 있는데 CatBoost는 훈련과 함께 이를 진행합니다. 기본적으로 categorical feature의 값이 두 종류라면 One-Hot을 진행합니다. 그 외에는 one_hot_max_size parameter를 통해 사용할 수 있습니다.

  2. 그 외에도 다음과 같은 방법을 사용하여 Categorical을 다룹니다. CatBoost는 해당 category의 level마다 바로 이전 data points의 target value들만 고려합니다.(이 과정에서 이전은 time을 의미합니다. CatBoost에서는 순서를 위해 가상의 시간 순서를 만듭니다.) 그 과정에서 기댓값에 따라 categorical value의 값을 결정합니다. (이 방식에서는 첫 값을 얻을 수 없기에 prial과 가중치 a값을 도입한다.)

  3. 범주형 간의 상관관계가 있는 경우를 대비하여 자체적으로 Feature를 Combination해서 만들어줍니다. NP-Hard 문제이기에 Greedy하게 Tree로 만들어, 새로운 Feature를 수치화하여 사용합니다.

  4. 수치는 다른 GBM과 같이 수치로 취급됩니다. cat_feature로 범주로 넘겨줄 수도 있습니다.

Ordered Boosting

기존의 알고리즘은 이전에 사용했던 데이터를 다시 재사용하여 과적합이 쉽게 되었습니다. (target leackage 발생)

그렇기에 CatBoost는 첫 번째 학습된 잔차로, 두 번째 모델을 만들고, 그 값에서 graient로 업데이트하고 ~ 를 반복하여 모델을 만듭니다. 이 방법은 target이 아닌 관측된 기록에만 의존하기에 leackage를 막을 수 있습니다.

이 방법을 사용하기 위해서는 메모리 관리가 필수인데, CatBoost는 균형잡힌 Tree 모델을 사용했습니다. 모델을 확장하며 위의 leaf를 cut-off하는 방식입니다. 이런 이진 모델의 특징 덕분에 leaf node의 idx만 가지고 value를 불러낼 수 있어 매우 빠르게 테스트를 할 수 있다고 합니다.

또한 랜덤화된 순열을 한 번만 사용하면 기존 데이터보다 분산이 큰 결과만 나오게 되므로, 각 부스팅 단계마다 다른 순열을 사용합니다.

장단점

정리하면 다음과 같습니다.

  • missing data를 처리 해주지않는다.
  • 대신 categorical에 특화되어 있다.
  • 수치형 데이터가 많다면 LightGBM보다 느리다.
  • 하지만 그래도 비슷하게 빠르다.
  • 다른 GBM에 비해 overfitting이 적다.

Wrapped Up…

상위 3개의 알고리즘을 사용하는 것은 옳은 선택입니다. 하지만 다음을 고려하면 좋을 것 같습니다.

  • 완전한 정답은 없다.
  • XGBoost는 느리다.
  • CatBoost는 범주형 데이터가 많을 때 좋다.
  • GBM 기반은 overfitting을 방지하기 위한 튜닝이 중요하다.

다들 Keep Going 합시다!!

느낀점

  • 이런 모델을 만들 수 있는 사람이 되고 싶다는 생각이 드는 공부였습니다.
  • 반나절 정도 읽고 정리한 것 같은데 정리가 조금 마음에 안드네요. 읽은 것보다 양이 너무 적기도 하고..
  • ‘글을 알고리즘 별로 쓸 걸…;이라는 생각을 했습니다. (보다 상세한 코드 적용을 위한 글은 개별로 써야겠습니다.)

Reference

AdaBoost

GBM

XGBoost

LightGBM

CatBoost

ALL

 

( 윗 부분에 출처가 붙여지지 않아 하단부에 붙입니다. )

출처 : https://subinium.github.io/introduction-to-ensemble-2-boosting/

 

 

 

 

 

 

 

 

'데이터사이언스 > MachineLearning' 카테고리의 다른 글

Ensemble 1/2 (앙상블)  (0) 2020.04.23
:

Ensemble 1/2 (앙상블)

데이터사이언스/MachineLearning | 2020. 4. 23. 17:56 | Posted by youGom

Part 1. What is Ensemble Learning?

0. Intro

머신러닝 튜토리얼에 Advanced 알고리즘을 보면 항상 앙상블 학습이라는 내용이 포함되어 있습니다. 최근 캐글 우승자의 인터뷰를 보면 대다수가 앙상블 기법 중 하나를 이용했다고 합니다.

이는 앙상블을 알아야 캐글에서 좋은 성적을 받을 수 있다는 말이기도 합니다.

앙상블 알고리즘에 대해 포스팅은 3개 정도로 나누어 올리겠습니다. 예상으로는 다음과 같이 나눌 수 있을 것 같습니다.

  • Part 1. What is Ensemble Learning
  • Part 2. Voting & Bagging with Code
  • Part 3. Boosting with Code
  • Part 4. Stacking with Code

(포스팅을 적으며 목록을 수정했습니다.)

첫 번째 포스팅은 종류와 개념에 대해 다뤄보겠습니다. 구체적인 방법에 대한 내용은 다음 포스팅에서 다루겠습니다.

1. What is Ensemble Learning?

Coursera의 How to Win a Data Science Competition: Learn from Top Kagglers의 코스에서 실전 전의 마지막 강의 | 출처 :
https://www.coursera.org/learn/competitive-data-science

앙상블(Ensemble) 학습은 여러 개의 학습 알고리즘을 사용하고, 그 예측을 결합함으로써 보다 정확한 최종 예측을 도출하는 기법입니다. 하나의 강한 머신러닝 알고리즘보다 여러 개의 약한 머신러닝 알고리즘이 낫다 라는 아이디어를 가지고 이해하면 좋습니다.

이미지, 영상, 음성 등의 비정형 데이터의 분류는 딥러닝이 뛰어난 성능을 보이고 있지만, 대부분의 정형 데이터 분류 시에는 앙상블이 뛰어난 성능을 나타내고 있습니다.

문제와 데이터에 따라 단일 모델의 성능이 더 좋은 경우도 있습니다. 하지만 앙상블 기법을 사용하면 더 유연성있는 모델을 만들며 더 좋은 예측 결과를 기대할 수 있습니다.

캐글에서는 높은 성적을 얻기 위해서 시도해볼 수 있는 테크닉 중 하나이며, 최근 많은 winning solution에서 앙상블 기법이 사용되었습니다.

앙상블 학습의 유형은 가장 많이 알려진 Voting, Bagging, Boosting, Stacking 등이 있으며, 그 외에도 다양한 앙상블 학습의 유형이 있습니다.

2. Voting & Averaging

모델들의 투표가 최종 결과가 된다! | 출처 :
https://facingtoday.facinghistory.org

보팅(Voting) 또는 에버리징(Averaging) 은 가장 쉬운 앙상블 기법입니다. 이 둘은 서로 다른 알고리즘을 가진 분류기를 결합하는 방식입니다. Voting은 분류 에서 사용하며 Averaging은 회귀 에서 사용합니다. (categorical인 경우에는 voting, numerical인 경우에는 averaging이기도 합니다.)

단어 그대로 투표, 평균의 방식으로 진행이 됩니다. 좀 더 구체적으로 서술하면 다음과 같은 과정으로 진행이 됩니다.

  1. 일정 수의 base model과 predict를 만듭니다.
    • 1-1. 훈련 데이터를 나누어 같은 알고리즘을 사용하거나
    • 1-2. 훈련 데이터는 같지만 다른 알고리즘을 사용하거나
    • 1-3. 등등의 방법을 사용합니다.
  2. 여기서 여러가지 방법으로 voting을 진행합니다.

base model은 Linear Regression, KNN, SVM 등 여러 머신러닝 모델을 사용하면 됩니다. Voting과 Averaging은 다음과 같은 분류로 나눌 수 있습니다.

2-1. Majority Voting (Hard Voting)

각 모델은 test 데이터셋(또는 인스턴스)의 결과를 예측합니다. 그리고 예측값들의 다수결로 예측값을 정합니다. 이진 분류에 있어서는 과반수 이상이 선택한 예측값을 최종 예측으로 선택하는 것입니다.

이런 다수결의 성격때문에 max voting, plurality voting 라고도 부릅니다.

2-2. Weighted Voting (Soft Voting)

위의 보팅 방법과 다르게, 좀 더 유연한 보팅 방법입니다.

이번에는 test 데이터셋(또는 인스턴스)의 결과 가능성을 예측합니다. 그리고 이 가능성(가중치)를 특정 연산을 하여 분류 label의 확률값을 계산합니다. 이 방법에서 가중치의 연산은 원하는 방식으로 할 수 있고, 보통 평균을 사용합니다.

보통 Majority Voting보다 유연한 결과를 얻을 수 있으며, 예측 성능이 좋아 더 많이 사용합니다.

2-3. Simple Averaging

회귀 문제에서 사용하는 방법으로, 각 예측값을 평균내어 사용합니다. 이 방법은 경우에 따라 과대적합을 줄여주고, 더 부드러운 회귀모델을 만들어줍니다.

2-4. Weighted Averaging

위에서 평균을 낼 때, 각 모델별 가중치를 두어 평균내는 방식입니다.

3. Bagging

Bagging의 대표 알고리즘 중 하나인 Random Forest를 시각화한 이미지 ㅣ 출처 :
https://towardsdatascience.com/random-forest-learning-essential-understanding-1ca856a963cb

배깅(Bagging) 은 Bootstrap Aggregating의 약자입니다. 배깅의 핵심은 평균을 통해 분산(variance)값을 줄여 모델을 더 일반화시킨다는 점입니다.

배깅은 보팅과 유사한 방식으로 진행이 됩니다. 정확히는 최종적으로는 보팅을 사용합니다.

  1. 일정 수의 base model을 만듭니다.
  2. 모델들의 알고리즘은 모두 같습니다.
  3. 각각의 모델은 훈련데이터셋에서 랜덤으로 만든 서브 데이터셋을 각각 사용합니다.

3에서 서브 데이터셋을 만드는 과정을 부트스트래핑(Bootstrapping) 분할 방식이라고 합니다. 각각의 서브 데이터셋은 중첩이 가능합니다. 즉 다음과 같은 식이 만족될 수 있습니다.

StotS1S2SkStot≠S1∪S2∪⋯∪Sk

배깅의 경우에는 데이터 생성과 훈련이 개별 모델에서 진행되므로, 병렬 연산이 가능합니다.

배깅의 대표적인 알고리즘은 랜덤 포레스트(Random Forest) 입니다. 그 외에도 Bagging meta-estimator가 있습니다.

3-1. Bagging meta-estimator

Bagging meta-estimator는 랜덤 포레스트의 모체가 되는 알고리즘입니다. 위에서 언급한 방식을 그대로 사용하는 알고리즘입니다.

3-2. Random Forest

랜덤 포레스트 알고리즘은 여러 결정 트리(Decision Tree) 를 사용하여 보팅(soft voting)을 통해 예측을 결정하는 것입니다.

Bagging meta-estimator과 다르게 결정트리만 사용하고, 특성(feature)을 랜덤으로 선택하여 Bagging을 진행한다는 점이 다릅니다.

tree가 모여 forest라니 너무 귀엽지 않나요 :-)

결정 트리의 경우, 쉽고 직관적인 성격때문에 다른 앙상블 알고리즘에서도 많이 채택하고 있습니다. 랜덤 포레스트는 앙상블 알고리즘 중 비교적 빠른 속도를 가지고 있으며, 다양한 분야에서 좋은 성능을 낸다는 점에서 매우 장점이 많은 알고리즘입니다.

단점은 트리 기반의 앙상블 알고리즘은 하이퍼파라미터가 많아 튜닝을 위한 시간이 많이 소모된다는 것입니다. (속도 자체는 다른 알고리즘에 비해 빠릅니다.) 또한 하이퍼파라미터의 조정을 통한 성능의 향상이 비교적 미비하다는 단점을 가지고 있습니다.

4. Boosting

부스팅(Boosting) 알고리즘은 여러 개의 약한 학습기(weak learner)를 순차적으로 학습-예측하며 잘못 예측한 데이터에 가중치 부여를 통해 오류를 개선해 나가면서 학습하는 방식입니다.

계속해서 분류기에게 가중치를 부스팅하면서 학습을 진행하기에 부스팅 방식으로 불립니다.

기존 Boosting 방법은 순차적인 연산이 필수적이므로 병렬 연산이 불가능합니다. 그렇기에 대용량 데이터셋에서는 학습 시간이 매우 많이 필요할 수 있습니다.

부스팅의 대표적인 알고리즘은 AdaBoostGradient Boost 가 있고, 최근 성능면에서 인정을 받아 가장 많이 사용하는 부스팅 계열 알고리즘으로 XGBoostLightGBM 이 있습니다. 그 외에도 CatBoost와 같은 알고리즘이 있습니다.

4-1. AdaBoost

에이다 부스트(AdaBoost) 는 Adaptive boosting의 약자로 오류 데이터에 가중치를 부여하며 부스팅을 수행하는 대표적인 알고리즘입니다.

메인 아이디어는 잘못 분류한 데이터에 가중치를 부여하여, 다음 분류기는 이를 더 잘 분류하게 만드는 것입니다. 최종적으로는 이 분류기를 합쳐 최종 분류기를 만듭니다. (분류 문제에 대하여)

오류 데이터에 가중치를 부여하기 때문에 이상치(outlier)에 민감합니다.

4-2. Gradient Boost

그래디언트 부스트(Gradient Boost Machine) 알고리즘은 AdaBoost와 거의 유사합니다. 하지만 가중치 업데이트를 경사하강법(Gradient Descent) 로 한다는 점이 다릅니다.

평균적으로 랜덤 포레스트보다 좋은 예측 성능을 가지지만, 하이퍼파라미터 튜닝 노력이 필요하고 그만큼 수행 시간이 오래걸린다는 단점도 있습니다. 순차적인 진행때문에 병렬 수행이 불가능하다는 단점도 있습니다. 성능면에 초점을 두어 많은 GBM 기반 알고리즘이 연구되었고, 그 중 가장 많이 사용하는 것이 아래 두 알고리즘입니다.

4-3. XGBoost

XGBoost(eXtra Gradient Boost) 는 GBM에 기반하는 알고리즘이며, 여러 가지 장점을 가진 알고리즘입니다. GBM에 비해 빠르고, 과적합 규제 등의 장점을 가집니다. 그 외에도 분류/회귀 모두 예측 성능이 우수하고, 자체 내장 교차 검증, 결손값 처리 등의 장점이 있습니다.

병렬 CPU를 이용하여 GBM보다 빠른 수행을 합니다. 반대로 말하면 속도를 기대하려면 multi-CPU core가 필요합니다. 이 외에도 tree pruning 등의 다양한 기능을 통해 속도를 향상시켰습니다.

XGBoost는 GBM보다는 빠르지만 여전히 느린 알고리즘입니다. 심지어 GridSearchCV를 이용하여 하이퍼파라미터 튜닝을 수행하면 시간이 너무 오래 걸립니다.

4-4. LightGBM

LightGBM 은 이름에서 알 수 있듯이 Light한 GBM입니다.

XGBoost에 비해 훨씬 빠르며, 메모리 사용량도 상대적으로 적습니다. 예측 성능 자체도 큰 차이는 없습니다. 하지만 적은 수의 데이터셋에는 과대적합이 발생하기 쉽다는 단점이 있습니다. 적다는 기준은 애매하나 공식 문서에는 10000건 이하의 데이터셋이라고 기술하고 있습니다.

알고리즘의 메인 아이디어는 GBM 계열의 트리 분할 방법에서 트리 균형 맞추는 과정을 생략하며 성능을 높였다는 점입니다. 대부분의 트리 기반 알고리즘은 트리의 깊이를 효과적으로 줄이기 위해 균형 트리 분할(Level Wise) 방식을 사용합니다. 균형 잡힌 트리는 과대적합에 강하지만 시간 비용이 큽니다.

LightGBM에서는 리프 중심 트리 분할(Leaf Wise) 방식을 사용해 비대칭이지만 예측 오류 손실 값을 줄이는 방식을 선택하여 트리를 분할합니다. 그렇기에 빠르고, 좋은 성능을 가질 수 있는 것입니다.

4-5. CatBoost

CatBoost 는 범주형 변수를 위해 만든 Boosting 알고리즘입니다. 범주형 변수의 경우에는 원-핫 인코딩을 할 경우에 많은 수의 특성이 생기기에 부스팅 알고리즘을 사용하는 경우, 매우 오랜 시간이 걸립니다. 그렇기에 범주형 변수를 자동으로 처리하기 위해 만든 알고리즘입니다.

아직 경험이 부족해서 사용하는 컴페티션을 본 적은 없습니다.

5. Stacking & Blending

Stacking과 Blending은 거의 같지만, 분류하는 경우도 있어 따로 서술했습니다.

5-1. Stacking (Stacked generalization)

스태킹 알고리즘 시각화 | 출처 :
http://supunsetunga.blogspot.com/

스태킹(Stacking) 또는 stacked generalization으로 알려진 기법입니다.

현실 모델에 적용하는 경우는 적으나, 대회에서 높은 순위를 위해 많이 사용됩니다.

가장 핵심 아이디어는 머신러닝 알고리즘으로 훈련 데이터셋을 통해 새로운 데이터셋을 만들고, 이를 데이터셋으로 사용하여 다시 머신러닝 알고리즘을 돌리는 것입니다. 보통은 서로 다른 타입의 모델들 을 결합합니다.

스태킹에는 총 2가지 종류의 모델이 필요합니다.

  1. 개별적인 기반 모델 : 성능이 비슷한 여러 개의 모델
  2. 최종 메타 모델 : 기반 모델이 만든 예측 데이터를 학습 데이터로 사용할 최종 모델

다시 정리해서 말하면 여러 개의 개별 모델들이 생성한 예측 데이터를 기반으로 최종 메타 모델이 학습할 별도의 학습 데이터 세트와 예측할 테스트 데이터 세트를 재 생성하는 기법입니다.

모델을 통해 input을 만들고, 다시 모델에 넣는 구조때문에 meta-model 이라고도 부릅니다.

Stacking에는 다양한 유형이 있고, 내용 자체가 직관적으로 이해하기 힘듭니다. 이 부분에 대해 자세한 내용은 2부에 다루겠습니다.

5-2. Blending

Blending 은 스태킹과 매우 유사한 방법입니다. 하지만 보다 간단하고, 정보누설의 위험을 줄입니다. 일부는 Stacking과 Blending을 혼용해서 사용합니다. (대부분은 스태킹과 같은 의미로 사용하는 것 같습니다.)

과정 자체는 거의 같습니다. 차이점이 있다면 Stacking에서는 cross-fold-validation을 사용하고, Blending은 holdout validation을 사용합니다.

그렇기 때문에 Blending의 결과는 holdout set에 과대적합이 된 결과를 얻을 가능성이 높습니다.

6. Conclusion

결과를 높이기에는 좋은 방법이지만, 해석 가능성을 낮추는 방법이기도 합니다. 그렇기에 과정을 중시하는 곳에서는 선호하지 않는 방법입니다.

하지만 컴페티션에 있어서는 정확도가 높다는 것은 매우 중요합니다. 캐글을 해보신 분이라면 0.1%의 정확도 향상도 얼마나 대단한 것인지 아실겁니다. 또한 의료 분야 등 정확도가 반드시 높아야 하는 경우에는 필요합니다. 과정보다는 결과가 중요한 곳이 있기 때문입니다.

다음 포스팅에서는 분야별로 구체적인 내용에 대해서 다뤄보겠습니다. Part2에서 뵙겠습니다. :-)

Reference

세상에는 좋은 자료가 너무 많습니다. 시간이 된다면 아래 링크와 책 모두 읽는 것을 추천합니다.

 

 

( 위 쪽에 출처가 써지지 않아서 하단부에 붙입니다. )

 출처 : https://subinium.github.io/introduction-to-ensemble-1/

'데이터사이언스 > MachineLearning' 카테고리의 다른 글

Ensemble 2/2 (앙상블)  (0) 2020.04.23
: