From Decision Trees to Advanced Boosting: A Simple Yet Deep Guide to Tree-Based Models
From the publisher’s feed, collected in the ZeroLabs newsroom.
Image created by the author using FigmaIf you’ve worked with tabular data, you’ve likely noticed something:No matter how advanced deep learning becomes, tree-based models often outperform everything else.From credit risk prediction to medical decision support, models like XGBoost, LightGBM, and CatBoost dominate real-world machine learning tasks.But why are they so powerful? And how did we get from a simple decision tree to these highly optimized algorithms?This article breaks it down from first principles — in a way that builds intuition before diving into advanced concepts.Imagine you’re trying to decide whether a patient is at risk based on some features:AgeBlood pressureCholesterolA human might think like this:“If age is high and cholesterol is high → risk is high.”That’s exactly how a Decision Tree works.1. Decision Trees — Learning Like a HumanA Decision Tree is essentially a series of yes/no questions.Image created by the author using FigmaExample:Is age > 50?Yes → Go rightNo → Go leftIs cholesterol high?Yes → High riskNo → Low riskIt keeps splitting the data until it reaches a final decision.How Decision Trees Decide Splits: Gini Index and EntropyWhen a decision tree is built, its most important task is deciding how to split the data at each step.At every node, the model asks a simple question:“Which feature split will separate the classes in the best possible way?”To answer this, the tree needs a way to measure how “mixed” or “pure” a group of data is. This is where Gini Index and Entropy come in.Both are impurity measures, meaning they tell us how disorganized a dataset is at a given node.Gini Index — Measuring ImpurityThe Gini Index tells us how often a randomly chosen data point would be incorrectly classified if it were labeled according to the class distribution in a node.In simpler terms:If a node contains only one class, it is perfectly pure. If it contains many classes mixed together, it is impure.FormulaIntuitionIf all samples belong to one class, Gini = 0If classes are evenly mixed, Gini increasesThe higher the Gini value, the more mixed the node is.ExampleIf a node contains only one class (for example, all dogs):This means the node is completely pure.If a node contains 50% dogs and 50% cats:This represents a mixed and impure node.Key IdeaDecision trees try to choose splits that reduce the Gini Index as much as possible, because lower impurity means better separation of classes.Entropy — Measuring UncertaintyEntropy comes from information theory and measures the level of uncertainty in a dataset.While Gini focuses on impurity, entropy focuses on:“How uncertain are we about the class of a data point?”If a node is perfectly pure, there is no uncertainty. If classes are evenly mixed, uncertainty is at its highest.FormulaIntuitionLow entropy means the model is confidentHigh entropy means the model is uncertainExampleFor a pure node (all samples belong to one class):Entropy=0There is no uncertainty.For a balanced node (50% two classes):This is maximum uncertainty.Information GainDecision trees using entropy aim to maximize information gain, which measures how much uncertainty is reduced after a split.Gini vs Entropy — What’s the Difference?Both Gini Index and Entropy measure impurity, but they do it in slightly different ways.In most modern implementations, including scikit-learn, Gini Index is often preferred because it is computationally efficient and produces very similar results to entropy.Final IntuitionThink of it this way:A decision tree is constantly asking:“Which split makes the data most organized?”Gini Index measures how messy the data isEntropy measures how uncertain the prediction isBoth guide the tree toward cleaner and more separable groups of data.Ensemble Learning: How Weak Models Become Powerful PredictorsSingle machine learning models often struggle with one of two problems:They are too simple and underfit the dataOr they are too complex and overfit the dataEnsemble learning solves this by combining multiple models to create a stronger one.The core idea is simple:“Many weak models together can create a strong model.”There are three main ensemble strategies:BaggingBoostingStacking (brief mention)We will focus on bagging and boosting, since they form the foundation of modern tree-based systems like XGBoost, LightGBM, and CatBoost.1. Bagging — Building Independent ModelsBagging stands for Bootstrap Aggregation.Image created by the author using FigmaHow It WorksTake the original datasetCreate multiple random samples (with replacement)Train a model on each sample independentlyCombine their outputs (majority vote or average)IntuitionThink of asking multiple doctors the same question:Each doctor sees slightly different patient dataEach gives an independent opinionFinal decision = majority voteNo doctor learns from another.Why Bagging WorksBagging reduces variance.Individual decision trees are unstableSmall data changes → very different treesAveraging them stabilizes predictionsPython Example (Bagging with Decision Trees)from sklearn.ensemble import BaggingClassifierfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scoreX, y = load_breast_cancer(return_X_y=True)X_train, X_test, y_train, y_test = train_test_split(X, y)base_model = DecisionTreeClassifier()model = BaggingClassifier( estimator=base_model, n_estimators=50, random_state=42)model.fit(X_train, y_train)y_pred = model.predict(X_test)print("Accuracy:", accuracy_score(y_test, y_pred))2. Boosting — Learning from MistakesBoosting is fundamentally different.Image created by the author using FigmaInstead of training models independently, boosting trains models sequentially.Each new model focuses on correcting the mistakes of the previous ones.How It WorksTrain a weak modelIdentify errorsTrain next model to fix those errorsRepeatCombine all models (weighted sum)IntuitionThink of a student improving over time:First attempt → many mistakesTeacher highlights errorsStudent improves step by stepEach new model is smarter than the previous one.Why Boosting WorksBoosting reduces bias + variance.Learns complex patternsFocuses on hard samplesImproves performance iterativelyPython Example (Basic Gradient Boosting)from sklearn.ensemble import GradientBoostingClassifiermodel = GradientBoostingClassifier( n_estimators=100, learning_rate=0.1, max_depth=3)model.fit(X_train, y_train)y_pred = model.predict(X_test)print("Accuracy:", accuracy_score(y_test, y_pred))3. XGBoost — Optimized Gradient BoostingXGBoost is one of the most widely used ML algorithms in the world.What Makes It Special?1. RegularizationIt penalizes complex trees:Prevents overfittingEncourages simpler models2. Second-Order OptimizationInstead of only using errors, it uses:Gradient (first derivative)Hessian (second derivative)This improves accuracy and convergence.3. Handles Missing Values AutomaticallyLearns best direction for missing splits.Python Examplefrom xgboost import XGBClassifiermodel = XGBClassifier( n_estimators=200, learning_rate=0.05, max_depth=6, subsample=0.8, colsample_bytree=0.8)model.fit(X_train, y_train)y_pred = model.predict(X_test)print("Accuracy:", accuracy_score(y_test, y_pred))4. LightGBM — Speed and ScalabilityLightGBM is designed for large-scale data.Key Idea: Histogram-Based LearningInstead of using raw values:Continuous features are grouped into binsSplits are computed on binsThis makes it extremely fastTree Growth DifferenceXGBoost → level-wise growthLightGBM → leaf-wise growthLeaf-wise growth:Focuses on most important leafLeads to better accuracyBut can overfit if not controlledPython Examplefrom lightgbm import LGBMClassifiermodel = LGBMClassifier( n_estimators=200, learning_rate=0.05, num_leaves=31)model.fit(X_train, y_train)y_pred = model.predict(X_test)print("Accuracy:", accuracy_score(y_test, y_pred))5. CatBoost — Best for Categorical DataCatBoost is designed to handle categorical features directly.The ProblemTraditional models require encoding:One-hot encoding → too largeLabel encoding → misleadingCatBoost SolutionUses ordered target encoding:Converts categories into meaningful statisticsAvoids data leakageUses only past information during encodingKey Feature: Symmetric TreesSame structure at each levelFaster inferenceMore stable trainingPython Examplefrom catboost import CatBoostClassifiermodel = CatBoostClassifier( iterations=200, depth=6, learning_rate=0.05, verbose=0)model.fit(X_train, y_train)y_pred = model.predict(X_test)print("Accuracy:", accuracy_score(y_test, y_pred))6. Final Comparison7. Selection of ModelImage created by the author using FigmaFinal IntuitionBagging = “many independent opinions”Boosting = “learning from mistakes step-by-step”XGBoost = “optimized disciplined boosting”LightGBM = “fast and aggressive boosting”CatBoost = “smart handling of categorical data”Referencesscikit-learn — Machine Learning in PythonXGBoost — Official DocumentationLightGBM — Official DocumentationCatBoost — Official DocumentationBreiman, L. (2001). Random ForestsChen, T., & Guestrin, C. (2016). XGBoost: A Scalable Tree Boosting SystemKe, G. et al. (2017). LightGBM: A Highly Efficient Gradient Boosting Decision TreeProkhorenkova, L. et al. (2018). CatBoost: Unbiased Boosting with Categorical FeaturesFrom Decision Trees to Advanced Boosting: A Simple Yet Deep Guide to Tree-Based Models was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.