# Q-32: Split by athlete, not by row

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

Web page: https://apopt.com/course/tutorials/q32-split-by-athlete/ · Data: https://apopt.com/data/tutorials/q32-split-by-athlete/

## The decision

Before a model's score goes into a report for a coach, decide what it will be used on. For a
runner the model has never seen, only a split that keeps each runner on one side gives the
honest score.

## The raw data

- `raw/biomechanics.txt`: one row per left-foot step on an instrumented treadmill, nine gait measures and the peak force (2,625 rows) From the Data-Driven Engineering case study [Biomechanic Regression](https://apmonitor.com/dde/index.php/Main/BiomechanicRegression); data courtesy of Iain Hunter, BYU Biomechanics.

The file holds about 2,600 left-foot steps from an instrumented treadmill. Each runner
contributes many steps, and neighboring steps of one runner are nearly copies of
each other. A model tested on steps from runners it has already seen will look far better
than it will be for a new runner. The fix is to split by **athlete**: every step of a runner
goes to the same side.

### Open the file and label the runners

The file names no runner. Each runner ran a ladder of rising speeds, so a speed the ladder
has already used starts a new runner (the same inference as CS-13).

*Predict first:* About how many runners do you expect in 2,600 steps, if each runs five speeds of about 25 steps?

```python
import numpy as np
import pandas as pd

df = pd.read_csv("raw/biomechanics.txt").replace(-9999, np.nan).dropna()
df = df[(df["lgt"] > 0) & df["lkneeswing"].between(0, 150)].copy()
df["trial"] = (df["speed"] != df["speed"].shift()).cumsum()   # a run of one speed
runner, seen, ids = 0, set(), {}
for t, speed in df.groupby("trial")["speed"].first().items():
    if not seen or speed in seen:          # a repeated speed starts a new ladder
        runner, seen = runner + 1, set()
    seen.add(speed)
    ids[t] = runner
df["runner"] = df["trial"].map(ids)
print(f"{len(df)} steps, {df['trial'].nunique()} trials, {df['runner'].nunique()} runners")
print("median steps per runner:", int(df.groupby("runner").size().median()))
```

Output:

```
2568 steps, 102 trials, 17 runners
median steps per runner: 125
```

### Two splits, one model

The model is five nearest neighbors on the nine gait measures, scaled inside a pipeline.
The row split shuffles the steps into five folds. The athlete split makes the fold from the
runner number: runner 1, 6, 11 and 16 in one fold, and so on (`runner % 5`). Fixed folds
give the same answer in every version of scikit-learn; `GroupKFold` does the same job, but
how it assigns runners to folds has changed between versions.

*Predict first:* The row split scores R² near 0.9. What will the split by runner give?

```python
from sklearn.model_selection import KFold, PredefinedSplit, cross_val_predict
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score

FEATURES = ["lgt", "sr", "sl", "lkneeswing", "lhipflex", "lhipext", "lcmvert", "lkneesep", "lcmtoe"]
X, y = df[FEATURES], df["lpeakforce"]
model = make_pipeline(StandardScaler(), KNeighborsRegressor(5))
splits = {"by row": KFold(5, shuffle=True, random_state=0),
          "by runner": PredefinedSplit(df["runner"] % 5)}      # fold = runner number mod 5
pred = {name: cross_val_predict(model, X, y, cv=cv) for name, cv in splits.items()}
for name, p in pred.items():
    print(f"split {name:10s} R² {r2_score(y, p):.2f}")
print("runners in fold 1:", sorted(int(r) for r in df.loc[df["runner"] % 5 == 1, "runner"].unique()))
```

Output:

```
split by row     R² 0.93
split by runner  R² 0.31
runners in fold 1: [1, 6, 11, 16]
```

### Where the difference comes from

Compare the error for each runner under the two splits.

```python
import matplotlib.pyplot as plt

err = pd.DataFrame({name: (p - y).abs() for name, p in pred.items()}).groupby(df["runner"]).mean()
print(err.mean().round(2).to_string())
print("runners whose error grew more than threefold:", int((err["by runner"] > 3 * err["by row"]).sum()))
fig, ax = plt.subplots(figsize=(6.4, 3.0))
ax.plot(err.index, err["by row"], "o", mfc="white", mec="black", label="split by row")
ax.plot(err.index, err["by runner"], "s", color="black", label="runner held out")
ax.set(xlabel="runner", ylabel="mean error (body weights)", xticks=err.index,
       title="Held out, most runners are predicted far worse")
ax.legend()
plt.tight_layout()
```

Output:

```
by row       0.06
by runner    0.22
runners whose error grew more than threefold: 10
```

![For each of 17 runners, the mean error in body weights with a row split (circles, all small) and with the runner held out (squares, mostly several times larger).](https://apopt.com/course/tutorials/q32-split-by-athlete/c05-1.png)

With a row split, every runner's own steps sat in the training folds, a few rows away, and
the nearest neighbors found them. Held out, the model has to predict a runner it never saw,
which is the job a coach would give it. Report the second number.

**For the athlete:** "A model like this one would get your peak force wrong by about a
fifth of your body weight on an average step, so we use it to rank gait measures, not to
tell you your force."

## Acknowledgements

The data set and the original case study are from the Data-Driven Engineering course, with data courtesy of Iain Hunter, BYU Biomechanics.

## Action card

- **Finding:** The same model scores R² 0.93 on shuffled steps and 0.31 on runners it has not seen.
- **Evidence:** With runners held out by fixed folds, the mean error per step rose from 0.06 to 0.22 body weights.
- **Sure:** Moderate. 17 runners inferred from speed ladders on one treadmill.
- **Action:** Report the score with runners held out, and say how the folds were made.
- **Retest:** Recheck with another assignment of runners to folds (for example `(runner + 1) % 5`).

## References

- Data-Driven Engineering: [Biomechanic Regression](https://apmonitor.com/dde/index.php/Main/BiomechanicRegression).
- Machine Learning for Engineers: [Split Data: Train, Validate, Test](https://apmonitor.com/pds/index.php/Main/SplitData).

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