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.
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.
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:
Here is the number of columns and is the customer's value on column . Each past customer also has an outcome, : 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 is the average outcome of the training customers in its leaf, :
In words: find the leaf, add up the first-year values of the past customers in it, and divide by how many there are. is the number of customers in the leaf, and the hat on 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 with the smallest total squared error,
is always the group's average, . (Take the derivative with respect to , which is , and set it to zero: .) 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 its sum of squared errors:
where is the group's average. A split divides in two using one column and one cut-off : customers with go left, the rest go right. The tree picks the column and cut-off with the smallest combined error in the two halves:
means "the values that make this smallest". Equivalently, the tree maximizes the drop in error, which statisticians call variance reduction:
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 question | Yes: customers | Yes: average | No: customers | No: average | Squared error after | Error removed |
|---|---|---|---|---|---|---|
| Loyalty member? | 1,600 | $772.43 | 4,000 | $272.52 | 827.5 million | 25.7% |
| First order $99 or more? | 3,325 | $569.26 | 2,275 | $190.41 | 919.2 million | 17.4% |
| Created an account? | 3,523 | $544.55 | 2,077 | $196.21 | 954.5 million | 14.2% |
| First order in November or December? | 1,370 | $338.72 | 4,230 | $440.17 | 1,102.4 million | 1.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
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.
Growing the tree: a greedy search
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.
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 has at most 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.
- 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 of the full tree by
where is the tree's average squared error on the training customers, is its number of leaves, and (alpha) is a price charged for every leaf. For a given , the pruned tree with the lowest score wins. With nothing is pruned, since extra leaves never increase training error. As grows, a branch survives only if it lowers the average squared error by more than for each leaf it adds. At a large enough , 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 to prune it. The cross-validated R² is best at , 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.
In scikit-learn, 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 is the number of customers scored, what customer actually spent, and the prediction.
R², the coefficient of determination, is the share of squared error the model removes compared with predicting the average for everyone:
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:
The root mean squared error, RMSE, is also in dollars, but squares the misses before averaging, so it weighs large misses more:
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.
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.
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 trees to different samples and average them,
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.
Four things to try:
- 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 from the split formula. Press "find the best cut-off" to run the search the tree runs.
- 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.
- 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.
- 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.
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, , from every split that uses it, then divide by the total drop from all splits:
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:
Repeat 20 times per column and average. It measures how much the model relies on the column for customers it has not seen.
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.
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 textfit 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.
| Method | What it gives you | Strength | Watch out for |
|---|---|---|---|
| KNN | A score from similar examples | Explains itself with real examples | Scaling, slow at large scale |
| Linear regression | How much one number moves another | Simple, readable effects | Mistaking correlation for cause |
| Logistic regression | A probability for a yes or no outcome | Accurate, clear weights per column | Straight-line assumptions |
| Decision tree (this guide) | Rules that split customers into groups | Rules anyone can read | Unstable, overfits if allowed |
| XGBoost | Strong predictions from many trees | Usually the most accurate | Needs 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:
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.