# CS-13: Predicting peak left-leg force

Data-Driven Athletics tutorial · Week 9 · Chapter 9 · about 75 min · workflow steps: Gather, Statistics, Visualize, Cleanse, Features, Scale, Split

Web page: https://apopt.com/course/tutorials/cs13-peak-force/ · Data: https://apopt.com/data/tutorials/cs13-peak-force/

## The decision

A coach wants to know which gait measures are worth coaching if the aim is a lower peak force
under each foot. A model that predicts peak force from measures a phone can see would answer
that, **if** it works for a runner it has never seen. Part 1 builds the model the usual way.
Part 2 checks it the way the coach will use it.

## Predict first

The course page reports an R² of about 0.94 for this data. Predict the R² you will get when the model is tested on runners it has never seen: about the same, a little lower, or much lower?

## 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).
- `raw/biomechanics2.txt`: the same kind of steps with both legs and 49 columns, for the challenge (2,975 rows) Same source. The name and e-mail columns hold only placeholders.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| speed | treadmill speed | m/s | 3.15–6.50 | none |
| lgt | left-foot ground contact time | s | 0.12–0.27 | -9999 |
| sr | stride rate | strides/s | 1.26–1.95 | -9999 |
| sl | stride length | m | 2.0–4.1 | -9999 |
| lkneeswing | left knee angle at peak swing flexion | degrees | 70–145 | -9999 |
| lhipflex | left hip peak flexion | degrees | 32–96 | -9999 |
| lhipext | left hip peak extension | degrees | −37 to 4 | -9999 |
| lcmvert | vertical travel of the center of mass | m | 0.03–0.13 | -9999 |
| lkneesep | distance between the knees at toe-off | m | 0.15–0.46 | -9999 |
| lcmtoe | center of mass to toe at contact | m | 0.27–0.46 | -9999 |
| lpeakforce | left-foot peak vertical force (target) | body weights | 2.1–4.7 | -9999 |

What is wrong with it: 25 rows hold the missing-value code −9999 in every measure; a few knee
angles are outside the range a knee can reach; and the file names no runner, although each
runner contributes hundreds of rows. The units are not stated with the data; the ones shown
are those the values are consistent with (Chapter 11, Table 11.2).

## Part 1 (Week 9): reproduce the course result

The Data-Driven Engineering course fits this data set and reports an R² near 0.94. Part 1
repeats that work step by step, the way it is usually done. Part 2 (Week 11) checks whether
the score holds for a runner the model has never seen.

### Step 1 · Gather

The file is one row per left-foot step on an instrumented treadmill. Open it and look at
the first rows before doing anything else.

*Predict first:* How many rows (steps) and how many columns do you expect?

```python
import pandas as pd

raw = pd.read_csv("raw/biomechanics.txt")
print(raw.shape)
print(raw.head(3).to_string())
```

Output:

```
(2625, 11)
   speed      lgt       sr       sl  lkneeswing  lhipflex  lhipext  lcmvert  lkneesep   lcmtoe  lpeakforce
0   3.35  0.22083  1.47239  2.27521     96.7956   41.4798 -8.88041  0.10011   0.17483  0.30648       2.853
1   3.35  0.21667  1.49068  2.24729    100.4880   43.7456 -8.45414  0.09074   0.17382  0.30648       2.992
2   3.35  0.23333  1.45455  2.30313     99.1766   42.9101 -8.01754  0.09697   0.20828  0.32225       2.891
```

### Step 2 · Statistics

A profile first: count, mean, smallest and largest value of every column. The smallest
value is where bad data usually shows itself.

*Predict first:* What is the smallest peak force you expect, in body weights?

```python
profile = raw.describe().T[["count", "mean", "min", "max"]]
print(profile.round(3).to_string())
print("rows holding -9999:", int((raw == -9999).any(axis=1).sum()))
```

Output:

```
             count     mean      min      max
speed       2625.0    4.527     3.15    6.500
lgt         2625.0  -95.034 -9999.00    0.267
sr          2625.0  -93.700 -9999.00    1.951
sl          2625.0  -92.350 -9999.00    4.144
lkneeswing  2625.0   14.372 -9999.00  179.321
lhipflex    2625.0  -37.156 -9999.00   96.165
lhipext     2625.0 -112.436 -9999.00    3.865
lcmvert     2625.0  -95.148 -9999.00    0.130
lkneesep    2625.0  -94.943 -9999.00    0.464
lcmtoe      2625.0  -94.861 -9999.00    0.461
lpeakforce  2625.0  -92.293 -9999.00    4.744
rows holding -9999: 25
```

Every measure has a minimum of −9999. That is not a force or an angle: it is the code the
recording software wrote when it had no value. A model fitted with those rows in it would
treat −9999 as a real number.

### Step 3 · Visualize

Plot the target in recorded order. A picture shows the missing-value codes and also how
the data is arranged: runs of steps at one speed.

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ax[0].plot(raw["lpeakforce"].values, ".", ms=2)
ax[0].set(title="Raw: the -9999 codes", xlabel="row", ylabel="peak force (BW)")
ok = raw["lpeakforce"] > -9999
ax[1].plot(raw.index[ok], raw["lpeakforce"][ok], ".", ms=2)
ax[1].set(title="Without them", xlabel="row", ylabel="peak force (BW)")
plt.tight_layout()
```

![Two panels. Left: the raw peak force in row order with a few points at -9999. Right: the same series without them, rising in steps as treadmill speed rises.](https://apopt.com/course/tutorials/cs13-peak-force/c05-1.png)

### Step 4 · Cleanse

Write the rules down before applying them, keep the raw file untouched, and log how many
rows each rule removes. The two range rules are the ones the Data-Driven Engineering page
uses: contact time must be positive and the knee angle at peak swing must lie between 0 and
150 degrees.

Two columns are added while the rows are still in recorded order: `trial` (a run of steps
at one speed) and `runner` (a ladder of rising speeds; a speed the ladder has already used
starts a new runner). The file has no runner names, so this is an inference, and it matters
in Part 2.

```python
import numpy as np
import os

df = raw.replace(-9999, np.nan)
df["trial"] = (df["speed"] != df["speed"].shift()).cumsum()
runner, seen, ids = 0, set(), {}
for t, g in df.groupby("trial"):
    s = g["speed"].iloc[0]
    if not seen or s in seen:
        runner, seen = runner + 1, set()
    seen.add(s)
    ids[t] = runner
df["runner"] = df["trial"].map(ids)

RULES = {
    "missing value (-9999)": lambda d: d.drop(columns=["trial", "runner"]).isna().any(axis=1),
    "contact time not positive": lambda d: ~(d["lgt"] > 0),
    "knee swing angle outside 0-150 deg": lambda d: ~d["lkneeswing"].between(0, 150),
}
log = []
for name, rule in RULES.items():
    bad = rule(df)
    log.append({"rule": name, "rows_removed": int(bad.sum()), "rows_left": int((~bad).sum())})
    df = df[~bad]
df = df.reset_index(drop=True)
os.makedirs("clean", exist_ok=True)
df.to_csv("clean/biomechanics_clean.csv", index=False)
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
print(pd.DataFrame(log).to_string(index=False))
print(f"{len(df)} steps, {df['trial'].nunique()} trials, {df['runner'].nunique()} runners")
```

Output:

```
                              rule  rows_removed  rows_left
             missing value (-9999)            25       2600
         contact time not positive             0       2600
knee swing angle outside 0-150 deg            32       2568
2568 steps, 102 trials, 17 runners
```

### Step 5 · Features, including one from physics

Two kinds of feature. The nine measured gait features are already columns. The tenth comes
from physics: over a whole step the vertical force must average one body weight, or the
runner would rise or sink. The foot is down for only part of the step, so the force during
contact is larger, and if it is shaped like half a sine wave its peak is π/2 times its mean:

peak force / body weight ≈ (π/2) × step time / contact time, with step time = 1 / (2 × stride rate).

This uses two columns and no fitting at all. How close does it get?

*Predict first:* Will the physics estimate be too high, too low, or about right on average?

```python
from sklearn.feature_selection import f_regression

FEATURES = ["lgt", "sr", "sl", "lkneeswing", "lhipflex", "lhipext", "lcmvert", "lkneesep", "lcmtoe"]
X, y = df[FEATURES], df["lpeakforce"]
F, _ = f_regression(X, y)
scores = pd.Series(F, index=FEATURES).sort_values()

df["physics"] = (np.pi / 2) / (2 * df["sr"] * df["lgt"])
err = df["physics"] - y
r2_phys = 1 - (err ** 2).sum() / ((y - y.mean()) ** 2).sum()
print("strongest features:", ", ".join(f"{k} {v:.0f}" for k, v in scores[::-1][:3].items()))
print(f"physics estimate: mean error {err.mean():+.2f} BW, R² {r2_phys:.2f}, "
      f"correlation {np.corrcoef(df['physics'], y)[0, 1]:.2f}")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.4))
ax[0].barh(scores.index, scores.values)
ax[0].set(title="F-score with peak force", xlabel="F-score")
ax[1].plot(y, df["physics"], ".", ms=2, alpha=0.4)
ax[1].plot([2, 5], [2, 5], "k--", lw=1)
ax[1].set(title="Physics alone, no fitting", xlabel="measured (BW)", ylabel="estimate (BW)")
plt.tight_layout()
```

Output:

```
strongest features: lgt 2480, sl 2469, lkneeswing 924
physics estimate: mean error -0.32 BW, R² -0.09, correlation 0.74
```

![Left: bar chart of the F-scores of the nine measured features. Right: physics estimate of peak force against the measured peak force, with the line of equality.](https://apopt.com/course/tutorials/cs13-peak-force/c09-1.png)

Contact time and stride length are the two strongest single features, well ahead of the
rest. The physics estimate, built from
contact time and stride rate with no fitting at all, rises and falls with the measured force
(correlation 0.74), but it runs about 0.3 body weights low, because a real force curve is
more peaked than half a sine wave. R² punishes that offset, so on its own the estimate scores
below zero: worse than always guessing the average. Keep it anyway; Part 2 shows why.

### Steps 7 and 8 · Scale and split, the usual way

Now the course recipe: shuffle the rows, scale every column to mean 0 and standard
deviation 1, keep the first 80% for training and the last 20% for testing, and compare
several regressors. Five are fitted here so you can see each one; the Data-Driven
Engineering page uses a package that fits dozens.

*Predict first:* Which model will score best, and roughly what R²?

```python
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor
from sklearn.svm import SVR
from sklearn.metrics import r2_score, mean_squared_error

MODELS = {
    "linear": lambda: LinearRegression(),
    "5 neighbors": lambda: KNeighborsRegressor(5),
    "random forest": lambda: RandomForestRegressor(100, random_state=0),
    "extra trees": lambda: ExtraTreesRegressor(100, random_state=0),
    "support vector": lambda: SVR(),
}
data = df[FEATURES + ["lpeakforce"]].sample(frac=1, random_state=0)
scaled = pd.DataFrame(StandardScaler().fit_transform(data), columns=data.columns)
n = int(0.8 * len(scaled))
Xtr, Xte = scaled[FEATURES][:n], scaled[FEATURES][n:]
ytr, yte = scaled["lpeakforce"][:n], scaled["lpeakforce"][n:]
row_split = {}
for name, make in MODELS.items():
    pred = make().fit(Xtr, ytr).predict(Xte)
    row_split[name] = r2_score(yte, pred)
    print(f"{name:15s} R² {row_split[name]:.2f}  RMSE {mean_squared_error(yte, pred) ** 0.5:.2f} (scaled units)")
```

Output:

```
linear          R² 0.67  RMSE 0.58 (scaled units)
5 neighbors     R² 0.93  RMSE 0.27 (scaled units)
random forest   R² 0.93  RMSE 0.28 (scaled units)
extra trees     R² 0.94  RMSE 0.25 (scaled units)
support vector  R² 0.89  RMSE 0.34 (scaled units)
```

The tree ensembles and the nearest-neighbor model score above 0.9, the linear model far
lower. That matches the course page. Before believing it, notice two things the recipe did.
The scaler learned the mean and spread of **all** rows, including the 20% it was about to
test on. And the split was by row: steps from the same runner, often the step just before
and just after, sit on both sides of it.

## Part 2 (Week 11): would it work on a new runner?

### Step 7 again · Fit the scaler on the training rows only

A pipeline fits the scaler inside each training set, so the test rows never inform it. The
split is still by row, to change one thing at a time.

```python
from sklearn.pipeline import make_pipeline

shuffled = df.sample(frac=1, random_state=0)
tr, te = shuffled[:n], shuffled[n:]
for name in ["5 neighbors", "extra trees"]:
    pipe = make_pipeline(StandardScaler(), MODELS[name]()).fit(tr[FEATURES], tr["lpeakforce"])
    print(f"{name:15s} R² {r2_score(te['lpeakforce'], pipe.predict(te[FEATURES])):.2f} "
          f"(was {row_split[name]:.2f})")
```

Output:

```
5 neighbors     R² 0.93 (was 0.93)
extra trees     R² 0.94 (was 0.94)
```

Almost no change. With 2,600 rows the scaler's mean and spread barely move when 20% are
removed, so this leak is small here. It is still a leak, and in a small data set it is not
small. Keep the habit: anything that learns from data is fitted on training rows only.

### Step 8 again · Hold out whole runners

The question a coach asks is about a runner who was not in the data. So hold out whole
runners: five folds made from the runner number (runner 1, 6, 11, 16 in fold 1, and so on), so no
runner is ever on both sides. scikit-learn's `GroupKFold` does the same job, but how it assigns
runners to folds has changed between versions; fixed folds give the same answer everywhere.

*Predict first:* The row split gave about 0.94 for extra trees. What will it give with whole runners held out?

```python
from sklearn.model_selection import PredefinedSplit, cross_val_predict

cv = PredefinedSplit(df["runner"] % 5)        # fold number from the runner number
grouped = {}
for name, make in MODELS.items():
    pred = cross_val_predict(make_pipeline(StandardScaler(), make()), df[FEATURES], df["lpeakforce"], cv=cv)
    grouped[name] = r2_score(df["lpeakforce"], pred)
    if name == "extra trees":
        trees_pred = pred
print(pd.DataFrame({"row split": row_split, "runners held out": grouped}).round(2).to_string())

rows_pipe = make_pipeline(StandardScaler(), MODELS["extra trees"]()).fit(tr[FEATURES], tr["lpeakforce"])
fig, ax = plt.subplots(1, 2, figsize=(9, 3.6), sharex=True, sharey=True)
ax[0].plot(te["lpeakforce"], rows_pipe.predict(te[FEATURES]), ".", ms=3, alpha=0.5)
ax[0].set(title=f"Row split: R² {row_split['extra trees']:.2f}", xlabel="measured (BW)", ylabel="predicted (BW)")
ax[1].plot(df["lpeakforce"], trees_pred, ".", ms=2, alpha=0.3)
ax[1].set(title=f"Runners held out: R² {grouped['extra trees']:.2f}", xlabel="measured (BW)")
for a in ax:
    a.plot([2, 5], [2, 5], "k--", lw=1)
plt.tight_layout()
```

Output:

```
                row split  runners held out
linear               0.67              0.47
5 neighbors          0.93              0.31
random forest        0.93              0.50
extra trees          0.94              0.60
support vector       0.89              0.52
```

![Two panels of predicted against measured peak force for extra trees. Left, row split: points hug the line. Right, runners held out: points scatter widely around it.](https://apopt.com/course/tutorials/cs13-peak-force/c15-1.png)

The score falls a long way. With a row split, the model had already seen steps from the same
runner at the same speed, a few rows away, and nearest-neighbor and tree models are very good
at finding them. That is memory, not prediction.

### Step 5 again · Does the physics feature help a new runner?

Add the physics estimate as a tenth feature and compare four answers under the honest split:
physics alone, the mean (always predict the average), and the linear and extra-trees models
with and without the physics feature.

*Predict first:* Will the physics feature help the linear model, the trees, both, or neither?

```python
def held_out_r2(features, make):
    pred = cross_val_predict(make_pipeline(StandardScaler(), make()), df[features], df["lpeakforce"], cv=cv)
    return r2_score(df["lpeakforce"], pred)

print(f"always the mean          R² {0:.2f}")
print(f"physics alone            R² {r2_phys:.2f}")
print(f"physics, one fitted line R² {held_out_r2(['physics'], MODELS['linear']):.2f}")
for name in ["linear", "extra trees"]:
    print(f"{name:12s} 9 features R² {held_out_r2(FEATURES, MODELS[name]):.2f}   "
          f"+ physics R² {held_out_r2(FEATURES + ['physics'], MODELS[name]):.2f}")
```

Output:

```
always the mean          R² 0.00
physics alone            R² -0.09
physics, one fitted line R² 0.52
linear       9 features R² 0.47   + physics R² 0.45
extra trees  9 features R² 0.60   + physics R² 0.59
```

Read the table from the top. Physics alone is biased. Give it one fitted straight line,
learned from the other runners, and the bias is gone. That one-feature model, built from two
numbers a phone can measure, comes within about 0.1 of the best of the five fitted models
with all nine features, and beats the nine-feature linear model. Adding the physics feature
to the models does not help them: they already have contact time and stride rate.

That is the finding to carry to the coach. Most of what can be predicted about peak force
for a new runner comes from step timing, the share of each step the foot spends on the
ground, through a relation physics explains. The other measures add little that transfers
from one runner to the next.

## How good is the number?

Three numbers describe the same model, and only one answers the coach's question. On rows it was
trained on it is nearly perfect; on shuffled rows held out it scores 0.94; on whole runners held
out it scores about 0.60. The last is the one to report. With 17 inferred runners, that number is
itself uncertain: assign the runners to the five folds differently and it moves by several
hundredths. The physics estimate needs no fitting to the runner, so it does not leak at all, but
it is biased about 0.3 body weights low until one straight line is fitted to it.

## Track it

Add one row per session: `date, test=run-form-3.5, metric=contact_time_s, value, unit=s`, and a
second row for flight time. The modeled peak force follows from them (CS-12).

## With your own data

You cannot measure peak force with a phone, but you can measure contact and flight time (Q-25,
CS-12). Put your own times into the physics formula and read the estimate as a modeled number,
with the bias found here.

## The same method in another field

The same leak appears whenever rows share a source: several readings from one pump, one patient,
one machine. In equipment-failure models, splitting by machine rather than by reading plays the
role that splitting by runner plays here. See the Machine Learning for Engineers pages on
[splitting data](https://apmonitor.com/pds/index.php/Main/SplitData) and
[scaling data](https://apmonitor.com/pds/index.php/Main/ScaleData).

## 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:** Peak force under the foot is mostly set by step timing, the share of each step the foot is on the ground.
- **Evidence:** For runners the model had not seen, contact time and stride rate through one physics formula predicted nearly as well (R² 0.52) as the best nine-feature model (0.60).
- **Sure:** Moderate. 17 runners on one treadmill; the 0.94 from a row split overstates what a new runner would see.
- **Action:** Coach cadence and a lighter, quicker contact before knee or hip angles, and measure contact and flight time on video to watch it.
- **Retest:** Film the same speed in four weeks and compare contact time against its typical error.

## Challenge: Both legs, honestly

The Data-Driven Engineering challenge asks for models of both left and right peak force from
`biomechanics2.txt`. Do that, and hold out whole runners while you do it.

1. Load `raw/biomechanics2.txt`, drop the placeholder name and e-mail columns, and apply the same cleaning rules with a change log.
2. Infer trials and runners: a trial is a run of rows at one speed with consecutive `step` numbers; a repeated speed, or a change in `sex` or `group`, starts a new runner.
3. Fit models for `lpeakforce` and `rpeakforce` with folds by runner (`PredefinedSplit(runner % 5)`); compare a mean baseline, physics alone with one fitted line, linear regression and extra trees.
4. Rank the features for each leg. Do the same features matter for both legs?
5. Compute an asymmetry index between legs for each runner and say whether any runner's difference is larger than the scatter of their own steps.

Deliverables:

- a notebook that runs top to bottom
- a table of R² by model and leg, with the split stated
- one paragraph for the coach

## References

- Data-Driven Engineering: [Biomechanic Regression](https://apmonitor.com/dde/index.php/Main/BiomechanicRegression).
- Machine Learning for Engineers: [Data Engineering](https://apmonitor.com/pds/index.php/Main/DataPreparation) (the nine-step workflow).
- Morin, J.-B., Dalleau, G., Kyröläinen, H., Jeannin, T., and Belli, A. (2005). A simple method for measuring stiffness during running. *Journal of Applied Biomechanics*, 21(2), 167–180.

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