Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»AI & Machine Learning»Decision Tree in Machine Learning: An Interactive Guide (with Python)
    AI & Machine Learning

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    Anirudh KhuranaBy Anirudh Khurana18 November 2026No Comments38 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Decision tree diagram for a loan decision, with yes and no branches leading to leaf nodes
    Share
    Facebook Twitter LinkedIn Pinterest Email

    A decision tree in machine learning is a model that makes predictions by asking a series of yes or no questions about the data, like “is the salary above ₹36,500?” and then “is the credit score above 665?”, until it reaches an answer. It works for both classification (pass or fail, spam or not spam) and regression (the price of a flat).

    Decision trees are one of the first algorithms you should learn properly. They are easy to explain to anyone, they need almost no data preparation, and they are the building block of random forests and gradient boosting, which win a lot of real-world problems on tabular data. They also come up in nearly every data science interview.

    This guide starts with the picture and builds up from there. You will grow a tree one question at a time in the playground, calculate Gini impurity and entropy with a live calculator, see overfitting happen as the tree gets deeper, and then write the same thing in Python, including a version from scratch. You only need basic Python. If you have read our logistic regression guide, a few ideas will feel familiar.

    Free PDF
    Decision tree notes with code and interview questions
    11 pages, ready to print or read offline. No sign-up needed.
    Download PDF

    What is a decision tree in machine learning?

    Think about how a bank officer decides on a loan. They might first look at your salary. If it is low, they reject straight away. If it is high enough, they check your credit score next. Each check narrows things down until there is a clear yes or no. Written as a diagram, that process looks like an upside-down tree: one question at the top, branches for each answer, and decisions at the bottom.

    A decision tree model learns those questions from data. You give it past examples (applicants, their salary and credit score, and whether the loan was approved), and it works out which questions to ask, in which order, and where to put each cut-off. Then it uses the same questions to predict for new applicants.

    It is a supervised learning algorithm, because it learns from labelled examples. When the answer is a category it is called a classification tree, and when the answer is a number it is called a regression tree. Together they are known as CART (classification and regression trees).

    Decision tree terminology

    TermWhat it means
    Root nodeThe first question, at the top. It sees all the training data.
    Decision node (internal node)Any node that asks a question and splits the data into two or more groups.
    Leaf node (terminal node)A node with no more questions. It holds the prediction: a class, or a number for regression.
    BranchThe path from a node to one of its children, usually labelled yes or no.
    SplittingDividing a node into child nodes using a question like salary ≤ 36.5.
    Parent and childA node that is split is the parent; the nodes it splits into are its children.
    DepthThe number of questions from the root to the deepest leaf.
    PruningRemoving branches that do not help, to make the tree simpler and stop it overfitting.

    Decision tree playground: grow one yourself

    The lessons below walk you through the main ideas. Each one loads a dataset and settings and tells you what to look for. The chart shows the regions the tree has created, the diagram below it shows the same tree as questions, and the small chart at the bottom tracks training and test accuracy as the tree gets deeper. Filled points train the tree; hollow points are test points it never sees.

    Interactive

    Decision tree playground

    A real decision tree (CART, like scikit-learn) trains in your browser every time you change something.

    Guided lessons

    Loading the chart…

    Class AClass BTest pointSplitNewest split
    The same tree as questions
    Training vs test accuracy at each depth

    Loading the chart…

    Dataset
    Split criterion
    Click on the chart to

    One point per line as x, y, label. Labels can be 0/1 or A/B. Up to 400 points. With 12 or more points, every fourth one is kept aside as test data.

    After the lessons, try this: pick Moons, set min_samples_leaf to 1, and drag max_depth from 1 to 12 while watching the small chart. Training accuracy keeps rising, but test accuracy stops improving after a few levels and then drops. The gap between the two lines is overfitting, and finding the depth where the test line peaks is most of the work of tuning a tree.

    How does a decision tree work?

    Building a tree is a simple loop, repeated for every node:

    1. Start with all the training data in the root node.
    2. For every feature, try every reasonable cut-off point. For numbers, that means the midpoints between neighbouring values. Each cut-off splits the node into a left group and a right group.
    3. Score each possible split by how pure the two groups are, using Gini impurity or entropy. Keep the best one.
    4. Split the node and repeat the same steps on each child.
    5. Stop when a node is pure (only one class), when it hits a limit such as max_depth or min_samples_leaf, or when no split makes things better. That node becomes a leaf, and it predicts the majority class of the training points inside it.

    This is called recursive binary splitting. It is also a greedy algorithm: at each node it picks the best split for that node only, without looking ahead to see whether a worse split now would allow a much better tree later. Finding the truly best tree is far too slow for real data, and greedy splitting works well in practice. Lesson 3 in the playground shows one of the rare cases where it goes wrong.

    To predict for a new point, you start at the root, answer each question, follow the matching branch and read the answer at the leaf. That takes as many steps as the tree is deep, which is why trees predict so quickly.

    Gini impurity, entropy and information gain

    The whole algorithm depends on one question: how do you measure whether a split is good? A good split creates groups where most points belong to the same class. A node with 10 passes and 0 fails is perfectly pure; a node with 5 and 5 is as mixed as it can be. Gini impurity and entropy are two ways of putting a number on that.

    Gini impurity

    Gini impurity is the chance that you label a random point from the node wrongly if you guess its class using the node’s own class proportions. If pi is the share of class i in the node:

    Gini = 1 − Σ pi²

    For two classes it goes from 0 (pure) to 0.5 (a 50/50 mix). A node with 4 passes and 1 fail has Gini = 1 − (0.8² + 0.2²) = 1 − 0.68 = 0.32.

    Entropy

    Entropy comes from information theory and measures how uncertain you are about the class of a random point from the node:

    Entropy = − Σ pi log2(pi)

    For two classes it goes from 0 (pure) to 1 (a 50/50 mix). The same 4 pass and 1 fail node has entropy = −(0.8 × log2 0.8 + 0.2 × log2 0.2) = 0.722.

    Information gain

    A split is scored by how much it lowers the impurity. You take the impurity of the parent and subtract the weighted average impurity of the children, where each child is weighted by its share of the points. With entropy, this drop is called information gain:

    Information gain = Entropy(parent) − Σ (nchild / nparent) × Entropy(child)

    The tree picks the split with the highest information gain, or, with Gini, the split with the lowest weighted Gini. The calculator below lets you try every split on a small dataset and see both numbers change. Click any student to flip them between pass and fail and watch the best split move.

    Interactive

    Split calculator: Gini vs entropy

    20 students, by hours studied. Squares passed, circles failed. Drag the cut-off, or click a student to flip their result.

    Loading the chart…

    Left chart: how much each possible cut-off lowers Gini (blue) and entropy (orange). Right chart: the Gini and entropy curves for any mix of pass and fail, with the left (L) and right (R) groups of your current split marked on them.

    Two things stand out when you play with it. First, both measures nearly always agree on the best split, because their curves have the same shape: zero at the ends and highest in the middle. Second, the best split is not always where the classes look most separated to the eye, because a small, perfectly pure group can be worth less than a large, mostly pure one.

    Gini vs entropy: which should you use?

    Gini impurityEntropy
    Formula1 − Σ p²−Σ p log₂ p
    Range for two classes0 to 0.50 to 1
    SpeedSlightly faster (no logarithm)Slightly slower
    Used byCART, scikit-learn defaultID3 and C4.5
    ResultsAlmost always the same treeAlmost always the same tree

    In practice, start with Gini because it is the default and a little faster. Add entropy as one more option in your grid search and let cross-validation decide. On the wine dataset later in this guide, the search picks entropy.

    Decision tree example: choosing the first split by hand

    Exam questions often ask you to pick the root node by hand. Here are 10 students. For each, we know whether they studied, whether they attended the revision class, whether they slept at least 7 hours, and whether they passed.

    StudentStudiedRevision classSlept 7+ hrsResult
    1YesYesYesPass
    2YesNoYesPass
    3YesYesNoPass
    4YesNoNoFail
    5YesYesYesPass
    6NoNoYesPass
    7NoNoYesFail
    8NoYesNoFail
    9NoNoNoFail
    10NoNoYesFail

    Step 1: impurity of the root. There are 5 passes and 5 fails, so Gini = 1 − (0.5² + 0.5²) = 0.5 and entropy = 1. The root is as mixed as it can be.

    Step 2: try “Studied”. The Yes group has 4 pass and 1 fail, so its Gini is 0.32. The No group has 1 pass and 4 fail, also 0.32. Each group holds half the students, so the weighted Gini is 0.5 × 0.32 + 0.5 × 0.32 = 0.32.

    Step 3: try “Revision class”. Yes has 3 pass and 1 fail (Gini 0.375), No has 2 pass and 4 fail (Gini 0.444). Weighted: 0.4 × 0.375 + 0.6 × 0.444 = 0.417.

    Step 4: try “Slept 7+ hours”. Yes has 4 pass and 2 fail (0.444), No has 1 pass and 3 fail (0.375). Weighted: 0.6 × 0.444 + 0.4 × 0.375 = 0.417.

    Step 5: pick the lowest. “Studied” leaves the lowest weighted Gini (0.32), so it becomes the root. The tree then repeats the same process inside the Yes group and inside the No group. Here is the same calculation in Python, with information gain added:

    import numpy as np
    
    # 10 students: did they study, attend the revision class, sleep 7+ hours? 1 = pass, 0 = fail
    studied  = np.array(["Y", "Y", "Y", "Y", "Y", "N", "N", "N", "N", "N"])
    revision = np.array(["Y", "N", "Y", "N", "Y", "N", "N", "Y", "N", "N"])
    slept    = np.array(["Y", "Y", "N", "N", "Y", "Y", "Y", "N", "N", "Y"])
    passed   = np.array([1, 1, 1, 0, 1, 1, 0, 0, 0, 0])
    
    def gini(labels):
        p = np.bincount(labels, minlength=2) / len(labels)
        return 1 - np.sum(p ** 2)
    
    def entropy(labels):
        p = np.bincount(labels, minlength=2) / len(labels)
        p = p[p > 0]
        return -np.sum(p * np.log2(p))
    
    print(f"Root: Gini = {gini(passed):.3f}, Entropy = {entropy(passed):.3f}\n")
    
    for name, feature in [("studied", studied), ("revision", revision), ("slept", slept)]:
        left, right = passed[feature == "Y"], passed[feature == "N"]
        wl, wr = len(left) / len(passed), len(right) / len(passed)
        w_gini = wl * gini(left) + wr * gini(right)
        gain = entropy(passed) - (wl * entropy(left) + wr * entropy(right))
        print(f"{name:9s} Yes: {left.sum()} pass / {len(left) - left.sum()} fail | "
              f"No: {right.sum()} pass / {len(right) - right.sum()} fail | "
              f"weighted Gini = {w_gini:.3f} | information gain = {gain:.3f}")

    Output:

    Root: Gini = 0.500, Entropy = 1.000
    
    studied   Yes: 4 pass / 1 fail | No: 1 pass / 4 fail | weighted Gini = 0.320 | information gain = 0.278
    revision  Yes: 3 pass / 1 fail | No: 2 pass / 4 fail | weighted Gini = 0.417 | information gain = 0.125
    slept     Yes: 4 pass / 2 fail | No: 1 pass / 3 fail | weighted Gini = 0.417 | information gain = 0.125

    Entropy agrees: “Studied” has the highest information gain (0.278), and the other two features tie at 0.125.

    Decision tree in Python with scikit-learn

    Now the loan example from the start, with 14 applicants. We train a DecisionTreeClassifier with at most two levels of questions, print the tree as text, and ask it about two new applicants.

    import numpy as np
    from sklearn.tree import DecisionTreeClassifier, export_text
    
    # Monthly salary (in thousand rupees) and credit score for 14 loan applicants
    X = np.array([
        [25, 620], [30, 710], [18, 580], [45, 640], [22, 700], [35, 600], [28, 560],  # rejected
        [60, 720], [55, 760], [40, 780], [75, 690], [50, 740], [90, 810], [38, 750],  # approved
    ])
    y = np.array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1])  # 0 = rejected, 1 = approved
    
    model = DecisionTreeClassifier(max_depth=2, random_state=42)
    model.fit(X, y)
    
    print(export_text(model, feature_names=["salary_k", "credit_score"]))
    
    new_applicants = np.array([[42, 745], [80, 610]])
    print("Predictions:", model.predict(new_applicants))
    print("Depth:", model.get_depth(), "| Leaves:", model.get_n_leaves())

    Output:

    |--- salary_k <= 36.50
    |   |--- class: 0
    |--- salary_k >  36.50
    |   |--- credit_score <= 665.00
    |   |   |--- class: 0
    |   |--- credit_score >  665.00
    |   |   |--- class: 1
    
    Predictions: [1 0]
    Depth: 2 | Leaves: 3

    The tree learned two rules, and you can read them straight from the output. Anyone earning ₹36,500 or less a month is rejected. Above that, the credit score decides: 665 or below is rejected, and above 665 is approved. That readability is the biggest selling point of decision trees. You could hand these rules to the bank officer and they would understand them.

    The first new applicant earns ₹42,000 with a credit score of 745, so they pass both checks and are approved (1). The second earns ₹80,000 but has a score of 610, so the second question rejects them (0). Note that the tree never needed to scale the features: salary in thousands and credit score in hundreds work fine together, because each question only looks at one feature at a time.

    The main DecisionTreeClassifier parameters

    ParameterWhat it doesTypical values
    criterionHow splits are scored"gini" (default), "entropy", "log_loss"
    max_depthMaximum number of questions from root to leaf3 to 10; None means no limit
    min_samples_splitA node needs at least this many points to be split2 (default) to 20
    min_samples_leafEvery leaf must keep at least this many points1 (default) to 20
    max_featuresHow many features to try at each splitNone (all); random forests use fewer
    ccp_alphaStrength of cost complexity pruning0 (default); tune with the pruning path
    class_weightGives rare classes more weightNone or "balanced"

    Overfitting in decision trees

    Left alone, a decision tree keeps splitting until every leaf is pure. On real data with some noise, that means it eventually creates tiny leaves around single unusual points. It gets 100% on the training data and does worse on new data. Decision trees overfit more easily than almost any other model, so controlling depth is not optional.

    from sklearn.datasets import make_moons
    from sklearn.model_selection import train_test_split
    from sklearn.tree import DecisionTreeClassifier
    
    X, y = make_moons(n_samples=600, noise=0.35, random_state=7)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=7)
    
    print("max_depth | leaves | train acc | test acc")
    for depth in [1, 2, 3, 4, 6, 8, 12, None]:
        tree = DecisionTreeClassifier(max_depth=depth, random_state=7).fit(X_train, y_train)
        train_acc = tree.score(X_train, y_train)
        test_acc = tree.score(X_test, y_test)
        print(f"{str(depth):>9} | {tree.get_n_leaves():>6} | {train_acc:>9.3f} | {test_acc:.3f}")

    Output:

    max_depth | leaves | train acc | test acc
            1 |      2 |     0.826 | 0.772
            2 |      4 |     0.914 | 0.844
            3 |      6 |     0.914 | 0.844
            4 |     10 |     0.919 | 0.844
            6 |     19 |     0.933 | 0.861
            8 |     31 |     0.964 | 0.872
           12 |     49 |     1.000 | 0.850
         None |     49 |     1.000 | 0.850

    With one question (depth 1) the tree underfits: 82.6% on training data and 77.2% on test data. Test accuracy peaks at depth 8 with 87.2%. From depth 12 onwards the tree has 49 leaves and a perfect training score, but test accuracy has dropped back to 85%. This is the same pattern as lesson 5 in the playground, with the training line climbing to the top and the test line bending down.

    Pruning: pre-pruning and post-pruning

    Pruning means making the tree smaller on purpose so it generalises better. There are two ways to do it.

    Pre-pruning (early stopping) stops the tree while it grows. You set limits such as max_depth, min_samples_split, min_samples_leaf or max_leaf_nodes, and the tree does not split a node that would break them. It is fast and simple, and it is what most people use.

    Post-pruning grows the full tree first and then removes branches that do not earn their place. scikit-learn uses cost complexity pruning: each subtree is scored by its error plus ccp_alpha times its number of leaves, and branches are cut when the error they save is not worth their extra leaves. A larger ccp_alpha gives a smaller tree.

    from sklearn.datasets import load_breast_cancer
    from sklearn.model_selection import train_test_split, GridSearchCV
    from sklearn.tree import DecisionTreeClassifier
    
    X, y = load_breast_cancer(return_X_y=True)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
    
    # 1. A fully grown tree
    full = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
    print(f"Full tree:   depth {full.get_depth()}, {full.get_n_leaves()} leaves, "
          f"test acc {full.score(X_test, y_test):.3f}")
    
    # 2. Pre-pruning: limit the tree while it grows
    params = {"max_depth": [2, 3, 4, 5, 6, None], "min_samples_leaf": [1, 3, 5, 10]}
    grid = GridSearchCV(DecisionTreeClassifier(random_state=0), params, cv=5)
    grid.fit(X_train, y_train)
    pre = grid.best_estimator_
    print(f"Pre-pruned:  {grid.best_params_}, {pre.get_n_leaves()} leaves, "
          f"test acc {pre.score(X_test, y_test):.3f}")
    
    # 3. Post-pruning: grow fully, then cut back weak branches (cost complexity pruning)
    alphas = full.cost_complexity_pruning_path(X_train, y_train).ccp_alphas
    grid2 = GridSearchCV(DecisionTreeClassifier(random_state=0), {"ccp_alpha": alphas[:-1]}, cv=5)
    grid2.fit(X_train, y_train)
    post = grid2.best_estimator_
    best_alpha = grid2.best_params_["ccp_alpha"]
    print(f"Post-pruned: ccp_alpha={best_alpha:.4f}, {post.get_n_leaves()} leaves, "
          f"test acc {post.score(X_test, y_test):.3f}")

    Output:

    Full tree:   depth 5, 18 leaves, test acc 0.902
    Pre-pruned:  {'max_depth': 4, 'min_samples_leaf': 5}, 11 leaves, test acc 0.923
    Post-pruned: ccp_alpha=0.0138, 5 leaves, test acc 0.902

    The fully grown tree on the breast cancer data has 18 leaves and 90.2% test accuracy. Pre-pruning with a grid search picked max_depth=4 and min_samples_leaf=5, which gave 11 leaves and the best test accuracy, 92.3%. Post-pruning found that the same 90.2% needs only 5 leaves, a tree you could draw on a single page. Both are better than the full tree: one is more accurate, and the other is just as accurate and much simpler.

    Always choose the pruning settings with cross-validation on the training data, as the code does, and only check the test set at the end. To judge the final model properly, look at more than accuracy; our interactive confusion matrix guide explains precision, recall and the other metrics.

    Decision tree regression

    A regression tree works the same way, with two changes. Splits are scored by how much they reduce the squared error (variance) of the target instead of Gini, and each leaf predicts the average of the training targets that end up in it. So the prediction is not a smooth line but a staircase of flat steps. Drag the slider below to see it on flat sizes and rents.

    Interactive

    Regression tree: predicting rent from flat size

    Each step is one leaf, and its height is the average rent of the training flats inside it.

    Loading the chart…

    Here is the same idea in scikit-learn with DecisionTreeRegressor. MAE is the mean absolute error, the average gap between the predicted and actual rent, in thousand rupees.

    import numpy as np
    from sklearn.tree import DecisionTreeRegressor
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import mean_absolute_error
    
    # Flat size (sq ft) vs monthly rent (thousand rupees), with some noise
    rng = np.random.default_rng(3)
    size = rng.uniform(400, 2000, 200)
    rent = 6 + 0.012 * size + 4 * np.sin(size / 250) + rng.normal(0, 2, 200)
    X = size.reshape(-1, 1)
    X_train, X_test, y_train, y_test = train_test_split(X, rent, test_size=0.3, random_state=3)
    
    for depth in [1, 3, 5, None]:
        reg = DecisionTreeRegressor(max_depth=depth, random_state=3).fit(X_train, y_train)
        print(f"max_depth={str(depth):4s} leaves={reg.get_n_leaves():3d}  "
              f"train MAE={mean_absolute_error(y_train, reg.predict(X_train)):.2f}  "
              f"test MAE={mean_absolute_error(y_test, reg.predict(X_test)):.2f}")
    
    reg = DecisionTreeRegressor(max_depth=3, random_state=3).fit(X_train, y_train)
    print("Rent for 900 and 1500 sq ft:", reg.predict([[900], [1500]]).round(1))

    Output:

    max_depth=1    leaves=  2  train MAE=2.55  test MAE=2.65
    max_depth=3    leaves=  8  train MAE=1.52  test MAE=1.65
    max_depth=5    leaves= 31  train MAE=1.16  test MAE=1.90
    max_depth=None leaves=140  train MAE=0.00  test MAE=2.30
    Rent for 900 and 1500 sq ft: [15.  24.1]

    Depth 3 gives 8 leaves and the lowest test error (₹1,650 a month on average). With no depth limit, the tree makes 140 leaves for 140 training flats, so the training error is exactly zero, while the test error rises to ₹2,300. One more thing to know: a regression tree cannot predict outside the range of its training targets. Ask it about a 5,000 sq ft flat and it will return the average of the biggest flats it has seen. For smooth trends or extrapolation, linear regression is the better tool.

    Decision tree from scratch with NumPy

    Writing a tree yourself takes about 40 lines, and it makes the algorithm stick. This version uses Gini impurity and binary splits, the same as CART. best_split tries every feature and every midpoint between sorted values, build calls itself on the two halves until it hits the depth limit, and a leaf is just the majority class.

    import numpy as np
    from sklearn.datasets import make_moons
    from sklearn.model_selection import train_test_split
    from sklearn.tree import DecisionTreeClassifier
    
    class SimpleTree:
        def __init__(self, max_depth=3, min_samples=2):
            self.max_depth, self.min_samples = max_depth, min_samples
    
        def gini(self, y):
            p = np.bincount(y) / len(y)
            return 1 - np.sum(p ** 2)
    
        def best_split(self, X, y):
            best = (None, None, self.gini(y))          # feature, threshold, impurity
            for f in range(X.shape[1]):
                values = np.unique(X[:, f])
                for t in (values[:-1] + values[1:]) / 2:  # midpoints between sorted values
                    left = X[:, f] <= t
                    w = (left.sum() * self.gini(y[left]) + (~left).sum() * self.gini(y[~left])) / len(y)
                    if w < best[2]:
                        best = (f, t, w)
            return best
    
        def build(self, X, y, depth):
            f, t, _ = self.best_split(X, y)
            if depth == self.max_depth or len(y) < self.min_samples or f is None:
                return np.bincount(y).argmax()           # leaf: majority class
            left = X[:, f] <= t
            return (f, t, self.build(X[left], y[left], depth + 1), self.build(X[~left], y[~left], depth + 1))
    
        def fit(self, X, y):
            self.root = self.build(X, y, 0)
            return self
    
        def predict_one(self, x, node):
            while isinstance(node, tuple):
                f, t, l, r = node
                node = l if x[f] <= t else r
            return node
    
        def predict(self, X):
            return np.array([self.predict_one(x, self.root) for x in X])
    
    X, y = make_moons(n_samples=400, noise=0.3, random_state=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1)
    
    mine = SimpleTree(max_depth=4).fit(X_train, y_train)
    sk = DecisionTreeClassifier(max_depth=4, random_state=1).fit(X_train, y_train)
    print("Root split (feature, threshold):", mine.root[0], round(mine.root[1], 3))
    print("Our tree test accuracy:     ", round(np.mean(mine.predict(X_test) == y_test), 3))
    print("scikit-learn test accuracy: ", round(sk.score(X_test, y_test), 3))
    print("Same predictions on test set:", np.mean(mine.predict(X_test) == sk.predict(X_test)))

    Output:

    Root split (feature, threshold): 1 0.124
    Our tree test accuracy:      0.83
    scikit-learn test accuracy:  0.83
    Same predictions on test set: 1.0

    Our tree splits first on feature 1 at 0.124, reaches 83% test accuracy, and makes exactly the same prediction as scikit-learn on every test point. scikit-learn is much faster because it is written in Cython and sorts each feature smartly, and it adds things like sample weights and pruning, but the core logic is the same as these few lines. Interviewers sometimes ask you to write best_split on a whiteboard, so it is worth being able to do it.

    Decision tree on a real dataset: wine classification

    The wine dataset in scikit-learn has 178 wines from three cultivars, each described by 13 chemical measurements. It has three classes, which shows that nothing changes in the code for multiclass problems. We tune the criterion, depth and leaf size with 5-fold cross-validation, then look at the report, the feature importances and the top of the tree.

    import numpy as np
    from sklearn.datasets import load_wine
    from sklearn.model_selection import train_test_split, GridSearchCV
    from sklearn.tree import DecisionTreeClassifier, export_text
    from sklearn.metrics import classification_report
    
    data = load_wine()
    X_train, X_test, y_train, y_test = train_test_split(
        data.data, data.target, test_size=0.3, stratify=data.target, random_state=42)
    
    grid = GridSearchCV(DecisionTreeClassifier(random_state=42),
                        {"criterion": ["gini", "entropy"], "max_depth": [2, 3, 4, 5, None],
                         "min_samples_leaf": [1, 2, 5]}, cv=5)
    grid.fit(X_train, y_train)
    tree = grid.best_estimator_
    print("Best settings:", grid.best_params_)
    print("Test accuracy:", round(tree.score(X_test, y_test), 3), "\n")
    print(classification_report(y_test, tree.predict(X_test), target_names=data.target_names))
    
    top = np.argsort(tree.feature_importances_)[::-1][:4]
    print("Top features:")
    for i in top:
        print(f"  {data.feature_names[i]:30s} {tree.feature_importances_[i]:.3f}")
    print()
    print(export_text(tree, feature_names=list(data.feature_names), max_depth=2))

    Output:

    Best settings: {'criterion': 'entropy', 'max_depth': 3, 'min_samples_leaf': 2}
    Test accuracy: 0.907
    
                  precision    recall  f1-score   support
    
         class_0       0.94      0.89      0.91        18
         class_1       0.86      0.90      0.88        21
         class_2       0.93      0.93      0.93        15
    
        accuracy                           0.91        54
       macro avg       0.91      0.91      0.91        54
    weighted avg       0.91      0.91      0.91        54
    
    Top features:
      flavanoids                     0.413
      alcohol                        0.335
      hue                            0.150
      proline                        0.101
    
    |--- flavanoids <= 1.58
    |   |--- hue <= 0.90
    |   |   |--- class: 2
    |   |--- hue >  0.90
    |   |   |--- alcohol <= 12.62
    |   |   |   |--- class: 1
    |   |   |--- alcohol >  12.62
    |   |   |   |--- class: 1
    |--- flavanoids >  1.58
    |   |--- alcohol <= 13.02
    |   |   |--- class: 1
    |   |--- alcohol >  13.02
    |   |   |--- proline <= 597.50
    |   |   |   |--- class: 1
    |   |   |--- proline >  597.50
    |   |   |   |--- class: 0

    The tuned tree uses entropy, a depth of 3 and at least 2 points per leaf, and gets 90.7% of the test wines right. Flavanoids is the most important feature (0.413), followed by alcohol (0.335). The tree diagram shows why: the very first question is about flavanoids, and alcohol shows up on both sides below it.

    You may notice that some splits lead to the same class on both sides, such as “alcohol ≤ 12.62” giving class 1 either way. That is normal. The split made the two groups purer, even though the majority class did not change. If it bothers you, a slightly larger ccp_alpha removes those branches.

    Feature importance

    A tree’s feature_importances_ adds up how much each feature reduced the impurity across all the splits that used it, weighted by how many points went through those splits, and scales the total to 1. It is a quick way to see what the model relies on. Be careful with it, though: it favours features with many unique values, and it can be unstable when two features carry the same information. For a more reliable check, use sklearn.inspection.permutation_importance.

    ID3, C4.5 and CART

    You will see these three names in textbooks and exams. They are different recipes for building a tree:

    AlgorithmSplit criterionSplitsNotes
    ID3 (1986)Information gain (entropy)Multi-way, one branch per categoryCategorical features only; no pruning; favours features with many values
    C4.5 (1993)Gain ratio (information gain divided by split information)Multi-wayHandles numbers and missing values; prunes after growing
    CART (1984)Gini for classification, squared error for regressionAlways binary (yes or no)Handles both tasks; cost complexity pruning; used by scikit-learn

    scikit-learn uses an optimised version of CART. In recent versions it can also handle missing values on its own, by sending them down whichever branch works best during training.

    Decision tree vs random forest vs logistic regression

    Decision treeRandom forestLogistic regression
    ModelOne tree of if-else questionsHundreds of trees, each trained on a random sample, then averagedA weighted sum passed through a sigmoid
    Boundary shapeAxis-parallel boxesSmoother combination of many boxesA straight line (unless you add features)
    OverfittingHigh risk without pruningLow; averaging cancels out the noiseLow to medium
    InterpretabilityVery easy: read the rulesHard: too many trees to readEasy: one weight per feature
    Feature scalingNot neededNot neededRecommended
    Typical accuracy on tabular dataGoodVery goodGood when the relationship is roughly linear

    A single tree is the right choice when people need to understand and trust the rules, for example in loan approvals or medical triage. When accuracy matters most, a random forest or gradient boosting model, which are both built from many trees, nearly always does better. If the classes are separated by a roughly straight line, logistic regression or a linear support vector machine needs far fewer parameters than a staircase of tree splits.

    Advantages and disadvantages of decision trees

    Advantages

    • Easy to understand, explain and draw, even for people with no maths background.
    • Little data preparation: no feature scaling, and it handles a mix of numbers and categories (after encoding).
    • Captures non-linear patterns and interactions between features without you creating them by hand.
    • Very fast at prediction time: one path from the root to a leaf.
    • Works for both classification and regression, including multiclass and multi-output problems.

    Disadvantages

    • Overfits easily unless you limit depth or prune.
    • Unstable: a small change in the training data can produce a completely different tree.
    • Boundaries are made of axis-parallel steps, so diagonal or smooth patterns need many splits.
    • Greedy splitting does not guarantee the best possible tree.
    • Can be biased towards the majority class on imbalanced data; use class_weight="balanced" if needed.

    Most of these weaknesses are exactly what random forests and gradient boosting were invented to fix, which is why trees are the foundation of so many strong models.

    Decision tree interview questions and answers

    These are the decision tree questions that come up most in data science and machine learning interviews, with answers you can say out loud.

    1. What is a decision tree?

    A supervised learning model that predicts by asking a sequence of questions about the features, each splitting the data into smaller groups, until it reaches a leaf that holds the prediction. It can be used for classification and regression.

    2. How does a decision tree decide where to split?

    At each node it tries every feature and every candidate threshold, measures the impurity of the resulting child nodes, and keeps the split that reduces impurity the most. For classification that is Gini or entropy; for regression it is usually squared error.

    3. What is Gini impurity?

    One minus the sum of squared class proportions in a node. It is the chance of labelling a random point wrongly if you guess using the node’s class distribution. It is 0 for a pure node and 0.5 for a 50/50 node with two classes.

    4. What is entropy?

    A measure of uncertainty: minus the sum of p times log base 2 of p over the classes. It is 0 for a pure node and 1 for a 50/50 node with two classes.

    5. What is information gain?

    The drop in entropy from a parent node to its children, where each child’s entropy is weighted by its share of the points. The split with the highest information gain is chosen.

    6. Gini or entropy: which is better?

    Neither is clearly better. They produce almost the same tree in most cases. Gini is slightly faster because it avoids logarithms, which is why it is the default in scikit-learn.

    7. Why do decision trees overfit, and how do you stop it?

    Without limits a tree keeps splitting until each leaf is pure, which means it learns the noise in the training data. You stop it with pre-pruning (max_depth, min_samples_leaf, min_samples_split, max_leaf_nodes) or post-pruning (cost complexity pruning with ccp_alpha), tuned with cross-validation.

    8. What is the difference between pre-pruning and post-pruning?

    Pre-pruning stops the tree from growing past certain limits. Post-pruning grows the full tree first and then removes branches that do not improve validation performance enough to justify their size.

    9. What is cost complexity pruning?

    A post-pruning method that scores each subtree by its training error plus alpha times its number of leaves. As alpha increases, more branches are removed. The best alpha is chosen by cross-validation.

    10. Do decision trees need feature scaling?

    No. Each split compares one feature with a threshold, so rescaling a feature only moves the threshold and gives the same tree.

    11. How does a regression tree make predictions?

    It splits the data to reduce the squared error of the target, and each leaf predicts the mean target value of the training points in it. The result is a step-shaped function.

    12. What are ID3, C4.5 and CART?

    Three tree-building algorithms. ID3 uses information gain and multi-way splits on categorical features. C4.5 uses gain ratio, handles numeric features and missing values, and prunes. CART makes binary splits, uses Gini or squared error, and supports regression; scikit-learn uses CART.

    13. What is feature importance in a decision tree?

    The total impurity reduction a feature contributes across all its splits, weighted by the number of samples reaching those splits, normalised to sum to 1. It is biased towards high-cardinality features, so permutation importance is a useful check.

    14. Why is a decision tree called a greedy algorithm?

    Because it chooses the best split at each node based only on that node, without considering how the choice affects later splits. Finding the globally optimal tree is NP-hard, so greedy splitting is used instead.

    15. Are decision trees stable?

    No. They have high variance: small changes in the data can change the top split and therefore the whole tree. Bagging, as in random forests, reduces this variance by averaging many trees.

    16. What is the difference between a decision tree and a random forest?

    A decision tree is a single model. A random forest trains many trees on bootstrap samples of the data, with a random subset of features at each split, and averages their predictions. The forest is more accurate and stable but much harder to interpret.

    17. How do decision trees handle categorical features?

    In theory they can split on categories directly, as ID3 and C4.5 do. In scikit-learn you usually encode them first, with one-hot encoding or ordinal encoding. Recent versions of scikit-learn also add native categorical support in some tree-based models.

    18. What is the time complexity of a decision tree?

    Training is roughly O(n × m × log n) for n rows and m features when the tree is balanced, because each level sorts and scans the features. Prediction is O(depth), which is about O(log n) for a balanced tree.

    Test yourself: decision tree quiz

    Ten questions on everything above. Eight or more right means you are ready for decision tree questions in an interview.

    Quiz

    Decision tree quiz

    10 questions, about three minutes.

    Download the free decision tree notes (PDF)

    Everything on this page in a printable format: the key ideas, the Gini and entropy formulas with the worked example, the parameter cheat sheet, all seven code examples with their outputs, and the interview questions.

    Free PDF

    Decision tree notes by Code and Debug

    11 pages, no sign-up needed.

    Download PDF

    Frequently asked questions

    Is a decision tree supervised or unsupervised learning?

    A decision tree is supervised learning. It needs labelled training data, where the correct answer is known for each example, to learn which questions to ask.

    Is a decision tree used for classification or regression?

    Both. A classification tree predicts a category and uses Gini or entropy to choose splits. A regression tree predicts a number, uses squared error to choose splits, and predicts the average value in each leaf.

    What is the difference between Gini and entropy in a decision tree?

    Both measure how mixed a node is. Gini is 1 minus the sum of squared class shares and ranges from 0 to 0.5 for two classes. Entropy uses logarithms and ranges from 0 to 1. They choose the same split in most cases.

    How do I choose max_depth for a decision tree?

    Try a range of values, for example 2 to 12 and None, with cross-validation using GridSearchCV, and keep the value with the best validation score. Tune min_samples_leaf alongside it.

    Is decision tree better than random forest?

    A random forest is usually more accurate and less prone to overfitting, because it averages many trees. A single decision tree is better when you need a model that people can read and explain.

    Which algorithm does scikit-learn use for decision trees?

    scikit-learn uses an optimised version of CART, which makes binary splits and supports both classification and regression.

    What to learn next

    • Support vector machine (SVM) in machine learning, a very different way to draw boundaries, with its own interactive playground.
    • Confusion matrix in machine learning, to judge your tree beyond plain accuracy.
    • Logistic regression in machine learning, the classic linear classifier to compare trees against.
    • How to learn AI and ML from scratch, our full roadmap with a personal study planner.
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleSupport Vector Machine (SVM) in Machine Learning: An Interactive Guide
    Next Article K-Means Clustering in Machine Learning: An Interactive Guide (with Python)
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    AI & Machine Learning

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026
    AI & Machine Learning

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026
    AI & Machine Learning

    Confusion Matrix in Machine Learning: An Interactive Guide

    21 October 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (7)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (5)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (1)
    Recent Posts

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026

    100 OOPs Interview Questions and Answers (Freshers to Experienced)

    16 November 2026

    100 Computer Networks Interview Questions and Answers (Freshers to Experienced)

    15 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.