apopt.comCBE 493R Data-Driven Athletics

Course / Tutorials / Week 9 / CS-13

Case study CS-13 · Week 9 and 11 · about 75 min · Core

Predicting peak left-leg force

Reproduce the course regression of peak left-foot force from gait measures, then find out why its R² of 0.94 does not hold for a new runner, and what physics adds.

  1. 1Gather (used)
  2. 2Statistics (used)
  3. 3Visualize (used)
  4. 4Cleanse (used)
  5. 5Features (used)
  6. 6Balance
  7. 7Scale (used)
  8. 8Split (used)
  9. 9Deploy
  1. Ask (this week)
  2. Collect
  3. Check (this week)
  4. Interpret (this week)
  5. Coach (this week)
  6. Reassess

Every cell runs in this page; the first run downloads Python (about 30 s). Nothing you load leaves your browser. Helpful first: Q-25 Find foot contacts in an ankle trace, Q-31 Scale two features, the right way and the wrong way, Q-32 Split by athlete, not by row.

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

Data dictionary
FieldMeaningUnitRangeMissing
speedtreadmill speedm/s3.15–6.50none
lgtleft-foot ground contact times0.12–0.27-9999
srstride ratestrides/s1.26–1.95-9999
slstride lengthm2.0–4.1-9999
lkneeswingleft knee angle at peak swing flexiondegrees70–145-9999
lhipflexleft hip peak flexiondegrees32–96-9999
lhipextleft hip peak extensiondegrees−37 to 4-9999
lcmvertvertical travel of the center of massm0.03–0.13-9999
lkneesepdistance between the knees at toe-offm0.15–0.46-9999
lcmtoecenter of mass to toe at contactm0.27–0.46-9999
lpeakforceleft-foot peak vertical force (target)body weights2.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).

Step by step

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.

PythonStep 1 · Open the raw file

Type a prediction to enable Run.

Show the expected result without running
(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.

PythonStep 2 · Profile every column

Type a prediction to enable Run.

Show the expected result without running
             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.

PythonStep 3 · Look before you clean

Show the expected result without runningTwo 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.

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.

PythonStep 4 · Rules, a change log and a clean copy

Show the expected result without running
                              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?

PythonStep 5 · Rank the measured features, then try the physics estimate

Type a prediction to enable Run.

Show the expected result without running
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.

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.

PythonSteps 7–8 · Scale everything, split by row, compare five models

Type a prediction to enable Run.

Show the expected result without running
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.

PythonStep 7, done right · Scaling inside a pipeline

Show the expected result without running
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.

PythonStep 8, done right · Split by runner

Type a prediction to enable Run.

Show the expected result without running
                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.

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.

PythonPhysics, regression, and both together

Type a prediction to enable Run.

Show the expected result without running
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.

Action card

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).
How 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.
Test again
Film the same speed in four weeks and compare contact time against its typical error.

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).

Open your athlete record

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.

Check the AI

An assistant was asked to "build the best model of peak force for this file and tell me how accurate it will be for our athletes." It answered:

> I standardized all columns, shuffled, used an 80/20 split and compared 40 regressors. > Extra trees won with R² = 0.94, so you can expect predictions within about 0.25 units for > your athletes. Contact time is the most important variable.

What is wrong with it?

Two errors. The split was by row, so steps from the same runner were on both sides; for new athletes the honest R² is about 0.6. And "0.25 units" is in standardized units, not body weights. The last sentence is fine.

Check yourself

  1. Why does a split by row overstate how well the model will do for a new runner?

  2. The physics estimate correlates 0.74 with measured peak force but has R² −0.09. How can both be true?

  3. Which number should go in the report to the coach?

  4. A runner has contact time 0.20 s and stride rate 1.5 strides/s. What does the half-sine model give for peak force?

    body weights

0 of 4 answered · 0 right the first time

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.

Hand in

How it is judged

Hints

    The solution unlocks after you make an attempt. Comparing your own attempt with it is where the learning happens.

    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 and scaling data.

    Acknowledgements

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

    References

    Built 2026-11-30 with Python packages numpy 2.5.5, pandas 3.1.1, matplotlib 3.11.2, sklearn 1.9.1, scipy 1.18.1. In the browser the same code runs on Pyodide, so the last digit can differ.