Course / Tutorials / Week 4 / CS-5
Case study CS-5 · Week 4 and 6 · about 75 min · Core
Phone in a pocket: walk, jog, or run?
Profile, clean and window eight phone accelerometer logs (Part 1), then classify walk, jog and run for a person the model has never seen, against the majority-class baseline, with balancing applied to the training rows only (Part 2).
- 1Gather (used)
- 2Statistics (used)
- 3Visualize (used)
- 4Cleanse (used)
- 5Features (used)
- 6Balance (used)
- 7Scale (used)
- 8Split (used)
- 9Deploy
- Ask
- Collect (this week)
- Check (this week)
- Interpret (this week)
- Coach (this week)
- Reassess
Download notebook ·Python file ·Read as Markdown ·Data folder ·Chapter 4 (sections 4.2, 4.3, 6.4, 11.6, 11.7)
Every cell runs in this page; the first run downloads Python (about 30 s). Nothing you load leaves your browser. Helpful first: Q-10 Open a phone sensor log and plot it, Q-12 Find and mark the missing values without deleting anything.
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.
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'sprepare.pyfrom the step model of the book's synthetic activity windows (Chapter 11); made-up people, not real ones. P2 to P8 are beside it inraw/.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 sameprepare.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.
Step by step
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
Type a prediction to enable Run.
Show the expected result without running
(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 standThe 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
Show the expected result without running
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.1Every 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
Show the expected result without running
{'stand': np.float64(0.36), 'walk': np.float64(1.58), 'jog': np.float64(4.75), 'run': np.float64(5.4)}
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
- Sort by time; a row whose time stamp repeats an earlier one is a copy and is dropped (logged).
- A total acceleration above 6 g (58.9 m/s²) is a spike: that sample is set missing (logged).
- A gap is not filled. A window that contains a gap longer than 0.2 s is flagged.
- 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.
Show the expected result without running
person rule rows
P2 repeated time stamp dropped 30
P7 spike over 6 g set missing 1
73150 clean samples from 73180 raw rowsCut 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).
Type a prediction to enable Run.
Show the expected result without running
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: 1289 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.
Type a prediction to enable Run.
Show the expected result without running
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
Show the expected result without running

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).
Type a prediction to enable Run.
Show the expected result without running
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).
Show the expected result without running
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.
Show the expected result without running
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.
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.
- How 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.
- Test again
- Repeat with a second session in different shoes or on a hill; if the minutes still match, start logging 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.
Check the AI
Asked to "train a walk/jog/run classifier on these windows and report its accuracy", an assistant replied:
> I balanced the data set by oversampling jog and run windows until each class had 144, shuffled > all rows, and used an 80/20 train/test split. The random forest scores 0.97 accuracy and 0.98 > recall for running, so it is ready to use.
What is wrong with it?
Two leaks. Oversampling before the split put copies of the same run windows on both sides, and balanced the test set, which no longer looks like real data. And a row split puts windows from the same person on both sides. Split by person first, balance the training rows only, and report recall for running beside the majority-class baseline.
Check yourself
Of the 190 walk, jog and run windows, 146 are walking. What accuracy does a model that always says walk get?
Why is every test done on a whole person held out?
Where is oversampling applied, and why there?
Why use the magnitude of the three axes instead of one axis?
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.
- Profile both logs and write your cleaning rules before you apply them; keep a change log.
- Cut them into 5-second windows with diary labels and the same margin rule.
- 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.
- Report recall per class, the majority-class baseline, and the minutes of each activity against your diary.
Hand in
- 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
How it is judged
- Rules written first and a change log (20%)
- Split by person or by session, never by row (30%)
- Balancing on training rows only, with the baseline reported (30%)
- An honest action card (20%)
Hints
The solution unlocks after you make an attempt. Comparing your own attempt with it is where the learning happens.
The same method in another field
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 and splitting data 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.
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).
Built 2026-11-30 with Python packages numpy 2.5.5, pandas 3.1.1, matplotlib 3.11.2, sklearn 1.9.1, scipy 1.18.1. In the browser the same code runs on Pyodide, so the last digit can differ.