Train a First Model: a Small Decision Tree
A first model turns a table of past examples into something that answers for new rows: here, whether a customer will leave a service (leaving is often called churn). A small decision tree is a good first model, because it learns a few yes-or-no questions from the data that you can read yourself. Its answers are then scored, and that score only means something next to a simple rule that ignores the data altogether.
Fit and predict: the pattern every model follows
In scikit-learn, every model is an object you create, then teach, then ask. Teaching is one method, fit, and asking is another, predict. The same two calls work for every kind of model in the library, so once you know them for one model you know them for all.
fit(X, y) takes two things. X holds the features: one row per example and one column per feature, such as how many months someone has been a customer and what they pay each month. y holds the label of each row, the known answer, such as "Yes" if that customer left and "No" if they stayed. The i-th entry of y belongs to the i-th row of X. During fit the model looks for a rule that links the features to the answers and stores what it found inside itself.
predict(X_new) then takes rows with the same feature columns but no answers, and returns one answer per row, always one of the answers the model saw in y. The model does not learn again when it predicts: a fitted model answers as many new rows as you give it.
- Training rows features X and labels y
- New rows features only
- Fitted model holds the learned rule
- Predicted answers one per new row
- Training rows to Fitted model: fit(X, y)
- New rows to Fitted model: predict(X_new)
- Fitted model to Predicted answers
Two practical rules come with the pattern. The rows passed to predict must have the same feature columns as the rows passed to fit: when X is a pandas table, the model remembers the column names and checks them. And the decision tree on this page computes with numbers only, so every feature column you give it must hold numbers; a column of text such as a contract name has to be left out or turned into numbers first.
True or false?
A fitted model has to be trained again before each call to predict.
False. fit stores what the model learned. After that, predict can answer new rows any number of times without training again.
If y holds the words Yes and No, predict also returns Yes and No.
True. A classifier predicts one of the answers it was fitted on, in the same form.
A decision tree: yes-or-no questions about the features
A decision tree is a model made of questions. Each question looks at one feature and compares it with a number, such as "has this customer been here 10.5 months or less?". A row answers it with yes or no and goes down the matching branch to the next question, until it reaches an end point called a leaf. Each leaf holds an answer, and that answer is the prediction for every row that ends there.
Take ten past customers with two features, the months they have been a customer and their monthly charge, and the known answer: did they leave?
| Customer | Months | Monthly charge | Left? |
|---|---|---|---|
| A | 2 | 80 | Yes |
| B | 3 | 95 | Yes |
| C | 4 | 30 | No |
| D | 5 | 70 | Yes |
| E | 8 | 90 | Yes |
| F | 13 | 85 | No |
| G | 20 | 40 | No |
| H | 30 | 100 | No |
| I | 45 | 60 | No |
| J | 60 | 75 | No |
Fitted on these rows, a tree learns two questions. The first splits the newer customers from the long-standing ones. Among the newer ones, a second question about the monthly charge separates the one who stayed from the four who left.
- months ≤ 10.5? 10 customers, 4 left
- monthly charge ≤ 50? 5 customers, 4 left
- Stays 5 customers, none left
- Stays 1 customer, stayed
- Leaves 4 customers, all left
- months ≤ 10.5? to monthly charge ≤ 50?: yes
- months ≤ 10.5? to Stays: no
- monthly charge ≤ 50? to Stays: yes
- monthly charge ≤ 50? to Leaves: no
A new customer with 6 months and a charge of 85 answers yes to the first question and no to the second, so the tree predicts that they leave. A customer with 40 months answers no to the first question and lands on "stays" straight away, whatever they pay. Each leaf predicts the most common answer among the training rows that reached it.
This is what makes a small tree easy to trust: every prediction comes with its reason, a short chain of yes-or-no answers anyone can check by hand.
In scikit-learn the model is DecisionTreeClassifier, and the function export_text writes its questions out as text. The code below fits a tree on the ten customers and predicts the two new ones. The pandas call pd.DataFrame builds a table from a dictionary of columns, and train[["months", "monthly_charge"]] picks the feature columns from it:
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text
train = pd.DataFrame({
"months": [2, 3, 4, 5, 8, 13, 20, 30, 45, 60],
"monthly_charge": [80, 95, 30, 70, 90, 85, 40, 100, 60, 75],
"left": ["Yes", "Yes", "No", "Yes", "Yes", "No", "No", "No", "No", "No"],
})
X = train[["months", "monthly_charge"]]
y = train["left"]
model = DecisionTreeClassifier(max_depth=3, random_state=0)
model.fit(X, y)
new = pd.DataFrame({"months": [6, 40], "monthly_charge": [85, 85]})
print(model.predict(new))
print(export_text(model, feature_names=list(X.columns)))['Yes' 'No']
|--- months <= 10.50
| |--- monthly_charge <= 50.00
| | |--- class: No
| |--- monthly_charge > 50.00
| | |--- class: Yes
|--- months > 10.50
| |--- class: NoEach question prints twice, once for the yes branch (<=) and once for the no branch (>), and the indentation shows how deep it sits. A line that starts with class: is a leaf and its answer. Without feature_names, the questions would name the columns feature_0, feature_1 and so on.
How the tree chooses each question
The tree is not given its questions; it builds them from the training rows. At each step it tries every feature and every possible threshold, and keeps the one question that separates the answers most cleanly: after the split, each side should hold mostly one answer.
To compare questions, the tree needs a number for how mixed a group is. scikit-learn uses the Gini impurity by default. For a group with two possible answers, where a share \( p \) of the rows has one answer:
Gini impurity, two answers 0 when every row has the same answer, 0.5 for an even mix
Before any question, the ten customers above form one group: 4 of 10 left, so \( p = 0.4 \) and the impurity is \( 2 \times 0.4 \times 0.6 = 0.48 \). A question splits them into two groups. To score it, the tree takes the impurity of each group, multiplies it by that group's share of the rows, and adds the two results. The lower the score, the cleaner the split. Here are three of the questions the tree tries at the start:
| Question | Yes side | No side | Weighted impurity |
|---|---|---|---|
| months ≤ 10.5 | 5 rows: 4 left, 1 stayed | 5 rows: 0 left, 5 stayed | 0.16 |
| months ≤ 6.5 | 4 rows: 3 left, 1 stayed | 6 rows: 1 left, 5 stayed | 0.32 |
| monthly charge ≤ 77.5 | 5 rows: 1 left, 4 stayed | 5 rows: 3 left, 2 stayed | 0.40 |
For "months ≤ 10.5", the yes side has impurity \( 2 \times 0.8 \times 0.2 = 0.32 \) and the no side is pure, so the score is \( 0.5 \times 0.32 + 0.5 \times 0 = 0.16 \). No other question on these rows scores lower, so it becomes the first question. The tree then repeats the same search inside each group: the yes side is still mixed and gets its own question, while the no side is already pure and becomes a leaf.
Three details follow from this search. The thresholds lie halfway between two values that occur in the data: 10.5 sits between 8 and 13 months, which is why a tree on whole numbers prints thresholds like 10.50. The search is greedy: it picks the best question for the current step and never goes back, so the finished tree is a good tree but not guaranteed to be the best possible one. And when two questions tie, the tree breaks the tie at random, so passing a fixed random_state gives the same tree on every run.
True or false?
The thresholds in a decision tree are always values that appear in the training data.
False. Each threshold lies halfway between two neighbouring values, such as 10.5 between 8 and 13.
A question scores well when each side of the split holds mostly one answer.
True. The tree keeps the question with the lowest weighted impurity, which is the cleanest separation of the answers.
The depth limit keeps a tree readable
Left alone, a tree keeps asking questions until every leaf is pure or too small to split. On a large table that can mean hundreds of questions, and a tree that size can no longer be read or checked by hand. The setting max_depth limits how many questions deep the tree may grow. Its default, None, means no limit.
The depth counts levels, not questions in total. With max_depth=3, each row answers at most three questions on its way to a leaf, but the tree can hold up to 7 questions (1 at the top, 2 below it, 4 below those) and up to 8 leaves. Each extra level can double the number of leaves:
A limit is a ceiling, not a target: the tree on the ten customers was allowed depth 3 but stopped at depth 2, because both groups under the second question were already pure. scikit-learn's own guide suggests starting with max_depth=3 to get a feel for how a tree fits the data. When a leaf is reached early because of the limit, it may still hold a mix of answers, and it predicts the most common one.
True or false?
A tree with max_depth=3 contains at most three questions in total.
False. It asks each row at most three questions, but the whole tree can hold up to 7 questions and 8 leaves.
A leaf reached because of the depth limit can hold training rows with different answers.
True. The limit stops splitting before the group is pure; the leaf then predicts the most common answer in it.
Accuracy: the share of right answers
Once a model predicts, you need a number that says how good the predictions are. The simplest is accuracy: the share of predictions that match the true answer.
Accuracy
If a model answers 10 rows and 8 answers are right, its accuracy is 0.8, or 80 percent. It runs from 0 (every answer wrong) to 1 (every answer right). In scikit-learn, accuracy_score(y_true, y_pred) computes it from the true answers and the predictions, in that order. A classifier's score(X, y) method does both steps in one call: it predicts the rows and returns the same number.
Accuracy only tells you something about new rows when it is measured on rows the model did not learn from, such as validation rows held out before training. On its own training rows, the tree above scores 1.0, because every training customer ends in a pure leaf. A tree can always repeat its training answers; whether it is right about other customers is the real question.
Accuracy counts every mistake the same. Predicting "stays" for a customer who leaves and predicting "leaves" for a customer who stays each cost one right answer, which is part of why accuracy needs something to compare against.
A baseline: the bar a model must clear
An accuracy of 0.8 sounds good, but whether it is good depends on the data. Suppose 7 of every 10 customers stay. A "model" that never looks at the features and always answers "stays" is then right 7 times in 10, an accuracy of 0.7, without learning anything. That rule is the baseline: it always gives the most common answer of the training rows, and a real model is only worth its questions if it scores clearly above it.
Here are ten validation customers that neither model has seen. The tree from above answers by its two questions; the baseline answers "No" for everyone, because "No" was the most common training answer.
| Months | Monthly charge | Really left? | Tree says | Baseline says |
|---|---|---|---|---|
| 3 | 90 | Yes | Yes | No (wrong) |
| 7 | 75 | Yes | Yes | No (wrong) |
| 25 | 95 | Yes | No (wrong) | No (wrong) |
| 6 | 35 | No | No | No |
| 9 | 65 | No | Yes (wrong) | No |
| 15 | 55 | No | No | No |
| 40 | 80 | No | No | No |
| 52 | 45 | No | No | No |
| 18 | 70 | No | No | No |
| 33 | 100 | No | No | No |
The tree makes two mistakes and the baseline three, so the tree clears the bar by 0.1. Without the baseline, 0.8 would be hard to judge. If 9 of 10 customers stayed, the baseline would reach 0.9 and the same 0.8 would be worse than doing nothing. The baseline's accuracy is the share of its one answer in the rows being scored, so it changes with the data and has to be measured each time.
scikit-learn has the baseline as a model of its own, DummyClassifier. With strategy="most_frequent" it learns the most common answer of the y passed to fit and predicts it for every row. Its default strategy, "prior", predicts the same answers. Because it follows the same fit and predict pattern, it is scored exactly like the tree. Given training rows X_train, y_train, validation rows X_val, y_val and a tree created as before:
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)
tree.fit(X_train, y_train)
print(accuracy_score(y_val, baseline.predict(X_val)))
print(accuracy_score(y_val, tree.predict(X_val)))True or false?
A model with an accuracy of 0.90 is useful whatever the data.
False. If 92 percent of the rows share one answer, always giving that answer scores 0.92 and beats the model.
The most-frequent baseline gives the same answer for every row, whatever its features.
True. It ignores the features entirely and repeats the most common answer of its training labels.