We will use housing prices to investigate a question from last lecture: does a great training score mean we have a useful model? We will build a first model, question how we evaluated it, and improve our workflow together.
By the end, you should be able to distinguish training, validation, and test performance, recognize underfitting and overfitting, and use cross-validation to select a model configuration.
The opening steps are deliberately naive: we explore and fit on all the data before introducing splitting. By the end, we will explain what we would do differently on a fresh project.
Setup and data
Run cells in order with the repository’s Python environment selected as the kernel. From the repository root, start Jupyter with uv run --locked jupyter lab, then open book/demo-chapter-03-ml-fundamentals.ipynb. Data paths work from either the repository root or book/. If using a downloaded notebook separately, place its required files in a data/ folder beside it.
Use data/kc_house_data.csv, included in the repository.
Class route: Work through Activities 1–5 in order. The feature-importance exploration at the end is optional.
Predict before running a comparison, Try the coding step, and Discuss what the output supports. Code labelled “Worked solution” is expandable on the rendered page. In Jupyter, try writing your answer before reading that cell.
Rendered pages show saved outputs; run the notebook locally to try your own changes. General environment and download guidance is on the Demos page.
Show imports
from pathlib import Pathimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.dummy import DummyRegressorfrom sklearn.model_selection import cross_validate, train_test_splitfrom sklearn.tree import DecisionTreeRegressor, plot_treeRANDOM_STATE =123
Activity 1: Understand the data
The King County housing dataset contains records of house sales, including sale prices and information about each property. The data are available from House Sales in King County, USA.
Imagine that we want to estimate a property’s sale price from its recorded characteristics.
What does one example represent? What is the target?
Is this a classification problem or a regression problem?
What would it mean for this model to generalize?
Inspect the data
Before building anything, let’s get to know these house sales.
Try: Take a first look. How many rows and columns do we have? What do the summaries and missing-value counts tell us?
We’re using the full dataset in this opening demonstration. On a fresh project, we would reserve test data before EDA. Keep track of this shortcut—we’ll return to it at the end.
# How many data points do we have? housing_df.shape[0]
21613
# What are the columns in the dataset? housing_df.columns
For today, we’ll omit id, date, and zipcode to focus on evaluation. This is a teaching simplification, not a claim that dates or location are useless. We’ll revisit feature preparation later.
Separate inputs and target
Try: create X without the target and the three omitted columns, and create y from price. Why must price stay out of X?
Worked solution: Separate the input columns
X = housing_df.drop(columns = ['id', 'date', 'zipcode', 'price'])
Worked solution: Extract the target
y = housing_df['price']
Activity 2: Establish a baseline
Predict: if you had to predict one price for everyone, what would you choose?
Try: fit a DummyRegressor on X, y, inspect a few predictions, and score it on those same data. We have no validation set yet: this is a training score.
For these regressors, .score() returns R², not accuracy. Higher is better: 1 is perfect; 0 matches predicting the mean target of the evaluated data; negative values are possible. A baseline fitted on another subset need not score exactly 0 on held-out data.
Worked solution: Fit and score the baseline
# Train a DummyRegressor model from sklearn.dummy import DummyRegressor # Import DummyRegressor # Create a class object for the sklearn model.dummy_regr = DummyRegressor()# fit the dummy regressordummy_regr.fit(X, y)# score the model dummy_regr.score(X, y)
0.0
Discuss: why is this training score approximately zero? Does that mean none of the predicted prices are useful?
Predict: will its training score be higher than the baseline’s?
Try: fit an unrestricted DecisionTreeRegressor on X, y and score it on the same examples.
Worked solution: Fit and score a decision tree
# Train a decision tree model from sklearn.tree import DecisionTreeRegressor # Import DecisionTreeRegressor # Create a class object for the sklearn model.dt_regr = DecisionTreeRegressor(random_state=RANDOM_STATE)# fit the decision tree regressor dt_regr.fit(X, y)# score the model dt_regr.score(X, y)
0.9991338290544213
Intuition of regression trees
In classification trees, a “good split” is one that makes each group more pure in terms of labels (e.g., mostly happy 🙂 vs. mostly unhappy 🙁).
In regression trees, a good split is one that creates groups where the target values have low variance around their mean.
Our training score looks impressive. Would you deploy this model?
Which examples did the model see during fitting?
Have we measured performance on any unseen examples?
What evidence would make you more confident?
What’s the depth of this model?
dt_regr.get_depth()
38
Evaluate on held-out examples
Our first score answered, ‘How well can the model fit data it has already seen?’ We want to ask, ‘How well will it predict new examples?’
Discuss: Use an analogy to distinguish the roles of training, validation, test, and deployment: practice questions, held-out practice questions, an exam, and interview questions. Where does the analogy help, and where might it break down?
Try: split X, y into 80% training and 20% test data. Fit a fresh tree on training data only.
This keeps the new fit separate from the held-out rows, but does not undo our earlier full-data exploration. We’ll use this split to learn the mechanics; it is not a pristine final assessment.
Worked solution: Create the training and test split
# Split the data from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=RANDOM_STATE)
X.shape, X_train.shape, X_test.shape
((21613, 17), (17290, 17), (4323, 17))
# Instantiate a class object dt = DecisionTreeRegressor(random_state=RANDOM_STATE)# Train a decision tree on X_train, y_traindt.fit(X_train, y_train)# Score on the train setdt.score(X_train, y_train)
0.9994394006711425
# Score on the test setdt.score(X_test, y_test)
0.719915905190645
What changed?
How do the training and held-out scores compare? What could explain the gap?
What do we gain and lose by reserving a larger test set?
Why fix random_state? Would searching for a favourable split improve the model or just its reported score?
Try: also fit the dummy baseline on training data only. Compare its training and held-out scores with the tree’s.
Worked solution: Compare the baseline and tree
# Compare with a baseline fitted only on the training subset.dummy_split = DummyRegressor().fit(X_train, y_train)pd.DataFrame({"train_score": [dummy_split.score(X_train, y_train), dt.score(X_train, y_train)],"held_out_score": [dummy_split.score(X_test, y_test), dt.score(X_test, y_test)],}, index=["Dummy regressor", "Decision tree"])
train_score
held_out_score
Dummy regressor
0.000000
-0.000108
Decision tree
0.999439
0.719916
Activity 4: Select model complexity
Explore tree depth
Predict: what will happen to both scores if we allow only one split?
Try: fit a decision stump and inspect its split. We’re about to try model choices against the test set—watch for the evaluation problem this creates.
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
dt.score(X_train, y_train) # Score on the train set
0.9968347348881582
dt.score(X_test, y_test) # Score on the test set
0.7378551974307357
Which depth looks more promising? Which dataset just influenced that choice?
Discuss: Connect the results to underfitting, overfitting, and the golden rule. In the exam analogy, how does learning too little differ from memorizing practice-specific details?
Use a validation set
We’ve been looking at test scores to compare depths. That turns the test set into part of model selection: it is no longer an independent final assessment.
Let’s introduce a validation set for further choices. This improves our workflow from here onward, but does not make the already-used test set fresh again.
Try: reserve 20% of X_train, y_train for validation. What fractions of the original data are now used for fitting, validation, and testing?
Worked solution: Create a validation set
# Create a validation set X_tr, X_valid, y_tr, y_valid = train_test_split(X_train, y_train, test_size=0.2, random_state=RANDOM_STATE)
Worked solution: Compare depths on the validation split
tr_scores = []valid_scores = []depths = np.arange(1, 35, 2)for depth in depths: # Create and fit a decision tree model for the given depth dt = DecisionTreeRegressor(max_depth=depth, random_state=RANDOM_STATE) dt.fit(X_tr, y_tr)# Calculate and append r2 scores on the training and validation sets tr_scores.append(dt.score(X_tr, y_tr)) valid_scores.append(dt.score(X_valid, y_valid))results_single_valid_df = pd.DataFrame({"train_score": tr_scores, "valid_score": valid_scores},index = depths)results_single_valid_df
train_score
valid_score
1
0.319559
0.326616
3
0.603739
0.555180
5
0.754938
0.677567
7
0.833913
0.737285
9
0.890456
0.763480
11
0.931896
0.790521
13
0.963024
0.769030
15
0.981643
0.752728
17
0.991810
0.735637
19
0.996424
0.745925
21
0.998370
0.734048
23
0.999213
0.741060
25
0.999480
0.722873
27
0.999544
0.723951
29
0.999558
0.734986
31
0.999562
0.724068
33
0.999567
0.724410
# Plot the scores collected above.results_single_valid_df.plot( xlabel="Maximum tree depth", ylabel="R² score", title="Tree depth and performance on a single validation split",)plt.show()
Read the plot together
Where do you see evidence of underfitting or overfitting? Use both scores.
Does extra depth always improve validation performance?
Which depth would you choose?
Would another validation split lead to the same choice?
Worked solution: Find the highest-scoring depth
# What depth gives the "best" validation score?best_depth = results_single_valid_df['valid_score'].idxmax() best_depth
np.int64(11)
Compare depths with cross-validation
In five-fold cross-validation, each configuration is fitted five times, with a different fold held out each time.
Try: compare the same depths with five-fold CV on X_train, y_train. Record mean training score, mean validation score, and validation-score standard deviation.
Predict:
Does test_score in cross_validate mean our final test set?
How does this comparison differ from the single validation split?
How much do validation scores vary across folds? How does that affect your confidence in small differences between depths?
If a shallower tree scores nearly as well as the highest-scoring tree, which would you choose? Explain.
Have we found the best possible depth, or the best choice according to a particular comparison?
Activity 5: Evaluate and reflect
Predict: fix your chosen depth and explain why you chose it.
Try: fit a fresh tree on all non-test training data, then evaluate it on the test set. Why do we refit instead of keeping one of the CV models?
In a fresh workflow, this would be our first look at test performance. Here, we already used these data during EDA and model comparisons, so this score is illustrative—not an independent final estimate. A new independent evaluation would be needed for that claim.
Worked solution: Record the choice and refit
# Try: record your choice before looking at the final score.selected_depth =int(best_depth)selection_reason ="Highest mean validation R² among the depths compared with CV."print(f"Selected depth: {selected_depth}. {selection_reason}")# Refit on all non-test training data.dt_final = DecisionTreeRegressor(max_depth=selected_depth, random_state=RANDOM_STATE)dt_final.fit(X_train, y_train)dt_final.score(X_train, y_train)
Selected depth: 11. Highest mean validation R² among the depths compared with CV.
0.9308647034083802
Worked solution: Evaluate the selected tree
# Evaluate on the test setdt_final.score(X_test, y_test)
0.7784948928666875
How does this score compare with the CV estimate? What might explain a difference?
If we now changed the depth because of this score, which role would the test set be playing?
Reflect on the workflow
Discuss with a neighbour:
Why wasn’t the initial training score enough?
When did our test set start influencing model selection?
Why didn’t creating a validation set later undo that?
What did CV add beyond one validation split?
Where did you see underfitting or overfitting?
The workflow to take away
On a fresh project:
Define the prediction task and reserve a test set using an appropriate split.
Explore the training data and prepare features.
Establish a baseline; compare models and hyperparameters using CV on the training data. Learn any preprocessing within each training fold.
Fix the configuration and refit on all training data.
Evaluate on the untouched test set.
Optionally inspect feature importances to understand the fitted model.
The golden rule: test data must not guide training or model selection.
Our opening shortcuts helped us discover this workflow. They are not steps to copy into a final evaluation.
Optional exploration: What features did the tree use?
The core activity ends with the workflow above. This extension previews Chapter 12; it is not needed to choose the tree depth.
#What's the depth of the model? dt_final.get_depth()
Try: pair each importance with its feature name and sort the table. Which features does this tree rely on most?
These are impurity-based importances for this fitted tree. They do not establish causation; correlated features can share importance, and features with many possible splits can be favoured. If this exploration motivates another modeling choice, return to validation.
Worked solution: Match importances to feature names
df = pd.DataFrame( data = {"features": dt_final.feature_names_in_,"feature_importances": dt_final.feature_importances_ })df.sort_values("feature_importances", ascending=False)