<!-- Generated by book/tools/make-index.py from the book source. -->

> Hedengren, J. (Ed.) (2027). Chapter 11: Is the Change Real? Statistics and Machine Learning. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 291–328). IRSRI Sports Research Institute. CC BY 4.0.

**Question.** The athlete jumped 2 cm higher than last month. Is that training, or noise?

**Objectives.**
- Measure your own typical error from a test and a retest, set a smallest worthwhile change, and judge one athlete's result with a decision rule that ends in words.
- Compare two devices or two methods with bias and limits of agreement, and explain why a high correlation does not show that they agree.
- Put a range on a mean or a median by resampling the independent unit, and report a group result as a size with an interval.
- Say what a $p$-value and a fitted slope do and do not tell a coach, name the likely confounders, and write a one-page experiment plan.
- Fit and check a regression on real running data, compare it with a shallow tree and a mean baseline, and fit simple models to one athlete.
- Train and test a classifier without leaking information, choose its threshold from precision and recall, and judge a forecast against persistence with a chronological split.
- Say what ten athletes, or ten sessions, can and cannot support.

# 11 Is the Change Real? Statistics and Machine Learning

Harper plays middle blocker on a university volleyball team. In week 1 Harper filmed a countermovement jump and the jump app reported 30.1 cm. Six weeks of plyometric work later, the app says 32.1 cm. Harper is pleased. The coach asks the question this chapter is about: is that 2 cm the training, or would Harper have jumped 32 cm on a good day anyway?

Every number in this book wobbles. The athlete is not the same from day to day, the camera is not placed in exactly the same spot, and the pose model puts the hip a few pixels away from where it put it last time. Statistics is the set of tools for telling a change from that wobble. Machine learning uses the same ideas to build models that predict, and then asks the same question of the model: is it right, or did it only memorize?

The chapter runs from one athlete to many. Section 11.1 measures the wobble and decides about Harper. Section 11.2 compares two ways of measuring. Section 11.3 summarizes groups. Sections 11.4 to 11.7 fit models, using a real data set of 22 runners from the course module https://apmonitor.com/dde/index.php/Main/BiomechanicRegression, and show how a model can look far better than it is. The last sections deal with data in time order and with small samples.

## 11.1 One Athlete, Many Days

Measure the same athlete twice, a few days apart, with nothing changed in between. The two numbers differ. That difference has two sources. *Biological variation* is the athlete: sleep, soreness, warm-up, mood. *Technical variation* is the measurement: camera height, lighting, the frame on which the app calls takeoff, the keypoints. You cannot separate them with one test, and for a decision you do not need to. What you need is their combined size, measured on the people and the protocol you will use.

### 11.1.1 Typical error from a test and a retest

The standard way to measure that size is a *test–retest* study: a group of athletes is measured twice under the same conditions, close enough in time that no real change is expected. Five of Harper's teammates did this with the jump app, two days apart, at the same time of day, after the same warm-up (Table 11.1).

*Table 11.1. Countermovement jump heights from the jump app, two days apart, for five teammates. Illustrative values used throughout Section 11.1.*

| Athlete | Day 1 (cm) | Day 2 (cm) | Change (cm) |
|---|---|---|---|
| A | 31.2 | 32.2 | $+1.0$ |
| B | 28.4 | 27.0 | $-1.4$ |
| C | 35.0 | 36.1 | $+1.1$ |
| D | 26.3 | 25.8 | $-0.5$ |
| E | 30.1 | 31.7 | $+1.6$ |
| Mean | 30.20 |  | $+0.36$ |
| Standard deviation | 3.26 |  | 1.26 |

Look first at the changes. They go both ways, from $-1.4$ to $+1.6$ cm. Their mean, $+0.36$ cm, is small: as a group, nobody improved in two days, which is what you expect. Their spread is what interests us. The *standard deviation* of the changes is 1.26 cm.

Each change is the difference of two noisy numbers, so it carries the noise of both. If one test has a noise of size $\sigma$, the difference of two has a noise of $\sqrt{2}\,\sigma$ (the Engineer's note below shows why). The noise of one test, the *typical error*, is therefore

$$\TE = \frac{s_\text{diff}}{\sqrt{2}},$$

where $s_\text{diff}$ is the standard deviation of the test–retest changes . For the five teammates, $\TE = 1.26/\sqrt2 = \SI{0.89}{\centi\metre}$. That is the size of the wobble in one jump test, with this app, this protocol and these athletes. Hopkins calls it the most useful single measure of reliability for exactly this reason: it is in the units of the test, so you can set it next to a change .

> **Engineer's note: Why the square root of two.**
> 
> Write one test as $x = \mu + e$, where $\mu$ is the athlete's true value and $e$ is a random error with standard deviation $\sigma$. A retest is $x' = \mu + e'$ with a new, independent error. The change is $x' - x = e' - e$. Variances of independent terms add, so $\operatorname{Var}(e'-e) = \sigma^2 + \sigma^2 = 2\sigma^2$, and the standard deviation of a change is $\sqrt2\,\sigma$. Divide by $\sqrt2$ to get back to one test. The same fact runs the other way in Section 11.1.3: the noise of a change between two single tests is $\sqrt2\,\TE$.

> **Check it by hand: Typical error from five pairs.**
> 
> Changes: $+1.0, -1.4, +1.1, -0.5, +1.6$. Mean $= 1.8/5 = 0.36$. Squared deviations from the mean: $0.410, 3.098, 0.548, 0.740, 1.538$; sum $6.332$. Divide by $n-1=4$: variance $1.583$; $s_diff = \sqrt{1.583} = 1.258$. Then $\TE = 1.258/1.414 = 0.89 cm$. Confirm with Listing 11.1.

Two practical points. First, the typical error belongs to a protocol, not to an app. Film from a different height, skip the warm-up or test at a different time of day and you have a different, usually larger, typical error. Second, five pairs give only a rough estimate. Section 11.10 puts an interval on it, and the interval is wide.

### 11.1.2 The smallest worthwhile change

The typical error says how big the noise is. It does not say how big a change has to be to matter. That is a separate number, the *smallest worthwhile change* (SWC), and it comes from the sport, not from the measurement.

For a fitness test in a team sport, where the test is a proxy and there is no race time to translate it into, a common default is a fifth of the spread between athletes:

$$\SWC = 0.2\, s_\text{between},$$

where $s_\text{between}$ is the standard deviation of the athletes' values. The 0.2 is the boundary of a “small” standardized effect (Section 11.3) . For the five teammates, $s_\text{between} = \SI{3.26}{\centi\metre}$ from the day-1 column, so $\SWC = \SI{0.65}{\centi\metre}$. In a sport scored by time or distance, the SWC is better set from the result itself, for example the change in a jump that moves an athlete one place in a typical competition. Either way, a coach and an athlete should agree on it before the retest, not after.

> **Key idea.**
> 
> Two numbers judge every change: the *typical error*, how much the test wobbles, and the *smallest worthwhile change*, how much would matter. The first comes from a retest. The second comes from the sport.

### 11.1.3 A decision rule with words

Now Harper. The change is $\Delta = 32.1 - 30.1 = \SI{2.0}{\centi\metre}$. Both numbers are single tests, so the noise in the change is $\sqrt2\,\TE = 1.414 \times 0.89 = \SI{1.26}{\centi\metre}$.

Treat the observed change as the best guess of Harper's true change, with that noise around it. Then ask three questions: how likely is it that the true change is bigger than $+\SWC$ (worthwhile gain), between $-\SWC$ and $+\SWC$ (trivial), or below $-\SWC$ (worthwhile loss)? With a normal curve for the noise,

$$P(\text{gain}) = 1 - \Phi\!\left(\frac{\SWC - \Delta}{\sqrt2\,\TE}\right),$$

where $\Phi$ is the cumulative normal distribution (the $z$-table), and the other two chances follow in the same way. Hopkins recommends reporting exactly these three chances, that the true change is beneficial, trivial or harmful . For Harper, $(0.65 - 2.0)/1.26 = -1.07$, and $1 - \Phi(-1.07) = 0.86$. The chances are 86 % gain, 12 % trivial, 2 % loss.

Numbers like these are hard to say aloud. Put words on them. Table 11.2 gives the scale used in sport science ; 86 % is “likely”. So the honest sentence is: *Harper's jump has likely improved by a worthwhile amount, but a trivial change cannot be ruled out.*

*Table 11.2. Words for chances, from Hopkins and colleagues . Use them for the chance that a true change is worthwhile.*

| Chance | Word | What you might say |
|---|---|---|
| below 0.5% | most unlikely | “almost certainly not” |
| 0.5–5% | very unlikely | “very probably not” |
| 5–25% | unlikely | “probably not” |
| 25–75% | possibly | “unclear; could go either way” |
| 75–95% | likely | “probably” |
| 95–99.5% | very likely | “very probably” |
| above 99.5% | most likely | “almost certainly” |

> **Check it by hand: Harper's 2 cm, with round numbers.**
> 
> Take $\TE = 1.0 cm$ and $\SWC = 1.0 cm$. Noise of the change: $\sqrt2 \times 1.0 = 1.41$. $z = (1.0 - 2.0)/1.41 = -0.71$. From a $z$-table, $\Phi(-0.71) = 0.24$, so $P(gain) = 0.76$: *likely*, but only just. A 90% interval for the true change is $2.0 \pm 1.645 \times 1.41$, that is $-0.3$ to $+4.3$ cm. It spans the SWC, which is why the verdict is “likely” and not “very likely”.

Figure 11.1 draws the same reasoning as intervals against the SWC band. When the whole interval is above $+\SWC$, the gain is clear. When it straddles a boundary, the chance words do the work. When the interval sits inside the band, the change is trivial whatever its sign.

*Figure 11.1. A change and its 90% interval against the band of trivial changes (shaded, $$). Harper's 2.0 cm with $=0.89 cm$ (top) reaches into the band. A 4.0 cm change with the same noise (middle) clears it. A 0.2 cm change measured with a smaller noise (bottom) stays close to zero.*

Listing~\ref{ch11-statistics:lst:te} computes all of this. The script and every other listing in the chapter are in the chapter's \texttt{code/} folder.

**Listing 11.1.** Typical error, SWC and the three chances (`code/typical_error.py`). (`code/typical_error.py`)

```python
# Typical error, smallest worthwhile change and a decision with words.
import numpy as np
from scipy.stats import norm

day1 = np.array([31.2, 28.4, 35.0, 26.3, 30.1])   # jump height, cm
day2 = np.array([32.2, 27.0, 36.1, 25.8, 31.7])
diff = day2 - day1
te = diff.std(ddof=1) / np.sqrt(2)          # typical error
swc = 0.2 * day1.std(ddof=1)                # smallest worthwhile change
print(f"mean change {diff.mean():.2f} cm, SD of changes {diff.std(ddof=1):.2f} cm")
print(f"typical error {te:.2f} cm, SWC {swc:.2f} cm")

change = 2.0                                # one athlete's gain, cm
noise = np.sqrt(2) * te                     # SD of a change score
for name, p in [("beneficial", 1 - norm.cdf((swc - change) / noise)),
                ("trivial", norm.cdf((swc - change) / noise)
                            - norm.cdf((-swc - change) / noise)),
                ("harmful", norm.cdf((-swc - change) / noise))]:
    print(f"chance {name}: {100 * p:.0f}%")
```

**Listing 11.2.** Output of Listing 11.1.

```text
mean change 0.36 cm, SD of changes 1.26 cm
typical error 0.89 cm, SWC 0.65 cm
chance beneficial: 86%
chance trivial: 12%
chance harmful: 2%
```

> **Limits and cautions: What the chances assume.**
> 
> The three chances treat the observed change as the center of a normal curve whose width is the typical error. That is fair only if the typical error was measured under the same conditions, and only if nothing else is known about Harper. Statisticians have criticized the way this “magnitude-based” reasoning was used in published sport research, because it was applied to group studies as if it were a formal test, and it called too many chance findings real . For one athlete and a training decision, use the words as a plain summary of size and noise, not as proof. When the verdict is “possibly”, the right action is a retest.

> **Try it in the app: Your own typical error.**
> 
> Film three countermovement jumps on each of two days, same place, same warm-up, phone on a tripod at waist height at 60 fps or more. Set the capture rate you filmed at. Keep the results files. Your typical error comes from the day-1 and day-2 means (Exercise 11.9).
> 
> 
> https://apopt.com/jump/jump.php

### 11.1.4 More than two tests

Two practical improvements follow from Equation~\eqref{ch11-statistics:eq:te}. Averaging $k$ trials on a day divides the typical error of that day's value by about $\sqrt{k}$, if the trials are independent: three jumps instead of one take a \SI{0.89}{\centi\metre} noise to about \SI{0.51}{\centi\metre}. And a baseline of several sessions beats a single ``before'' test, because the mean of $n$ sessions carries a noise of $\TE/\sqrt n$. Comparing one new session with a baseline mean, the noise of the difference is $\TE\sqrt{1 + 1/n}$, which is the formula the build step of this chapter uses (Section~\ref{ch11-statistics:sec:build}). Repeated measurement is the cheapest precision there is.

Some apps do this already. The disc app builds a personal baseline from your own clips and refuses to grade a measure until it has five matching representative clips; after that it grades each new throw by its distance from your personal median, in units of the median absolute deviation of those clips, scaled to a standard deviation (disc app source, \texttt{metric-registry.ts}). The idea is the same as this section: compare the athlete with the athlete, and know the wobble first.

### 11.1.5 A range by resampling
\label{ch11-statistics:sec:bootstrap}

The typical error puts a range on one test. Often you want a range on a summary of several values instead: the mean of five repeats, or their median. For a mean there is a formula (Section~\ref{ch11-statistics:sec:groups}); for a median, and for most other summaries, there is no simple one. The \term{bootstrap} gets the range by resampling~\cite{ch11-statistics:efron1993introduction}:

- From your $n$ values, draw $n$ at random \emph{with replacement}, so some appear twice and some not at all.

- Compute the summary (mean, median, anything) of that resample.

- Repeat thousands of times. The middle 95\% of the resampled summaries is a 95\% \term{bootstrap interval}.

The spread of the resampled summaries stands in for how much the summary would move if you could repeat the whole data collection.

The workout example of the Heart app (\chref{ch05-heart}) has five hard efforts with jogging between them. For each effort, take the top of the 10-second mean heart rate and the 10-second mean 60 seconds later. The difference is that repeat's one-minute recovery: 23.3, 18.5, 22.9, 29.3 and \SI{30.1}{\bpm}. (These are measured from the top of each effort, not from the end-of-work point the app uses, so they differ a little from the app's reported drop.) The mean is \SI{24.8}{\bpm} and the median \SI{23.3}{\bpm}. Like every recovery number, these are training information, to be compared only with the same athlete's recoveries after the same kind of effort.

> **Check it by hand: One resample.**
> 
> Roll a die five times, rerolling sixes: 4, 2, 2, 5, 1. The resample is efforts 4, 2, 2, 5, 1: 29.3, 18.5, 18.5, 30.1, 23.3. Its mean is $119.7/5 = 23.94$ and its median 23.3. A second roll, 3, 3, 1, 4, 3, gives 22.9, 22.9, 23.3, 29.3, 22.9: mean 24.26, median 22.9. Listing 11.3 does this ten thousand times.

**Listing 11.3.** Bootstrap intervals for the mean and median of repeats, and the cost of resampling the wrong unit (`code/bootstrap.py`). (`code/bootstrap.py`)

```python
# A range by resampling: resample the independent unit, never the samples.
from pathlib import Path
import numpy as np
import pandas as pd
DATA = Path(__file__).resolve().parent.parent / "data"
rng = np.random.default_rng(1)
B = 10000                                    # number of resamples
def interval(x, stat):
    """95% percentile interval of stat over B resamples of the values x."""
    idx = rng.integers(0, len(x), size=(B, len(x)))
    return np.percentile(stat(x[idx], axis=1), [2.5, 97.5])
real = pd.read_csv(DATA / "workout_recovery.csv")["drop"].to_numpy()
for name, f in [("mean", np.mean), ("median", np.median)]:
    lo, hi = interval(real, f)
    print(f"5 efforts, {name} {f(real):.1f} bpm, 95% interval {lo:.1f} to {hi:.1f}")

arch = pd.read_csv(DATA / "interval_archive_synthetic.csv")
lo, hi = interval(arch["drop"].to_numpy(), np.mean)
print(f"40 repeats as units: mean {arch['drop'].mean():.1f}, {lo:.1f} to {hi:.1f}")
by = arch.groupby("session")["drop"].mean().to_numpy()   # 8 sessions, 5 each
lo, hi = interval(by, np.mean)
print(f" 8 sessions as units: mean {by.mean():.1f}, {lo:.1f} to {hi:.1f}")
```

**Listing 11.4.** Output of Listing 11.3.

```text
5 efforts, mean 24.8 bpm, 95% interval 21.2 to 28.5
5 efforts, median 23.3 bpm, 95% interval 18.5 to 30.1
40 repeats as units: mean 24.8, 23.8 to 25.7
 8 sessions as units: mean 24.8, 23.0 to 26.5
```

Read the first two lines with care. The $t$ formula of Section~\ref{ch11-statistics:sec:groups} gives 18.8 to \SI{30.8}{\bpm} for the mean; the bootstrap's 21.2 to 28.5 is narrower, because resamples of five values can be no more varied than those five values. The median's interval runs from 18.5 to 30.1, the smallest value to the largest: a median of five is always one of the five, so the bootstrap can say little more than ``somewhere in the range you saw''. The bootstrap is honest with ten or more units; with five, report the values themselves beside any interval.

\paragraph{Resample the unit that is independent.} The bootstrap treats the values it draws as independent draws. The decision that matters is what to resample. Never resample individual samples: the one-second heart rates inside one recovery nearly copy their neighbors (Section~\ref{ch11-statistics:sec:time}), and resampling them gives an interval far too narrow. Within one session the unit is the repeat. Across sessions, the repeats of one day share that day's sleep, heat and fatigue, and the unit is the session. The last two lines of the listing show the cost on a \textbf{synthetic} archive of eight interval sessions of five repeats each, in which sessions differ by a day effect (made by \texttt{code/make\_new\_data.py}). Treating the 40 repeats as units gives 23.8 to \SI{25.7}{\bpm}. Resampling the eight session means gives 23.0 to \SI{26.5}{\bpm}, almost twice as wide. The second is the honest range for this athlete's usual recovery on an interval day, because the next session brings a new day, not just five more repeats. It is the rule of Section~\ref{ch11-statistics:sec:groups} again: count the independent units, not the rows.

## 11.2 Two Methods
\label{ch11-statistics:sec:two}

\chref{ch05-heart} compared a chest strap with a wrist sensor. The question there, and here, is \term{agreement}: can one method be used in place of the other? It is a different question from ``are they related?'', and it needs a different tool.

### 11.2.1 Correlation is not agreement

The jump app computes two jump heights from the same clip. One is the rise of the hip midpoint, scaled from pixels to meters. The other comes from flight time. For the second, with a pose model that tracks the toes, the app counts the athlete as airborne only once a foot is \SI{4}{\centi\metre} above the ground line, so the flight it sees is shorter than the real one; it corrects the flight time to $t = \sqrt{t_\text{obs}^2 + 8c/g}$ with $c = \SI{0.04}{\metre}$ (jump app source, \texttt{flight-time.ts}, lines 34 and 170--178). Suppose a careless analyst forgets the correction for some jumps and not for others. How far apart are the two versions?

Put $t$ into $h = g t^2/8$:

$$h_corrected = \frac{g}{8}\left(t_obs^2 + \frac{8c}{g}\right) = h_plain + c.$$

The two always differ by exactly \SI{4}{\centi\metre}. Plot one against the other over any set of jumps and you get a perfect straight line: the \term{correlation coefficient} is $r = 1.000$. Yet they never agree. A correlation measures how well one number tracks another along \emph{some} straight line, not whether they are the same number. Bland and Altman made this point in 1986, and it is still the most common error in comparing methods~\cite{ch11-statistics:bland1986statistical,ch11-statistics:atkinson1998statistical}.

### 11.2.2 Bias and limits of agreement

Bland and Altman's alternative is simple. For each pair, compute the difference $d = a - b$ and the mean $(a+b)/2$. Then report

$$bias = \bar d, limits of agreement = \bar d \pm 1.96  s_d,$$

where $s_d$ is the standard deviation of the differences. Bland and Altman's paper works with $\bar d \pm 2 s_d$ and gives 1.96 as the more precise multiplier~\cite{ch11-statistics:bland1986statistical}. The bias is the average offset. The limits of agreement are where about 95\% of individual differences will fall. A plot of difference against mean, the \term{Bland--Altman plot}, shows whether the difference grows with size and whether a few points are far out. Whether the limits are narrow enough is not a statistical question: compare them with the SWC. Limits of $\pm\SI{3}{\centi\metre}$ are useless for detecting a \SI{1}{\centi\metre} change.

When differences grow with the size of the measurement, report them as a \term{percentage error}: the limits divided by the mean, times 100. And when each person contributes several pairs, do not pool them as if they were independent people; Bland and Altman give a method for repeated pairs~\cite{ch11-statistics:bland2007agreement}.

### 11.2.3 An agreement check that finds a data error

The running data set of this chapter (Section~\ref{ch11-statistics:sec:regression}) holds, for every step, the treadmill speed, the stride rate and the stride length. A stride length can also be computed as speed divided by stride rate. If the file is consistent, the two should agree to rounding. Listing~\ref{ch11-statistics:lst:agree} checks.

**Listing 11.5.** Bias and limits of agreement, applied to stride length (`code/agreement.py`). (`code/agreement.py`)

```python
# Bland-Altman agreement: bias and 95% limits of agreement.
import numpy as np
import gait_data

def agreement(a, b):
    """Return r, bias and the 95% limits of agreement of a - b."""
    a, b = np.asarray(a, float), np.asarray(b, float)
    d = a - b
    bias, sd = d.mean(), d.std(ddof=1)
    return np.corrcoef(a, b)[0, 1], bias, bias - 1.96 * sd, bias + 1.96 * sd

d = gait_data.load(check_speed=False)       # keep every row this time
recorded = d["sl"]                          # stride length in the file, m
derived = d["speed"] / d["sr"]              # belt speed / stride rate, m
print("all rows:  r %.3f, bias %.4f m, limits %.3f to %.3f m"
      % agreement(recorded, derived))
far = (recorded - derived).abs() > 0.05
print(f"{far.sum()} rows disagree by more than 5 cm, all from runner "
      f"{d.loc[far, 'runner'].unique()} at labeled speeds "
      f"{d.loc[far, 'speed'].unique()} m/s")
print("without them: r %.3f, bias %.4f m, limits %.4f to %.4f m"
      % agreement(recorded[~far], derived[~far]))
```

**Listing 11.6.** Output of Listing 11.5.

```text
all rows:  r 0.991, bias 0.0085 m, limits -0.124 to 0.141 m
50 rows disagree by more than 5 cm, all from runner [11] at labeled speeds [3.84 4.47] m/s
without them: r 1.000, bias -0.0007 m, limits -0.0077 to 0.0062 m
```

The correlation of 0.991 would pass most people's eye. The limits of agreement, $-12$ to $+14$\,cm on a stride of about \SI{2.9}{\metre}, would not. The Bland--Altman plot (Figure~\ref{ch11-statistics:fig:ba}) shows why: almost every trial sits on zero, and two sit far above it. Both are from one runner. Their stride length times stride rate gives \SI{4.46}{} and \SI{5.36}{\metre\per\second}, not the \SI{3.84}{} and \SI{4.47}{\metre\per\second} in the speed column: the steps were run one rung higher on the speed ladder than labeled. Remove those 50 rows and the limits shrink to under \SI{1}{\centi\metre}. The agreement check did what checks are for. The rest of the chapter uses the data with those rows removed.

*Figure 11.2. Bland–Altman plot of recorded stride length against speed divided by stride rate, one point per trial (mean of its steps). The dashed line is the bias and the dotted lines the 95% limits of agreement computed from all steps. Two trials of one runner pull the limits wide; the rest lie on zero.*

> **Coach's translation: Two devices, one athlete.**
> 
> “The watch and the strap correlate at 0.95” tells you nothing useful. Ask instead: on average, how far apart are they, and how far apart can they be on a single day? If that second number is bigger than the change you care about, do not switch devices partway through a block, and never compare one device's numbers with the other's.

## 11.3 Groups
\label{ch11-statistics:sec:groups}

Sometimes the question is about a group: did the squad get faster, do runners load the leg harder at a higher speed? Three numbers answer it: the size of the effect, the interval around it, and how it compares with the spread between athletes.

### 11.3.1 Means and intervals

The running data set has each runner at a ladder of five treadmill speeds. Take the step from the first rung to the second (about \SI{0.4}{\metre\per\second} faster). For each runner, compute the change in mean peak force of the left leg. Peak force in this file is in multiples of body weight (BW; the values, about 2 to 5, match peak vertical forces in running, though the course page does not state the unit). The 21 runners with both rungs give a mean change of $+0.091\BW$.

A mean from 21 runners is itself uncertain. The \term{confidence interval} expresses that: with the $t$ distribution, a 95\% interval is $\bar x \pm t_{0.975,\,n-1}\, s/\sqrt n$. Here it is $+0.068$ to $+0.114\BW$. Read it as the range of true mean changes that fit the data. Cumming argues that intervals like this should replace yes-or-no tests as the main way to report results, because they show size and precision together~\cite{ch11-statistics:cumming2014new}.

### 11.3.2 Effect size

Is $+0.09\BW$ a lot? A \term{standardized effect size} divides the change by the spread between athletes, here the standard deviation of the runners' mean peak forces on the first rung. The result, $d = 0.40$, can be compared across measures and sports. Cohen's rough scale calls 0.2 small, 0.5 medium and 0.8 large~\cite{ch11-statistics:cohen1988statistical}; sport science uses 0.2, 0.6, 1.2, 2.0 and 4.0 for small, moderate, large, very large and extremely large~\cite{ch11-statistics:hopkins2009progressive}. By either, one rung up the ladder is a small-to-moderate increase in load. From the fourth rung to the fifth the mean change is $+0.33\BW$ (interval $+0.17$ to $+0.49$), $d = 1.07$: moderate to large.

The individual changes matter too. On the step from rung four to five, the 18 runners' changes run from $-0.08$ to $+0.94\BW$. A mean of $+0.33$ describes almost none of them. Some runners barely change; some take a much larger load. That is the reason Section~\ref{ch11-statistics:sec:one} exists: a group result tells a coach what to expect on average, and only individual measurement with a known typical error tells them about the athlete in front of them~\cite{ch11-statistics:swinton2018statistical}.

**Listing 11.7.** Change in peak force for one rung up the speed ladder (`code/groups.py`). (`code/groups.py`)

```python
# One speed step up: mean change, interval, effect size and p-value.
import numpy as np
from scipy import stats
import gait_data

d = gait_data.load()
d["level"] = (d["speed"].round(1).groupby(d["sex"])   # rung on the ladder
              .rank(method="dense").astype(int))
m = d.groupby(["runner", "level"])["lpeakforce"].mean().unstack()
for a, b in [(1, 2), (4, 5)]:
    ch = (m[b] - m[a]).dropna()             # one change per runner
    n, mean, sd = len(ch), ch.mean(), ch.std(ddof=1)
    half = stats.t.ppf(0.975, n - 1) * sd / np.sqrt(n)
    d_between = mean / m[a].std(ddof=1)     # standardized by runner spread
    p = stats.ttest_1samp(ch, 0).pvalue
    print(f"level {a}->{b}: n={n} change {mean:.3f} BW "
          f"95% CI {mean - half:.3f} to {mean + half:.3f}, "
          f"d={d_between:.2f}, p={p:.1e}, range {ch.min():.2f} to {ch.max():.2f}")
# The same 4->5 comparison with every step counted as if independent:
s4 = d.loc[d["level"] == 4, "lpeakforce"]; s5 = d.loc[d["level"] == 5, "lpeakforce"]
print(f"steps as units: n={len(s4)}+{len(s5)}, p={stats.ttest_ind(s5, s4).pvalue:.1e}")
```

**Listing 11.8.** Output of Listing 11.7.

```text
level 1->2: n=21 change 0.091 BW 95% CI 0.068 to 0.114, d=0.40, p=6.4e-08, range 0.02 to 0.26
level 4->5: n=18 change 0.328 BW 95% CI 0.171 to 0.486, d=1.07, p=4.0e-04, range -0.08 to 0.94
steps as units: n=524+496, p=4.4e-49
```

### 11.3.3 What a $p$-value answers

The output also prints a \term{$p$-value}. It answers this question: if the true mean change were exactly zero, how often would data like these turn up? For the first rung, $p = 6.4\times10^{-8}$; almost never. So the change is not zero.

A coach did not ask whether it is zero. A coach asked whether it is big enough to matter, and how sure we are. The $p$-value cannot say. It shrinks with the size of the effect \emph{and} with the amount of data, so a trivial effect becomes ``significant'' with enough rows. The last line of the output shows it. Take the rung four to rung five comparison, $p = 4.0\times10^{-4}$ with runners as the units. Counting all 1{,}020 steps on those two rungs as if they were independent athletes gives $p = 4.4\times10^{-49}$, a number 45 orders of magnitude smaller, for the same mean change. The steps are not independent; there are still only 18 runners. The American Statistical Association's statement on $p$-values puts it plainly: a $p$-value does not measure the size of an effect or the importance of a result~\cite{ch11-statistics:wasserstein2016asa}.

> **Key idea.**
> 
> Report the size, its interval and what it means in the sport. A $p$-value alone answers “is it exactly zero?”, which is rarely the coach's question. And count athletes, not rows.

### 11.3.4 What a comparison can claim
\label{ch11-statistics:sec:claim}

The comparison above is close to an experiment: the protocol set the speeds, and each runner was compared with themselves. Most athlete data are not like that. Suppose a team's watch archives show that athletes who did more strength sessions ran their easy runs faster. Did the strength work make them faster? Perhaps. But a \term{confounder}, a third thing that drives both, would produce the same pattern. Athlete data are full of them:

- \textbf{Fitness.} Fitter athletes train more of everything and run faster, so almost any training habit ``predicts'' performance.

- \textbf{Fatigue.} A heavy week lowers the next test, whatever the new drill did.

- \textbf{Weather.} Heat raises heart rate and slows pace; a block that runs from spring into summer can look like lost fitness.

- \textbf{Shoes and equipment.} A new shoe tends to arrive with a new season, a new coach or a new surface.

- \textbf{Time of day.} A test that drifts from morning to evening changes the warm-up, the meals and the sleep before it.

The same holds for a fitted slope (Section~\ref{ch11-statistics:sec:regression}). A slope describes the data you have: where $x$ is higher by one unit, $y$ is higher by $b$ on average. It is not the change you would get by changing $x$ for an athlete. Only three things move a comparison toward a cause. You can \emph{make} the change yourself and decide by chance who or which day gets it, so confounders are spread evenly. You can hold confounders fixed by design: same time, same shoes, same warm-up. Or you can measure them and compare like with like, which helps only with the confounders you thought to measure.

A plan written before testing (Section~\ref{ch11-statistics:sec:small}) makes these choices visible. For a comparison, one page names six things:

- \textbf{Question and decision}: what will be done differently depending on the answer.

- \textbf{Comparison}: what against what, and how each athlete or day is assigned (a coin, or alternation fixed in advance).

- \textbf{Controls}: what is held the same (time, surface, shoes, camera spot, warm-up).

- \textbf{Sample unit}: the thing that receives the treatment and is independent (an athlete, or a day for one athlete), and how many.

- \textbf{Likely confounders}: each one, and whether it is held fixed, randomized, measured or only admitted.

- \textbf{Measure and analysis}: the outcome, its typical error and SWC, and the words you will use for each result.

For one athlete testing a new warm-up, a good plan is ten test days at 4~p.m., indoors, with a coin deciding each day's warm-up. The unit is the day, sleep is recorded, and the result is the difference between the two warm-ups' mean jumps, judged against the typical error. Ten days of one athlete answer the question for that athlete, not for the team.

## 11.4 Regression
\label{ch11-statistics:sec:regression}

\term{Regression} fits a formula that predicts one number, the \term{target}, from others, the \term{features} or predictors. This section uses a real data set: the running mechanics data of the course module \dde{BiomechanicRegression}. The module's question is whether the peak force under a runner's left foot can be predicted from ten gait measures, the kind a camera and a pose model can estimate.

### 11.4.1 The data set and what had to be cleaned

The module offers two files. The first, \texttt{biomechanics.txt}, has the ten measures and the target, with missing values marked $-9999$. The second, \texttt{biomechanics2.txt}, has the same measures for the same kind of steps plus 38 more columns, including a step counter and both legs. This chapter uses the second, because the step counter keeps the rows in the order they were recorded. Table~\ref{ch11-statistics:tab:columns} lists the columns used. The units are not given on the course page; the ones shown are those the values are consistent with (for example, stride length equals speed divided by stride rate to the third decimal, so stride rate is in strides per second).

*Table 11.3. Columns of the running data set used in this chapter. Units inferred from the values.*

| Column | Meaning | Range in the cleaned data |
|---|---|---|
| `speed` | treadmill speed | 3.15–6.50 m/s |
| `lgt` | left-foot ground contact time | 0.12–0.27 s |
| `sr` | stride rate | 1.26–1.95 strides/s |
| `sl` | stride length | 2.0–4.1 m |
| `lkneeswing` | left knee angle at peak swing flexion | 70–145° |
| `lhipflex`, `lhipext` | left hip peak flexion, peak extension | 32 to 96°; $-37$ to 4° |
| `lcmvert` | vertical travel of the center of mass | 0.03–0.13 m |
| `lkneesep` | forward distance between the knees at toe-off | 0.15–0.46 m |
| `lcmtoe` | center of mass to toe at contact | 0.27–0.46 m |
| `lpeakforce` | left-foot peak force (target) | 2.1–4.7 |

The file names no runners. It does show their structure: rows come in trials of about 25 steps at one speed, and trials come in ladders of four or five speeds, the men's ladder from 3.35 to \SI{6.50}{\metre\per\second} and the women's from 3.15 to \SI{5.95}{\metre\per\second}. The loader in \texttt{code/gait\_data.py} treats each ladder as one runner. It is an inference, and the chapter says so wherever it matters. The loader also cleans, and each step is a lesson from \chref{ch04-python}:

- 292 rows repeat earlier rows exactly in every gait measure, including one whole runner stored twice and one trial stored under two speeds. They are removed.

- Trials shorter than 10 steps (fragments) are dropped, and the course page's range checks (contact time positive, knee angle 0--150°) are applied.

- The 50 rows whose speed label disagrees with their own stride data (Section~\ref{ch11-statistics:sec:two}) are removed.

That leaves 2{,}620 steps from 22 runners in 104 trials.

### 11.4.2 A straight line

Start with one predictor. Peak force rises with speed, and a straight line $\hat y = a + b x$ through the points is the simplest description. \term{Least squares} picks the slope $b$ and intercept $a$ that make the squared vertical distances from the points to the line as small as possible. The answer has a closed form:

$$b = \frac{\sum (x_i-\bar x)(y_i-\bar y)}{\sum (x_i - \bar x)^2},a = \bar y - b \bar x.$$

> **Check it by hand: A line through three points.**
> 
> Runner 1's mean peak force at three speeds: $(3.35,\ 2.918)$, $(4.47,\ 3.073)$, $(6.50,\ 3.251)$. Means: $\bar x = 4.7733$, $\bar y = 3.0807$. Deviations in $x$: $-1.4233, -0.3033, +1.7267$; in $y$: $-0.1627, -0.0077, +0.1703$. Sum of products $= 0.2316 + 0.0023 + 0.2941 = 0.5280$. Sum of squares in $x$ $= 2.0258 + 0.0920 + 2.9814 = 5.0993$. Slope $b = 0.5280/5.0993 = 0.1035\BW$ per m/s; intercept $a = 3.0807 - 0.1035 \times 4.7733 = 2.586\BW$. Confirm: `numpy.polyfit(x, y, 1)` gives $[0.1035,\ 2.5864]$ (`code/hand_checks.py`).

The slope is the number a coach can use: for this runner, each extra \SI{1}{\metre\per\second} of speed adds about $0.10\BW$ to the peak force under the left foot. Over all 2{,}620 steps (Listing~\ref{ch11-statistics:lst:reg}) the slope is steeper, $0.250\BW$ per \si{\metre\per\second}, and speed alone explains 47\% of the variation in peak force ($R^2 = 0.466$). The \term{coefficient of determination}, $R^2$, is the share of the target's variance that the fitted values account for. Figure~\ref{ch11-statistics:fig:force} shows the trial means and the fitted line. Notice that runners differ: at any one speed, the trial means spread over about $1\BW$. That spread between runners will matter in Section~\ref{ch11-statistics:sec:leakage}.

*Figure 11.3. Mean left-foot peak force of each trial against treadmill speed (104 trials, 22 runners), with the least-squares line fitted to all 2,620 steps. Data: https://apmonitor.com/dde/index.php/Main/BiomechanicRegression, cleaned as described in the text.*

### 11.4.3 Several predictors

With all ten measures the model becomes $\hat y = a + b_1 x_1 + \dots + b_{10} x_{10}$, fitted the same way. The \texttt{statsmodels} library~\cite{ch11-statistics:seabold2010statsmodels} prints the coefficients, their standard errors and diagnostics.

**Listing 11.9.** Peak force from one gait measure, then from ten (`code/regression.py`). (`code/regression.py`)

```python
# Peak force from gait measures: one predictor, then ten.
import statsmodels.api as sm
import gait_data

d = gait_data.load()
y = d[gait_data.TARGET]
one = sm.OLS(y, sm.add_constant(d[["speed"]])).fit()
print("slope %.3f BW per m/s, intercept %.3f, R2 %.3f"
      % (one.params["speed"], one.params["const"], one.rsquared))
ten = sm.OLS(y, sm.add_constant(d[gait_data.FEATURES])).fit()
print("ten measures: R2 %.3f, residual SD %.3f BW"
      % (ten.rsquared, ten.resid.std(ddof=11)))
print(ten.params.round(4).to_string())
print("speed p-value %.2f, Durbin-Watson %.2f"
      % (ten.pvalues["speed"], sm.stats.durbin_watson(ten.resid)))
```

**Listing 11.10.** Output of Listing 11.9.

```text
slope 0.250 BW per m/s, intercept 1.821, R2 0.466
ten measures: R2 0.644, residual SD 0.235 BW
const         6.4288
speed         0.6480
lgt          -6.4913
sr           -1.9374
sl           -0.5297
lkneeswing    0.0070
lhipflex     -0.0123
lhipext       0.0042
lcmvert       4.2702
lkneesep     -0.1489
lcmtoe       -2.3841
speed p-value 0.00, Durbin-Watson 0.38
```

$R^2$ rises from 0.47 to 0.64. The typical miss, the \term{residual} standard deviation, is $0.235\BW$. Each coefficient is the change in predicted force for one unit of that measure \emph{with the other nine held fixed}. That phrase is where multiple regression misleads. Speed, stride rate and stride length are tied together exactly: stride length is speed divided by stride rate. You cannot change one with the other two held fixed. The model can still fit, but it cannot decide how to share the credit among them, and the shares are unstable. Before the 50 mislabeled rows were removed, the same fit gave speed a coefficient of $0.035$; after, $0.648$. Stride length went from $+0.48$ to $-0.53$. Fifty rows out of 2{,}670 flipped a sign. A \term{variance inflation factor} measures the problem: it is $1/(1-R_j^2)$, where $R_j^2$ is how well predictor $j$ is explained by the others. Values above about 10 are a warning; here speed's is 740 and stride length's 452 (\texttt{code/vif.py}). The lesson for a coach: use a model like this to predict, and do not read one coefficient as ``what happens if the athlete changes this''.

> **Key idea.**
> 
> A fitted slope describes the data you have: what is higher where $x$ is higher. It does not say what will happen if an athlete changes $x$. Only a change you made, with the confounders held fixed or randomized, shows a cause (Section 11.3.4).

### 11.4.4 Residuals

A \term{residual} is the observed value minus the predicted one. Look at them before believing a fit. Plotted against the fitted values they should look like even noise; a curve means a missing term (peak force rises faster than linearly at the top speeds, Figure~\ref{ch11-statistics:fig:force}), and a fan shape means the noise grows with size. Plotted in recorded order they should not run in streaks. The Durbin--Watson statistic tests that: about 2 means no streaks, and the 0.38 here means long ones. Neighboring rows are steps of the same runner, and the model has no term for which runner it is. Section~\ref{ch11-statistics:sec:time} returns to this.

### 11.4.5 Overfitting

A flexible model can fit its training data almost perfectly. An \term{extra-trees} model (an average of many randomized decision trees) scores $R^2 = 1.00$ on the steps it was trained on. That is not skill; it is memory. The model is judged only on data it has not seen, and how you choose that unseen data is the subject of Section~\ref{ch11-statistics:sec:leakage}.

\paragraph{Scaling.} Some models measure the distance between rows: nearest
neighbors (Section~\ref{ch11-statistics:sec:leakage}) predicts a new step from the
training steps closest to it. A distance adds up the differences in every column,
so the column with the biggest numbers wins. In Table~\ref{ch11-statistics:tab:columns}
knee angle spans 75 units (70--145°) and contact time 0.15 (0.12--0.27\,s); unscaled,
the distance between two steps is almost all knee angle. \term{Scaling} puts the
columns on one footing: subtract each column's mean and divide by its standard
deviation. Those means and standard deviations are learned from data, so they are
part of the model. Fit the scaler on the training rows only and apply it unchanged
to the test rows. Fitting it on all rows before the split lets the test rows shape
the model, a small form of the leak measured in Section~\ref{ch11-statistics:sec:leakage}.
The chapter's listings put the scaler inside a pipeline,
\texttt{make\_pipeline(StandardScaler(), \ldots)} in \texttt{code/leakage.py} and
\texttt{code/classify.py}, so it is refitted inside every training split. Scaling and
splitting are steps 7 and 8 of the workflow page in the front matter; Case
Study~\ref{ch:part5-casestudies/cases/cs13-peak-force} in Part~V reproduces the
\dde{BiomechanicRegression} recipe, which scales before it splits, then audits it one
change at a time.

## 11.5 Individual Models
\label{ch11-statistics:sec:individual}

The regression above was fitted across runners. Many of the most useful models in coaching are fitted to one athlete, from a handful of efforts. Three are worth knowing.

### 11.5.1 Critical speed from two or three race results

Take two hard efforts of different lengths that the athlete has already run, usually races, say \SI{1200}{\metre} in \SI{240}{\second} and \SI{3000}{\metre} in \SI{660}{\second}. Nobody has to run an all-out trial for this course. An athlete who chooses to run a time trial does it after a full warm-up and stops at once for pain, dizziness, chest discomfort or unusual breathlessness; the heart-rate-against-speed line below needs only steady, submaximal stages and is the alternative for anyone who would rather not. Plot distance against time. The points lie close to a straight line,

$$d = CS\cdot t + D',$$

where the slope CS is the \term{critical speed} and the intercept $D'$ is a fixed distance the runner can cover above it. It is the running form of the straight line of work against time whose slope is critical power and whose intercept is $W'$~\cite{ch11-statistics:poole2016critical}.

> **Body science: What critical speed marks.**
> 
> Below critical speed, a runner's oxygen uptake and blood lactate settle to a steady value and the effort can last a long time. Above it they keep rising until the runner must stop, and the time to stop is set by how fast $D'$ is used up. Critical speed is the running form of critical power, the boundary between the heavy and severe exercise domains . Chapter 2 introduced the idea; here it is a line through two or three points.

> **Check it by hand: Critical speed from two races.**
> 
> $CS = (3000 - 1200)/(660 - 240) = 1800/420 = 4.286 m/s$. $D' = 1200 - 4.286 \times 240 = 171 m$. Add a third race, 2000 m in 425 s, and fit Equation \eqref{ch11-statistics:eq:cs} by least squares: $CS = 4.284 m/s$, $D' = 174 m$ (Listing 11.11).

Three races do not make the estimate precise; they let you see whether the points lie on a line at all. A point far off the line means a bad pacing day, or an effort the model does not describe well. The typical error of each race result carries into CS, so the rules of Section~\ref{ch11-statistics:sec:one} apply: a change in CS smaller than the noise of the races is not a change.

### 11.5.2 Heart rate against speed

On a treadmill or a measured track, run four steady stages and note the heart rate in the last minute of each. Over the middle of the range, heart rate rises close to linearly with speed. For one athlete the four stages 3.0, 3.5, 4.0 and \SI{4.5}{\metre\per\second} gave 131, 142, 154 and \SI{165}{\bpm}, and the fitted line is $\HR = 62.5 + 22.8\,v$. Weeks later the same stage at \SI{4.0}{\metre\per\second} reads \SI{149}{\bpm}, about \SI{5}{\bpm} under the line's \SI{153.7}{\bpm}. A lower heart rate at the same speed is consistent with improved aerobic fitness, but heart rate also moves with heat, hydration, sleep and caffeine. Judge the \SI{5}{\bpm} against your own typical error for that stage, measured as in Section~\ref{ch11-statistics:sec:one}, before reading anything into it.

**Listing 11.11.** Critical speed and heart rate against speed (`code/individual.py`). (`code/individual.py`)

```python
# Two individual models: critical speed and heart rate against speed.
import numpy as np

dist = np.array([1200, 2000, 3000])         # race distances, m
time = np.array([240, 425, 660])            # finishing times, s
cs, d_prime = np.polyfit(time, dist, 1)     # distance = CS * time + D'
print(f"critical speed {cs:.3f} m/s, D' {d_prime:.0f} m")
print(f"predicted 5000 m: {(5000 - d_prime) / cs:.0f} s")

speed = np.array([3.0, 3.5, 4.0, 4.5])      # treadmill stages, m/s
hr = np.array([131, 142, 154, 165])         # last-minute heart rate, bpm
slope, icpt = np.polyfit(speed, hr, 1)
print(f"HR = {icpt:.1f} + {slope:.1f} x speed")
print(f"expected at 4.0 m/s: {icpt + slope * 4.0:.1f} bpm")
```

**Listing 11.12.** Output of Listing 11.11.

```text
critical speed 4.284 m/s, D' 174 m
predicted 5000 m: 1126 s
HR = 62.5 + 22.8 x speed
expected at 4.0 m/s: 153.7 bpm
```

### 11.5.3 A load–response model

Training makes an athlete fitter and, for a while, more tired. The \term{impulse--response model} of Banister writes performance on day $t$ as a baseline plus a fitness term minus a fatigue term, each a decaying memory of past training loads $w$:

$$p(t) = p_0 + k_1 \sum_{s<t} w_s  e^{-(t-s)/\tau_1} - k_2 \sum_{s<t} w_s  e^{-(t-s)/\tau_2},$$

with a long fitness time constant $\tau_1$ and a short fatigue time constant $\tau_2$. Clarke and Skiba describe the model, and how it captures the way performance capacity changes with training, as a teaching resource~\cite{ch11-statistics:clarke2013rationale}. The four constants $k_1, \tau_1, k_2, \tau_2$ belong to one athlete and are fitted from that athlete's loads and performance tests.

Both of the course's data apps use pieces of this model. The Heart app scores a session's load as a TRIMP that weights each beat by an exponential of heart-rate reserve (Heart app source, \texttt{ecg-analysis.js}, line 796). The Watch dashboard scores each run as minutes times the square of the fraction of maximum heart rate, and keeps a 42-day ``fitness'' and a 7-day ``fatigue'' exponentially weighted average whose difference it calls form (Watch dashboard source, \texttt{fit-analysis.js}, lines 1986--1994 and 5425--5501). That is Equation~\eqref{ch11-statistics:eq:ir} with $k_1 = k_2$ and fixed time constants, not constants fitted to you. The dashboard also reports an acute:chronic workload ratio and labels a spike above 1.5 ``Load well above your recent average'' (line 5463). The label describes the load and nothing more, and rightly so: a review of that ratio found no evidence supporting its use for reducing injury risk and showed that the ratio itself adds noise~\cite{ch11-statistics:impellizzeri2020acute}. Treat it as a description of your recent load, not a forecast.

Can you fit them to yourself? Listing~\ref{ch11-statistics:lst:ff} simulates an athlete whose true constants are known (a jump test every fourth day for 16 weeks, with a typical error of \SI{0.9}{\centi\metre}), then fits the model to the tests three times with three different draws of noise.

**Listing 11.13.** Fit an impulse–response model to simulated tests (`code/fitness_fatigue.py`, lines 4–27). (`code/fitness_fatigue.py`)

```python
days = np.arange(112)
load = np.where(days % 7 < 5, 60.0, 0.0) * (1 + 0.3 * (days // 28))  # builds
load[84:] *= 0.4                            # a lighter last four weeks

def model(p, w=load):
    p0, k1, t1, k2, t2 = p
    lag = days[:, None] - days[None, :]     # days since each session
    past = lag > 0                          # only earlier days count
    fit = (w * np.exp(-lag / t1) * past).sum(axis=1)
    fat = (w * np.exp(-lag / t2) * past).sum(axis=1)
    return p0 + k1 * fit - k2 * fat

true = np.array([30.0, 0.004, 42.0, 0.010, 7.0])   # cm, per load unit, days
tests = days[::4]                           # a jump test every fourth day
print("true model: best day", np.argmax(model(true)))
for seed in range(3):
    obs = model(true)[tests] + np.random.default_rng(seed).normal(0, 0.9, len(tests))
    res = least_squares(lambda p: model(p)[tests] - obs, x0=[30, .003, 30, .008, 10],
                        bounds=([0, 0, 5, 0, 1], [60, .05, 90, .1, 30]))
    p = res.x
    print(f"seed {seed}: tau1 {p[2]:4.1f} d, tau2 {p[4]:4.1f} d, "
          f"best day {np.argmax(model(p))}, "
          f"largest gap to truth {np.abs(model(p) - model(true)).max():.2f} cm")
```

**Listing 11.14.** Output of Listing 11.13.

```text
true model: best day 98
seed 0: tau1 85.4 d, tau2  3.2 d, best day 98, largest gap to truth 0.42 cm
seed 1: tau1 33.8 d, tau2  5.1 d, best day 91, largest gap to truth 0.76 cm
seed 2: tau1 32.9 d, tau2  4.8 d, best day 91, largest gap to truth 0.63 cm
```

The fitted fitness time constant ranges from 33 to 85 days, against a true 42. Yet every fitted curve stays within \SI{0.8}{\centi\metre} of the true one, less than the test's own noise (Figure~\ref{ch11-statistics:fig:ff}). Many combinations of constants describe the same 28 tests almost equally well. The model is useful for the shape of the response to a block and a taper; its individual constants, from data like these, are not to be quoted as facts about the athlete.

*Figure 11.4. An impulse–response model fitted to a jump test every fourth day. Training builds for twelve weeks and is reduced in the last four. The fitted curve, with a fitness time constant of 34 days, tracks the true 42-day model to within the test's noise.*

### 11.5.4 A shallow tree against a line
\label{ch11-statistics:sec:tree}

The models above are fitted to one athlete. Before moving on, go back to the group data of Section~\ref{ch11-statistics:sec:regression} and compare the two simplest shapes a model can take. One is the straight line. The other is a \term{decision tree}: a short list of yes-or-no questions about the features, such as ``is contact time at most \SI{0.181}{\second}?'', in which each answer leads to the next question until a \emph{leaf} is reached. The prediction at a leaf is the mean target of the training steps that reached it. The \emph{depth} is the number of questions on the longest path, so a depth-2 tree has four leaves and a depth-3 tree eight. A tree can catch a threshold or an interaction that a line cannot, and a shallow one can be read aloud.

Judge both against a baseline that knows nothing: predict every step with the mean of the training steps. Score all three by the \term{mean absolute error} (MAE), the average size of a miss, in the units of the target. And score them on runners the model has not seen: Listing~\ref{ch11-statistics:lst:tree} holds out whole runners with \texttt{GroupKFold}, for the reason Section~\ref{ch11-statistics:sec:leakage} explains.

**Listing 11.15.** A line, two shallow trees and the mean baseline, each scored on held-out runners (`code/tree.py`). (`code/tree.py`)

```python
# A shallow tree against a line, scored on runners the model has not seen.
import numpy as np
from sklearn.model_selection import GroupKFold, cross_val_predict
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor, export_text
from sklearn.dummy import DummyRegressor
import gait_data

d = gait_data.load()
X, y, runner = d[gait_data.FEATURES], d[gait_data.TARGET], d["runner"]
models = {"mean of training": DummyRegressor(),
          "straight line": LinearRegression(),
          "tree, depth 2": DecisionTreeRegressor(max_depth=2, random_state=0),
          "tree, depth 3": DecisionTreeRegressor(max_depth=3, random_state=0)}
pred = {}
for name, m in models.items():
    pred[name] = cross_val_predict(m, X, y, cv=GroupKFold(5), groups=runner)
    print(f"{name:17s} MAE {np.abs(y - pred[name]).mean():.3f} BW")
print(export_text(models["tree, depth 2"].fit(X, y), feature_names=list(X.columns),
                  decimals=3))
```

**Listing 11.16.** Output of Listing 11.15.

```text
mean of training  MAE 0.313 BW
straight line     MAE 0.229 BW
tree, depth 2     MAE 0.267 BW
tree, depth 3     MAE 0.265 BW
|--- lgt <= 0.181
|   |--- sl <= 3.219
|   |   |--- value: [3.038]
|   |--- sl >  3.219
|   |   |--- value: [3.400]
|--- lgt >  0.181
|   |--- lgt <= 0.198
|   |   |--- value: [2.967]
|   |--- lgt >  0.198
|   |   |--- value: [2.709]
```

All three models beat the mean baseline, and the line beats both trees. The depth-2 tree is easy to read: short contacts and long strides go with high force, which is the speed story of Figure~\ref{ch11-statistics:fig:force} told in four steps. A deeper tree does not help on new runners (Exercise~\ref{ch11-statistics:ex:treedepth}).

\paragraph{A failure case.} Runner~3 has the highest forces in the data. Held out, this runner's trial means and the two models' predictions are, in \BW:
\small

| Speed (m/s) | 3.35 | 3.84 | 4.47 | 5.36 | 6.50 |
|---|---|---|---|---|---|
| Measured | 3.11 | 3.27 | 3.50 | 3.84 | 3.97 |
| Line | 2.71 | 2.87 | 3.02 | 3.23 | 3.54 |
| Tree, depth 3 | 2.73 | 2.76 | 3.01 | 3.21 | 3.21 |

Both models are too low throughout, because nothing in this runner's gait says ``high-force runner'': that is the 44\% of the variation that lies between runners (Section~\ref{ch11-statistics:sec:leakage}). But look at the two fastest trials. The tree gives both the same 3.21: they land in the same leaf, and a tree's prediction can never go above its highest leaf mean (3.45 for the depth-3 tree fitted to all runners, against measured steps up to 4.74). The line keeps rising with speed. A tree predicts in steps and cannot extrapolate; a line extrapolates whether or not it should. Choose with that in mind, and choose on held-out runners, not on the training fit.

## 11.6 Classification
\label{ch11-statistics:sec:classify}

\term{Classification} predicts a category instead of a number: made or missed, freestyle or breaststroke, walking or running, fresh or fatigued. The parts are the same as in regression. The \emph{features} are measured numbers. The \emph{labels} are the known categories. A \term{training set} is used to fit the model, and a separate \term{test set}, held back, to judge it.

As an example with the running data: can seven measures that a side-view camera could estimate (contact time, knee swing angle, hip flexion and extension, vertical travel, knee separation and the center-of-mass-to-toe distance) tell a fast step (treadmill above \SI{5}{\metre\per\second}) from a slower one? Speed, stride rate and stride length are left out, because they would give the answer away. A \term{logistic regression} turns a weighted sum of the features into a probability of ``fast'' and calls a step fast when that probability is over one half.

### 11.6.1 The confusion table

The result of a classifier on a test set is a \term{confusion table}: counts of each true category against each predicted one. With ``fast'' as the positive class:

- true positives (TP): fast steps called fast; false negatives (FN): fast steps called slow;

- false positives (FP): slow steps called fast; true negatives (TN): slow steps called slow.

Three rates summarize it:

$$accuracy = \frac{TP+TN}{all},sensitivity = \frac{TP}{TP+FN},specificity = \frac{TN}{TN+FP}.$$

Sensitivity is how many of the real positives you catch; specificity is how many of the real negatives you leave alone.

> **Check it by hand: A made-or-missed classifier.**
> 
> An app labels 100 shots from video. Of 40 made shots it calls 34 made (TP) and 6 missed (FN). Of 60 missed shots it calls 48 missed (TN) and 12 made (FP). Accuracy $= (34+48)/100 = 0.82$. Sensitivity $= 34/40 = 0.85$. Specificity $= 48/60 = 0.80$. Of the 46 shots called made, $34/46 = 0.74$ were made: the *precision*.

Accuracy alone can mislead when one class is rare (Section~\ref{ch11-statistics:sec:threshold} returns to this). If only 5\% of steps were ``fast'', a model that always says ``slow'' would be 95\% accurate and useless. Look at sensitivity and specificity, and compare accuracy with the share of the larger class (\pds{ImbalancedData}).

**Listing 11.17.** Fast or slow step, tested two ways (`code/classify.py`). (`code/classify.py`)

```python
# Easy run or fast run? A classifier tested on runners it has not seen.
import numpy as np
from sklearn.model_selection import GroupKFold, KFold, cross_val_predict
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
import gait_data

d = gait_data.load()
X = d[["lgt", "lkneeswing", "lhipflex", "lhipext", "lcmvert", "lkneesep", "lcmtoe"]]
y = (d["speed"] > 5).astype(int)            # 1 = fast (above 5 m/s)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
for name, cv, grp in [("random", KFold(5, shuffle=True, random_state=0), None),
                      ("by runner", GroupKFold(5), d["runner"])]:
    pred = cross_val_predict(model, X, y, cv=cv, groups=grp)
    tn, fp, fn, tp = confusion_matrix(y, pred).ravel()
    print(f"{name}: TP {tp} FN {fn} FP {fp} TN {tn}  accuracy "
          f"{(tp + tn) / len(y):.3f} sensitivity {tp / (tp + fn):.3f} "
          f"specificity {tn / (tn + fp):.3f}")
print(f"fast share {y.mean():.3f}")
```

**Listing 11.18.** Output of Listing 11.17.

```text
random: TP 707 FN 63 FP 66 TN 1784  accuracy 0.951 sensitivity 0.918 specificity 0.964
by runner: TP 677 FN 93 FP 106 TN 1744  accuracy 0.924 sensitivity 0.879 specificity 0.943
fast share 0.294
```

29\% of steps are fast, so a model that always says ``slow'' would score 0.71. The classifier does much better. The listing tests it twice, once with steps assigned to test sets at random and once with whole runners held out, and the second is worse on every rate. The next section explains why the second number is the honest one.

### 11.6.2 Moving the threshold
\label{ch11-statistics:sec:threshold}

A classifier that gives a probability does not decide by itself. The rule ``call it positive above one half'' is a choice, the \term{decision threshold}, and moving it trades one kind of mistake for the other. Two rates show the trade. \term{Recall} is sensitivity under another name: of the real positives, the share you caught, $\text{TP}/(\text{TP}+\text{FN})$. Precision, from the box above, is of the windows you called positive, the share that were, $\text{TP}/(\text{TP}+\text{FP})$.

A phone in a pocket records acceleration. Cut the record into 5-second windows and compute two features per window: the step cadence (\si{\hertz}) and the standard deviation of the acceleration magnitude (in $g$). Listing~\ref{ch11-statistics:lst:thresh} asks of each window, ``is this running?'', against walking and jogging. The data are \textbf{synthetic}: 4{,}800 windows from 12 people, made by \texttt{code/make\_new\_data.py} with 70\% walking, 20\% jogging and 10\% running, as in a day in which most movement is walking. The model is tested by person, with \texttt{GroupKFold}, as Section~\ref{ch11-statistics:sec:leakage} requires.

**Listing 11.19.** Running or not, at three thresholds, with the majority-class baseline (`code/thresholds.py`). (`code/thresholds.py`)

```python
# Walk, jog or run from 5-s phone accelerometer windows (synthetic data).
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupKFold, cross_val_predict

d = pd.read_csv(Path(__file__).resolve().parent.parent / "data"
                / "activity_windows_synthetic.csv")
X, y = d[["cadence_hz", "accel_sd_g"]], (d["label"] == "run").astype(int)
print(d["label"].value_counts(normalize=True).round(3).to_dict())
p = cross_val_predict(LogisticRegression(), X, y, cv=GroupKFold(4),
                      groups=d["person"], method="predict_proba")[:, 1]
for cut in [0.2, 0.5, 0.8]:
    call = p >= cut
    tp, fp = (call & (y == 1)).sum(), (call & (y == 0)).sum()
    fn = (~call & (y == 1)).sum()
    print(f"threshold {cut}: TP {tp} FP {fp} FN {fn}  precision {tp/(tp+fp):.2f}"
          f"  recall {tp/(tp+fn):.2f}  accuracy {(call == y).mean():.3f}")
print(f"always 'not run': accuracy {(y == 0).mean():.3f}, recall 0.00")
```

**Listing 11.20.** Output of Listing 11.19.

```text
{'walk': 0.7, 'jog': 0.2, 'run': 0.1}
threshold 0.2: TP 463 FP 178 FN 17  precision 0.72  recall 0.96  accuracy 0.959
threshold 0.5: TP 408 FP 35 FN 72  precision 0.92  recall 0.85  accuracy 0.978
threshold 0.8: TP 268 FP 4 FN 212  precision 0.99  recall 0.56  accuracy 0.955
always 'not run': accuracy 0.900, recall 0.00
```

At a threshold of 0.2 the model catches 96\% of running windows, but 28\% of the windows it calls running are fast jogs. At 0.8 almost every ``run'' is right, but it misses 44\% of the running. Neither is wrong. The threshold should follow the cost of each mistake in the use: an app that counts running minutes for a weekly load wants the two kinds of error about equal, so that they cancel in the total; an app that asks ``you seem to be running, start a session?'' wants high precision, because false alarms annoy. Choose the threshold on training data, or on a separate validation set, and only then score it on the test set.

### 11.6.3 Why accuracy misleads

Look down the accuracy column. While recall moved from 0.56 to 0.96, accuracy moved only between 0.955 and 0.978. And the last line shows a model with no skill at all: always say ``not running''. It scores 0.900, because 90\% of windows are not running, and it never finds a single run. That number is the \term{majority-class baseline}, and every accuracy should be reported beside it. When one class is rare, a case of \term{class imbalance}, accuracy is mostly a score on the common class. Report instead the confusion table, precision and recall for the class you care about, and the baseline. On imbalanced data the precision--recall view is the more informative one, because it judges the positive calls directly rather than through the large count of easy negatives~\cite{ch11-statistics:saito2015precision}. Two fixes for a rare class are to move the threshold and to weight the rare class more in training (Exercise~\ref{ch11-statistics:ex:imbalance}). One thing is never a fix: changing the mix of the test set, which must look like the data the model will meet.

## 11.7 Leakage
\label{ch11-statistics:sec:leakage}

\term{Leakage} is information in the training data that would not be available when the model is used for real, and that makes the test score look better than the model is~\cite{ch11-statistics:kaufman2012leakage}. In athlete data the most common leak is simple: rows from the same athlete on both sides of the split.

### 11.7.1 The leak, measured

The course module scores its models by putting a random 20\% of the rows in the test set. Every runner then has steps on both sides. The model can learn ``this runner's steps look like this and have this force'' from the training rows and use it on that runner's test rows. That is not a skill it will have on a new runner. Listing~\ref{ch11-statistics:lst:leak} scores three models four ways: on their own training rows; with 5-fold \term{cross-validation} over randomly shuffled steps; with whole trials held out; and with whole runners held out (\texttt{GroupKFold} in \texttt{scikit-learn}~\cite{ch11-statistics:pedregosa2011scikit}).

**Listing 11.21.** The same models, scored with four splits (`code/leakage.py`). (`code/leakage.py`)

```python
# The same models scored with a random split and with a split by runner.
from sklearn.model_selection import KFold, GroupKFold, cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import gait_data

d = gait_data.load()
X, y = d[gait_data.FEATURES], d[gait_data.TARGET]
models = {"linear": LinearRegression(),
          "5 neighbors": make_pipeline(StandardScaler(), KNeighborsRegressor(5)),
          "extra trees": ExtraTreesRegressor(200, random_state=0, n_jobs=-1)}
splits = {"random steps": (KFold(5, shuffle=True, random_state=0), None),
          "by trial": (GroupKFold(5), d["trial"]),
          "by runner": (GroupKFold(5), d["runner"])}
print(" " * 12 + "  train  random  trial  runner   (R2)")
for name, model in models.items():
    r2 = [model.fit(X, y).score(X, y)]     # scored on its own training rows
    r2 += [cross_val_score(model, X, y, cv=cv, groups=grp).mean()
           for cv, grp in splits.values()]
    print(f"{name:12s}" + "".join(f"{v:7.2f}" for v in r2))
```

**Listing 11.22.** Output of Listing 11.21: $R^2$ on unseen data, averaged over five folds.

```text
              train  random  trial  runner   (R2)
linear         0.64   0.64   0.48   0.32
5 neighbors    0.95   0.92   0.15   0.12
extra trees    1.00   0.93   0.18   0.38
```

*Figure 11.5. The same three models scored three ways on the running data. Random splits put steps of every runner on both sides and make the flexible models look excellent. Holding out whole runners shows what they do for a runner they have not seen.*

The random split says the nearest-neighbor model explains 92\% of the variance in peak force. Held out by runner, it explains 12\%. The course page, with a random 80/20 split of the first file, reports an $R^2$ of 0.94 for an extra-trees model; held out by runner here, the same kind of model scores 0.38. The flexible models fell furthest because they are best at memorizing. The linear model, which cannot memorize much, fell least. The ranking of the models changed too: by runner, extra trees and the plain linear model are close, and nearest neighbors is worst. Saeb and colleagues showed the same pattern in wearable-sensor studies, where record-wise splits overstated accuracy compared with subject-wise splits~\cite{ch11-statistics:saeb2017need}.

Why is the gap so big here? Recall Figure~\ref{ch11-statistics:fig:force}: at one speed, runners differ by about $1\BW$. In fact 44\% of all the variation in peak force lies between runners' means (\texttt{code/autocorr.py}). A model that recognizes the runner gets that 44\% nearly free. Hold the runner out and it must predict the level from gait alone, which is the real task. Holding out whole trials removes most of the apparent skill too: for the linear model it lands between the random and the runner split, and for the two flexible models it is as low as holding out runners, even though each runner's other speeds stay in training.

### 11.7.2 Splitting by athlete and by day

Choose the split to match the use:

- \textbf{A model for new athletes} (a team screening tool, an app): split by athlete. No athlete in the test set may appear in training.

- \textbf{A model for the same athletes in the future} (a personal model): split by time. Train on earlier days, test on later days. Never let rows from the test day, or after it, into training.

- \textbf{Frames and steps}: never split them at random. Neighboring frames of a video are near copies of each other (Section~\ref{ch11-statistics:sec:time}).

Other leaks to check for: scaling or selecting features using the whole data set before splitting (fit the scaler on the training set only, \pds{ScaleData}); duplicated rows, like the 292 found in Section~\ref{ch11-statistics:sec:regression}, which put identical rows on both sides; and features that contain the answer, like speed when the label is ``fast''. The course project asks for a written \emph{leakage audit} for this reason (\pds{CourseProject}).

> **Check the AI: A model that is too good.**
> 
> You ask an AI assistant to predict peak force from the running data. It returns code with `train_test_split(X, y, test_size=0.2, random_state=1)`, an extra-trees model, and the message: “Excellent results: $R^2 = 0.94$ on the test set. The model can predict a runner's peak force from video features with high accuracy.” The code runs and the number is right. What is wrong with the claim, and what one change would you ask for? (Answer: the split is by row, so every runner is in both sets; ask for `GroupKFold` by runner, and expect about 0.4.)

## 11.8 Time Series
\label{ch11-statistics:sec:time}

Most athlete data come in time order: frames, steps, heartbeats, days. Three ideas handle them.

A \term{trend} is a slow change, the thing you usually want to see. A \term{rolling window} estimates it: the mean of the last seven days, recomputed each day, smooths day-to-day noise at the cost of reacting late. Figure~\ref{ch11-statistics:fig:hr} shows six weeks of simulated morning heart rate with a 7-day rolling mean, against a band of $\pm 1$ standard deviation around the first four weeks' mean. In the sixth week the true level rises by \SI{4}{\bpm}. Only three of the seven mornings fall above the band; the rolling mean climbs from 49.9 to \SI{53.5}{\bpm} and makes the shift plain. Single days are noisy; a week is a better unit for a decision.

*Figure 11.6. Six weeks of simulated morning heart rate. The shaded band is the mean $1$ standard deviation of the first 28 days. The true level rises by 4 bpm after day 35 (dashed line); the rolling mean shows it more clearly than the single mornings do.*

\term{Autocorrelation} is the correlation of a series with itself shifted by one or more samples. The morning series has a lag-1 autocorrelation of 0.37: a high morning tends to follow a high morning. This matters because most formulas for intervals assume independent samples. A series of $n$ samples with lag-1 autocorrelation $r$ carries roughly the information of

$$n_eff \approx n \frac{1-r}{1+r}$$

independent ones. This is a standard approximation for a series in which each sample remembers only the last; Hyndman and Athanasopoulos define the autocorrelation and show how to plot it for every lag .

The running data show where the dependence comes from. Within a trial, one step's peak force barely predicts the next: the median lag-1 autocorrelation over 104 trials is 0.10. But the residuals of the ten-measure regression, taken in recorded order, have a lag-1 autocorrelation of 0.81. By Equation \eqref{ch11-statistics:eq:neff}, the 2{,}620 rows carry about as much independent information as 278. The step-to-step memory is small; the shared runner is what makes neighbors alike. This is the same fact that made the random split leak and the step-counted $p$-value tiny. Each says: count the units that are independent, which here are runners.

**Listing 11.23.** Dependence within trials and across the data set (`code/autocorr.py`). (`code/autocorr.py`)

```python
# Are neighboring steps independent? Two ways to look.
import numpy as np
import statsmodels.api as sm
import gait_data

d = gait_data.load()
r1 = [np.corrcoef(f[:-1], f[1:])[0, 1] for _, g in d.groupby("trial")
      for f in [g.sort_values("step")["lpeakforce"].to_numpy()] if len(f) >= 20]
print(f"within a trial: median lag-1 r {np.median(r1):.2f} over {len(r1)} trials")

fit = sm.OLS(d["lpeakforce"], sm.add_constant(d[gait_data.FEATURES])).fit()
e = fit.resid.to_numpy()                    # rows are in recorded order
r = np.corrcoef(e[:-1], e[1:])[0, 1]
n = len(e)
print(f"model residuals: lag-1 r {r:.2f}; {n} rows carry about "
      f"{n * (1 - r) / (1 + r):.0f} rows' worth of independent information")
share = d.groupby("runner")["lpeakforce"].mean().var() / d["lpeakforce"].var()
print(f"share of peak-force variance between runner means: {share:.2f}")
```

**Listing 11.24.** Output of Listing 11.23.

```text
within a trial: median lag-1 r 0.10 over 104 trials
model residuals: lag-1 r 0.81; 2620 rows carry about 278 rows' worth of independent information
share of peak-force variance between runner means: 0.44
```

### 11.8.1 A forecast has to beat “same as last week”

A forecast predicts the next value of a series from its past: next week's training minutes from the weeks before. The simplest forecast is “same as last week”. It is called the *persistence baseline*, or the naive method, and it is hard to beat: forecasting texts use it as the benchmark any method must clear before it is worth using . Listing 11.25 builds a forecast from a watch archive in four steps. The archive is **synthetic**: two years of runs, three to five a week on irregular days, with a seasonal rhythm and six weeks in which nothing was recorded (`code/make_new_data.py`).

- **Sum by week.** Runs come on irregular dates; a weekly sum puts them on a regular grid. A week with no recorded runs is *missing*, a watch left at home, not a week of rest, unless the athlete's log says rest. Coding it as zero would teach the model a rest week that never happened.

- **Use only the past.** A *lag feature* is the series shifted back: last week's minutes, the week before. A rolling mean of the last four weeks is shifted by one week *before* it is averaged, so the week being forecast is never inside it.

- **Split by time.** A *chronological split* trains on the earlier weeks and tests on the last 26. A random split would let the model learn from the weeks after the one it predicts.

- **Compare with persistence.** Score every method by its MAE on the same test weeks.

**Listing 11.25.** Forecast next week's minutes and compare with persistence (`code/forecast.py`). (`code/forecast.py`)

```python
# Next week's training minutes: a model must beat "same as last week".
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

runs = pd.read_csv(Path(__file__).resolve().parent.parent / "data"
                   / "watch_runs_synthetic.csv", parse_dates=["date"])
wk = runs.resample("W-SUN", on="date")["minutes"].sum()   # weeks end on Sunday
wk[wk == 0] = np.nan                     # no runs recorded: missing, not rest
f = pd.DataFrame({"y": wk, "lag1": wk.shift(1), "lag2": wk.shift(2),
                  "mean4": wk.shift(1).rolling(4, min_periods=3).mean()}).dropna()
train, test = f.iloc[:-26], f.iloc[-26:]           # chronological split
mae = lambda pred: np.abs(test["y"] - pred).mean()
lin = LinearRegression().fit(train[["lag1", "lag2", "mean4"]], train["y"])
print(f"{len(wk)} weeks, {wk.isna().sum()} missing; train {len(train)}, test {len(test)}")
print(f"persistence (last week) MAE {mae(test['lag1']):.1f} min")
print(f"mean of last 4 weeks    MAE {mae(test['mean4']):.1f} min")
print(f"linear on lags          MAE {mae(lin.predict(test[['lag1', 'lag2', 'mean4']])):.1f} min")
cen = wk.rolling(5, center=True, min_periods=3).mean()   # uses the future!
print(f"centered 5-week mean    MAE {mae(cen.loc[test.index]):.1f} min  (leaks)")
```

**Listing 11.26.** Output of Listing 11.25.

```text
104 weeks, 6 missing; train 57, test 26
persistence (last week) MAE 22.1 min
mean of last 4 weeks    MAE 25.5 min
linear on lags          MAE 23.1 min
centered 5-week mean    MAE 14.0 min  (leaks)
```

The regression on lags does not beat persistence, and neither does the four-week mean. That is a result, and it goes in the report: with 57 training weeks and a series that wanders from week to week, the best guess for next week is this week (Figure 11.7). The missing weeks cost something too. Every week that lacks a lag is dropped, and 21 of the 78 earlier weeks were lost to the start of the series and to the six gaps.

The last line is a warning about smoothing. A centered 5-week mean, the kind a plotting tool draws to make a series look smooth, scores 14.0, far better than anything else. It uses the two weeks *after* the one it “predicts”. Any smoother that looks both ways, applied to the whole series before the features are made, leaks the future in the same way. Smooth with a trailing window, as the four-week mean does, and expect it to lag behind real changes, as the rolling mean of Figure 11.6 did.

*Figure 11.7. Two years of weekly training minutes from a synthetic watch archive. Gaps are weeks with no recorded runs, kept as missing. The shaded test period holds the last 26 weeks, where the dashed line is the persistence forecast, last week's value.*

## 11.9 Small Data, Honestly

A class project will have ten athletes, or one athlete and ten sessions. That is enough for some questions and not for others, and it is better to know which before collecting.

### 11.9.1 What ten athletes can show

Two numbers set the limits. The 95% interval of a mean from $n$ athletes is about $\pm t_{0.975,\,n-1}/\sqrt n$ standard deviations wide: $\pm1.24$ SD with 5 athletes, $\pm0.72$ with 10, $\pm0.47$ with 20 and $\pm0.32$ with 40. And the *statistical power* of a study, the chance it detects an effect of a given size, is low for small effects. With 10 athletes measured before and after, a paired test at the usual 5% level detects a medium effect ($d = 0.5$) only 29% of the time, and needs 34 athletes to reach 80%. A large effect ($d = 0.8$) needs 15. A small one ($d = 0.2$) needs 199 (`code/small_data.py`).

So ten athletes can show a large average effect, describe each athlete's own change against their typical error, and generate questions. They cannot show that a small average effect is real, and they cannot show that an effect is absent: “we found no difference” from ten athletes usually means “we could not have found one”.

### 11.9.2 Write the plan first

The defense against fooling yourself with small data is to decide before you look. *Preregistration* means writing down, before data collection, the question, the measure, the analysis and what result would count as an answer . Sport science has been urged to adopt it, and the journal form of it, the Registered Report, in which the plan is reviewed before the data exist . A class version fits on half a page:

- The question, in one sentence, and the decision it serves.

- The measure, the app or device, the protocol, and the typical error you will use (measured or planned).

- The smallest worthwhile change, and why.

- Who: how many athletes or sessions, and the rule for excluding a trial (written now, not after seeing it).

- The analysis: the exact comparison, the split for any model, and the words you will use for each outcome.

### 11.9.3 Report what did not work

Report every measure you planned, including those that showed nothing, and every trial you dropped, with the reason. Say what the data cannot show. A short “What we could not tell” paragraph is a mark of good work, not a weakness. If the leakage audit lowered your model's score from 0.92 to 0.12, report both numbers and say which one an athlete should believe.

## 11.10 How Good Is the Number?

This chapter's “numbers” are statistics, and they have their own errors.

\paragraph{The typical error is itself uncertain.} Five pairs give four degrees of freedom. A 90% interval for a standard deviation uses the chi-squared distribution: $\TE\sqrt{\nu/\chi^2_{0.95,\nu}}$ to $\TE\sqrt{\nu/\chi^2_{0.05,\nu}}$ with $\nu = 4$. For $\TE = \SI{0.89}{\centi\metre}$ that is 0.58 to 2.11 cm. The true wobble could be twice what was measured. Hopkins recommends far more than five athletes and more than two trials for a reliability study ; for a class, pool the whole class's pairs and say how many you used.

\paragraph{The typical error depends on the protocol.} A camera that moves between sessions, a different warm-up or a different time of day adds variation the test–retest did not include. Measure the typical error under the conditions of the decision.

\paragraph{The measurement's own resolution.} For a jump timed by flight, one frame at 60 fps on a 0.50 s flight changes the height from 30.65 to 32.72 cm: about 2 cm, the same size as Harper's gain. A jump app's typical error cannot be smaller than what one frame costs. Film faster if the decision depends on centimeters (Chapter 8, Chapter 10).

\paragraph{Read a band with its definition.} The disc app's personal bands are built from the median absolute deviation (MAD) of your clips. For normal noise the raw MAD is only about 0.67 standard deviations, so a band of $\pm1.5$ raw MADs would be about $\pm1.0$ SD, and about a third of genuinely unchanged throws would fall outside it. The app therefore multiplies the MAD by 1.4826 ($1/0.6745$) before using it, so its “Elite” band of $\pm1.5$ scaled MADs is about $\pm1.5$ SD, and about 13%, one unchanged throw in eight, still falls outside it. Even a well-built band flags some throws that did not change.

\paragraph{The split decides the score.} A model's $R^2$ or accuracy is only as honest as the split it was tested on (Section 11.7). Ask how it was split before you ask how good it is.

\paragraph{Inferred structure.} The runner labels in this chapter's data were inferred from the speed ladders, and one inferred runner may still be two people. The grouped results would change a little with a different inference; their direction would not.

## 11.11 Telling the Athlete

The hardest message in this chapter is “your result is within the noise”. Done badly, it tells an athlete their work did nothing. Done well, it keeps them training and tells them when you will know more.

Suppose a different athlete, Riley, retested after four weeks and gained 0.5 cm, with a typical error of 0.89 cm and an SWC of 0.65 cm. The chances are 45% worthwhile gain, 37% trivial and 18% loss: “possibly”, which means unclear.

**A poor version.**
“Your jump went from 30.4 to 30.9 cm. That's not statistically significant ($p > 0.05$), so there's no real improvement. The typical error is 0.89 cm, so the change is within measurement error.”

It is accurate and it fails. It uses a $p$-value the athlete cannot use, it turns “we cannot tell yet” into “no improvement”, it gives the athlete nothing to do, and it ends on the word “error”.

**A better version.**
“Your jump was 30.9 cm today, up half a centimeter from 30.4. On this test, a jump can move about a centimeter from day to day with no change in you, so we can't tell yet whether that half centimeter is the training. Keep the plan as it is. We'll test again in three weeks with three jumps instead of one, which makes the number steadier, and then we'll know more.”

It states the number, gives the noise in the athlete's units, says plainly what is and is not known, gives one action (keep going), and names the reassessment and how it will be more precise. It makes no claim the data do not support. Compare the five-line rubric of the communicate exercises: accurate, plain, one recommendation, uncertainty stated, within scope.

> **Coach's translation: Words that work.**
> 
> “We can't tell yet” instead of “no change”. “The test wobbles about a centimeter” instead of “measurement error”. “Likely” and “very likely” instead of percentages. Always end with what happens next.

## 11.12 Build Step B-11: A Baseline on the Device

This week your app learns the athlete. It stores every session on the device and judges a new result against the athlete's own earlier ones, using the ideas of Section 11.1. Nothing leaves the phone.

The judgment needs only the mean and standard deviation of the stored values. One new result compared with the mean of $n$ earlier sessions has noise $s\sqrt{1+1/n}$, where $s$ is the standard deviation of those sessions (the athlete's own typical error, if nothing has changed over them). The rule, in the same spirit as the disc app's personal baseline:

- Fewer than five sessions: say “baseline building (3/5)” and grade nothing.

- Change smaller than the SWC: “within your usual range”.

- Change at least the SWC and more than two noise units: “clearly higher (or lower) than usual”.

- Otherwise: “possibly higher (or lower) than usual; retest”.

**Listing 11.27.** B-11: store sessions and judge a new result (`code/baseline.js`). (`code/baseline.js`)

```python
// B-11: keep sessions on the device and judge a new result against them.
export function judge(history, value, swc, minSessions = 5) {
  const n = history.length;
  if (n < minSessions) return { n, word: `baseline building (${n}/${minSessions})` };
  const mean = history.reduce((s, v) => s + v, 0) / n;
  const sd = Math.sqrt(history.reduce((s, v) => s + (v - mean) ** 2, 0) / (n - 1));
  const diff = value - mean;
  const z = diff / (sd * Math.sqrt(1 + 1 / n));   // noise of one new value vs a mean
  const dir = diff > 0 ? "higher" : "lower";
  let word = `possibly ${dir} than usual; retest`;
  if (Math.abs(diff) < swc) word = "within your usual range";
  else if (Math.abs(z) >= 2) word = `clearly ${dir} than usual`;
  return { n, mean, sd, diff, z, word };
}

export function loadSessions(key, store = globalThis.localStorage) {
  try { return JSON.parse(store.getItem(key)) ?? []; } catch { return []; }
}

export function saveSession(key, session, store = globalThis.localStorage) {
  const all = [...loadSessions(key, store), session];
  try { store.setItem(key, JSON.stringify(all)); } catch { /* full or blocked */ }
  return all;
}
```

Browser `localStorage` keeps a few megabytes of text per site, survives reloads, and stays on the device. Every read and write is wrapped in `try`: storage can be full, blocked, or empty in a private window, and the page must still work. Pass a stand-in store in tests, as `code/baseline.test.mjs` does. Its known answer: five sessions of 30.1, 31.0, 29.6, 30.4 and 30.9 cm have mean 30.40 and standard deviation 0.579; a new 32.1 cm with an SWC of 0.65 gives $z = 2.68$ and “clearly higher than usual”. Run it with `node baseline.test.mjs`; it must print `all tests pass`. Exercise 11.19 turns this into a page with a chart of the athlete's range.

> **Limits and cautions: Privacy of a stored history.**
> 
> A stored history of one person's results is personal data. Keep it on the device, key it by an athlete code rather than a name, give the athlete a button that deletes it, and export it only when the athlete asks.

## Going Further

The machine-learning course modules cover the same ground with more code: https://apmonitor.com/pds/index.php/Main/StatisticsMath, https://apmonitor.com/pds/index.php/Main/FeatureEngineering, https://apmonitor.com/pds/index.php/Main/ScaleData, https://apmonitor.com/pds/index.php/Main/SplitData, https://apmonitor.com/pds/index.php/Main/ImbalancedData, https://apmonitor.com/pds/index.php/Main/RegressionOverview, https://apmonitor.com/pds/index.php/Main/LinearRegression and https://apmonitor.com/pds/index.php/Main/ClassificationOverview. The running data set and its original notebook are at https://apmonitor.com/dde/index.php/Main/BiomechanicRegression. Hopkins' review of reliability  and Atkinson and Nevill's  are the two papers to read next.

## Summary

- Every measure wobbles. Measure the wobble, the typical error, with a test and retest: $\TE = s_\text{diff}/\sqrt2$.

- The bootstrap puts a range on a mean or median by resampling. Resample the independent unit (the repeat within a session, the session across days), never individual samples; with five values, show the values.

- Set the smallest worthwhile change from the sport (a default is $0.2$ of the between-athlete SD), before the retest.

- Judge one athlete's change against both, with noise $\sqrt2\,\TE$, and say the result in words: likely, unclear, very likely.

- Agreement is bias and limits of agreement, not correlation. A perfect correlation can hide a constant offset.

- For groups, report the size, its interval and an effect size; a $p$-value answers only whether the effect is exactly zero, and it shrinks with the number of rows. Count athletes, not rows.

- A slope or a difference in observational data can come from a confounder (fitness, fatigue, weather, shoes, time of day). Only a change you assign, with confounders held fixed or randomized, shows a cause. Plan the comparison, controls, sample unit and confounders on one page first.

- Regression coefficients of tied predictors are unstable; check residuals; judge any model on data it has not seen.

- Compare every model with a baseline. On held-out runners the line (MAE $0.229\BW$) beat depth-2 and depth-3 trees (0.267, 0.265) and the mean (0.313); a tree predicts in steps and cannot extrapolate.

- Individual models (critical speed, heart rate against speed, load–response) fit one athlete; their constants can be poorly determined even when the curve fits.

- Leakage makes models look better than they are. Split by athlete for new athletes and by time for the same athletes. On the running data a random split gave $R^2 = 0.92$ where holding runners out gave 0.12.

- A threshold trades precision against recall. With a rare class, accuracy follows the majority-class baseline; report precision, recall and the baseline.

- A forecast uses only the past (lags, trailing means), is tested on later weeks, and must beat persistence, “same as last week”. Missing weeks are missing, not zero; a centered smoother leaks the future.

- Neighboring samples are not independent; the effective sample size can be a tenth of the row count.

- Ten athletes can show large effects and individual changes; plan the analysis first and report what did not work.

*Table 11.4. Formulas of Chapter 11.*

| Quantity | Formula |
|---|---|
| Typical error | $\TE = s_\text{diff}/\sqrt2$ |
| Smallest worthwhile change (default) | $\SWC = 0.2\,s_\text{between}$ |
| Noise of a change between two tests | $\sqrt2\,\TE$ |
| Noise of one test against a mean of $n$ | $\TE\sqrt{1+1/n}$ |
| Chance of a worthwhile gain | $1-\Phi\big((\SWC-\Delta)/(\sqrt2\,\TE)\big)$ |
| Limits of agreement | $\bar d \pm 1.96\,s_d$ |
| 95% interval of a mean | $\bar x \pm t_{0.975,n-1}\,s/\sqrt n$ |
| Least-squares slope | $b = \sum(x-\bar x)(y-\bar y)/\sum(x-\bar x)^2$ |
| Critical speed | $d = \text{CS}\,t + D'$ |
| Accuracy, sensitivity, specificity | $\frac{TP+TN}{N}$ , $\frac{TP}{TP+FN}$ , $\frac{TN}{TN+FP}$ |
| Precision, recall | $\frac{TP}{TP+FP}$ , $\frac{TP}{TP+FN}$ |
| Mean absolute error | $\frac1n\sum\|y_i-\hat y_i\|$ |
| Effective sample size | $n(1-r)/(1+r)$ |

**New terms.** typical error; test–retest; smallest worthwhile change; agreement; bias; limits of agreement; Bland–Altman plot; percentage error; bootstrap; bootstrap interval; confidence interval; effect size; $p$-value; confounder; regression; residual; least squares; coefficient of determination; variance inflation factor; overfitting; decision tree; mean absolute error; critical speed; impulse–response model; classification; confusion table; sensitivity; specificity; precision; recall; decision threshold; majority-class baseline; class imbalance; leakage; cross-validation; grouped split; trend; rolling window; autocorrelation; lag feature; chronological split; persistence baseline; effective sample size; statistical power; preregistration.

**Track it:** the typical error and smallest worthwhile change of each battery test (Appendix J).

## Exercises

> **Course use: Week 11.**
> 
> **P22** (due Class 22, *Measure*): 11.1, 11.2, 11.5, 11.9, 11.18, 11.26; about 115 minutes.
> 
> **P23** (due Class 23, *Model and tell*): 11.11, 11.19, 11.20, 11.21, 11.29, 11.32; about 190 minutes. A case-file exercise may be done on your own data instead. The full map is in the Course Guide.

> **Project step: Week 11.**
> 
> The team project: checkpoint 2 is due with P22 (Class 22). What to hand in is in Appendix G.

**Exercise 11.1** (Concept check · Foundation · 2 min · CORE)

A sprint coach says the timing gates' typical error for a 20 m sprint is 0.03 s. What does that number describe?
\choices{The amount by which the gates read faster than a stopwatch}
{How much one athlete's time would vary from test to test with no real change}
{The smallest improvement in sprint time that matters in a race}
{The spread of 20 m times between the athletes on the team}

**Exercise 11.2** (Concept check · Foundation · 2 min · CORE)

A watch and a chest strap recorded the same ten interval sessions. The average heart rates correlate at $r = 0.98$. What can you conclude?
\choices{The two devices agree to within about 2 %}
{The watch can replace the strap for this athlete}
{The watch reads high, because a correlation below 1 shows a bias}
{The two rise and fall together, but how far apart they are is still unknown}

**Exercise 11.3** (Concept check · Core · 2 min)

A student's model predicts sprint split times from video. It scores $R^2 = 0.92$ with a random 80/20 split of the frames and $R^2 = 0.12$ when whole athletes are held out. The app will be used on athletes who were not in the data. Which score belongs in the report?
\choices{0.12, because new athletes are the use and the random split puts every athlete on both sides}
{0.92, because it uses more of the data for training}
{The average, 0.52, because neither split is perfect}
{Neither; $R^2$ cannot be computed for frames}

**Exercise 11.4** (Concept check · Core · 2 min)

An analysis of 2{,}620 running steps from 22 runners finds that peak force differs between two shoe conditions with $p = 10^{-12}$. What does the $p$-value tell a coach?
\choices{The difference is large enough to change shoe choice}
{There is a $10^{-12}$ chance that the shoes have no effect}
{Data like these would be very rare if the true difference were exactly zero, and nothing about its size}
{The result will replicate in another group of runners}

**Exercise 11.5** (Hand calculation · Foundation · 10 min · CORE)

Five athletes did a jump test twice, two days apart (heights in cm): day 1: 42.0, 38.5, 45.2, 40.1, 36.8; day 2: 43.1, 37.9, 44.0, 41.6, 37.0.

- Compute the five changes, their mean and their standard deviation. *Checkpoint:* {changes $+1.1, -0.6, -1.2, +1.5, +0.2$; mean $0.20$; SD $1.13$ cm.}

- Compute the typical error. *Checkpoint:* {0.80 cm.}

- Compute the SWC as $0.2$ times the day-1 standard deviation. *Checkpoint:* {day-1 SD 3.25; SWC 0.65 cm.}

- An athlete improves by 1.5 cm. Compute the noise of the change and the chance of a worthwhile gain, and give the word from Table 11.2. *Checkpoint:* {noise 1.13; $z=-0.75$; 77%, likely.}

- Repeat (d) for a 3.0 cm gain. *Checkpoint:* {98%, very likely.}

**Exercise 11.6** (Hand calculation · Core · 10 min)

A chest strap and a watch recorded six steady efforts (mean heart rate, bpm): strap 142, 150, 158, 163, 171, 176; watch 145, 149, 163, 161, 178, 180.

- Compute the differences (watch minus strap) and the bias. *Checkpoint:* {$3, -1, 5, -2, 7, 4$; bias 2.67 bpm.}

- Compute the standard deviation of the differences and the 95% limits of agreement. *Checkpoint:* {SD 3.50; limits $-4.2$ to 9.5 bpm.}

- The correlation is 0.974. Explain in two sentences why the watch should not replace the strap for detecting a 4 bpm change in steady-state heart rate.

- Do the differences seem to grow with heart rate? Use the pair means.

**Exercise 11.7** (Hand calculation · Core · 8 min)

A swim app labels 100 lengths as freestyle or not. Of 60 freestyle lengths it labels 52 freestyle and 8 not. Of 40 other lengths it labels 35 not freestyle and 5 freestyle.

- Write the confusion table with freestyle as the positive class. *Checkpoint:* {TP 52, FN 8, FP 5, TN 35.}

- Compute accuracy, sensitivity, specificity and precision. *Checkpoint:* {0.87, 0.867, 0.875, 0.912.}

- What accuracy would a model that always says “freestyle” get? What does that tell you about reading accuracy alone? *Checkpoint:* {0.60.}

**Exercise 11.8** (Hand calculation · Foundation · 6 min)

A runner's season races include 800 m in 150 s and 3200 m in 750 s, both run hard and evenly paced.

- Compute critical speed and $D'$ from Equation \eqref{ch11-statistics:eq:cs}. *Checkpoint:* {CS 4.00 m/s; $D' = \SI{200}{\metre}$.}

- Predict the time for 5000 m. *Checkpoint:* {1200 s (20:00).}

- Name one reason the prediction could be wrong for this runner.

**Exercise 11.9** (App lab · Core · 30 min · CORE)

*Your own typical error.* Use the jump app, https://apopt.com/jump/jump.php, in Basic mode.

- Film yourself: one countermovement jump per clip, from the side, whole body in frame from the start to the landing, phone still on a tripod at about waist height, at 60 fps or more. For slow motion, set the capture rate to the rate you filmed at. Each clip needs only 4–6 s.

- Day 1: warm up the same way each time, then film three jumps a minute apart. Save each PDF and text result.

- Day 2, at the same time of day, in the same place with the same camera position: repeat step 2.

- Pick one jump and confirm its height by hand from the flight time printed in the result: $h = g t^2/8$ with $g = 9.807$.

- Open Advanced mode on one clip. Find the height from the pixel scale and the height from flight time (the “cm derived” figure), and say which the result uses as “Jump height”.

- Pool your day-1 and day-2 means with four or more classmates' (with their agreement) and compute the class typical error. Then write half a page: what you measured, your two means, the class typical error and SWC, whether the difference between your two days is within noise, and when you would retest.

Keep your result files; do not share them unless you choose to.

**Exercise 11.10** (App lab · Extension · 40 min)

*Two methods in one app.* The jump app reports two heights for each jump: one from the hip's rise on the pixel scale and one derived from flight time. Film eight jumps (yourself or a teammate who has given written consent, protocol as in Exercise 11.9), and from the Advanced-mode results record both heights for each.

- Compute the bias and limits of agreement of pixel-scaled minus flight-derived height, and draw the Bland–Altman plot (you may reuse the agreement function of Listing 11.5).

- Which way would you expect the bias to go if you entered a stature 5 cm too tall? Test it on two clips.

- Which of the two would you use to track change over a season, and why?

**Exercise 11.11** (Python analysis · Foundation · 20 min · CORE)

Edit `code/typical_error.py` (Listing 11.1) to read the day-1 and day-2 heights of Exercise 11.5 and a change of 1.5 cm. Before running it, write down the three chances you expect from your hand answer. Then run it and compare. Finally, ask an AI assistant to add a 90% interval for the change, and check its output by hand.

**Exercise 11.12** (Python analysis · Core · 30 min)

Using `code/gait_data.py` and Listing 11.21:

- Score a random forest (200 trees, `random_state=0`) with a random 5-fold split and with `GroupKFold` by runner, using all ten measures. *Checkpoint:* {about 0.92 and 0.16.}

- Repeat without speed, stride rate and stride length, the three a camera cannot measure without a known scale and the belt speed. *Checkpoint:* {about 0.90 and 0.13.}

- In three sentences, say what the drop from (a) to (b) and the drop from random to grouped each tell you.

**Exercise 11.13** (Python analysis · Extension · 30 min)

Section 11.4 showed that removing 50 mislabeled rows moved the speed coefficient of the ten-measure model from 0.035 to 0.648.

- Refit the model without stride length (nine measures) twice: once with the loader option `check_speed` set to `False`, and once with the default. Report $R^2$ and the speed and stride-rate coefficients each time. *Checkpoint:* {speed 0.306 then 0.332.}

- Compute the variance inflation factors of the nine-measure model and compare them with `code/vif.py`.

- Explain why dropping one measure made the coefficients stable while $R^2$ barely changed.

**Exercise 11.14** (Body science · Foundation · 5 min)

Morning resting heart rate varies by a few beats a minute from day to day in a healthy, well-trained athlete. Name three biological sources of that variation and one technical source, and say why the typical error of morning heart rate should be measured on the athlete rather than taken from a published table.

**Exercise 11.15** (Body science · Core · 6 min)

In two short paragraphs for an engineer, explain what happens in the body when a runner holds a speed slightly below critical speed compared with slightly above it, and why the time to exhaustion above critical speed depends on $D'$.

**Exercise 11.16** (Science of the sport · Foundation · 5 min)

Hopkins suggests that the smallest worthwhile change in a solo sport scored by time is a fraction of the variation in an athlete's race-to-race performance, while for a fitness test in a team sport a default is a fifth of the between-athlete standard deviation. Explain in three or four sentences why the two sports need different rules.

**Exercise 11.17** (Science of the sport · Extension · 10 min)

For a volleyball middle blocker, propose a smallest worthwhile change in countermovement jump height that is tied to the sport rather than to the 0.2 rule. Use the net and the ball (diameter about 21 cm) in your reasoning, state your assumptions, and say how you would check that the jump test predicts blocking reach.

**Exercise 11.18** (Field collection · Core · 45 min · CORE)

*A test–retest with a teammate.* Measure the typical error of one test you will use in your project.

Equipment: the app or device for your test (for example the jump app on a phone and tripod), tape for marking the camera spot, a notebook.

- Consent: explain to your teammate what you will record, that it is for a class exercise, who will see it, that it will be kept on your device and deleted at the end of term, and that they can stop at any time. Get their written consent (the Appendix E form) before filming; for a teammate under 18, a parent or guardian also gives written consent and the teammate gives their own assent, and no image of a minor leaves the team.

- Write the protocol before you start: warm-up, time of day, camera spot (taped), number of trials, rest between trials, the number you will record.

- Day 1: run the protocol on yourself and your teammate. Record every trial, including any you think are bad, and the reason.

- Day 2, two to seven days later, same time and conditions: repeat step 3 exactly.

- Compute each person's day mean, the change, and with classmates' data (at least five people) the typical error and its 90% interval from Section 11.10.

Safety: stop if anyone feels pain or dizziness; no maximal effort is required, and anyone with an injury should sit this out. Record: the written protocol, every trial value, the day means, the typical error and its interval, and one sentence on what in the protocol you would tighten.

**Exercise 11.19** (Build · Core · 75 min · CORE)

*B-11: a baseline on the device.* Add to your app a page that:

- lets the athlete enter (or load from a results file) one number per session, with a date, and stores the list with `saveSession` from Listing 11.27 under a key made of an athlete code and the measure;

- shows the stored sessions as points on a chart with a shaded band at the baseline mean $\pm$ one standard deviation;

- shows the word from `judge()` for the newest session, with the SWC as a setting;

- has a button that deletes the athlete's history after a confirmation.

Your page must pass `node baseline.test.mjs` (it prints `all tests pass`) and a test you write yourself with a hand-computed answer for a “possibly lower than usual” case. Test it in a private browser window, where storage may be empty or blocked, and say what happens.

**Exercise 11.20** (Communicate · Core · 20 min · CORE)

Riley's jump went from 30.4 to 30.9 cm after four weeks of training. The class typical error is 0.89 cm and the SWC is 0.65 cm (chances: 45% worthwhile gain, 37% trivial, 18% loss). Write the message you would give Riley in no more than 100 words, then a two-sentence note to the coach that carries the numbers. Use the five-line rubric: accurate, plain, one recommendation, uncertainty stated, within scope.

**Exercise 11.21** (Check the AI · Core · 8 min)

A student asked an AI assistant to compute a typical error from the five pairs of Table 11.1. The answer:
“The differences are $+1.0, -1.4, +1.1, -0.5, +1.6$, with standard deviation 1.26 cm. The typical error is therefore 1.26 cm. Harper's 2.0 cm gain is less than two typical errors, so it is not a real change.”

Find the flaw, correct the typical error, and say what is wrong with the conclusion as well.

**Exercise 11.22** (Hand calculation · Core · 12 min)

The five one-minute recoveries of the Heart app's workout example (Section 11.1.5) are 23.3, 18.5, 22.9, 29.3 and 30.1 bpm.

- Compute the mean, the median and the standard deviation. *Checkpoint:* {24.82, 23.3, 4.84 bpm.}

- Make one bootstrap resample from the die rolls 5, 5, 2, 4, 3 (roll $k$ picks the $k$th effort). Compute its mean and median. *Checkpoint:* {30.1, 30.1, 18.5, 29.3, 22.9; mean 26.18, median 29.3.}

- Compute the 95% $t$ interval for the mean, $\bar x \pm t_{0.975,4}\,s/\sqrt5$ with $t_{0.975,4} = 2.776$, and set it beside the bootstrap interval of Listing 11.3, 21.2 to 28.5. *Checkpoint:* {18.8 to 30.8 bpm.}

- Explain in two sentences why every bootstrap median of these five values is one of the five values, and what that does to the median's interval.

**Exercise 11.23** (Python analysis · Core · 25 min)

Work with Listing 11.3 and the synthetic interval archive.

- Change the session-level interval to 90%. *Checkpoint:* {23.3 to 26.2 bpm.}

- Rerun the 95% session-level interval with seeds 0 to 4. How much do its ends move? *Checkpoint:* {low end 22.99 to 23.04, high end 26.47 to 26.48.}

- Bootstrap the median of the eight session means. *Checkpoint:* {median 24.9, 95% interval 22.2 to 27.5.}

- The standard deviation of the eight session means is 2.70 bpm; the mean within-session standard deviation of the repeats is 2.01 bpm. Use these to explain in three sentences why resampling the 40 repeats gives too narrow an interval.

**Exercise 11.24** (Concept check · Foundation · 3 min)

A watch archive from 30 runners shows that runners who logged more strength sessions per month also ran faster 5 km times, with a clear fitted slope. Which statement can you support?
\choices{Adding one strength session a month will make a runner faster by the fitted slope}
{The slope is a measurement error, because strength work cannot affect running}
{Runners who do more strength work are faster on average here; fitness, training volume or coaching could drive both}
{Because the slope is clear, no confounder can be present}

**Exercise 11.25** (Communicate · Core · 30 min)

A coach wants to know whether a new 10-minute warm-up raises the squad's countermovement jump compared with the usual one, and plans to try it next week and compare with last week's jumps.

- Write a one-page experiment plan with the six headings of Section 11.3.4: question and decision, comparison and assignment, controls, sample unit and number, likely confounders and how each is handled, measure and analysis.

- Write three sentences to the coach saying what the plan can claim at the end and what it cannot.

**Exercise 11.26** (Python analysis · Core · 25 min)

Extend Listing 11.15 to trees of depth 1, 2, 3, 4, 6, 8 and unlimited (`max_depth=None`). For each, report the MAE on the training data, with a random 5-fold split (`KFold(5, shuffle=True, random_state=0)`) and with `GroupKFold(5)` by runner.

- Which depth is best by runner, and does it beat the line? *Checkpoint:* {depth 1, MAE 0.259 against the line's 0.229.}

- What happens to the three scores as the tree gets deeper? *Checkpoint:* {unlimited: training 0.000, random 0.102, by runner 0.310.}

- In two sentences, say which score a coach choosing a depth for new runners should use and why.

**Exercise 11.27** (Check the AI · Core · 8 min)

An AI assistant reports on the running data: “A depth-10 decision tree reached a mean absolute error of 0.02 BW, ten times better than linear regression (0.23 BW). The first split is on ground contact time, which shows that contact time is the main cause of peak force. Coaches should shorten contact time to reduce load.” Find three problems.

**Exercise 11.28** (Hand calculation · Foundation · 8 min)

A phone classifier labels 2{,}000 windows, of which 200 are running. At a threshold of 0.5 it calls 200 windows running, 160 correctly. At 0.3 it calls 338 windows running, 188 correctly.

- At 0.5, compute precision, recall and accuracy. *Checkpoint:* {0.80, 0.80, 0.960.}

- At 0.3, compute the same three. *Checkpoint:* {0.556, 0.940, 0.919.}

- What accuracy does “never running” score, and which threshold would you choose to count weekly running minutes? *Checkpoint:* {0.900.}

**Exercise 11.29** (Python analysis · Core · 25 min)

Use the synthetic accelerometer windows of Listing 11.19 for all three classes.

- Fit `LogisticRegression(max_iter=1000)` to predict the class (walk, jog or run), with `GroupKFold(4)` by person and `cross_val_predict`. Print the $3\times3$ confusion table and the recall and precision of each class. *Checkpoint:* {accuracy 0.976; run recall 0.85, precision 0.92.}

- Refit with `class_weight="balanced"`. *Checkpoint:* {accuracy 0.974; run recall 0.91, precision 0.84.}

- Which classes does the model confuse, and why do the features make that likely? What did weighting change, and what did it cost?

**Exercise 11.30** (Python analysis · Core · 25 min)

Work with Listing 11.25.

- Replace the line that marks weeks with no runs as missing so that they stay zero. Report the training size and the three MAEs. *Checkpoint:* {train 75; persistence 37.5, four-week mean 36.9, linear 36.0 min.}

- Restore the missing weeks and test on the last 52 weeks instead of 26. *Checkpoint:* {train 31; persistence 23.3, four-week mean 22.4, linear 22.3 min.}

- In four sentences, say what (a) and (b) teach about irregular data and about how much one test period can show.

**Exercise 11.31** (Concept check · Core · 3 min)

You forecast next week's training minutes, week $t$, from a weekly series. Which feature may you use?
\choices{The mean of weeks $t-4$ to $t-1$}
{The mean of weeks $t-2$ to $t+2$, which is smoother}
{Week $t$'s minutes scaled by the athlete's season average, computed from all weeks}
{Last week's minutes after a two-sided smoothing filter run over the whole series}

**Exercise 11.32** (Python analysis · Core · 40 min)

Case file: your case-file athlete's chest-strap interval sessions (see apopt.com/data/athletes), or the instructor's case file.

- For each session, find each repeat's one-minute recovery as in Section 11.1.5: the top of the 10-second mean heart rate and the 10-second mean 60 seconds later. Use the marker column where it marks the efforts.

- Compute a typical error of the session mean recovery from pairs of consecutive sessions ($s_\text{diff}/\sqrt2$ of the session-to-session changes).

- Bootstrap a 95% interval for the athlete's usual recovery twice: resampling sessions, and resampling all repeats as if independent.

- Write three sentences: the recovery with its interval, the typical error, and which interval you trust and why.

**Exercise 11.33** (Python analysis · Extension · 45 min)

Case file: classify one-minute windows of your case-file athlete's chest-strap recordings (see apopt.com/data/athletes) by recording type: sleep, workout or interval session.

- Cut each recording into one-minute windows and compute two or three features per window (for example mean heart rate, its standard deviation, and the RMSSD of the RR intervals). Label each window with its recording's type.

- Train a classifier and score it twice: with windows assigned to folds at random, and with whole recordings held out (`GroupKFold` by recording).

- Report the majority-class baseline, the confusion table, and precision and recall for the interval class under the grouped split.
