# Q-31: Scale two features, the right way and the wrong way

Data-Driven Athletics tutorial · Week 11 · Chapter 11 · about 15 min · workflow steps: Scale, Split

Web page: https://apopt.com/course/tutorials/q31-scale-right/ · Data: https://apopt.com/data/tutorials/q31-scale-right/

## The decision

Before trusting a model's error on a small personal data set, check that the scaler learned
nothing from the test runs. If it did, the error you report is better than the athlete will see.

## The raw data

- `raw/sessions_fit.csv`: 693 watch activity summaries (FIT session fields), June 2024 to November 2026, in the watch's own units (step length in millimeters, cadence in strides per minute for one foot); this tutorial uses the first 30 outdoor runs Activity summaries from a COROS Training Hub archive of an adult male athlete in his mid-40s, published in the course case file (`athletes/jh/coros-history/`). GPS positions, per-second records and identifiers were removed before publication.

A nearest-neighbor model finds the past runs most like a new one by measuring a distance
between them. If one feature is in steps per minute (about 165) and the other in meters
(about 1.4), the distance is almost all step rate. **Scaling** puts both on one footing:
subtract a mean and divide by a standard deviation, so each feature has mean 0 and spread 1.

The question here is *whose* mean and standard deviation. The data are the first 30 runs an
adult male athlete in his mid-40s recorded on a new watch, in the summer of 2024. The model
learns from the first 20 and is tested on the last 10, in time order, the way a personal
model is used: on runs it has not seen yet (Chapter 11, splitting by day).

### Open the file and convert the units

*Predict first:* Step rate is about 155 steps per minute and step length about 0.95 m. How many times larger is the spread of step rate, in its own units?

```python
import pandas as pd

raw = pd.read_csv("raw/sessions_fit.csv")
# outdoor runs only: a blank sub_sport (treadmill and track runs have one)
runs = raw[(raw["sport"] == "running") & raw["sub_sport"].isna()]
runs = runs.sort_values("start_time").copy()
runs["km"] = runs["total_distance"] / 1000
runs["pace_s_km"] = runs["total_timer_time"] / runs["km"]  # pauses excluded
runs["cadence_spm"] = 2 * runs["avg_running_cadence"]      # one foot -> both feet
runs["step_m"] = runs["avg_step_length"] / 1000            # the watch stores mm
ok = (runs["km"] > 2) & (runs["cadence_spm"] > 100) & runs["step_m"].between(0.5, 3)
data = runs[ok].head(30).reset_index(drop=True)
X, y = ["cadence_spm", "step_m"], "pace_s_km"
train, test = data[:20], data[20:]
print(data[X + [y]].describe().loc[["mean", "std", "min", "max"]].round(2).to_string())
```

Output:

```
      cadence_spm  step_m  pace_s_km
mean       155.20    0.95     420.01
std         21.21    0.13      91.72
min        106.00    0.76     238.99
max        182.00    1.37     644.54
```

Step rate spreads by about 21 steps per minute and step length by about 0.13 m: a ratio
of more than a hundred. Unscaled, a difference of one step per minute counts as much as a
difference of a whole meter of step length. The low step rates (106 at the bottom) come from
runs with walking in them, which also have the slowest paces.

### The right way: fit the scaler on the training runs only

A **pipeline** joins the scaler and the model, so the scaler learns its mean and standard
deviation inside `fit`, from the 20 training runs alone. The test runs are then scaled with
those numbers, as a run next week would be.

*Predict first:* How much will scaling cut the error, in seconds per kilometer?

```python
from sklearn.neighbors import KNeighborsRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import mean_absolute_error

def test_error(model, Xtr, Xte):
    model.fit(Xtr, train[y])
    return mean_absolute_error(test[y], model.predict(Xte))

mae = {"no scaling": test_error(KNeighborsRegressor(3), train[X], test[X]),
       "scaler fitted on training runs": test_error(
           make_pipeline(StandardScaler(), KNeighborsRegressor(3)), train[X], test[X])}
for k, v in mae.items():
    print(f"{k:32s} mean error {v:.1f} s/km")
```

Output:

```
no scaling                       mean error 36.0 s/km
scaler fitted on training runs   mean error 27.3 s/km
```

### The wrong way: fit the scaler on all 30 runs first

The common shortcut scales the whole table and then splits it. The scaler has then seen
the 10 test runs, which in real use would not exist yet. With only 30 runs, ten of them move
the scaler's numbers a lot.

*Predict first:* Will the leaky version look better or worse than the right way?

```python
import matplotlib.pyplot as plt

leaky = StandardScaler().fit(data[X])                 # has seen the test runs
right = StandardScaler().fit(train[X])
mae["scaler fitted on all 30 runs"] = test_error(
    KNeighborsRegressor(3), leaky.transform(train[X]), leaky.transform(test[X]))
print("scaler mean, all runs:  ", leaky.mean_.round(2), " SD", leaky.scale_.round(3))
print("scaler mean, train only:", right.mean_.round(2), " SD", right.scale_.round(3))
print(f"leaky mean error {mae['scaler fitted on all 30 runs']:.1f} s/km")

order = ["no scaling", "scaler fitted on all 30 runs", "scaler fitted on training runs"]
fig, ax = plt.subplots(figsize=(6.4, 2.6))
ax.barh(["no scaling", "all 30 runs (leaks)", "training runs only"], [mae[k] for k in order],
        color=["0.75", "0.45", "0.15"], edgecolor="black")
ax.set(xlabel="mean error on the 10 test runs (s/km)", title="Scaling matters; the leak flatters")
plt.tight_layout()
```

Output:

```
scaler mean, all runs:   [155.2    0.95]  SD [20.852  0.125]
scaler mean, train only: [159.3    0.97]  SD [19.217  0.144]
leaky mean error 24.9 s/km
```

![Bar chart of mean test error in seconds per kilometer for three ways: no scaling, scaler fitted on all 30 runs, scaler fitted on the 20 training runs.](https://apopt.com/course/tutorials/q31-scale-right/c05-1.png)

Scaling cut the error by about a quarter, from 36.0 to 27.3 s/km. The leaky scaler looks
better again, at 24.9 s/km, but that gain is not real: it came from knowing the spread of runs that had not happened yet.
With thousands of rows the two scalers would be almost the same (CS-13 shows that); with 30
they are not. The rule does not depend on size: anything that learns from data, a scaler
included, is fitted on the training rows only.

**For the athlete:** "The pace model was checked only on runs it had never seen, so its
error of about 27 seconds per kilometer is the one you can expect next week."

## Action card

- **Finding:** Scaling the two features cut the model's pace error by about a quarter; the leaky scaler made it look better still.
- **Evidence:** Mean error on 10 later runs: 36.0 s/km unscaled, 27.3 s/km scaled on the training runs, 24.9 s/km scaled on all runs.
- **Sure:** Low. Ten test runs from one athlete in one summer, some with walking in them.
- **Action:** Report the 27.3 s/km, the number from a scaler that never saw the test runs.
- **Retest:** Repeat with the next 30 runs and see whether the ranking holds.

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
