EMBEDLIX RESEARCH · MACHINE LEARNING LABORATORY SERIES

Data acquisition and experimental methodology

From smartphone sensor recordings to a recording-aware, training-only preprocessing protocol.

Chathuranga Bandara PolkotuwaResearch portfolio · Labs 1–4Chapter 1 of 6

1.1 Research question and study design

This laboratory series asks whether smartphone acceleration and angular velocity can distinguish walking, running, jumping and forward/backward movement, and whether a model learned under one collection setup remains useful outside that setup. The progression is deliberate: first establish a classical baseline, then learn nonlinear row-level relationships, then preserve temporal order with a recurrent network. [1–5]

The development dataset comes from one participant. It contains 48 recordings: 12 per class, with 95,837 aligned sensor rows. The notebook label own names the fourth movement; it does not mean “own participant.” The presentation describes this trained activity as forward/backward movement. The external Lab 4 activity is three-position stepping and is not an equivalent fourth class.

This is a source-backed academic portfolio study, not a peer-reviewed journal article or a validated activity-recognition product. The supplied notebooks retain experiment outputs, but raw sensor CSV files and trained model artifacts were not uploaded, so the study has not been independently rerun here.

1.2 Sensor channels and physical meaning

FeatureMeasurementUnitInterpretation
ax, ay, azAcceleration along phone axesm/s²Translational movement and gravity-related orientation information
gx, gy, gzAngular velocity around phone axesrad/sRotation and changing phone orientation
timeSensor timestampsAlignment and temporal ordering, not a model input
labelActivity classcategoricalSupervised target
recording_idIdentity of one recordingstringGrouping for splitting and window boundaries

The six axes are the model inputs. The timestamp, activity label and recording identity must not accidentally become predictive features. The accelerometer can report nonzero acceleration when stationary because gravity is present. A rotated phone can therefore change axis distributions without changing the human activity.

The original exploration showed overlapping distributions: no single axis separates every activity. Running and jumping often produce stronger variability, while low-intensity movement can resemble individual walking samples. Combining acceleration and rotation is therefore more informative than assigning a class from one axis alone.

X-axis acceleration by activity. Original Lab 2 saved boxplot. Physical acceleration units; the plot does not imply separable classes.
Six channels, four activity distributions. Faithful crop of logbook p. 4. Original distributions; not reconstructed from approximate extracted tables.

1.3 Aligning the two sensor streams

Accelerometer and gyroscope exports do not necessarily have identical row counts or timestamps. One saved walking example contains 2,006 acceleration rows and 2,005 gyroscope rows. Concatenating by row index could pair measurements taken at different times.

The loading function renames exported column headers, sorts both streams by time and uses pd.merge_asof with nearest matching and a 0.02-second tolerance. The acceleration timeline is retained; a gyroscope row may be reused as the nearest match. This is timestamp matching, not interpolation or guaranteed clock synchronization.

Worked example (illustrative): an acceleration sample at 1.000 s and a gyroscope sample at 1.008 s differ by 0.008 s, so they can be matched. A nearest sample at 1.025 s lies outside the 0.02 s tolerance and would leave an unmatched value. Inspect missing values after merging before passing data to a model. The saved dataset checks report no missing sensor values.

The following is the original loading function from Lab 2. DATA_DIR and class_folders must be configured before calling it.

Original notebook cell · dependencies described above

def load_recording(label, recording_number):
    folder = DATA_DIR / class_folders[label]

    acc_file = folder / f"{label}_{recording_number}_acc.csv"
    gyro_file = folder / f"{label}_{recording_number}_gyro.csv"

    acc = pd.read_csv(acc_file).rename(columns={
        "Time (s)": "time",
        "X (m/s^2)": "ax",
        "Y (m/s^2)": "ay",
        "Z (m/s^2)": "az"
    })

    gyro = pd.read_csv(gyro_file).rename(columns={
        "Time (s)": "time",
        "X (rad/s)": "gx",
        "Y (rad/s)": "gy",
        "Z (rad/s)": "gz"
    })

    data = pd.merge_asof(
        acc.sort_values("time"),
        gyro.sort_values("time"),
        on="time",
        direction="nearest",
        tolerance=0.02
    )

    data["label"] = label
    data["recording_id"] = f"{label}_{recording_number}"

    return data

1.4 Recording-aware separation

ExperimentDevelopment / trainingValidationFinal test
Classical ML40 recordings; 79,795 rows5 grouped folds within development8 recordings; 16,042 rows
Feedforward network32 recordings; 63,849 rows8 recordings; 15,946 rows8 recordings; 16,042 rows
GRU32 recordings; 60,681 windows8 recordings; 15,154 windows8 recordings; 15,250 windows

Whole recordings are assigned to subsets before preprocessing or windowing. In Lab 2, StratifiedGroupKFold supplies five recording-aware folds; each fold has 32 training recordings and eight validation recordings. In Labs 3 and 4, the development pool is divided into separate training and validation recordings using fixed seeds.

The essential audit is empty intersections of recording IDs between training, validation and test. Nearby sensor samples can be almost identical; random row splitting would allow one movement episode to appear on both sides of the evaluation boundary. Grouping reduces this leakage, but it does not establish generalization to an unseen participant.

The original Lab 4 split code below reserves two test recordings per class, then two validation recordings per class. The test identities are held separately from model fitting.

Experimental protocol

  1. Record

    48 separate activity episodes

  2. Split first

    32 train / 8 validation / 8 test

  3. Fit training only

    Scaler → model → frozen evaluation

Explanatory schematic based on the supplied notebooks, not a measured signal or additional experiment.

Original notebook cell · dependencies described above

SEED = 42

# First reserve two recordings per class for final testing.
test_rng = np.random.default_rng(SEED)

development_ids = []
test_ids = []

for label in CLASS_FOLDERS:
    class_ids = full_data.loc[
        full_data["label"] == label,
        "recording_id",
    ].unique()

    selected_test_ids = test_rng.choice(
        class_ids,
        size=2,
        replace=False,
    )

    remaining_ids = [
        recording_id
        for recording_id in class_ids
        if recording_id not in selected_test_ids
    ]

    test_ids.extend(selected_test_ids.tolist())
    development_ids.extend(remaining_ids)


# Select two validation recordings from the remaining
# ten recordings in each class.
validation_rng = np.random.default_rng(SEED)

train_ids = []
validation_ids = []

for label in CLASS_FOLDERS:
    available_ids = full_data.loc[
        (full_data["label"] == label)
        & (full_data["recording_id"].isin(development_ids)),
        "recording_id",
    ].unique()

    selected_validation_ids = validation_rng.choice(
        available_ids,
        size=2,
        replace=False,
    )

    selected_train_ids = [
        recording_id
        for recording_id in available_ids
        if recording_id not in selected_validation_ids
    ]

    train_ids.extend(selected_train_ids)
    validation_ids.extend(selected_validation_ids.tolist())


train_data = full_data[
    full_data["recording_id"].isin(train_ids)
].copy()

validation_data = full_data[
    full_data["recording_id"].isin(validation_ids)
].copy()

test_data = full_data[
    full_data["recording_id"].isin(test_ids)
].copy()

1.5 Scaling without learning from evaluation data

Standardization transforms each channel using a mean and standard deviation fitted to training data:

zj=xj−μj,trainσj,trainz_j = \frac{x_j-\mu_{j,\mathrm{train}}}{\sigma_{j,\mathrm{train}}}

For KNN, the scaler is inside the cross-validation pipeline, so each fold learns its own training statistics. For the neural networks, it is fitted once on development training rows and reused unchanged for validation, test and external data. A test value need not lie near zero after this transformation: an unfamiliar distribution remains unfamiliar.

Illustrative arithmetic: if a training feature has mean −10 and standard deviation 2, a new reading of +9 becomes 9.5 after scaling. Standardization does not rotate a phone back to its training orientation. Refitting the scaler on external data would change the evaluation protocol and would not test the original frozen pipeline.

The original scaling cell retains recording identities and applies the same fitted transformation to all subsets.

Original notebook cell · dependencies described above

from sklearn.preprocessing import StandardScaler

CLASS_NAMES = ["walk", "run", "jump", "own"]

class_to_index = {
    class_name: index
    for index, class_name in enumerate(CLASS_NAMES)
}

index_to_class = {
    index: class_name
    for class_name, index in class_to_index.items()
}

print("Class mapping:", class_to_index)


# Make copies so the original sensor values remain unchanged.
train_scaled_data = train_data.copy()
validation_scaled_data = validation_data.copy()

scaler = StandardScaler()

# Fit and transform training data.
train_scaled_data[FEATURES] = scaler.fit_transform(
    train_data[FEATURES]
).astype(np.float32)

# Transform validation data with the training-fitted scaler.
validation_scaled_data[FEATURES] = scaler.transform(
    validation_data[FEATURES]
).astype(np.float32)

1.6 Experimental validity and repeated test access

The model configurations were selected using development validation results. However, Lab 2 reports test results at both Grade 3 and Grade 4, and the series compares models against a known test result. The final test was therefore inspected more than once over the study. This does not imply that test rows were used for training, but it weakens a strict “one final untouched evaluation” claim.

A future publication-quality protocol should freeze the entire analysis plan and all model choices before opening a new final test set. Validation should hold out participants or sessions when the goal is generalization, and evaluation uncertainty should reflect recordings or participants rather than treating thousands of correlated sensor rows as independent trials.