Lecture 7b · AI4ST

HAR on Mobile/Wearable Devices

From raw inertial signals to a deployed model on your phone: pre-processing, sliding windows, CNN/LSTM/Transformer architectures, and the compression & quantization tricks that make deep models fit on a smartwatch.

⏱ ~50 min 📚 6 sections ✅ 10 MCQ + 2 open-ended ⭐ Includes simulation exam Q14
1

HAR on Mobile & Wearables

Mobile and wearable devices are ubiquitous and packed with sensors that can track our activities — powering healthcare, well-being and sport applications.

Existing commercial solutions

Fitbit, Garmin, Suunto, Jawbone, Withings… offering lifestyle monitoring, sleep quality tracking, and activity recognition based on visited places.

Activity Recognition APIs in mobile OSes

Both Android and iOS have included activity-recognition APIs for years — usable to create context-aware applications (Lecture 1!).

🤖 Android

  • IN_VEHICLE, ON_BICYCLE, ON_FOOT
  • WALKING, RUNNING, TILTING
  • STILL, UNKNOWN

🍎 iOS

  • stationary, walking, running
  • automotive, cycling
  • unknown
Limits of existing solutions
Limited set of activities, recognition rate often not accurate, and the HAR model is not personalized on the end user — which is why HAR is still a hot research topic.
2

Sensors & Placement

Inertial sensors — the workhorses of mobile HAR

SensorWhat it measuresWhy it matters
AccelerometerAcceleration values on three axesThe most adopted sensor for HAR
GyroscopeAngular speed on three axesReveals changes in direction
MagnetometerMagnetic field on three axesField changes may hint about the activity
Key fact
Inertial sensors are the most considered for HAR on mobile/wearable devices, since they directly reveal physical body movements.

Other useful sensors (context!)

📍

Localization

e.g., GPS — where the activity happens

💡

Light sensor

Indoor/outdoor, pocket vs hand

🎤

Microphone

Activity-specific audio patterns

📳

Proximity

Device near body or surface

❤️

Physiological

e.g., heart-rate sensors

Device placement

Wearables can sit on the ear, necklace, chest, arm, wrist, hip, thigh, knee, foot… The most common HAR setting: smartphone in the pocket + smartwatch on the wrist. (Remember sensing heterogeneity from 7a: different placements → different signals!)

3

Pre-processing

Inertial sensor streams Data cleaning Segmentation Feature extraction Feature vector

Data cleaning

  • Inertial data are noisysmoothing filters keep only the informative part: median, low-pass, gaussian filters (same smoothing idea as Lecture 3!).
  • Linear acceleration: the accelerometer also captures gravity. Combining acceleration with orientation (from the gyroscope), the gravitational component is subtracted from each axis — the result better represents the user's actual movements/gestures.

Segmentation

Performed on a multivariate time series: multiple sensors per device, multi-channel data per sensor (3 axes), possibly multiple devices per user. Each sensor may have its own sampling rate → data must be temporally aligned and device clocks synchronized.

Sliding window segmentation

Window length = L  ·  Overlap = M
  • Two parameters to tune: segment length and overlap — the choice strictly depends on the target activities.
  • Overlap is crucial to capture transitions between activities.
  • Simple physical activities (running, walking, standing) → short windows, e.g. 3 seconds with 50% overlap. More complex activities → longer windows.
  • Real-time requirements also drive the choice: trade-off between the system's response delay and accuracy (literature reports a Wmin_size to prioritize speed and a Wmax_perf to prioritize accuracy per activity category).

Dynamic segmentation

  • Drawback of sliding windows: a segment may not fully represent an activity pattern, and choosing the size is not trivial.
  • Idea: unsupervised AI methods detect change points in the sensor stream — changes intuitively indicate transitions between activities.
  • Framed as an optimization problem: each segment has a cost (e.g., avg, std, slope); find the change points minimizing the total cost, plus a penalty per added change point — high penalty → too few change points, low penalty → too many.
  • Generally computationally expensive → not adequate for real-time requirements.

Segments labeling (training time)

Annotation ≠ window boundaries
Annotations and sliding-window intervals often do not match. Most common approach: label each window with the "prevalent" activity inside it.
ThinkYou use 3-second windows with 50% overlap on a 50 Hz accelerometer. How often does a new prediction become available, and why does the overlap help around the moment a user sits down?
Answer: With L = 3 s and 50% overlap, the window slides by 1.5 s → a new segment (and prediction) every 1.5 seconds (each containing 150 samples at 50 Hz). Around a transition (standing → sitting), overlapping windows guarantee that some window starts close to the change point, so at least one segment captures the new activity almost purely — that's why overlap is crucial to capture transitions.
4

Handcrafted Features

The "classic" pipeline (7a!) extracts handcrafted features from each segment and feeds them to classic ML models.

Time-based features

  • Statistics computed directly on sensor data; they capture temporal information
  • Mean, standard deviation, variance, IQR, mean absolute deviation (MAD), correlation between axes, entropy, kurtosis

Frequency-based features

  • Statistics capturing the frequency properties of sensor data
  • Fourier Transform (FT), Discrete Cosine Transform (DCT)
  • Others: PCA, LDA, Autoregressive models, HAAR filters.
  • Important: features must be computed on each axis of each sensor — feature vectors grow fast!
5

Automatic Feature Extraction

Still need pre-processing!
Cleaning and segmentation are still required. Then pre-processed raw segments go directly into a deep network that learns features during training, and extracts them automatically at classification time.

CNN

  • Designed for vision, but good for time series: local dependency (close signals are likely correlated) and scale-invariance (robustness to frequency changes).
  • Drawback: CNNs do not fully capture temporal relationships.
  • Input adaptation (HAR input = multivariate time series, a set of 1D vectors): single-head 1D CNN · multi-head 1D CNN (each axis a separate channel) · transform the input into a 2D image + 2D convolution.
  • Sensor-to-image example: stack the time series row-by-row (each repeated to be adjacent to every other) into a Signal Image, then apply 2D DFT and keep the magnitude as the Activity Image — letting the CNN find hidden correlations between neighboring signals.

LSTM & friends

ModelStrengthWatch out
LSTMAutomatically extracts strong temporal features — widely used for HAR (Lecture 3!)May overfit on small datasets
BiLSTMAdds a second LSTM processing the series backwards; forward + backward outputs are aggregated → better temporal properties, reduces overfittingHigher cost
LSTM ensemblesA pool of LSTMs trained at once — epoch-wise bagging (random training subsets) + different loss functions; best-M models fused at score level. Goal: robustness to noise and unbalanced dataExpensive to train

Hybrid CNN-LSTM & Transformers

  • Hybrid approaches are among the most effective for supervised HAR: convolutional layers first extract meaningful features from raw data, recurrent layers then capture temporal relationships.
  • Transformer for HAR: an encoder-only transformer — the architecture typically adopted for classification tasks (even in NLP). (Compare with Lecture 4: full encoder-decoder is for seq2seq generation.)
6

Deployment on Mobile Devices

Offline vs Online recognition

Offline

  • Devices only collect data, processed in another phase
  • Fine when real-time is not required, in favor of accuracy (e.g., behavior analysis)

Online

  • Recognizing activities in real-time
  • e.g., to support context-aware applications

Online: where should it run?

Server-side

  • Pro: high computational capabilities
  • Cons: network communication overhead, reduced privacy

Client-side

  • Pro: good real-time support, better privacy
  • Cons: complex models can't run efficiently on resource-constrained devices

How to deploy

Train offline (Python) Convert to the mobile SDK format Deploy in the app Segment + classify on-device
  • SDKs: Weka (Android), CoreML (iOS), TensorFlow Lite (both). The same SDK should be used to create and deploy the model.
  • After deployment, the device collects the stream and performs segmentation/pre-processing with the same parameters used during training! Each segment is classified to obtain the activity label.

Efficiency: making models fit

Mobile/wearables have computational constraints, and deep models hurt energy usage (and usability). Either design simpler models from the beginning, or reduce the size of existing complex models:

Compression

  • Pruning unimportant parts (neurons/weights with minor impact on accuracy)
  • Merging components (sharing weights for similar edges)
  • Knowledge distillation

Quantization

  • Reducing the resolution of weights storage — the numerical precision
  • 32-bit float → 16-bit; or integers/fixed point (8-bit)
  • Advanced: sub-byte quantization (<8 bits, hard since HW stores at byte level), mixed precision (different bit-widths per layer — better accuracy/size trade-off, much harder to design)
Exam trap
Compression and quantization are two different processes — but they can be combined! The major problem is guaranteeing the trade-off between recognition rate and efficiency.

Knowledge distillation

  • Train a small "student" model relying on the knowledge of a bigger "teacher".
  • The teacher's softmax output gives soft labels; the distillation loss forces the student to generate a similar probability distribution over activities on the same data.
  • The student loss is the target HAR task itself (e.g., cross-entropy with the ground truth) — the two losses are jointly learned.
ThinkA team trains a HAR model with 2-second windows and a low-pass filter, then ships an app that segments with 5-second windows and no filter. Recognition collapses. Why?
Answer: After deployment, segmentation and pre-processing must use the same parameters used during training. The model learned feature patterns from filtered 2-second segments; feeding it unfiltered 5-second segments shifts the input distribution completely (different noise level, different temporal extent), so the learned features no longer match. This is a deployment-pipeline bug, not a model problem.

Final Quiz — Exam Style

10 MCQs + 2 open-ended. Question 4 is the actual simulation-exam Q14, reproduced verbatim.

1
Which inertial sensor provides the angular speed on three axes, revealing changes in direction?
AAccelerometer
BMagnetometer
CGyroscope
DProximity sensor
C — gyroscope = angular speed on three axes (direction changes). Accelerometer = acceleration on three axes; magnetometer = magnetic field on three axes; proximity is not an inertial sensor at all.
2
What is linear acceleration in the context of HAR pre-processing?
AAcceleration measured only along the device's vertical axis
BAcceleration with the gravity component removed using the device orientation
CThe first derivative of the gyroscope's angular speed signal
DAcceleration smoothed with a median filter to suppress noise
B — raw accelerometer data incorporates gravity. Using the orientation (derived from the gyroscope), the gravitational component is subtracted from each axis: the resulting linear acceleration better represents the user's actual movements/gestures.
3
In sliding-window segmentation, why is the overlap between consecutive windows considered crucial?
AIt reduces the amount of data the model has to process
BIt removes the need to synchronize the device clocks
CIt guarantees every window contains exactly one activity
DIt helps capture the transitions between activities
D — overlap is crucial to capture transitions between activities: some overlapping window will start near the change point and represent the new activity well. (A is backwards: overlap increases the number of windows.)
4
Simulation exam · Q14
Which of the following options describes the "model quantization" approach to deploy HAR models on resource-constrained devices?
AThe original model is simplified by pruning unimportant parts (e.g., neurons/weights with minor impact on accuracy).
BA smaller model (i.e., the compressed model) is trained to mimic the behavior of the original model, leveraging the probability distribution emitted by the original model on input data.
CSome components of the original model are merged (e.g., sharing the same weights for similar edges).
DThe numerical precision of the weights in the original model is reduced.
D — quantization = reducing the resolution of weights storage (32-bit float → 16-bit, or 8-bit integers/fixed point). The other three are all compression techniques: A = pruning, B = knowledge distillation, C = merging/weight sharing. Remember: compression and quantization are different processes, but combinable!
5
In dynamic segmentation framed as an optimization problem, what happens if the penalty per change point is set too high?
AToo few change points are detected in the stream
BToo many change points are detected in the stream
CThe cost of each segment becomes impossible to compute
DThe segments are forced to all have the same length
A — every added change point pays the penalty, so a high penalty discourages adding them → too limited detected change points; a low penalty creates too many. Each segment has a cost (avg, std, slope…) and the goal is minimizing the total cost of all segments.
6
At training time, annotations and window intervals often don't match. What is the most common way to label a window?
AWith the activity that starts inside the window
BWith the label of the previous window
CWith the prevalent activity inside the window
DWith a special transition label for the window
C — the most common approach labels each window with the "prevalent" activity, i.e., the one occupying most of the window according to the ground truth.
7
Which drawback is correctly associated with its model in mobile HAR?
ACNNs cannot process multivariate input of any kind
BLSTMs may lead to overfitting on small datasets
CBiLSTMs cannot capture backward dependencies
DTransformers cannot be used for classification
B — LSTMs extract strong temporal features but may overfit small datasets (and HAR datasets are small!). CNNs can process multivariate input (1D/multi-head/2D adaptations) — their drawback is not fully capturing temporal relationships. BiLSTM exists exactly to capture backward dependencies; encoder-only transformers are used for classification.
8
What is the structure of the most effective hybrid approaches for supervised HAR?
AConvolutional layers extract features, then recurrent layers capture temporal relationships
BRecurrent layers extract features, then convolutional layers capture temporal relationships
CTwo CNNs in parallel, one per sensor, merged with a voting scheme
DAn autoencoder compresses the data, then a decision tree classifies it
A — CNN first (meaningful features from raw sensor data), LSTM/recurrent then (temporal relationships). This order plays to each architecture's strength and compensates the CNN's temporal weakness.
9
For online HAR, which is an advantage of client-side over server-side recognition?
AIt can rely on much higher computational capabilities
BIt allows running arbitrarily complex deep models
CIt removes the need for any pre-processing on the device
DIt offers better privacy and good real-time support
D — client-side: good support to real-time recognition and better privacy (data never leaves the device). Its cons is exactly the opposite of A/B: complex models cannot run efficiently on resource-constrained devices — hence compression & quantization.
10
In knowledge distillation, what does the distillation loss compare?
AThe student's hard predictions against the ground-truth labels
BThe student's probability distribution against the teacher's soft labels
CThe teacher's weights against the student's weights, layer by layer
DThe number of parameters of the teacher and student networks
B — the teacher's softmax output gives soft labels; the distillation loss forces the student to produce a similar probability distribution on the same data. A describes the student loss (e.g., cross-entropy with ground truth) — the two losses are jointly learned.
11
Open-ended · Pre-processing for mobile HAR
a) Describe the pre-processing pipeline for inertial data and the sliding-window segmentation: which parameters must be tuned, and which trade-offs guide the choice?
b) What is dynamic segmentation, how does it work as an optimization problem, and what is its main limit?
Model answer

a) The pipeline is data cleaning → segmentation → feature extraction → feature vector. Cleaning: inertial data are noisy, so smoothing filters (median, low-pass, gaussian) keep the informative part; often the gravity component is removed from acceleration (using the orientation from the gyroscope) obtaining linear acceleration, which better represents actual movements. Segmentation works on a multivariate time series (multiple sensors, multiple axes, possibly multiple devices; data must be temporally aligned and clocks synchronized). Sliding windows have two parameters: window length L and overlap M, chosen based on the target activities — simple physical activities need short windows (e.g., 3 s with 50% overlap), complex activities need longer ones. Overlap is crucial to capture transitions. With real-time requirements there is a trade-off between response delay and accuracy (short windows → fast but less accurate; longer windows → more accurate but delayed). At training time each window is labeled with the prevalent activity.

b) Sliding windows may not fully represent an activity pattern and the size choice is non-trivial. Dynamic segmentation uses unsupervised methods to detect change points in the sensor stream — intuitively, transitions between activities. It is framed as an optimization problem: each segment is associated with a cost (e.g., avg, std, slope) and the goal is to find the change points minimizing the total cost; a penalty is added per change point (high penalty → too few change points; low penalty → too many). Main limit: these methods are computationally expensive, hence inadequate when there are real-time requirements.

12
Open-ended · Deploying HAR models on mobile devices
a) Compare offline vs online recognition, and server-side vs client-side execution for online HAR.
b) Explain how to make deep HAR models efficient enough for mobile devices: compare compression and quantization, and describe knowledge distillation.
Model answer

a) Offline recognition: devices only collect data, which are stored and processed in another phase — useful when real-time is not required, favoring accuracy (e.g., behavior analysis). Online recognition: activities recognized in real-time, e.g., to support context-aware applications. Online can run server-side (pro: high computational capabilities; cons: network communication overhead and reduced privacy, since sensor data leave the device) or client-side (pro: good real-time support and better privacy; cons: complex models cannot run efficiently on resource-constrained devices). Deployment workflow: train offline (e.g., Python), convert to the format of the mobile SDK (Weka for Android, CoreML for iOS, TensorFlow Lite for both — the same SDK should create and deploy the model), then on-device the stream is segmented and pre-processed with the same parameters used during training before classification.

b) Either design simpler models from the start, or reduce existing models. Compression shrinks the model structure: pruning unimportant neurons/weights (minor impact on accuracy), merging components (sharing weights for similar edges), or knowledge distillation. Quantization instead reduces the numerical precision of the weights: 32-bit floats → 16-bit, or 8-bit integers/fixed point; advanced variants are sub-byte quantization (<8 bits, hard because hardware stores data at byte level) and mixed precision (different bit-widths per layer — better accuracy/size trade-off, harder to design). They are two different processes but can be combined; the key problem is the trade-off between recognition rate and efficiency. Knowledge distillation: a small student learns from a large teacher — the teacher's softmax output provides soft labels, and the distillation loss forces the student to produce a similar probability distribution on the same data, while the student loss (e.g., cross-entropy with ground truth) optimizes the actual HAR task; the two losses are learned jointly.

0/10
MCQ score 0/10