← Blog/How Decision Trees Work: The Math and Intuition, Explained for Marketers
Machine LearningDecision TreePythonStatisticsMarketing Analytics
Machine Learning · 30 min read

How Decision Trees Work: The Math and Intuition, Explained for Marketers

Decision trees explained for marketers: how splits are chosen, why trees overfit, pruning, error in dollars and instability, with interactive charts.

· Martin Guzman

A decision tree predicts a number by asking a short series of yes-or-no questions about a customer, then reporting the average for past customers who gave the same answers. This guide explains how it works from the ground up: how the questions are chosen, the math behind each choice, how to stop the tree from memorizing its data, how to judge it in dollars, and the weakness that leads to the more advanced methods in the next part of the series. On new customers, the tree in this guide misses first-year value by $159.99 on average, against $315.14 for guessing the average.

The business case that applies it is a separate guide, so this one can focus on the model. That case, predicting a new customer's first-year value, is coming soon, and every example on this page uses its data: an invented Canadian online outdoor gear retailer, Tamarack & Talus, estimating how much each of 8,000 new customers will spend in their first year, from what it knows at their first order. Every number and chart here is real output from code you can download.

Unlike the other guides in this series, which use Northpine Software, this one uses its own dataset, generated with step-like rules such as a free-shipping line and holiday gift buyers, because that is the kind of pattern a tree is built to find. On data where value rises smoothly with each input, linear regression can beat a tree; when not to use a tree explains why.

How a decision tree works

A decision tree is a set of questions arranged like a flowchart. To predict a new customer's first-year value, start at the top, answer each question about that customer, follow the branch the answer points to, and stop when there are no questions left. The end point is called a leaf, and its prediction is the average first-year value of the past customers who ended up there.

How a decision tree predicts one new customer
Step 1
Start at the top
Every new customer begins with the same first question
Step 2
Answer a question
For example: did they join the loyalty program at checkout?
Step 3
Follow the branch
Each answer leads to the next question, until there are none left
Step 4
Read the leaf
Prediction = average first-year value of the past customers in that leaf
The tree is a list of yes-or-no questions learned from past customers. A prediction is the average value of the past customers who gave the same answers.

The questions are not written by a person. The tree learns them from past customers, by trying every possible question and keeping the one that best separates high spenders from low spenders, then repeating the search inside each group. In the running example, the first question it chooses is "did this customer join the loyalty program at checkout?" and the second, on both sides, is about the size of the first order.

That design has three consequences you will meet throughout this guide:

  • Every prediction comes with its reasons. "Loyalty member, first order over $102.88, first bought a tent, no discount code" is a rule anyone in the business can read and argue with. Few models explain themselves this plainly.
  • Predictions come in steps. A tree can only give as many different answers as it has leaves. Two customers who land in the same leaf get exactly the same prediction, even if one spent $104 on their first order and the other $450.
  • A tree will memorize its data if you let it. Nothing stops it from asking questions until every leaf holds one customer. Most of the tuning in this guide is about deciding when to stop.

The math behind decision trees

Decision trees need less algebra than most models, because there is no equation to solve. There are five pieces: turning a customer into numbers, predicting from a leaf, choosing a split, deciding when to stop, and judging the result. A sixth, instability, is the tree's main weakness.

A customer is a list of answers

To the tree, each customer is a row of values called a vector:

x=(x1,x2,…,xp)\mathbf{x} = (x_1, x_2, \ldots, x_p)

Here pp is the number of columns and xjx_j is the customer's value on column jj. Each past customer ii also has an outcome, yiy_i: their first-year value in dollars.

Most columns are already numbers: the first order's value, the number of items in it, the month it was placed. Yes-or-no columns, like joining the loyalty program, become 1 or 0. Columns with named categories, like the acquisition channel, become one yes-or-no column per category, a step called one-hot encoding: "came from paid social" is 1 for paid social customers and 0 for everyone else.

Two things that matter for other models do not matter here. A tree never adds or multiplies columns together, it only compares one column at a time with a cut-off, so it does not care whether first-order value is measured in dollars or cents. There is no need to rescale columns. And a tree is not bothered by skewed columns: a cut-off at $99 works the same whether a few first orders are $1,000 or $10,000.

The prediction is the average of a leaf

Every customer who answers the questions the same way lands in the same leaf. The tree's prediction for a new customer x\mathbf{x} is the average outcome of the training customers in its leaf, L(x)L(\mathbf{x}):

y^(x)=1∣L(x)∣∑i∈L(x)yi\hat{y}(\mathbf{x}) = \frac{1}{|L(\mathbf{x})|} \sum_{i \in L(\mathbf{x})} y_i

In words: find the leaf, add up the first-year values of the past customers in it, and divide by how many there are. ∣L(x)∣|L(\mathbf{x})| is the number of customers in the leaf, and the hat on y^\hat{y} marks it as a prediction rather than a known value.

In the running example, one leaf holds customers who joined the loyalty program, spent more than $102.88 on a first order that was a tent, used no discount code, bought more than one item, and spent more than $457.44 in total. Thirty training customers meet all six conditions, and their first-year values average $2,068.46. Any new customer who answers the same way is predicted to spend $2,068.46, the highest prediction the tree makes. You can follow this path in the tree diagram further down.

Why the average?

The tree judges its predictions by squared error: the difference between the actual and predicted value, squared, then added up over all customers. Squaring makes every error positive and punishes large misses far more than small ones: missing by $400 counts sixteen times as much as missing by $100.

For one group of customers, the single number cc with the smallest total squared error,

∑i(yi−c)2,\sum_{i} (y_i - c)^2,

is always the group's average, yˉ\bar{y}. (Take the derivative with respect to cc, which is −2∑i(yi−c)-2\sum_i (y_i - c), and set it to zero: c=1n∑iyic = \frac{1}{n}\sum_i y_i.) So once the tree has decided how to group customers, the average is the best prediction it can give each group under this rule. Everything else in fitting a tree is about choosing the groups.

Choosing a split: the drop in squared error

Call the squared error of a group of customers SS its sum of squared errors:

SSE(S)=∑i∈S(yi−yˉS)2\text{SSE}(S) = \sum_{i \in S} \left(y_i - \bar{y}_S\right)^2

where yˉS\bar{y}_S is the group's average. A split divides SS in two using one column jj and one cut-off ss: customers with xj≤sx_j \le s go left, the rest go right. The tree picks the column and cut-off with the smallest combined error in the two halves:

(j∗,s∗)=arg⁡min⁡j, s[SSE(Sleft)+SSE(Sright)](j^*, s^*) = \underset{j,\, s}{\arg\min} \Big[ \text{SSE}(S_{\text{left}}) + \text{SSE}(S_{\text{right}}) \Big]

arg⁡min⁡\arg\min means "the values that make this smallest". Equivalently, the tree maximizes the drop in error, which statisticians call variance reduction:

Δ=SSE(S)−SSE(Sleft)−SSE(Sright)\Delta = \text{SSE}(S) - \text{SSE}(S_{\text{left}}) - \text{SSE}(S_{\text{right}})

The drop can never be negative: two separate averages always fit at least as well as one.

Here is the first split worked out on the running example's 5,600 training customers. Before any split, everyone is predicted to spend the average, $415.35, and the sum of squared errors is 1,113.1 million (the unit is dollars squared, which has no everyday meaning; only the comparisons matter). Now try four questions:

First questionYes: customersYes: averageNo: customersNo: averageSquared error afterError removed
Loyalty member?1,600$772.434,000$272.52827.5 million25.7%
First order $99 or more?3,325$569.262,275$190.41919.2 million17.4%
Created an account?3,523$544.552,077$196.21954.5 million14.2%
First order in November or December?1,370$338.724,230$440.171,102.4 million1.0%

For loyalty membership: the 1,600 members have a squared error of 570.9 million around their own average, and the 4,000 others 256.6 million around theirs. Together that is 827.5 million, so the split removes

1,113.1−827.51,113.1=0.257, or 25.7%\frac{1{,}113.1 - 827.5}{1{,}113.1} = 0.257, \text{ or } 25.7\%

of the error. No other question does better, so loyalty membership becomes the first question in the tree.

For a column with many values, like first-order value, the tree tries every cut-off between two neighbouring values. The chart below shows the four questions; switch to the cut-off view to watch the search over 19 cut-offs on first-order value. Of those, the best removes 17.9 percent, at $110, but the curve is almost flat from $99 to $200: within that range, the exact cut-off barely matters to the tree.

The first split, by hand: which question removes the most error?
Try it
0%10%20%30%loyalty member?25.7%first order $99 or more?17.4%created an account?14.2%first order in Nov or Dec?1.0%share of squared error removed
Before any split: 5,600 training customers, average $415.35, squared error 1,113.1 million. Hover a question.
The 5,600 training customers. Each bar is one candidate first split, scored by the share of squared error it removes.

After the first split, the tree treats each half as a new problem and runs the same search inside it, then inside each of those halves, and so on. Computer scientists call this a greedy search: at each step it takes the best split available right now, without asking whether a weaker split now would allow better splits later.

The tree has to work this way. The number of possible trees grows astronomically with the number of columns and cut-offs, so checking every tree is out of reach even for a few thousand customers. The greedy search checks a few thousand splits per step instead and finishes in a fraction of a second.

The cost is that the tree can miss patterns that only appear in combination. In the running example, "first order in November or December" removes just 1.0 percent of the error at the top, because holiday gift buyers rarely come back unless they join the loyalty program, while members who start in December come back as often as anyone. Averaged over everyone, the effect is diluted. The tree only finds it lower down, inside the group of customers who did not join, where it matters. Greedy search finds such interactions when one half of the combination is strong enough on its own to be chosen first. When neither half is, it can miss them.

The map below shows what the search produces. It grows trees on just two columns, first-order value and month, so the prediction can be drawn at every point. Each split draws a straight line across one axis, so the predictions form rectangles. At depth 1 there is one cut, on first-order value. Month first appears at depth 3, in one narrow strip of first-order values. At depth 4 a darker band appears across November and December for first orders between about $65 and $340: the holiday gift buyers, found once the tree has room to look for them. Press play to watch it grow.

Predictions come in rectangles: a tree on two columns
Try it
JanMarMayJulSepNov$20$50$99$200$500first-order value (log scale)
prediction$100 → $900+16 leaves · cross-validated R² 0.270
Hover the map to read the prediction anywhere. Press play to grow the tree one depth at a time.
Trees fitted to first-order value and month only, using the 5,600 training customers, with at least 30 customers per leaf.

With only these two columns, the best tree has 8 leaves (depth 3) and a cross-validated R² of 0.271, which tests it on customers it did not learn from and is explained below. Deeper trees on the same two columns do slightly worse: 0.244 with 87 leaves. That is the first sign of the problem the next section deals with.

When to stop: depth and leaf size

Left alone, the greedy search keeps splitting until every leaf holds customers with identical outcomes, which usually means one customer per leaf. Such a tree has memorized its training data: its predictions on those customers are perfect, and on new customers they are poor, because each leaf's "average" is one person's quirks. This is called overfitting.

Two settings stop the growth early:

  • Maximum depth caps the number of questions between the top and any leaf. A tree of depth dd has at most 2d2^d leaves.
  • Minimum leaf size refuses any split that would leave fewer than a set number of customers in a leaf, so every prediction is an average over at least that many people.

They trade two kinds of error against each other:

  • A shallow tree is blurry. With few leaves, very different customers share a prediction. At depth 1 everyone gets one of two numbers. Statisticians call this high bias.
  • A deep tree is noisy. With tiny leaves, each prediction rests on a handful of customers and would change completely with a different handful. This is high variance.

To find the balance, use cross-validation, which tests the model on customers it did not train on. It splits the training customers into five parts, builds the tree on four, scores the fifth, and repeats so every part is scored once. The chart compares that score with the score on the customers the tree trained on, for every depth from 1 to 15.

Deeper trees memorize: training against cross-validated R²
Try it
0.20.40.60.81.013579111315maximum depthR²
training customers (the tree has seen them)cross-validated (unseen customers)
Depth 6: training R² 0.734, cross-validated R² 0.677, average error $158.66 (the best depth)
Five-fold cross-validation on the 5,600 training customers, for every maximum depth from 1 to 15.
  • With no minimum leaf size, the two lines split apart. Training R² climbs to 0.965 at depth 15; cross-validated R² peaks at 0.677 at depth 6 and falls to 0.456 at depth 15. The deep tree looks better on the customers it memorized and is far worse on new ones.
  • With at least 30 customers per leaf, the fall disappears. Cross-validated R² reaches 0.680 at depth 8 and then levels off, because the leaf-size rule stops the tree from splitting further no matter how deep it is allowed to go.

The tuning step in the downloadable notebook tries 50 combinations of the two settings. The best is depth 8 with at least 30 customers per leaf, giving a tree with 106 leaves. Several neighbours score almost the same: depth 6 with 30 per leaf reaches 0.678. The search keeps the top score, but a smaller tree such as depth 6 would lose almost nothing; the pruned 28-leaf tree below makes the same point.

Pruning: grow it all, then cut back

Stopping early has a flaw that greedy search makes worse: a split that looks useless may enable a valuable split below it, and stopping rules never get to see that. Cost-complexity pruning takes the other route. Grow the full tree, then cut back the branches that do not pay for themselves.

It scores every possible pruned version TT of the full tree by

Rα(T)=R(T)+α ∣T∣R_\alpha(T) = R(T) + \alpha \, |T|

where R(T)R(T) is the tree's average squared error on the training customers, ∣T∣|T| is its number of leaves, and α\alpha (alpha) is a price charged for every leaf. For a given α\alpha, the pruned tree with the lowest score wins. With α=0\alpha = 0 nothing is pruned, since extra leaves never increase training error. As α\alpha grows, a branch survives only if it lowers the average squared error by more than α\alpha for each leaf it adds. At a large enough α\alpha, only the root is left.

On the running example, the full tree has 5,556 leaves for 5,600 training customers: nearly one leaf per person. Slide α\alpha to prune it. The cross-validated R² is best at α=544\alpha = 544, which leaves 28 leaves and scores 0.672. That is almost as good as the 106-leaf tuned tree (0.680), at about a quarter of the size.

Pruning: grow everything, then cut back
Try it
α = 544
leaves left
28
training R²
0.715
cross-validated R²
0.672
cross-validated error
$164.18
0.40.60.81.01,000100102leaves in the pruned tree (log scale)R²
training customerscross-validated
α = 544: a split survives only if it cuts the average squared error by more than 544 per extra leaf. 28 leaves, cross-validated R² 0.672, the best of the values tried.
Cost-complexity pruning of a full tree on the training customers. Five-fold cross-validated R² for each α.

In scikit-learn, α\alpha is the ccp_alpha setting, and cost_complexity_pruning_path lists every value at which a branch disappears. Pruning and the depth-and-leaf-size rules usually land in the same place. Pruning has one practical advantage for marketing: a 28-leaf tree fits on a single page that a team can read, check and argue with.

Judging the result: R², and error in dollars

Three numbers describe how good the predictions are. Here nn is the number of customers scored, yiy_i what customer ii actually spent, and y^i\hat{y}_i the prediction.

R², the coefficient of determination, is the share of squared error the model removes compared with predicting the average for everyone:

R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2 = 1 - \frac{\sum_{i} (y_i - \hat{y}_i)^2}{\sum_{i} (y_i - \bar{y})^2}

R² of 0 means no better than the average; 1 means perfect. It is the same "error removed" used to choose splits, measured on customers the tree has not seen.

The mean absolute error, MAE, is the typical miss in dollars:

MAE=1n∑i=1n∣yi−y^i∣\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} \left| y_i - \hat{y}_i \right|

The root mean squared error, RMSE, is also in dollars, but squares the misses before averaging, so it weighs large misses more:

RMSE=1n∑i=1n(yi−y^i)2\text{RMSE} = \sqrt{\frac{1}{n} \sum_{i=1}^{n} \left( y_i - \hat{y}_i \right)^2}

On the 2,400 test customers the tuned tree never saw, R² is 0.650, MAE is $159.99 and RMSE is $261.52. Predicting the average for everyone gives an MAE of $315.14 and an RMSE of $441.81, so the tree halves the typical miss.

How far off is each prediction, in dollars?
Try it
0400800$0$250$500$750$1,000MAE $159.99RMSE $261.52how far off the prediction is (last bar: $1,200 or more)customers
mean absolute errorroot mean squared error
54% of predictions are within $100. R² 0.650. Hover a bar.
The 2,400 test customers the model never saw. Real output from the notebook.

The chart shows why the two dollar figures differ. Most predictions are off by less than $200, but a long tail of customers are off by $1,000 or more. MAE treats a $1,000 miss as ten $100 misses; RMSE treats it as a hundred. When RMSE is much larger than MAE, as here, the errors are concentrated in a few customers.

Why insist on dollars, when R² is the standard summary? Because the decisions this model feeds are made in dollars. A marketer setting how much to pay to acquire a customer needs to know that the estimate is typically $159.99 off; an R² of 0.650 does not tell them that. The notebook also breaks the error down by channel and by predicted tier, and the business case will walk through it.

How trees fail: instability

A single tree is unstable: a small change in the training data can change its questions. A split chosen because it removes 17.9 percent of the error can lose to one that removes 17.8 percent after a few customers are added or removed, and every split below it then changes too.

To see how much, draw a bootstrap sample: pick 5,600 customers at random from the 5,600 training customers, with replacement, so some appear twice and others not at all. Fit the same tree to it. Repeat six times.

Same settings, slightly different data, different tree
Try it
test R², this depth-3 tree
0.550
test R², tuned tree on this sample
0.630
Depth-3 tree fitted to sample 1
Five test customers: what each of the six tuned trees predicts
$0$200$400$600$800customer 1customer 2customer 3customer 4customer 5
Dots: the six trees. Green: the sample shown above. Amber marker: what the customer actually spent. Hover a row.
Six bootstrap samples of the training customers, each drawn with replacement. Scored on the same 2,400 test customers.

On this data, all six trees ask about loyalty membership first: that split is strong enough to survive any sample. Below it the trees agree on the column, first-order value, but choose different cut-offs; from the third level down they also choose different columns. Their accuracy is similar, between 0.624 and 0.643 R² on the test customers for the tuned settings, but their predictions for any one customer are not. The first test customer gets predictions from $144.90 to $267.09 depending on which sample the tree happened to see.

The cure is to stop relying on a single tree. If you fit BB trees f1,…,fBf_1, \ldots, f_B to different samples and average them,

fˉ(x)=1B∑b=1Bfb(x),\bar{f}(\mathbf{x}) = \frac{1}{B} \sum_{b=1}^{B} f_b(\mathbf{x}),

the random disagreements largely cancel out. That is the idea behind random forests and, in a different form, gradient boosting, which builds each new tree to correct the errors of the ones before it. Part 5 of this series covers boosting with XGBoost.

Try it

The playground below uses 400 of the running example's training customers, few enough that every split can be computed in your browser. Each dot is a customer; the height is their first-year value.

Split the customers yourself, then let the tree grow
Try it
1. Pick a question for the first split
first order > $128.17
$0$100$500$1,000$2,000$20$50$99$200$500$1,000first-year value
yes: average
$626
199 customers
no: average
$201
201 customers
squared error left
69.7m
from 87.7m
error removed
20.5%
best cut-off here: 21.3%
2. Let the greedy search grow the tree on these 400 customers
Depth 1: 2 leaves, R² on these customers 0.263. Each leaf predicts the average of the customers in it.
400 training customers drawn at random, so every split can be computed in your browser. The tuned model uses all 5,600.

Four things to try:

  1. Move the cut-off on first-order value. Watch the two averages and the squared error change as you drag. The "error removed" figure is the Δ\Delta from the split formula. Press "find the best cut-off" to run the search the tree runs.
  2. Switch to loyalty. A yes-or-no column has only one possible split. On these 400 customers, as on all 5,600, it removes more error than any cut-off on first-order value.
  3. Try month and channel. Month removes very little at the top, for the reason in the greedy search section. Paid social removes a little more than the other channels, because those customers spend less on average, but still very little.
  4. Grow the tree. In the second part, step from no split to depth 3. Each extra level adds a question to every branch, and R² on these customers rises. On customers the tree has not seen, it would rise more slowly, as the depth chart showed.

Looking inside a decision tree

A tree's main selling point is that you can read it. This section reads the tuned tree, then asks which columns it relies on, whether it ignores a column that should not matter, and how much data it needs.

The whole tree, one rule at a time

The tuned tree has 106 leaves and is 8 questions deep. The diagram opens at the first two levels. Click any + to open a branch, or follow the customer with the highest prediction from the math section. Each row shows the rule, how many training customers meet it, and their average first-year value.

The whole tree, one rule at a time
Try it
leaves
106
depth
8
leaf values
$34–$2,068
Each row: the rule, the training customers who meet it, and their average first-year value. Click + to open a node.
The tuned tree (depth 8, at least 30 customers per leaf), fitted to the 5,600 training customers.

Two things stand out. First, the tree's top levels match what a marketer might guess: loyalty members are worth far more ($772.43 against $272.52 on average), and bigger first orders lead to bigger first years. Second, the followed customer's prediction is $2,068.46 and they actually spent $1,137.53. Even in a well-built leaf, individual customers vary widely around the average. A tree predicts groups well and individuals only roughly.

Which columns matter: two answers

There are two common ways to measure how much a tree relies on each column, and they can disagree.

The first, impurity importance, comes free with the tree. For each column, add up the drop in squared error, Δ\Delta, from every split that uses it, then divide by the total drop from all splits:

Impj=∑splits on jΔ∑all splitsΔ\text{Imp}_j = \frac{\sum_{\text{splits on } j} \Delta}{\sum_{\text{all splits}} \Delta}

In scikit-learn this is feature_importances_. It measures how much the column helped while the tree was being built, on the training customers.

The second, permutation importance, tests the finished model. Shuffle one column in the test data, so it no longer carries information, and measure how much R² falls:

PIj=R2−Rcolumn j shuffled2\text{PI}_j = R^2 - R^2_{\text{column } j \text{ shuffled}}

Repeat 20 times per column and average. It measures how much the model relies on the column for customers it has not seen.

Which columns matter? Two answers
Try it
0.000.200.400.60Loyalty signupFirst-order valueFirst categoryAccount createdChannelFirst-order monthDiscount codeItems in first orderDeviceProvincedrop in R² when the column is shuffled
Hover a row. The white line spans one standard deviation across the 20 shuffles.
Shuffle test: each column shuffled 20 times in the 2,400 test customers. Split credit: the tree’s own feature_importances_.

The two measures agree on the top three columns but not on their order:

  • Permutation importance ranks loyalty signup first. Shuffling it lowers R² by 0.617, against 0.379 for first-order value.
  • Impurity importance ranks first-order value first, with 40.8 percent of all error removed, against 35.0 percent for loyalty signup.

The difference comes from how each is built. First-order value takes hundreds of different values, so the tree can split on it again and again deep in every branch, and each small split adds a little credit. Impurity importance is known to favour columns with many possible cut-offs for this reason, and it counts gains on training customers, including splits that do not generalize. Loyalty signup is used once, at the top, but everything below depends on it, so scrambling it does the most damage to test predictions. When the two disagree, trust permutation importance for questions about what the model needs.

A column that should not matter

Province has no effect on first-year value in this data; it was built that way. The tree mostly ignores it: only 2 of its 105 splits use a province, and both measures score it at zero. Those two splits are not free, though. Dropping province does not lower cross-validated R² (0.680 with it, 0.684 without), because each province split spends a level of the tree, and some customers, on noise. Trees cope with useless columns better than many methods, since a column that never wins a split is simply never used, but they do not cope perfectly.

How much data it needs

The learning curve trains the tuned settings on smaller samples of the training customers. With 250 customers, cross-validated R² is 0.501; with 1,000 it is 0.615; with all 4,480 in each training fold it is 0.680. The curve is flattening: more history would still help a little, but most of what this data can teach the tree, it has learned by a few thousand customers. A tree with at least 30 customers per leaf can only have as many leaves as the data allows, so small datasets give coarse trees.

How many customers does it need?
Try it
0.400.500.600.7001,0002,0003,0004,000training customersR²
4,480 training customers: R² 0.680, ±0.030 across the five folds
Five-fold cross-validated R² with the tuned settings, trained on samples of the training customers.

Decision trees in Python

The whole model is a few lines of scikit-learn. One-hot encoding goes inside the pipeline so it is learned from the training customers only; no scaling is needed:

from sklearn.compose import make_column_transformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.tree import DecisionTreeRegressor, export_text
 
prep = make_column_transformer(
    (OneHotEncoder(handle_unknown="ignore", sparse_output=False), categorical),
    ("passthrough", numeric),
    verbose_feature_names_out=False,
)
tree = make_pipeline(prep, DecisionTreeRegressor(max_depth=8, min_samples_leaf=30,
                                                 random_state=42))
tree.fit(X_train, y_train)
predicted = tree.predict(X_test)        # the average of each customer's leaf
 
print(export_text(tree[-1], feature_names=list(tree[0].get_feature_names_out()),
                  max_depth=2))         # the rules, as text

fit runs the greedy search; predict drops each new customer down the tree. Setting random_state matters even though the search looks deterministic: when two splits tie exactly, scikit-learn breaks the tie at random. The downloadable notebook runs this end to end on the data, with every output shown.

When to use a decision tree, and when not to

A decision tree is a good choice when:

  • People need to read the model. The rules can go in a slide, a CRM workflow or a spreadsheet formula. A 28-leaf pruned tree fits on one page.
  • The pattern comes in steps and combinations. Thresholds, like a free-shipping line, and effects that only hold for some customers, like gift buyers who join the loyalty program, are what trees are built to find. On the running example's test customers, the tree's typical miss is $159.99 against $192.50 for linear regression (both computed in the downloadable notebook).
  • Your data is messy. Trees need no scaling, handle skewed values and mostly ignore useless columns.

Choose something else when:

  • The relationship is smooth. A tree approximates a straight line with a staircase. If value rises steadily with first-order size, linear regression describes that with one number, and the tree needs dozens of leaves to imitate it.
  • You need stable, accurate predictions for individuals. A single tree is unstable, as the bootstrap chart showed. Averaging many trees, in a random forest or with boosting, is almost always more accurate.
  • You need to predict beyond what you have seen. A tree's prediction can never exceed the highest leaf average. A customer unlike any past customer gets the prediction of whichever edge leaf it falls into, however far it is from the customers in that leaf.
MethodWhat it gives youStrengthWatch out for
KNNA score from similar examplesExplains itself with real examplesScaling, slow at large scale
Linear regressionHow much one number moves anotherSimple, readable effectsMistaking correlation for cause
Logistic regressionA probability for a yes or no outcomeAccurate, clear weights per columnStraight-line assumptions
Decision tree (this guide)Rules that split customers into groupsRules anyone can readUnstable, overfits if allowed
XGBoostStrong predictions from many treesUsually the most accurateNeeds extra tools to explain

Business cases

Each case applies decision trees to one marketing job, from the business problem to a working model, with the code and data:

Case 1Predict a new customer’s first-year valuecoming soon

Download the data and the notebook

The notebook builds the tree and computes every chart on this page, in its appendix. The dataset's generator, with every rule that made the data, is in the site's source code at scripts/ml-guides/make_tree_data.py.

Want this on your own data?

If you would like to know whether a decision tree, or another method, fits a problem in your own data, get in touch and we can talk it through on a short call.