EMBEDLIX RESEARCH · MACHINE LEARNING LABORATORY SERIES

GRU sequence modelling: from windows to predictions

Boundary-safe time windows, recurrent architecture, validation searches and controlled-test results.

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

4.1 Why temporal information changes the problem

A sequence model can use the rise and fall of acceleration, rotational changes and repetition within a movement. Instead of classifying one instant, the GRU receives 100 consecutive rows × 6 channels, approximately one second at 100 Hz. [1,5]

A hidden state carries information through the window. Gates regulate what to retain and what to update. The final hidden representation feeds a four-output softmax layer. This is sequence-to-one classification: one activity label is assigned per window, not one label per timestep.

The saved walking-window figure is real standardized notebook data. Its vertical axes are dimensionless after standardization; the source plot’s physical-unit labels describe the original channels, not the standardized numerical units. Its caption here preserves that distinction.

A real walking sequence from the notebook. Original Lab 4 window: 100 standardized rows and six channels. Values after standardization are dimensionless.

4.2 Window generation and overlap

Windows are generated inside each recording, after recording-level separation. With length L = 100 and step S = 1, adjacent windows share 99 of their 100 samples:

overlap=1−SL=0.99\mathrm{overlap}=1-\frac{S}{L}=0.99

For a recording with N rows, the number of complete windows is:

nwindows=max⁡(0,⌊N−LS⌋+1)n_{\mathrm{windows}}=\max\left(0,\left\lfloor\frac{N-L}{S}\right\rfloor+1\right)

Illustrative example: 105 rows yield six complete length-100 windows, starting at indices 0 to 5. They are not six independent movement episodes. Never concatenate all activities and then window across the joined boundary: that would mix recordings or classes inside one input.

The saved tensors contain 60,681 training windows, 15,154 validation windows and 15,250 test windows. The site does not regenerate them without the missing raw CSV files. The original window function below includes metadata so predictions can be traced to recording identity and time.

Overlapping windows · illustrative indices

  1. Window A

    Rows 0–99

  2. Window B

    Rows 1–100 · 99 shared rows

  3. Window C

    Rows 2–101 · step of 1

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

Original notebook cell · dependencies described above

def create_windows(data, window_size, overlap=0.99):
    """
    Create overlapping windows separately within each recording.

    Returns:
        X: shape (number of windows, timesteps, features)
        y: numeric class label for each window
        metadata: recording and time information for each window
        step_size: number of samples between consecutive windows
    """

    step_size = max(
        1,
        int(round(window_size * (1 - overlap))),
    )

    X_windows = []
    y_windows = []
    metadata = []

    # Process every recording separately so that a window
    # can never cross a recording boundary.
    for recording_id, recording in data.groupby(
        "recording_id",
        sort=False,
    ):
        recording = (
            recording
            .sort_values("time")
            .reset_index(drop=True)
        )

        recording_labels = recording["label"].unique()

        if len(recording_labels) != 1:
            raise ValueError(
                f"{recording_id} contains multiple labels."
            )

        label = recording_labels[0]
        label_index = class_to_index[label]

        sensor_values = recording[
            FEATURES
        ].to_numpy(dtype=np.float32)

        time_values = recording[
            "time"
        ].to_numpy(dtype=np.float32)

        last_start = len(recording) - window_size

        for start_index in range(
            0,
            last_start + 1,
            step_size,
        ):
            end_index = start_index + window_size

            X_windows.append(
                sensor_values[start_index:end_index]
            )

            y_windows.append(label_index)

            metadata.append({
                "recording_id": recording_id,
                "label": label,
                "start_index": start_index,
                "end_index": end_index - 1,
                "start_time": time_values[start_index],
                "end_time": time_values[end_index - 1],
            })

    if not X_windows:
        raise ValueError("No windows were created.")

    X = np.stack(X_windows).astype(np.float32)
    y = np.asarray(y_windows, dtype=np.int32)
    metadata = pd.DataFrame(metadata)

    return X, y, metadata, step_size

4.3 Compact recurrent architecture

LayerOutputParameters
Input100 × 60
GRU32-unit final hidden state3,840
Dense softmax4 activity probabilities132
TotalSequence-to-one classifier3,972

The selected architecture has one GRU layer, zero dropout, Adam learning rate 0.001, sparse categorical cross-entropy and batch size 256. The original model-building function is configurable so width, depth and dropout can be compared without rewriting the whole experiment.

Early stopping monitors validation loss with patience 5, minimum delta 0.0001 and restoration of best weights, within a maximum of 40 epochs. The baseline completed 22 epochs; its reported minimum validation-loss epoch was 17. A minimum-delta stopping rule and an absolute minimum-loss epoch are distinct bookkeeping details, so do not assume that simply running exactly 17 epochs replicates every restored-weight evaluation.

Source-derived model architecture

  1. 100 × 6

    One standardized time window

  2. 32 GRU units

    Temporal hidden representation

  3. 4 outputs

    One activity per window

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

Original notebook cell · dependencies described above

def build_gru_model(
    window_size,
    gru_units=32,
    number_of_gru_layers=1,
    dropout=0.0,
    learning_rate=0.001,
):
    inputs = keras.Input(
        shape=(window_size, len(FEATURES)),
        name="sensor_window",
    )

    x = inputs

    for layer_number in range(number_of_gru_layers):
        return_sequences = (
            layer_number < number_of_gru_layers - 1
        )

        x = layers.GRU(
            units=gru_units,
            return_sequences=return_sequences,
            dropout=dropout,
            name=f"gru_layer_{layer_number + 1}",
        )(x)

    outputs = layers.Dense(
        units=len(CLASS_NAMES),
        activation="softmax",
        name="movement_probabilities",
    )(x)

    model = keras.Model(
        inputs=inputs,
        outputs=outputs,
        name="movement_gru",
    )

    model.compile(
        optimizer=keras.optimizers.Adam(
            learning_rate=learning_rate
        ),
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"],
    )

    return model

4.4 Validation-based search, not test-based tuning

SearchTestedSelected
Window length100, 200, 300 samples100
GRU units16, 32, 6432
Recurrent layers1, 21
Dropout0, 0.2, 0.40
Learning rate0.0001, 0.001, 0.0030.001

Saved evaluation outputs report window-length validation losses 0.000113, 0.000223 and 0.001655. Width 16 produced 0.001491, while width 64 produced 0.000274; the 32-unit baseline remained strongest. Adding a second recurrent layer increased parameters to 10,308 and validation loss to 0.002365.

Dropout 0.2 and 0.4 produced losses 0.000365 and 0.000348, compared with 0.000113 at zero dropout. A learning rate of 0.0001 produced loss 0.004170; 0.003 produced 0.000124. Faster training at a higher rate did not beat the chosen validation loss.

These are saved output values, not approximate numbers inferred from chart height. Some report chart transcriptions round or differ from their surrounding prose; the publication uses the notebook outputs and explicitly preserves original figures. The compact baseline was retained rather than declaring that a larger model is inherently better.

Window-length validation search. Original saved notebook figure. Recorded experiment output, not independently rerun here.
GRU width: validation and complexity. Original saved notebook figure. Recorded experiment output, not independently rerun here.
One versus two recurrent layers. Original saved notebook figure. Recorded experiment output, not independently rerun here.
Dropout: validation and training time. Original saved notebook figure. Recorded experiment output, not independently rerun here.
Learning-rate validation search. Original saved notebook figure. Recorded experiment output, not independently rerun here.

4.5 Training behaviour and final controlled test

Training converged rapidly. The selected baseline evaluation reported 100% validation accuracy with loss 0.000113. These highly correlated windows from eight validation recordings should not be interpreted as thousands of independent successes.

The final controlled test classified 15,127 of 15,250 windows correctly, corresponding to 99.19% after rounding. Test loss was 0.043053. Walking generated 122 errors into forward/backward; one jumping window became running. All running and fourth-class windows in this controlled test were correct.

Walking recall rose to 96.80%, compared with 78.51% for the FFN and 82.87% for KNN. The 9.10-point rounded difference relative to FFN is descriptive evidence that sequence modelling was useful under these conditions. It does not isolate the causal contribution of temporal order because the model and input representation changed together.

GRU baseline training and validation curves. Original saved notebook figure. Recorded experiment output, not independently rerun here.
GRU controlled-test confusion matrix. Original saved notebook figure. Recorded experiment output, not independently rerun here.

4.6 Applying the frozen model outside training

For a new recording, retain the six-feature order, transform with the training-fitted scaler, create windows using the same length and step, and pass them to the frozen model. Use the saved class mapping when converting indices back to names.

# Teaching inference pattern; trained artifacts and raw CSVs are required.
new_scaled = new_recording.copy()
new_scaled[FEATURES] = scaler.transform(new_recording[FEATURES])
X_new, _, metadata, step = create_windows(new_scaled, 100, overlap=0.99)
probabilities = final_model.predict(X_new, batch_size=256)
predicted_indices = probabilities.argmax(axis=1)
confidence = probabilities.max(axis=1)

This is an offline teaching example, not a live browser classifier. A maximum softmax probability is a confidence score inside a closed four-class model, not proof of correctness or a calibrated probability that an unfamiliar movement is one of the trained activities. The next chapter examines the continuous and external failures that expose this limitation.