Skip to main content

Hands-on: model and dataset combinations

Why This Matters

“Which algorithm is best?” has no general answer. It depends on the data, and on how the data was prepared. A model that is excellent on one dataset is useless on the same data unscaled. Training several models on several versions of the data, and comparing them on the same test set, is how teams choose, and how testers check that the choice was made on evidence.

What you will learn

  • Train and compare several algorithms on several versions of a dataset
  • See how a preparation step (scaling) matters for one algorithm and not for another
  • Compare models fairly: same test set, same metrics, and training time included

Syllabus: HO-3.3.3 (show the impact of different ML models and dataset combinations on training and model behaviour).

The experiment

Two versions of the loan training data, both from module 3:

  • dropped rows (41 rows): quick_clean from lesson 13, which throws away every row with a problem
  • prepared (48 rows): prepare from lesson 15, which repairs and imputes instead

Five algorithms, two of them with and without scaling:

ModelHow it decides
Decision tree, depth 2Two yes/no questions about one feature at a time (lesson 13)
Decision tree, no depth limitAs many questions as needed to fit the training data perfectly
Random forest100 trees, each on a random part of the data; they vote
Logistic regressionA weighted sum of the features, turned into a probability
k-nearest neighbours (k-NN)Looks up the 5 most similar training applicants and takes the majority; “similar” means close in distance

All are evaluated on the same 40-applicant test set from lesson 19, with accuracy and F1, and the training time is measured.

Hands-on

Create module-4/test_model_combinations.py:

"""Lesson "Hands-on: model and dataset combinations": train several models on several datasets and compare."""
import sys
import time
from pathlib import Path

import pandas as pd
import pytest
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier

sys.path.insert(0, str(Path(__file__).parent.parent / "module-3"))
from test_data_preparation import prepare  # noqa: E402
from test_first_model import quick_clean  # noqa: E402

FEATURES = ["age", "income", "creditScore"]

MODELS = {
    "tree depth 2": lambda: DecisionTreeClassifier(max_depth=2, random_state=0),
    "tree depth 2 scaled": lambda: make_pipeline(StandardScaler(), DecisionTreeClassifier(max_depth=2, random_state=0)),
    "tree no limit": lambda: DecisionTreeClassifier(random_state=0),
    "random forest": lambda: RandomForestClassifier(n_estimators=100, random_state=0),
    "logistic regr.": lambda: make_pipeline(StandardScaler(), LogisticRegression()),
    "k-NN unscaled": lambda: KNeighborsClassifier(n_neighbors=5),
    "k-NN scaled": lambda: make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)),
}


@pytest.fixture(scope="module")
def datasets(api):
    raw = pd.DataFrame(api.get(f"{api.base}/datasets/loans-train", timeout=10).json()["data"])
    return {"dropped rows": quick_clean(raw), "prepared": prepare(raw)}


@pytest.fixture(scope="module")
def test_set(api):
    return pd.DataFrame(api.get(f"{api.base}/test-set", timeout=10).json()["data"])

StandardScaler rescales every feature to mean 0 and standard deviation 1. make_pipeline glues the scaler to the model, so the scaling is learned from the training data only and applied the same way to the test data: no leakage (lesson 16).

The fixture results trains every model on every dataset, times the training, and evaluates on the test set:

@pytest.fixture(scope="module")
def results(datasets, test_set):
    """Train every model on every dataset; evaluate each on the same independent test set."""
    rows = []
    for data_name, data in datasets.items():
        for model_name, make in MODELS.items():
            model = make()
            start = time.perf_counter()
            model.fit(data[FEATURES], data["approved"] == "Yes")
            seconds = time.perf_counter() - start
            predicted = model.predict(test_set[FEATURES])
            rows.append({
                "data": f"{data_name} ({len(data)})", "model": model_name,
                "accuracy": accuracy_score(test_set["repaid"], predicted),
                "F1": f1_score(test_set["repaid"], predicted),
                "train ms": round(seconds * 1000, 1),
            })
    table = pd.DataFrame(rows)
    print("\n" + table.round(3).to_string(index=False))
    return table


def score(results, data, model, metric="accuracy"):
    row = results[results["data"].str.startswith(data) & (results["model"] == model)]
    return row[metric].item()

And three tests, each capturing one lesson from the table:

def test_scaling_matters_for_k_nearest_neighbours(results):
    # k-NN measures distances: unscaled, income (tens of thousands) drowns out age and credit score.
    for data in ["dropped rows", "prepared"]:
        assert score(results, data, "k-NN scaled") >= score(results, data, "k-NN unscaled") + 0.1


def test_scaling_does_not_matter_for_a_decision_tree(results):
    # A tree compares one feature at a time with a threshold, so the scale is irrelevant.
    for data in ["dropped rows", "prepared"]:
        assert score(results, data, "tree depth 2 scaled") == score(results, data, "tree depth 2")


def test_the_most_complex_model_is_not_automatically_the_best(results):
    assert score(results, "prepared", "random forest") <= score(results, "prepared", "tree depth 2")

Run it

pytest module-4/test_model_combinations.py -v -s
             data               model  accuracy    F1  train ms
dropped rows (41)        tree depth 2     0.800 0.778       1.4
dropped rows (41) tree depth 2 scaled     0.800 0.778       3.0
dropped rows (41)       tree no limit     0.800 0.778       1.9
dropped rows (41)       random forest     0.725 0.667      88.5
dropped rows (41)      logistic regr.     0.675 0.519       5.0
dropped rows (41)       k-NN unscaled     0.500 0.286       2.0
dropped rows (41)         k-NN scaled     0.750 0.667       2.9
    prepared (48)        tree depth 2     0.800 0.778       2.0
    prepared (48) tree depth 2 scaled     0.800 0.778       3.2
    prepared (48)       tree no limit     0.750 0.737       1.8
    prepared (48)       random forest     0.750 0.688      64.9
    prepared (48)      logistic regr.     0.725 0.621       4.5
    prepared (48)       k-NN unscaled     0.575 0.370       2.1
    prepared (48)         k-NN scaled     0.700 0.600       2.2
PASSED
...
============================== 3 passed

Your training times will differ: they depend on your computer, and the first model trained is often slower because libraries are still loading. The accuracy and F1 values are the same on every run.

What the table shows

The preparation matters per algorithm. Unscaled k-NN is no better than a coin: 0.500. k-NN decides by distance, and an income difference of $10,000 dwarfs a credit-score difference of 100 points, so it effectively looks at income only. Scaled, it reaches 0.750. For the decision tree, scaling changes nothing at all, because a tree compares one feature at a time with a threshold. “Did you scale the data?” is a critical question for one model and irrelevant for another.

More data is not automatically better. Logistic regression, the random forest and unscaled k-NN do better on the prepared data; the unlimited tree and scaled k-NN do worse. The prepared data has more rows, but also imputed values and the two wrongly labelled rows that quick_clean happened to drop. Every preparation choice changes the model.

The most complex model is not the best. The random forest (100 trees) is beaten by a single tree of depth 2, and takes 30 to 60 times longer to train. On 48 rows there is not enough data for a complex model to show its strength; it learns noise instead. With 50,000 rows the picture could be different.

The simple tree wins here, and that is a finding about this data. The real rule behind the data is two thresholds (credit score and income), which is exactly what a depth-2 tree can express. A model whose structure fits the problem beats a more powerful one that has to discover the structure from too little data.

Exercise

  1. The test set has 40 rows. The difference between the random forest (0.750) and the depth-2 tree (0.800) on the prepared data is two applicants. Should the team conclude the tree is better? What would you do before deciding?
  2. A data scientist reports: “I tried 7 models on 2 datasets and picked the best one on the test set.” What is wrong with that procedure (think of lesson 16), and how should it be done?
Show suggested answer
  1. Not from these numbers alone: two applicants on 40 is within the noise. Before deciding: use cross-validation on the training data to compare the models more robustly (lesson 16), collect more test data if possible, and weigh other factors that clearly differ: the tree is explainable and 30 times faster to train. With equal performance, the simpler and more explainable model is the better choice, especially for a loan decision that must be explained to the customer.

  2. Choosing between 14 combinations based on the test set turns the test set into a validation set; the winner’s test score is optimistic (it may have won by luck on these 40 rows). Do the comparison with cross-validation or a separate validation set, pick the combination, and only then run it once on the test set. In this lesson the test set is used for comparison on purpose, to show the effect of combinations; in a real project it would be the final step.

Exam-style questions

Quiz

1. A k-nearest neighbours model performs much worse than a decision tree on the same data. After the features are scaled, k-NN performs almost as well. What is the most likely explanation?

  • A. k-NN cannot be used for classification
  • B. k-NN is based on distances, so features with large values dominated before scaling; decision trees are not sensitive to scale
  • C. Scaling always improves every model
  • D. The decision tree was overfitting
Show answer
B. Distance-based algorithms need features on comparable scales; trees split on one feature at a time.
Quiz

2. Why should several model and dataset combinations be compared on the same test data?

  • A. To reduce training time
  • B. So that differences in the results are caused by the models and data, not by different test sets
  • C. Because each model needs its own test set
  • D. The syllabus requires exactly one test set per project
Show answer
B. A fair comparison keeps everything equal except what is being compared.

Your project so far

ai-testing-practice/
├── ...
└── module-4/
    ├── test_metrics.py
    ├── test_evaluate_model.py
    └── test_model_combinations.py    new in this lesson

The finished version is in the example repository: module-4/test_model_combinations.py.