# CS-5: Phone in a pocket: walk, jog, or run?

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

Web page: https://apopt.com/course/tutorials/cs05-walk-jog-run/ · Data: https://apopt.com/data/tutorials/cs05-walk-jog-run/

## The decision

An athlete wants to know how many minutes of each session she spent walking, jogging and running,
from the phone in her pocket. The answer is only worth giving if the model works on her, a person it
was not trained on, and finds the running she does least of. If it only found walking, the minutes
of hard work would be wrong.

## Predict first

Most of each session is walking. Before any code: what accuracy would a "model" get that always says walk, and which class will a trained model find least often?

## The raw data

- `raw/phone_P1.csv`: one of eight SYNTHETIC phone accelerometer logs (P1 to P8), about three minutes at about 50 samples a second; time in ns, x, y, z in m/s² along the phone's axes Made by this tutorial's `prepare.py` from the step model of the book's synthetic activity windows (Chapter 11); made-up people, not real ones. P2 to P8 are beside it in `raw/`.
- `raw/diary.csv`: the start of each part of each session (stand, walk, jog, run), in whole seconds, as the person wrote it (SYNTHETIC) Made by the same `prepare.py`.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| time | sample time | ns since 1970 (UTC) | increasing; one log has a repeated block | never |
| x, y, z | acceleration along the phone's own axes | m/s² | about −40 to +40 | never; one spike |
| person | who carried the phone (diary) | text | P1–P8 | never |
| start_s | second the part began | s from the start of the log | 0–190 | never |
| activity | what the person was doing | text | stand / walk / jog / run | never |

What is wrong with it: the phone's axes turn with the pocket, so no single axis means "up"; one log
repeats 30 rows, one has a gap of about a second, one has a single sample of 8 g; the diary is written
by hand in whole seconds and can be a second or two off at each boundary; and the classes are
unequal, about three quarters walking. Everything is synthetic, so the true labels are known.

## Part 1 (Week 4): from a phone log to labelled windows

Eight people each carried a phone in a trouser pocket through a three-minute session of standing,
walking, jogging and running, and wrote down in a diary the second each part began. The phone
logged its accelerometer about 50 times a second. The people and their logs are **synthetic**,
made by `prepare.py` from the same step model as the book's activity windows (Section 11.6), so
the right answers are known; the faults in them are the ones real logs have (Chapter 4).

### Step 1 · Gather

*Predict first:* About 50 samples a second for three minutes. How many rows will one log have?

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

diary = pd.read_csv("raw/diary.csv")
p1 = pd.read_csv("raw/phone_P1.csv")
print(p1.shape)
print(p1.head(3).to_string(index=False))
print(diary[diary["person"] == "P1"].to_string(index=False))
```

Output:

```
(9350, 4)
               time      x      y      z
1811235600000000000 -6.770 -6.716 -3.122
1811235600018222080 -7.164 -5.622 -2.764
1811235600039273472 -7.245 -5.469 -2.982
person  start_s activity
    P1        0    stand
    P1        8     walk
    P1       57      jog
    P1       84     walk
    P1      120      run
    P1      139     walk
    P1      171    stand
```

The log holds a time stamp in nanoseconds and three accelerations in m/s² along the **phone's**
axes. The diary holds only start times, in whole seconds, written by the person: each part ends
where the next begins.

### Step 2 · Statistics: profile every log before using any

```python
PEOPLE = [f"P{k}" for k in range(1, 9)]
logs, rows = {}, []
for p in PEOPLE:
    d = pd.read_csv(f"raw/phone_{p}.csv")
    d["t_s"] = (d["time"] - d["time"].iloc[0]) / 1e9
    d["mag"] = np.sqrt(d["x"] ** 2 + d["y"] ** 2 + d["z"] ** 2)          # independent of how the phone sits
    dt = d["t_s"].diff().dropna()
    logs[p] = d
    rows.append({"person": p, "rows": len(d), "seconds": round(d["t_s"].iloc[-1], 1),
                 "rate_Hz": round(1 / dt.median(), 1), "longest_gap_ms": round(1000 * dt.max()),
                 "not_forward": int((dt <= 0).sum()), "max_mag": round(d["mag"].max(), 1)})
profile = pd.DataFrame(rows)
print(profile.to_string(index=False))
```

Output:

```
person  rows  seconds  rate_Hz  longest_gap_ms  not_forward  max_mag
    P1  9350    186.9     50.0              25            0     20.4
    P2  8930    178.0     50.0              26           30     24.3
    P3  8550    171.3     49.9              26            0     23.1
    P4  9100    181.8     50.1              26            0     23.6
    P5  9250    185.9     50.0            1020            0     19.0
    P6  9250    184.9     50.1              26            0     24.1
    P7  9150    182.9     50.1              25            0     78.7
    P8  9600    192.2     49.9              25            0     25.1
```

Every log runs at about 50 samples a second, but three are not clean. P2 has 30 rows whose time does
not move forward: a block the phone wrote twice. P5 has a gap of about a second with no rows. P7 has a
total acceleration of 78 m/s², eight times gravity, in one sample: a spike, since the next sample is
back to normal. None of these was visible in the first three rows.

### Step 3 · Visualize: one session against its diary

```python
import matplotlib.pyplot as plt

d = logs["P1"]
parts = diary[diary["person"] == "P1"].reset_index(drop=True)
ends = list(parts["start_s"][1:]) + [d["t_s"].iloc[-1]]
fig, ax = plt.subplots(figsize=(9, 3.4))
shade = {"stand": "1.0", "walk": "0.92", "jog": "0.82", "run": "0.7"}
for (s, a), e in zip(parts[["start_s", "activity"]].values, ends):
    ax.axvspan(s, e, color=shade[a], lw=0)
    ax.text((s + e) / 2, 33, a, ha="center")
ax.plot(d["t_s"], d["mag"], "k-", lw=0.5)
ax.set(xlabel="time (s)", ylabel="total acceleration (m/s²)", ylim=(0, 36))
plt.tight_layout()
print({a: round(d.loc[(d["t_s"] > s + 2) & (d["t_s"] < e - 2), "mag"].std(), 2)
       for (s, a), e in zip(parts[["start_s", "activity"]].values, ends)})
```

Output:

```
{'stand': np.float64(0.36), 'walk': np.float64(1.58), 'jog': np.float64(4.75), 'run': np.float64(5.4)}
```

![Total acceleration in m/s squared against time over P1's 182-second session. Shaded bands mark the diary's parts: a quiet line near 9.8 while standing, a regular swing of about plus or minus 3 while walking, larger swings while jogging, the largest while running, then walking and standing again.](https://apopt.com/course/tutorials/cs05-walk-jog-run/c05-1.png)

The diary and the signal agree: the swing grows from walking to jogging to running and vanishes when
P1 stands. The edges are not sharp, and the diary's whole seconds will not fall exactly on them.

### Step 4 · Cleanse: rules first

1. Sort by time; a row whose time stamp repeats an earlier one is a copy and is dropped (logged).
2. A total acceleration above 6 g (58.9 m/s²) is a spike: that sample is set missing (logged).
3. A gap is not filled. A window that contains a gap longer than 0.2 s is flagged.
4. A window gets a label only if it lies wholly inside one diary part with 2 s to spare at each end,
   because the diary's times are rounded and written by hand. Other windows are kept, unlabelled.

```python
import os

log, clean = [], []
for p, d in logs.items():
    d = d.sort_values("time", kind="stable")
    copy = d["time"].duplicated()
    d = d[~copy].copy()
    spike = d["mag"] > 6 * 9.81
    d.loc[spike, "mag"] = np.nan
    log += [{"person": p, "rule": "repeated time stamp dropped", "rows": int(copy.sum())},
            {"person": p, "rule": "spike over 6 g set missing", "rows": int(spike.sum())}]
    d["t_s"] = (d["time"] - d["time"].iloc[0]) / 1e9
    clean.append(d.assign(person=p)[["person", "t_s", "mag"]])
clean = pd.concat(clean)
os.makedirs("clean", exist_ok=True)
clean.round(3).to_csv("clean/samples_clean.csv", index=False)
changes = pd.DataFrame(log)
changes[changes["rows"] > 0].to_csv("clean/change_log.csv", index=False)
print(changes[changes["rows"] > 0].to_string(index=False))
print(f"{len(clean)} clean samples from {sum(len(d) for d in logs.values())} raw rows")
```

Output:

```
person                        rule  rows
    P2 repeated time stamp dropped    30
    P7  spike over 6 g set missing     1
73150 clean samples from 73180 raw rows
```

### Cut the session into windows

A **window** is a short stretch of the signal treated as one example: here 5 seconds, long enough
for at least seven steps even when walking. Each window gets its person, its start time, a label
from the diary (rule 4), and a flag if it contains a gap (rule 3).

*Predict first:* Most of each session is walking. What share of the labelled windows will be running?

```python
WIN, MARGIN = 5.0, 2.0
rows = []
for p, d in clean.groupby("person"):
    parts = diary[diary["person"] == p].reset_index(drop=True)
    ends = list(parts["start_s"][1:]) + [d["t_s"].max()]
    for t0 in np.arange(0, d["t_s"].max() - WIN, WIN):
        w = d[(d["t_s"] >= t0) & (d["t_s"] < t0 + WIN)]
        inside = [a for (s, a), e in zip(parts[["start_s", "activity"]].values, ends)
                  if t0 >= s + MARGIN and t0 + WIN <= e - MARGIN]
        rows.append({"person": p, "t0_s": t0, "label": inside[0] if inside else "unlabelled",
                     "gap": bool(w["t_s"].diff().max() > 0.2)})
windows = pd.DataFrame(rows)
windows.to_csv("clean/windows.csv", index=False)
print(windows["label"].value_counts().to_string())
lab = windows[windows["label"] != "unlabelled"]
print("share of labelled windows:", (lab["label"].value_counts(normalize=True) * 100).round(0).to_dict())
print("windows with a gap:", int(windows["gap"].sum()))
```

Output:

```
label
walk          146
unlabelled     93
jog            26
run            18
stand           6
share of labelled windows: {'walk': 74.0, 'jog': 13.0, 'run': 9.0, 'stand': 3.0}
windows with a gap: 1
```

289 windows, 196 of them labelled. About three quarters of the labelled windows are walking and
only about one in eleven is running, as in a real day: the class you most want to find is the rarest.
The unlabelled windows sit on the diary's boundaries; they stay in the table for Part 2's last step.

## Part 2 (Week 6): walk, jog or run, for a person the model has never seen

### Step 5 · Features

Two numbers per window describe a gait (Section 6.4): the **cadence**, the strongest rhythm between
0.5 and 4 steps a second, found from the window's spectrum; and the **bounce**, the standard
deviation of the total acceleration, in units of g. This cell starts from the clean files, so Part 2
runs on its own.

*Predict first:* Which feature will separate jogging from running better?

```python
samples = pd.read_csv("clean/samples_clean.csv")
windows = pd.read_csv("clean/windows.csv")

def features(m):
    m = m.dropna().to_numpy()
    spec = np.abs(np.fft.rfft(m - m.mean(), n=1024))         # zero-padded for a finer frequency grid
    f = np.fft.rfftfreq(1024, d=WIN / len(m))
    band = (f >= 0.5) & (f <= 4.0)
    return f[band][np.argmax(spec[band])], m.std() / 9.81

feats = [features(samples.loc[(samples["person"] == r.person) & (samples["t_s"] >= r.t0_s)
                              & (samples["t_s"] < r.t0_s + WIN), "mag"]) for r in windows.itertuples()]
windows[["cadence_hz", "bounce_g"]] = np.round(feats, 3)
windows.to_csv("clean/windows_features.csv", index=False)
print(windows[windows["label"] != "unlabelled"].groupby("label")[["cadence_hz", "bounce_g"]].median().round(2).to_string())
```

Output:

```
       cadence_hz  bounce_g
label                      
jog          2.43      0.55
run          2.67      0.64
stand        2.25      0.04
walk         1.76      0.29
```

```python
lab = windows[windows["label"] != "unlabelled"]
fig, ax = plt.subplots(figsize=(6.4, 4))
for name, m in [("stand", "s"), ("walk", "o"), ("jog", "^"), ("run", "X")]:
    s = lab[lab["label"] == name]
    ax.plot(s["cadence_hz"], s["bounce_g"], m, ms=6, mfc="white" if name in ("walk", "jog") else "k",
            color="k", label=f"{name} ({len(s)})")
ax.set(xlabel="cadence (steps per second)", ylabel="bounce (g)")
ax.legend(loc="upper left")
plt.tight_layout()
```

![Scatter of bounce in g against cadence in steps per second for the labelled windows. Standing windows sit near zero bounce at scattered cadences; walking windows spread over 1.5 to 2.1 steps a second and 0.1 to 0.45 g; jogging over about 2.2 to 2.7 steps a second and 0.3 to 0.6 g; running over about 2.5 to 2.9 and 0.43 to 0.66 g, overlapping jogging.](https://apopt.com/course/tutorials/cs05-walk-jog-run/c12-1.png)

Walking stands apart. Jogging and running overlap at their edges: some people jog with as much
bounce as others run. Standing has no rhythm, so its "cadence" is just the largest wobble in the noise.

### Steps 7 and 8 · Scale inside the model, split by person, and beat the baseline

Standing needs no model: its bounce is under 0.1 g. The question is walk, jog or run, and what the
model will do on **someone new**, so every test holds out one whole person: train on seven, test on the eighth, eight times (`LeaveOneGroupOut`). The scaler is fitted
inside each training set (a pipeline). And every score is set beside the **majority-class
baseline**, a "model" that always says "walk" (Section 11.6.3).

*Predict first:* Always saying "walk" scores what accuracy? Will the model beat it by much?

```python
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import LeaveOneGroupOut
from sklearn.metrics import accuracy_score, recall_score

moving = lab[lab["label"] != "stand"]                      # standing: bounce under 0.1 g, no model needed
X, y, who = moving[["cadence_hz", "bounce_g"]].to_numpy(), moving["label"].to_numpy(), moving["person"].to_numpy()
CLASSES = ["walk", "jog", "run"]

def held_out(fit_rows):
    pred = np.empty(len(y), dtype=object)
    for tr, te in LeaveOneGroupOut().split(X, y, who):
        Xt, yt = fit_rows(X[tr], y[tr])
        pred[te] = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(Xt, yt).predict(X[te])
    return pred

plain = held_out(lambda a, b: (a, b))
print(f"majority class ('walk'): accuracy {np.mean(y == 'walk'):.2f}")
print(f"model, one person out:   accuracy {accuracy_score(y, plain):.2f}")
print("recall by class:", dict(zip(CLASSES, recall_score(y, plain, labels=CLASSES, average=None).round(2))))
```

Output:

```
majority class ('walk'): accuracy 0.77
model, one person out:   accuracy 0.94
recall by class: {'walk': np.float64(1.0), 'jog': np.float64(0.73), 'run': np.float64(0.72)}
```

Always saying "walk" is right about three times in four. The model does much better, 0.94, but
look at the recall for each class, the share of that class's windows it found. Walking is found
every time; jogging and running, the rare classes, only about seven times in ten, because a model
trained on mostly walking can afford to be careless with them and still score well.

### Step 6 · Balance: the training rows only

One fix is to **oversample**: inside each training set, repeat the windows of the rarer classes at
random until every class has as many as walking. The test person is never touched; the test set must
look like the data the model will meet (Section 11.6.3).

```python
rng = np.random.default_rng(0)

def oversample(Xt, yt):
    n = max(np.sum(yt == c) for c in CLASSES)
    idx = np.concatenate([rng.choice(np.flatnonzero(yt == c), n, replace=True) for c in CLASSES])
    return Xt[idx], yt[idx]

balanced = held_out(oversample)
table = pd.DataFrame({"plain": recall_score(y, plain, labels=CLASSES, average=None),
                      "balanced training": recall_score(y, balanced, labels=CLASSES, average=None)},
                     index=CLASSES).round(2)
print(table.to_string())
print(f"accuracy: plain {accuracy_score(y, plain):.2f}, balanced training {accuracy_score(y, balanced):.2f}")
print(pd.crosstab(pd.Series(y, name="diary"), pd.Series(balanced, name="model")).reindex(index=CLASSES, columns=CLASSES).to_string())
```

Output:

```
      plain  balanced training
walk   1.00               1.00
jog    0.73               0.73
run    0.72               0.78
accuracy: plain 0.94, balanced training 0.94
model  walk  jog  run
diary                
walk    146    0    0
jog       0   19    7
run       0    4   14
```

Balancing the training rows raises the recall for running from 0.72 to 0.78 and leaves the test
person exactly as recorded; overall accuracy does not move, which is the point of Section 11.6.3:
accuracy is mostly a score on the common class. The table of diary against model shows where the
remaining mistakes are: all between jogging and running, the two classes that overlap. Balancing
cannot fix that; only a better feature or more people can.

### Minutes at each intensity in a session

The athlete does not want windows; she wants minutes. For each person, using the model trained on
the other seven with balanced training rows, add up the predicted windows (5 s each) and set them
beside the diary.

```python
moving = moving.assign(model=balanced)
mins = moving.groupby("person").apply(lambda g: pd.Series(
    {f"{c} diary": (g["label"] == c).sum() * WIN / 60 for c in ["walk", "jog", "run"]} |
    {f"{c} model": (g["model"] == c).sum() * WIN / 60 for c in ["walk", "jog", "run"]}), include_groups=False)
print(mins.round(2).to_string())
err = {c: (mins[f"{c} model"] - mins[f"{c} diary"]).abs().mean() * 60 for c in ["walk", "jog", "run"]}
print("mean absolute error per session (s):", {c: round(v) for c, v in err.items()})
```

Output:

```
        walk diary  jog diary  run diary  walk model  jog model  run model
person                                                                    
P1            1.50       0.33       0.17        1.50       0.50       0.00
P2            1.50       0.17       0.17        1.50       0.00       0.33
P3            1.33       0.25       0.17        1.33       0.25       0.17
P4            1.58       0.17       0.25        1.58       0.17       0.25
P5            1.58       0.25       0.17        1.58       0.33       0.08
P6            1.50       0.33       0.25        1.50       0.42       0.17
P7            1.50       0.33       0.17        1.50       0.00       0.50
P8            1.67       0.33       0.17        1.67       0.25       0.25
mean absolute error per session (s): {'walk': 0, 'jog': 7, 'run': 7}
```

For a person it has never seen, the model gets the walking minutes right in every session and the
jogging and running minutes within 7 seconds on average. The misses are whole people, not scattered
windows: P1 runs in a way the model reads as jogging, and P7 jogs in a way it reads as running. Each
person's style shifts both features, which is exactly why the test holds out whole people. Two
limits to say out loud. These minutes cover only the labelled windows; the windows on the diary's
boundaries would add some time to each part. And the people are synthetic: a real pocket, real
shoes and real hills will spread the features more, so test the model on a recording of your own
before trusting its minutes.

## How good is the number?

Every score is for a person the model never saw: eight folds, one person held out each time, with
the scaler fitted inside each training set. The majority-class baseline sets the bar. Balancing is
done by oversampling inside each training set only; the held-out person is scored as recorded. The
remaining errors are almost all jogging against running, the two classes whose features overlap.
With 196 labelled windows from eight synthetic people, the recall for running rests on 18 windows,
so one window more or less moves it by 0.06; and real pockets, shoes and hills will
spread the features more than this model of them.

## Track it

Add one row per session: `test=session-mix`, `metric=run_min` (and `jog_min`, `walk_min`), `unit=min`,
`device=phone-pocket-50Hz`, `app` = your logging app, `note` = "model: logistic, balanced, trained on
the CS-5 synthetic set". A change of model or phone position is a change of `protocol_version`.

## With your own data

Put your own logs in `raw/` as `phone_<name>.csv` with the same columns (time in ns, x, y, z) and add
your parts to `diary.csv`. Most logging apps export these columns; rename them if needed.

## The same method in another field

Cutting a signal into windows, computing a few features per window and classifying them is how a
vibration sensor tells a healthy pump from a failing one, with the same traps: unequal classes and
windows from the same machine on both sides of a split. The Machine Learning for Engineers pages on
[imbalanced data](https://apmonitor.com/pds/index.php/Main/ImbalancedData) and
[splitting data](https://apmonitor.com/pds/index.php/Main/SplitData) cover both.

## Acknowledgements

The step model is the book's (Chapter 11, `code/make_new_data.py`); the logs, faults and diary are
made by `prepare.py` in this tutorial's folder.

## Action card

- **Finding:** From your phone alone, the model can tell your walking from your jogging and running, and gets your running minutes about right.
- **Evidence:** Tested on each person it had never seen, it scored 0.94 against 0.77 for always saying walk; with balanced training rows it found 78% of running windows, and its jogging and running minutes were within 7 s of the diary's on average.
- **Sure:** Moderate. The people are synthetic, and jogging and running overlap; treat the split between them as approximate.
- **Action:** Record one session with a diary of your own, run the model on it, and compare its minutes with yours before using it for your training log.
- **Retest:** Repeat with a second session in different shoes or on a hill; if the minutes still match, start logging them.

## Challenge: Your own pocket

Record two sessions of your own with a free sensor-logging app, phone in the same pocket, with a
diary of when you stood, walked, jogged and ran. Keep the files to yourself unless you choose to share them.

1. Profile both logs and write your cleaning rules before you apply them; keep a change log.
2. Cut them into 5-second windows with diary labels and the same margin rule.
3. Train the Part 2 model on the eight synthetic people and test it on your windows, then train on the synthetic people plus your first session and test on your second.
4. Report recall per class, the majority-class baseline, and the minutes of each activity against your diary.

Deliverables:

- the notebook with its outputs
- a table of recall per class for both tests
- an action card that says whether the model can be trusted for your own training log

## References

- *Data-Driven Athletics*, Chapter 4, Tables and Time Series (Section 4.2) and Cleaning (Section 4.3); Chapter 6, Motion Sensing (Section 6.4); Chapter 11, Classification (Section 11.6) and Leakage (Section 11.7).

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