Live build, 12–13 Dec: turn an app agentic, no fee. Register →

Courses / Data Science & ML with AI

Session 7 of 8

Decision Trees, Random Forests and Gradient Boosting

Notes

Decision Trees, Random Forests and Gradient Boosting: Cross-Validation and Hyperparameter Tuning

Course: Data Science & ML with AI

Before you start

You need Python 3 with pandas and scikit-learn installed (pip install pandas scikit-learn). The examples use a dataset that ships inside scikit-learn, so there is nothing to download, no account and no API key. You should know what a train/test split is and why a model is scored on rows it did not learn from, and what accuracy means; this chapter restates what it needs. No statistics background is assumed.

Keep one question in mind while you read: I have three kinds of model and a dozen settings for each. How do I pick one without fooling myself with a lucky score? By the end you will be able to read a decision tree, explain why a forest of trees usually beats one tree, use cross-validation to compare models, run a grid search that leaves the test rows alone, and catch an AI assistant that chose its settings by peeking at them.

Summary

A decision tree predicts by asking a chain of yes/no questions about the input columns, and an unrestricted tree can fit its training rows perfectly while generalising worse, which is overfitting. Random forests average many trees trained on random variations of the data, and gradient boosting builds small trees one after another, each correcting the errors of those before it, so both are ensembles that usually beat a single tree. A score from one train/test split depends on which rows happened to land in the test set, so models are compared with cross-validation, which repeats the split several times and reports the average and the spread. Hyperparameters, the settings a person chooses before training, are tuned with a grid search that scores every combination by cross-validation on the training rows only, which keeps the test rows for one final check. This chapter works through all of it on the bundled wine dataset and ends by checking an AI assistant’s proposed search against cross-validated scores.

Key concepts

Term Definition
Decision tree A model that predicts by asking a sequence of yes/no questions about the input columns, each answer leading to another question or to a final label.
Split and leaf A split is one yes/no question about one column, such as “is the colour intensity at most 3.82?”. A leaf is an end point of the tree that gives a prediction.
Tree depth The number of questions on the longest path from the first question to a leaf.
Overfitting Fitting the training rows so closely, noise included, that the model does worse on rows it has not seen.
Ensemble A model built from many smaller models whose predictions are combined, such as a forest of trees.
Random forest An ensemble of decision trees, each trained on a random sample of the rows and considering a random subset of the columns at each split, whose predictions are averaged.
Gradient boosting An ensemble that adds small trees one at a time, each trained to correct the errors left by the trees before it.
Hyperparameter A setting chosen by a person before training, such as the maximum depth of a tree or the number of trees. It is not learned from the data.
Cross-validation Splitting the training rows into k parts (folds), training on k - 1 of them and scoring on the remaining one, k times, so every row is used for scoring once.
Fold One of the k parts the training rows are divided into during cross-validation.
Standard deviation (of scores) A measure of how much the k fold scores differ from their mean. A large one means the score is not stable.
Grid search Trying every combination of listed hyperparameter values and scoring each one by cross-validation to find the best.
Test set (hold-out) Rows set aside before any tuning and used once, at the end, to estimate how the chosen model does on new rows.

Explanations

The failure, before the explanation

An analyst compares two wine classifiers. She splits her 178 labelled wines once, trains a decision tree, and scores it on the 54 wines she held back: 96.3% correct. A colleague repeats her work with a different random split, and gets 90.7% for the very same kind of tree. A third person gets 94.4%. Nobody made an error. The score depends on which wines landed in the test set, so a claim like “the tree is 96.3% accurate” is a statement about one split, not about the tree.

She makes a second mistake while tuning: she tries twelve settings, scores each on the held-back wines, and reports the best score as what the model will achieve. The settings were chosen by looking at the test rows, so the test rows can no longer say how the model performs on new ones. You will reproduce the instability in the section on cross-validation, and the second mistake in the section on an AI assistant’s search.

A decision tree is a chain of yes/no questions

Think of the game of twenty questions. To work out which animal you are thinking of, each question splits the candidates into two groups (“does it have fur?”), and the answer narrows the next question. A decision tree is the same game played with columns: at each step it picks one column and one cut-off that best separates the labels, asks “is this value at or below the cut-off?” and follows the answer to the next question until it reaches a leaf, which gives the label. A second picture is a flow chart on a wall in a pharmacy: start at the top, answer a question, follow an arrow, and the box you land in tells you what to do.

The wine dataset in scikit-learn describes 178 wines, each with 13 chemical measurements, and the target is which of three classes a wine belongs to. Its documentation lists 59, 71 and 48 samples in the three classes. Load it:

from sklearn.datasets import load_wine

wine = load_wine(as_frame=True)
X = wine.data
y = wine.target

print(X.shape)
print(wine.target_names.tolist())
print(y.value_counts().sort_index())
print(list(X.columns[:5]))
print(X.isna().sum().sum())
(178, 13)
['class_0', 'class_1', 'class_2']
target
0    59
1    71
2    48
Name: count, dtype: int64
['alcohol', 'malic_acid', 'ash', 'alcalinity_of_ash', 'magnesium']
0

Read it. There are 178 rows, 13 feature columns and no missing values. The three classes are named class_0, class_1 and class_2 and hold 59, 71 and 48 wines. This is a multi-class problem, three labels rather than two, and everything from the previous chapter about reading mistakes still applies. Now split the rows once and fit an unrestricted tree:

from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=42
)
print(X_train.shape, X_test.shape)

tree = DecisionTreeClassifier(random_state=42).fit(X_train, y_train)
print("train accuracy:", tree.score(X_train, y_train))
print("test accuracy:", round(tree.score(X_test, y_test), 3))
print("depth:", tree.get_depth(), "leaves:", tree.get_n_leaves())
(124, 13) (54, 13)
train accuracy: 1.0
test accuracy: 0.963
depth: 4 leaves: 8

The tree classifies every one of the 124 training wines correctly (accuracy 1.0) using eight leaves and a longest path of four questions, and gets 96.3% of the 54 test wines right. random_state=42 makes the choice reproducible, since scikit-learn permutes the columns randomly at each split.

You can read a tree, which is one reason people like them. The scikit-learn guide calls trees a “white box” model: the reasoning behind a prediction can be explained with simple yes/no logic. Here is a tree limited to two questions in a row, printed with export_text:

from sklearn.tree import export_text

small = DecisionTreeClassifier(max_depth=2, random_state=42).fit(X_train, y_train)
print(export_text(small, feature_names=list(X.columns)))
|--- color_intensity <= 3.82
|   |--- ash <= 3.00
|   |   |--- class: 1
|   |--- ash >  3.00
|   |   |--- class: 0
|--- color_intensity >  3.82
|   |--- flavanoids <= 1.58
|   |   |--- class: 2
|   |--- flavanoids >  1.58
|   |   |--- class: 0

Read it from the top. The first question is whether color_intensity is at most 3.82. If yes, ask whether ash is at most 3.00: yes means class 1, no means class 0. If the colour intensity is above 3.82, ask whether flavanoids is at most 1.58: yes means class 2, no means class 0. Four leaves, two questions deep. A wine with a colour intensity of 5.0 and flavanoids of 1.2 goes down the second branch and is labelled class 2.

Why a deep tree overfits

Back to the pharmacy flow chart. A chart with a few boxes is easy to follow and works for most customers. A chart that keeps adding boxes until every customer in last year’s file has a box of their own would “work” perfectly on last year’s file, and would be nonsense for the next customer. A tree that grows until its leaves are pure does exactly that. This is overfitting: the tree has fitted quirks of its training rows rather than a pattern that carries over. The scikit-learn guide notes that trees can build over-complex trees that do not generalise well, and lists limiting the maximum depth and the minimum samples in a leaf as ways to control that. Compare four depth limits:

print("max_depth  train  test")
for depth in [1, 2, 3, 5]:
    t = DecisionTreeClassifier(max_depth=depth, random_state=42).fit(X_train, y_train)
    print(f"{depth:>9}  {t.score(X_train, y_train):.3f}  {t.score(X_test, y_test):.3f}")
max_depth  train  test
        1  0.661  0.611
        2  0.935  0.889
        3  0.992  0.963
        5  1.000  0.963

A tree of depth 1 asks a single question and gets 61.1% of test wines right: it is too simple, an underfit. Depth 2 is better, depth 3 reaches 96.3%, and depth 5 improves only the training score, which is already 1.000. On this dataset the extra depth buys nothing on unseen rows. A hyperparameter like max_depth is set by you, not learned from the rows, and the right value has to be found by trying values and scoring them on rows the model did not train on. The question is which rows to score on, and the next section shows why the single test set is a poor answer.

Why one test split is not enough

Return to the analyst’s three colleagues. Re-run the same tree on five different random splits of the same 178 wines:

for seed in [0, 1, 2, 3, 4]:
    Xa, Xb, ya, yb = train_test_split(X, y, test_size=0.3, stratify=y, random_state=seed)
    t = DecisionTreeClassifier(random_state=42).fit(Xa, ya)
    print("split", seed, "test accuracy", round(t.score(Xb, yb), 3))
split 0 test accuracy 0.944
split 1 test accuracy 0.944
split 2 test accuracy 0.944
split 3 test accuracy 0.907
split 4 test accuracy 0.963

The same kind of model scores between 0.907 and 0.963, depending only on the split. With 54 test wines, each wine is worth about 1.9 percentage points, so moving a handful of hard wines between the training and test sets moves the score visibly. A single split is a single sample of the model’s performance, and a small one.

Cross-validation: five mock exams instead of one

A student who sits one mock exam and scores 70% does not know whether the paper was easy or the student was lucky. A student who sits five different papers and averages the marks, noting how far the marks vary, knows far more. Cross-validation applies this to models. Take the training rows and cut them into five parts called folds. Train on four folds, score on the fifth, then rotate so each fold is the exam once. The result is five scores. The scikit-learn guide says that when cross_val_score is given a whole number as cv and the model is a classifier, it uses stratified k-fold, which keeps the class shares in each fold close to those of the whole. The test set stays untouched: this process uses only the training rows.

from sklearn.model_selection import StratifiedKFold, cross_val_score

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(DecisionTreeClassifier(random_state=42), X_train, y_train, cv=cv)
print(scores.round(3))
print("mean", round(scores.mean(), 3), "std", round(scores.std(), 3))
[0.92  0.88  0.96  0.84  0.792]
mean 0.878 std 0.059

Read it. The five folds scored from 0.792 to 0.96, with a mean of 0.878 and a standard deviation of 0.059. The mean is the estimate; the standard deviation says how much the score moves. As a rule of thumb, a gap between two models smaller than that spread is too small to call from these folds; a formal comparison would need a paired statistical test, which is beyond this chapter.

Try it: compute the mean of the five printed scores by hand, (0.92 + 0.88 + 0.96 + 0.84 + 0.792) / 5, and check it against 0.878.

Random forests and gradient boosting: many trees instead of one

A single tree is unstable: the guide notes that small variations in the data can produce a completely different tree, and that using trees inside an ensemble reduces the problem. An ensemble combines many models. Two pictures help. A random forest is a committee of independent voters: each tree is trained on a random sample of the rows and, at each split, considers a random subset of the columns, so the trees make different mistakes, and averaging their votes cancels many of them out. Gradient boosting is a tutoring sequence: the first small tree makes a rough prediction, the second is trained to fix the errors the first left, the third fixes what remains, and so on. Forests build their trees side by side; boosting builds them one after another.

Compare the three on the same folds, again using only the training rows:

from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier

models = {
    "decision tree": DecisionTreeClassifier(random_state=42),
    "random forest": RandomForestClassifier(random_state=42),
    "gradient boosting": GradientBoostingClassifier(random_state=42),
}
for name, model in models.items():
    s = cross_val_score(model, X_train, y_train, cv=cv)
    print(f"{name:<18}{s.mean():.3f} +/- {s.std():.3f}")
decision tree     0.878 +/- 0.059
random forest     0.976 +/- 0.032
gradient boosting 0.903 +/- 0.049

The forest, at 0.976, is about ten points above the single tree, a gap larger than either spread, so the improvement is probably real. Gradient boosting at 0.903 is only 2.5 points above the tree, with spreads of 0.049 and 0.059, so on these folds you cannot say it is better. Boosting is not automatically stronger than a forest; which one wins depends on the data and on the settings.

Two forests can differ in how deep their trees may grow, and in the smallest number of wines a leaf may hold. These are hyperparameters. A grid search is the systematic way to compare settings: list the values to try for each, build every combination, score each combination by cross-validation, and keep the best. It is like testing every pairing of two bread flours and three oven temperatures rather than guessing one. GridSearchCV does it, and by default it then refits the best setting on all the rows it was given. It does this on the training rows only, so the test set stays unseen.

import pandas as pd
from sklearn.model_selection import GridSearchCV

param_grid = {"max_depth": [1, 2, 4, None], "min_samples_leaf": [1, 5, 10]}
search = GridSearchCV(RandomForestClassifier(random_state=42), param_grid, cv=cv)
search.fit(X_train, y_train)

table = pd.DataFrame(search.cv_results_)[
    ["param_max_depth", "param_min_samples_leaf", "mean_test_score", "std_test_score"]
]
print(table.round(3).to_string(index=False))
print("best:", search.best_params_, round(search.best_score_, 3))
print("fits:", len(table) * 5, "(", len(table), "settings x 5 folds )")
param_max_depth  param_min_samples_leaf  mean_test_score  std_test_score
              1                       1            0.968           0.030
              1                       5            0.968           0.030
              1                      10            0.968           0.030
              2                       1            0.976           0.032
              2                       5            0.976           0.032
              2                      10            0.976           0.032
              4                       1            0.976           0.032
              4                       5            0.976           0.032
              4                      10            0.976           0.032
           None                       1            0.976           0.032
           None                       5            0.976           0.032
           None                      10            0.976           0.032
best: {'max_depth': 2, 'min_samples_leaf': 1} 0.976
fits: 60 ( 12 settings x 5 folds )

Read it. Four depths times three leaf sizes make 12 settings, and each is trained five times, so the search runs 60 fits; the cost multiplies with every value you add to the grid. Nine of the twelve settings tie at 0.976, and the three depth-1 settings score 0.968, 0.8 points lower, which is smaller than the standard deviation of 0.030 across folds. Search reports one setting as best, here depth 2, but the table says the data cannot distinguish nine of them. The honest summary is “a forest with these settings scores about 0.976 in cross-validation, give or take 0.03”.

Only now is the test set used, once, on the model the search chose:

print("test accuracy of the chosen model:", round(search.score(X_test, y_test), 3))
test accuracy of the chosen model: 0.981

The refitted forest classifies 53 of the 54 held-back wines correctly. Because the test wines had no part in choosing the setting, 0.981 is a fair estimate, if a rough one: one test wine is worth 1.9 percentage points. If you tune again after seeing this number, the test set has become a second training set, and you need a fresh one.

With AI: check an assistant’s search against cross-validated scores

An AI assistant can propose a grid and write the search code quickly. It does not know which of your rows are test rows unless the code makes that clear, and it may choose the quickest way to get a number. Suppose you ask it: “Propose a search grid for a random forest on the wine data and tell me which setting is best.” It replies:

Assistant output

I tried every combination of max_depth in [1, 2, 4, None] and min_samples_leaf in [1, 5, 10] and scored each model on the held-out test wines:

from itertools import product

results = []
for depth, leaf in product([1, 2, 4, None], [1, 5, 10]):
    model = RandomForestClassifier(max_depth=depth, min_samples_leaf=leaf, random_state=42)
    model.fit(X_train, y_train)
    results.append((round(model.score(X_test, y_test), 3), depth, leaf))

for row in sorted(results, key=lambda r: -r[0])[:3]:
    print(row)

The best setting is max_depth=4, min_samples_leaf=1 with a test accuracy of 1.0, so the tuned model is perfect. Expect 100% accuracy in use.

Run its code and it prints what it claims:

(1.0, 4, 1)
(1.0, None, 1)
(0.981, 2, 1)

The code is correct and the conclusion is not. The tests you were taught are: was the setting chosen by cross-validation on the training rows, and is the winner’s lead larger than the spread? Try to find the problems yourself using the cross-validation table above, then compare.

Check your work. There are three flaws:

  1. It chose the setting on the test rows. All twelve models were scored on the 54 test wines and the best was picked, which is the analyst’s second mistake. Those wines can no longer give an independent estimate of how the chosen model will do on new ones.
  2. The lead is one row. One test wine is worth 0.019, and (1.0, 4, 1) is a single wine ahead of (0.981, 2, 1). The cross-validation table you computed on the training rows shows nine settings tied at 0.976 with a standard deviation of 0.032, and the assistant’s “best” depth of 4 is one of those nine. The data does not say that 4 beats 2 or None.
  3. “Expect 100%” has no support. A score of 1.0 on 54 wines, reached after picking the maximum of twelve tries, says little about new wines. The cross-validated estimate, 0.976 give or take 0.03, is the figure to report, and GridSearchCV scored the model it chose at 0.981 on the test rows once, without peeking.

The correct workflow has the same shape every time: tune with cross-validation on the training rows, look at the spread, and score the test set once.

Three situations you will meet, and what they mean for your work

  1. A colleague tells you their tuned model reached 99% on the test set, and mentions that they ran the search many times, each time adjusting the grid after looking at the test score.
  2. Two models differ by half a percentage point in cross-validation, and the team wants to ship the more complicated one.
  3. A single decision tree gives different top questions each time the data is refreshed with a few new rows, and the business team asks why the “rules” keep changing.
What you see What it means What to do
Tuning repeated against the test set (situation 1) The test set has become part of training, so its score is optimistic Tune with cross-validation on training rows; keep a fresh test set for a final check
A difference smaller than the spread (situation 2) The data cannot separate the models Prefer the simpler or cheaper model, or gather more rows
Rules that change with a few new rows (situation 3) Single trees are unstable Use a forest, which averages many trees, and trust its averaged vote rather than one tree’s questions

Flashcards

Say the answer aloud before revealing it. Speaking it is what exposes the gaps that reading past a written answer hides.

How does a decision tree make a prediction?

It asks a chain of yes/no questions, each about one column and one cut-off, and follows the answers down to a leaf, which gives the predicted label.

What is overfitting, and how did it show up with the wine tree?

It is fitting the training rows so closely that the model does worse on new rows. The unrestricted tree scored 1.0 on training wines, and limiting the depth to 3 already reached the same 0.963 on test wines.

What is a hyperparameter, and give two for a random forest?

A setting chosen before training, not learned from the rows. Two examples are max_depth, the deepest question chain a tree may use, and n_estimators, the number of trees in the forest.

Why is one train/test split an unreliable score?

The score depends on which rows land in the test set. The same tree scored between 0.907 and 0.963 on five different splits of the wine data.

How does k-fold cross-validation work?

It divides the training rows into k folds, trains on k - 1 of them and scores on the held-out fold, and repeats k times so each fold is the scoring set once. You report the mean and the standard deviation.

What does the standard deviation of the fold scores tell you?

How much the score moves from fold to fold. As a rule of thumb, a gap between two models that is smaller than the spread is not good evidence that one model is better.

How does a random forest differ from gradient boosting?

A forest trains many trees independently on random samples and averages them. Boosting trains small trees in sequence, each one fitted to correct the errors of the trees before it.

What does a grid search do, and what does it cost?

It scores every combination of the listed hyperparameter values by cross-validation. With 12 settings and 5 folds it ran 60 fits, and the cost multiplies with every value added to the grid.

Why must the test set stay out of the grid search?

If settings are chosen by their test score, the test rows have influenced the model, so the final score is optimistic. The test set is used once, on the model the search chose.

Why was the assistant's "test accuracy of 1.0" not trustworthy?

It was the best of twelve scores taken on the test rows, a lead of one wine, while cross-validation on the training rows showed nine settings tied at 0.976 with a standard deviation of 0.032.

Model answer

The question: “You have a classification problem and three candidate models. How do you choose one and set its hyperparameters without fooling yourself?” A strong answer hits five beats, in this order:

  1. Hold out a test set — split it off first and leave it alone.
  2. Cross-validate to compare — score each model by k-fold on the training rows.
  3. Search settings — grid search the hyperparameters, scoring by cross-validation.
  4. Read the spread — treat gaps smaller than the standard deviation as ties.
  5. Test once — score the chosen model on the test set a single time.

“First I would split off a test set and not touch it. On the training rows I would compare the candidate models by k-fold cross-validation, because a single split’s score depends on which rows landed in the test set. For the best candidates I would run a grid search over their hyperparameters, again scored by cross-validation on the training rows, remembering that the number of fits is the number of settings times the folds. Then I would look at the standard deviation, not only the mean: if two settings differ by less than the spread I treat them as tied and prefer the simpler one. Only at the end would I score the chosen model on the test set, once, and report that with the cross-validated estimate. If I tuned again after seeing the test score, I would need a new test set.”

Skip any of these five and the answer is incomplete. Without the test set there is no honest final number. Without cross-validation a lucky split picks the model. Without the search the settings are guesses. Without reading the spread a one-wine lead looks like a win. Without testing once, the test score is another training score; that is the beat that is easiest to forget.

Why this matters

  • Choosing models honestly. Cross-validated scores with their spread are the usual way to compare candidates, and a gap smaller than the spread is a reason to pick the cheaper model.
  • Reporting a number you can defend. A score chosen from many tries on the test rows is optimistic; one test-set check after tuning is not.
  • Starting with strong defaults. A random forest with its default settings often gives a strong first result, as it did here at 0.976 in cross-validation, so you know what a tuned model must beat.
  • Reviewing AI-written search code. An assistant can write a grid search that quietly uses the test rows. Checking where the scores come from is the quickest way to find it.

After this unit

You can now choose between supervised models and tune them fairly. Your assignment: on the breast cancer dataset from the classification chapter (load_breast_cancer), hold back a test set, compare a decision tree, a random forest and gradient boosting with five-fold cross-validation on the training rows, tune the winner with a small grid, and score the test set once. Check yourself with the questions in this chapter: did any score use test rows before the end, and is the winner’s lead larger than the spread? The next chapter leaves labels behind: k-means clustering groups rows when there is no target column, and principal component analysis (PCA) shrinks many columns to a few, together with a way to check what a cluster means.

Quiz

Answers are not marked on this page yet. Work through the questions and check the written ones against the criteria printed with each question. The answer key is kept back for now.

Quiz — Decision Trees, Random Forests and Gradient Boosting: Cross-Validation and Hyperparameter Tuning

Instructions: Eight multiple-choice questions. Pick one option per question. Work closed-book, then compare your letters with the answer key, which is held separately and holds the reasons.


1. [recall] What is a hyperparameter?

a) A number that the model learns from the training rows, such as a split cut-off b) A column in the table that holds the label the model is meant to predict c) A score taken on the test rows and used to compare two or more models d) A setting chosen by a person before training, such as the maximum tree depth


2. [application] A five-fold cross-validation run returns the scores 0.90, 0.80, 0.85, 0.95 and 0.90. What is the mean score?

a) 0.88, found by adding the five scores and dividing the total by five b) 0.90, because it is the value that appears most often among the folds c) 0.95, because the best fold shows what the model is really able to do d) 0.15, because the folds range from 0.80 up to a best score of 0.95


3. [scenario] Model A scores 0.912 with a standard deviation of 0.040 across five folds, and model B scores 0.920 with 0.038 on the same folds. Model B needs ten times the computing time. Which choice is best supported?

a) Model B, because a higher mean score is always the better evidence available b) Either one, because cross-validation cannot tell you anything about two models c) Model A, as the gap is much smaller than the spread, and A is cheaper to run d) Neither one, until a third kind of model has been scored on the same folds


4. [recall] Which description fits a random forest?

a) One deep tree that keeps asking questions until each leaf holds only one row b) Many trees, each trained on a random sample of rows, with their votes averaged c) Small trees added one at a time, each one fitted to fix the errors left before it d) A single straight line fitted through the rows, with a cut-off applied to its output


5. [application] A grid search uses max_depth in [2, 4, 6] and n_estimators in [50, 100], with five-fold cross-validation. How many times does it train a model while searching?

a) 30, which is 3 depths times 2 forest sizes times 5 folds in all b) 6, which is 3 depths times 2 forest sizes, one per setting c) 10, which is 2 forest sizes times 5 folds for the best depth only d) 15, which is 3 depths times 5 folds, since forest size is fixed


6. [scenario] An assistant scores twelve hyperparameter settings on the test rows, picks the one with a test accuracy of 1.0, and says to expect 100% accuracy in use. What is wrong with this?

a) The accuracy is too high, because no model can ever be right on every test row b) Twelve settings are too few, and a larger grid would have shown a lower score c) A test set should be used to train a model, but it was left out of it d) The setting was chosen on those test rows, so that result is not a fair test


7. [application] A learner fits a decision tree with no depth limit. It scores 1.000 on its training rows and 0.78 on rows it has not seen. What does this most likely show?

a) The tree is underfitting, because it needs more questions to find a pattern b) The tree is overfitting, because it has fitted its training rows too closely c) The test rows are broken, since a good model scores the same on any rows d) The tree is ready to deploy, because its training score is the highest possible


8. [scenario] You score a decision tree on a held-back set and get 0.963. A colleague trains the same kind of tree on the same data with a different random split and gets 0.907. What is the most likely explanation?

a) One of you made a coding error, since the same kind of tree must give one score b) The tree learned in a random way, so it changed its mind about the same rows c) The two splits put different rows in the test set, and each is a small sample d) The library was out of date, so the two scores came from two different formulas

Want help building this with someone?

Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.

Ask about mentor-led training

TechEazy Consulting training material — not affiliated with or endorsed by pandas, scikit-learn or any other project or company named in this course.