A4.3.10 Choosing and comparing models
HL onlyCommand term: Explain1. Model race: same data, four algorithms
Four classifiers are really trained in your browser on the same training data (● dots), then tested on unseen test data. The shaded background shows each model's decision regions. Change the shape of the data, the noise and the amount of data: does the same model always win?
Data set shape:2. What matters for this project? Weigh the factors
Accuracy isn't the only consideration. Set how important each factor is for your project, and see which model fits best. (Ratings are general rules of thumb.)
3. Choose the right model for the problem
Score: 0 /
In this lab you practise comparing models with cross-validation, using a baseline, and seeing how the shape of the data changes which model wins. Work through the sections in order: run it, read it, change it, then extend it.
1. Set up in PyCharm
- Open PyCharm and choose New Project (a pure Python project; any recent Python 3 works). Name it
shelfwise_ai. - Right-click the project folder → New → Python File, and give it the file name shown below.
- Press Copy code below and paste it into the empty file (or press Download .py and drag the file into the project).
- Right-click inside the editor and choose Run (Windows Shift+F10, Mac Ctrl+R). The output appears in the Run window at the bottom.
- No extra libraries are needed: the lab uses only Python's built-in modules, so you can see exactly how the algorithm works.
2. Copy and run the program
# ShelfWise AI - Lab A4.3.10: which model should ShelfWise use? A fair comparison
import random, math
SHAPE = "linear" # "linear": late if a weighted score is high; "ring": late if far from an average member
FOLDS = 5
random.seed(8)
def make_data(n=300):
rows = []
for _ in range(n):
x = (random.uniform(0, 1), random.uniform(0, 1)) # scaled books borrowed, distance
if SHAPE == "linear":
y = 1 if 0.6 * x[0] + 0.4 * x[1] + random.gauss(0, 0.08) > 0.55 else 0
else:
y = 1 if math.dist(x, (0.5, 0.5)) + random.gauss(0, 0.04) > 0.33 else 0
rows.append((x, y))
return rows
data = make_data()
# ---------------- four models, each with fit(train) -> predict(x) ----------------
def majority(train):
guess = 1 if sum(y for _, y in train) * 2 > len(train) else 0
return lambda x: guess
def knn(train, k=7):
def predict(x):
near = sorted(train, key=lambda r: math.dist(r[0], x))[:k]
return 1 if sum(y for _, y in near) * 2 > k else 0
return predict
def centroid(train):
c = {lab: [sum(x[i] for x, y in train if y == lab) / max(1, sum(1 for _, y in train if y == lab)) for i in range(2)]
for lab in (0, 1)}
return lambda x: min(c, key=lambda lab: math.dist(x, c[lab]))
def stump_tree(train, depth=3):
def build(rows, d):
ys = [y for _, y in rows]
maj = 1 if sum(ys) * 2 > len(ys) else 0
if d == 0 or len(set(ys)) == 1:
return maj
best = None
for i in range(2):
for t in [j / 20 for j in range(1, 20)]:
l = [r for r in rows if r[0][i] <= t]
rr = [r for r in rows if r[0][i] > t]
if not l or not rr:
continue
err = sum(min(sum(y for _, y in g), len(g) - sum(y for _, y in g)) for g in (l, rr))
if best is None or err < best[0]:
best = (err, i, t, l, rr)
if best is None:
return maj
_, i, t, l, rr = best
return (i, t, build(l, d - 1), build(rr, d - 1))
tree = build(train, depth)
def predict(x):
node = tree
while isinstance(node, tuple):
i, t, left, right = node
node = left if x[i] <= t else right
return node
return predict
MODELS = {"always the majority": majority, "nearest centroid": centroid,
"decision tree (depth 3)": stump_tree, "k-NN (k = 7)": knn}
def evaluate(fit):
fold = len(data) // FOLDS
accs, f1s = [], []
for f in range(FOLDS): # k-fold cross-validation
test = data[f * fold:(f + 1) * fold]
train = data[:f * fold] + data[(f + 1) * fold:]
predict = fit(train)
preds = [predict(x) for x, _ in test]
tp = sum(1 for p, (_, y) in zip(preds, test) if p and y)
fp = sum(1 for p, (_, y) in zip(preds, test) if p and not y)
fn = sum(1 for p, (_, y) in zip(preds, test) if not p and y)
accs.append(sum(p == y for p, (_, y) in zip(preds, test)) / len(test))
f1s.append(2 * tp / (2 * tp + fp + fn) if tp else 0)
return sum(accs) / FOLDS, sum(f1s) / FOLDS
print(f"Data shape: {SHAPE}; {len(data)} members; {FOLDS}-fold cross-validation\n")
print(f"{'model':26}{'accuracy':>9}{'F1':>7}")
results = {}
for name, fit in MODELS.items():
acc, f1 = evaluate(fit)
results[name] = f1
print(f"{name:26}{acc:9.0%}{f1:7.2f}")
best = max(results, key=results.get)
print(f"\nBest F1: {best}")
3. Expected output
The program uses a fixed random seed, so with the same settings you should see exactly this output.
Data shape: linear; 300 members; 5-fold cross-validation model accuracy F1 always the majority 58% 0.00 nearest centroid 88% 0.86 decision tree (depth 3) 82% 0.78 k-NN (k = 7) 86% 0.83 Best F1: nearest centroid
4. Read the output
Answer each question from your own output before you open the answer.
Why include a model that always predicts the majority class?
Why use 5-fold cross-validation instead of one train/test split?
Which model wins on the 'linear' data, and why?
5. Change it and predict
For each change: write down your prediction first, then edit the setting at the top of the program, run it, and compare. Change the setting back before the next task.
Task 1. Change SHAPE = "linear" → SHAPE = "ring"
Set SHAPE = "ring". Which model wins now?
Check your prediction
k-NN (F1 0.93). Late members now form a ring around typical members, which no single straight line can separate: nearest centroid drops to 0.59. The best model depends on the data, so models must be compared, not assumed.
Output with this change:
Data shape: ring; 300 members; 5-fold cross-validation model accuracy F1 always the majority 65% 0.78 nearest centroid 53% 0.59 decision tree (depth 3) 66% 0.66 k-NN (k = 7) 91% 0.93 Best F1: k-NN (k = 7)
6. Extended activity: Write a model-selection report
A longer project for homework or a double lesson. Save it as a new file so you keep the original.
- Create a third data shape of your own (e.g. two separate blobs of late members).
- Add a fifth model (a perceptron from the A4.3.8 lab, or logistic regression from scikit-learn).
- Run all models on all shapes and record F1 and the time taken to train and predict.
- Write a one-page report for ShelfWise recommending a model, considering accuracy, speed, explainability and how the data might change in future.
Success criteria
- Results are in one clear table.
- Your recommendation weighs more than one factor.
- You explain why no model is best for every data set.
7. Level up (optional): the same with scikit-learn
This optional part uses scikit-learn, the library professionals use. Install it once in PyCharm: Settings → Project → Python Interpreter → + → search scikit-learn → Install Package. Or type in PyCharm's Terminal: pip install scikit-learn. If the download is slow in China, use a mirror: pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple. Numbers may differ slightly between library versions.
# Optional: comparing models with scikit-learn cross-validation (pip install scikit-learn)
import random, math
from sklearn.model_selection import cross_val_score
from sklearn.dummy import DummyClassifier
from sklearn.neighbors import KNeighborsClassifier, NearestCentroid
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
random.seed(8)
X, y = [], []
for _ in range(300):
x = [random.uniform(0, 1), random.uniform(0, 1)]
X.append(x)
y.append(1 if math.dist(x, (0.5, 0.5)) + random.gauss(0, 0.04) > 0.33 else 0) # the "ring" shape
models = {"majority": DummyClassifier(strategy="most_frequent"), "nearest centroid": NearestCentroid(),
"logistic regression": LogisticRegression(), "decision tree": DecisionTreeClassifier(max_depth=3, random_state=0),
"k-NN (k=7)": KNeighborsClassifier(n_neighbors=7)}
for name, model in models.items():
f1 = cross_val_score(model, X, y, cv=5, scoring="f1").mean()
print(f"{name:20} F1 {f1:.2f}")
Output on our computer (scikit-learn 1.9):
majority F1 0.79 nearest centroid F1 0.54 logistic regression F1 0.79 decision tree F1 0.88 k-NN (k=7) F1 0.94
Compare this with your from-scratch version: which results match, and why might the library choose slightly different values?
Learning objectives
By the end of this page you should be able to:
- Explain why different algorithms give different results on the same problem.
- Explain the factors that guide model selection: the nature of the problem, its complexity and the desired outcomes.
- Explain how the characteristics of the data affect algorithm performance.
- Explain how to compare models fairly using test data and evaluation metrics.
- Justify the choice of a model for a given scenario.
Why model selection matters
There is no single best algorithm for every problem (the "no free lunch" idea). Each algorithm makes different assumptions: a linear model assumes a straight-line boundary; k-NN assumes nearby points are similar; decision trees split on one feature at a time; neural networks can learn almost any shape but need more data. When the assumptions match the data, the model performs well; when they don't, it performs badly. So developers train several candidate models and compare them on the same validation / test data before choosing.
Factors when selecting a model
| Factor | Questions to ask |
|---|---|
| Nature of the problem | Classification, regression, clustering, association, sequential decisions (RL), optimisation (GA)? Labelled or unlabelled data? Images, text, tables? |
| Complexity of the pattern | Is the relationship linear or highly non-linear? Simple models underfit complex patterns; complex models overfit simple ones. |
| Amount and quality of data | Deep learning needs lots of data; small data sets suit simpler models. Noise and outliers affect some models more (e.g. k = 1). |
| Desired outcomes | Highest accuracy? A specific metric (recall for medical screening)? Probabilities? |
| Interpretability / explainability | Must decisions be explained (loans, medicine, law)? Decision trees and linear models are transparent; neural networks are "black boxes". |
| Resources and speed | Training time, prediction speed (real-time?), memory, hardware (A4.1.2), cost. |
| Scalability and maintenance | Will the data grow? How easy is retraining? |
How to compare models fairly
- Use the same training data and the same validation / test data for every model.
- Choose a metric suited to the problem (accuracy, precision, recall, F1, r², A4.3.3), and tune each model's hyperparameters before comparing.
- Use cross-validation (several train/test splits) because results vary with the sample, especially for small data sets.
- Consider trade-offs, not just the top score: a slightly less accurate but explainable or faster model may be the better choice.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Explain why different machine learning algorithms can give different results on the same data set. [3]
2. A bank wants to use machine learning to decide whether to approve loans and must explain every decision to customers and regulators. Recommend a suitable model and justify your choice. [4]
3. Outline why models should be compared using the same test data. [2]
4. Explain how the size of the training data set might affect the choice between a deep neural network and a simpler model. [3]
5. Discuss factors, other than accuracy, that should be considered when selecting a model for a real-time object-detection system in a self-driving car. [4]