Lab: Baselines First with Dummy, Linear and Neighbour Models
Split two scikit-learn datasets into train, validation and test sets, compare dummy baselines with linear regression, logistic regression and k-nearest neighbours on validation data, test the chosen models once, and measure what each model costs at prediction time.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: A repeatable three-way split
- Step 2: Regression baselines on the diabetes data
- Step 3: Classification baselines on the cancer data
- Step 4: Refit the chosen models and test once
- Step 5: What each model costs to serve
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Machine Learning Fundamentals
- From Business Question to Learning Task Concept · 20 min
- The Estimator Contract: fit, predict, score Concept · 15 min
- Lab: Baselines First with Dummy, Linear and Neighbour Models Lab · 30 min
- Underfitting, Overfitting and Learning Curves Concept · 20 min
- Worked Example: Taming a Polynomial Fit with Ridge, Lasso and Elastic Net Worked example · 25 min
- Check: Framing, Baselines and Generalization Knowledge check · 8 questions
What you will learn
- Train and compare a dummy baseline, linear regression, logistic regression and k-nearest neighbours with the scikit-learn estimator API on a train/validation/test split.
Prerequisites: Data Handling
01. Goal and setup
In this lab you build the evaluation habit that every later model in this track relies on: baseline first, choose on validation, test once. You work on two small datasets that ship with scikit-learn, so nothing is downloaded. The diabetes data is a regression task (predict a disease-progression score). The breast cancer data is a classification task (malignant or benign). For each one you train a dummy baseline, a linear model and k-nearest-neighbour models with three values of k, all through the estimator contract from the previous lesson.
Why three splits? The training set fits the models. The validation set compares them and picks hyperparameters such as k. Every comparison you make on it nudges your choices towards that particular sample, so its score becomes slightly optimistic. The test set is touched once, at the end, to give an honest estimate for the model you chose. Here the split is 60% train, 20% validation and 20% test.
You need: Python 3.12, scikit-learn 1.9 (NumPy comes with it). The numbers below come from that version; other recent versions should match.
baselines-lab/
├── splits.py step 1: one repeatable 60/20/20 split per dataset
├── regression.py step 2: dummy, linear and k-NN regressors
├── classification.py step 3: dummy, logistic and k-NN classifiers
├── final.py step 4: refit the chosen models, test once
└── cost.py step 5: what each model costs to servemkdir baselines-lab && cd baselines-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install scikit-learn02. Step 1: A repeatable three-way split
scikit-learn splits in two, so call train_test_split twice: first hold out 20% as the test set, then take 25% of the remaining 80% (which is 20% of the total) as validation. A fixed random_state makes every script see the same rows. For classification, stratify keeps the share of each class equal across the three parts, which matters when one class is rare.
from sklearn.datasets import load_breast_cancer, load_diabetes
from sklearn.model_selection import train_test_split
def three_way_split(X, y, stratify=False, seed=0):
"""60% train, 20% validation, 20% test."""
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, random_state=seed, stratify=y if stratify else None
)
X_train, X_val, y_train, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, random_state=seed,
stratify=y_rest if stratify else None,
)
return X_train, X_val, X_test, y_train, y_val, y_test
def diabetes():
return three_way_split(*load_diabetes(return_X_y=True))
def cancer():
return three_way_split(*load_breast_cancer(return_X_y=True), stratify=True)
if __name__ == "__main__":
for name, parts in [("diabetes", diabetes()), ("cancer", cancer())]:
X_train, X_val, X_test, y_train, _, _ = parts
print(f"{name:<9} train {X_train.shape} val {X_val.shape} "
f"test {X_test.shape}")
y_train = cancer()[3]
print("cancer share benign in train:", round(y_train.mean(), 3))python splits.pydiabetes train (264, 10) val (89, 10) test (89, 10)
cancer train (341, 30) val (114, 30) test (114, 30)
cancer share benign in train: 0.628Note the 62.8% benign share. A model that always answers "benign" is right 62.8% of the time without looking at a single measurement. Keep that number in mind for step 3.
03. Step 2: Regression baselines on the diabetes data
DummyRegressor(strategy="mean") predicts the mean target of the training set for every row. The linear model and the k-NN models sit in pipelines with a StandardScaler, so the scaler is fitted on training rows only. k-NN needs scaled features because it measures distances. The script reports two validation metrics. MAE (mean absolute error) is the average size of a miss in target units, easy to explain to a doctor. R² compares the squared error with that of always predicting the mean of the rows being scored.
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from splits import diabetes
X_train, X_val, X_test, y_train, y_val, y_test = diabetes()
models = {
"dummy (mean)": DummyRegressor(strategy="mean"),
"linear regression": make_pipeline(StandardScaler(), LinearRegression()),
}
for k in [5, 15, 30]:
models[f"k-NN, k = {k}"] = make_pipeline(StandardScaler(), KNeighborsRegressor(k))
print(f"{'model':<18} {'val MAE':>8} {'val R2':>7}")
for name, model in models.items():
model.fit(X_train, y_train)
mae = mean_absolute_error(y_val, model.predict(X_val))
print(f"{name:<18} {mae:8.1f} {model.score(X_val, y_val):7.3f}")python regression.pymodel val MAE val R2
dummy (mean) 67.8 -0.035
linear regression 45.3 0.497
k-NN, k = 5 47.0 0.396
k-NN, k = 15 48.6 0.384
k-NN, k = 30 49.4 0.398The dummy model misses by 67.8 points on average, and its R² is slightly negative: the training mean is a little off for the validation rows. Linear regression cuts the average miss to 45.3, a third less, and has the best R². None of the k-NN models beats it, and changing k barely helps. With 264 training rows and ten features, a straight-line relationship is the more reliable pattern here than "patients like this one". On this dataset, the linear model is the one to carry forward.
04. Step 3: Classification baselines on the cancer data
For classification, DummyClassifier(strategy="most_frequent") always predicts the majority class. Besides accuracy, the script reports the recall of the malignant class: the share of malignant tumours that the model labels malignant. In a screening setting a missed malignant tumour costs far more than a false alarm, so a model with high accuracy and poor malignant recall would be a bad choice.
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from splits import cancer
X_train, X_val, X_test, y_train, y_val, y_test = cancer()
models = {
"dummy (majority)": DummyClassifier(strategy="most_frequent"),
"logistic regression": make_pipeline(StandardScaler(), LogisticRegression()),
}
for k in [1, 5, 15]:
models[f"k-NN, k = {k}"] = make_pipeline(StandardScaler(), KNeighborsClassifier(k))
print(f"{'model':<20} {'val accuracy':>12} {'malignant recall':>17}")
for name, model in models.items():
model.fit(X_train, y_train)
# class 0 is malignant: what share of malignant tumours did we catch?
recall = recall_score(y_val, model.predict(X_val), pos_label=0)
print(f"{name:<20} {model.score(X_val, y_val):12.3f} {recall:17.3f}")python classification.pymodel val accuracy malignant recall
dummy (majority) 0.623 0.000
logistic regression 0.991 1.000
k-NN, k = 1 0.982 0.977
k-NN, k = 5 0.974 0.953
k-NN, k = 15 0.982 0.953The baseline reaches 62.3% accuracy and catches no malignant tumour at all, which is exactly why accuracy alone is a weak guide. All real models are far above the baseline. Logistic regression is best on both columns on this split. The k-NN scores move up and down with k without a clear trend, a sign that the differences are within noise: with 114 validation rows, one row is 0.9 percentage points of accuracy. When models are this close, prefer the simpler and cheaper one, and confirm with cross-validation (covered later in the track) before trusting a small gap.
05. Step 4: Refit the chosen models and test once
You have chosen linear regression and logistic regression on validation data. Now refit each one on the training and validation rows together, which gives it more data, and score it on the test set exactly once. Score the baseline the same way, so the final report says how much the model adds.
import numpy as np
from sklearn.dummy import DummyClassifier, DummyRegressor
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from splits import cancer, diabetes
# Chosen on validation; now refit on train + validation and test ONCE
for task, parts, chosen, baseline in [
("diabetes R2", diabetes(),
make_pipeline(StandardScaler(), LinearRegression()), DummyRegressor()),
("cancer accuracy", cancer(),
make_pipeline(StandardScaler(), LogisticRegression()),
DummyClassifier(strategy="most_frequent")),
]:
X_train, X_val, X_test, y_train, y_val, y_test = parts
X_dev, y_dev = np.vstack([X_train, X_val]), np.concatenate([y_train, y_val])
model_score = chosen.fit(X_dev, y_dev).score(X_test, y_test)
base_score = baseline.fit(X_dev, y_dev).score(X_test, y_test)
print(f"{task:<16} test: model {model_score:.3f} baseline {base_score:.3f}")python final.pydiabetes R2 test: model 0.332 baseline -0.001
cancer accuracy test: model 0.982 baseline 0.632The diabetes model scores R² 0.332 on test against 0.497 on validation. Nothing is broken: with 89 rows per split, scores vary a lot from one sample to another, and the validation number was also the one you selected on. This is the reason for keeping a test set. Report 0.332, not 0.497. If you now went back and tried more models because the test score disappointed you, the test set would become a second validation set and lose its value.
06. Step 5: What each model costs to serve
Scores are not the only criterion. Time a logistic regression and a k-NN classifier on a larger synthetic table of 200,000 rows and 20 features. The timings depend on your machine, so yours will differ; compare the two models, not the absolute numbers.
import time
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
rng = np.random.default_rng(0)
X = rng.normal(size=(200_000, 20)) # a bigger, synthetic table
y = (X[:, 0] + X[:, 1] > 0).astype(int)
queries = rng.normal(size=(2_000, 20))
for model in [LogisticRegression(), KNeighborsClassifier(15)]:
start = time.perf_counter()
model.fit(X, y)
fit_s = time.perf_counter() - start
start = time.perf_counter()
model.predict(queries)
predict_s = time.perf_counter() - start
print(f"{type(model).__name__:<22} fit {fit_s:6.2f} s "
f"predict 2,000 rows {predict_s:6.3f} s")python cost.pyLogisticRegression fit 0.80 s predict 2,000 rows 0.001 s
KNeighborsClassifier fit 0.06 s predict 2,000 rows 1.073 sThe pattern is the point. k-NN "fits" almost instantly because it only stores the data, then pays at every prediction by searching 200,000 stored rows. Logistic regression pays once at training time and then predicts with one dot product per row, about a thousand times faster here. In a service that answers many requests, prediction cost and memory usually matter more than training time.
07. Check your understanding
08. Apply it: stretch tasks
- Another baseline. Add
DummyClassifier(strategy="stratified"), which guesses at random in the class proportions, and explain why its malignant recall is near 0.37 rather than 0. - Choose k properly. Try k from 1 to 40 for the cancer data, plot validation accuracy against k with Matplotlib, and describe the noise you see.
- Your practice dataset. Run the same lab on the public tabular dataset from your framing in lesson 1, with the baseline, a regularised linear or logistic model and k-NN, and write the test result next to the baseline in your report.
09. Review prompt
Without looking back, explain the job of each of the three splits and why the test set is used once; what a dummy baseline reveals about an accuracy or R² score; why the validation score of the chosen model tends to be higher than its test score; and why k-NN is fast to fit but slow to predict.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.