DEV Community

wellallyTech
wellallyTech

Posted on

Mastering Stress: Real-time HRV Outlier Detection with Bi-LSTM and TensorFlow πŸ§ πŸ’“

Have you ever wondered why your Apple Watch suddenly pings you to "take a breath" exactly when your boss sends that "Can we hop on a quick call?" Slack message? It’s not magicβ€”it's Heart Rate Variability (HRV).

HRV is a powerful window into our Autonomic Nervous System (ANS). However, raw wearable data is notoriously noisy. To turn those messy spikes into actionable insights, we need more than just simple averages. In this tutorial, we’ll build a real-time Bi-LSTM (Bidirectional Long Short-Term Memory) model to detect HRV outliers and identify stress states using TensorFlow/Keras.

Whether you're working with Apple Watch Core Motion data or generic time-series streams, mastering Time Series Analysis for health tech is a superpower in the modern dev market.


The Architecture: From Pixels to Pulse

To detect anomalies in HRV data, we can't just look at a single data point. We need the context of what happened before and after. This is where the Bi-LSTM shines.

graph TD
    A[Raw Sensor Data: Apple Watch] --> B[R-R Interval Extraction]
    B --> C[Signal Preprocessing & Normalization]
    C --> D{Bi-LSTM Model}
    D --> E[Forward Context Tracking]
    D --> F[Backward Context Tracking]
    E & F --> G[Anomaly Score Calculation]
    G --> H[Stress Alert / Outlier Flag]
    H --> I[Visualization/Dashboard]
Enter fullscreen mode Exit fullscreen mode

Prerequisites πŸ› οΈ

Before we dive into the code, make sure you have the following in your environment:

  • TensorFlow / Keras: For building our deep learning model.
  • NumPy / Pandas: For time-series manipulation.
  • Scikit-learn: For data scaling and metrics.

Step 1: Understanding the Data (The R-R Interval)

In the world of wearables, we care about the R-R intervalβ€”the time elapsed between two successive heartbeats. Unlike a steady heart rate, HRV focuses on the variance of these intervals. High variance usually means you're relaxed, while low variance (a "metronome" heart) often indicates high stress.

Step 2: Building the Bi-LSTM Model πŸ—οΈ

A standard LSTM only looks at past data. But for anomaly detection, looking at the "future" (the context immediately following a spike) helps the model distinguish between a sensor glitch and a genuine physiological stress response.

import tensorflow as tf
from tensorflow.keras import layers, Sequential

def build_hrv_model(sequence_length, feature_count):
    model = Sequential([
        # The Bi-LSTM layer allows the model to learn from past and future states
        layers.Bidirectional(layers.LSTM(64, return_sequences=True), 
                             input_shape=(sequence_length, feature_count)),
        layers.Dropout(0.2),

        layers.Bidirectional(layers.LSTM(32)),
        layers.Dropout(0.2),

        # Dense layer to output the probability of an "Outlier" or Stress state
        layers.Dense(16, activation='relu'),
        layers.Dense(1, activation='sigmoid') 
    ])

    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    return model

# Example usage:
# sequence_length = 30 (30 heartbeats window)
# feature_count = 1 (R-R interval value)
hrv_detector = build_hrv_model(30, 1)
hrv_detector.summary()
Enter fullscreen mode Exit fullscreen mode

Step 3: Real-time Preprocessing ⚑

When dealing with Apple Watch Core Motion or HealthKit data, you'll receive a stream of timestamps. You need to calculate the differences between them on the fly.

import numpy as np

def preprocess_raw_intervals(raw_timestamps):
    """
    Converts raw timestamps into R-R intervals and scales them.
    """
    # Calculate R-R intervals (in milliseconds)
    rr_intervals = np.diff(raw_timestamps) * 1000

    # Simple Z-score normalization for the model
    mean_val = np.mean(rr_intervals)
    std_val = np.std(rr_intervals)
    normalized_rr = (rr_intervals - mean_val) / (std_val + 1e-6)

    return normalized_rr.reshape(-1, 1)
Enter fullscreen mode Exit fullscreen mode

The "Official" Way to Scale πŸ₯‘

Building a prototype is easy, but making it production-ready involves handling data drift, battery consumption on the wearable, and edge-case filtering.

For more production-ready examples and advanced patterns on how to integrate health data with cloud architectures, I highly recommend checking out the WellAlly Tech Blog. They have deep-dive articles on optimizing AI models for low-power wearable devices that helped me refine my own anomaly detection logic!


Step 4: Training & Identifying Stress

Once the model is trained on labeled data (periods of rest vs. periods of high cognitive load), you can set a threshold for your anomaly score. If the Bi-LSTM predicts a value above 0.8, it’s time to tell your user to take a walk! πŸšΆβ€β™‚οΈ

# Assuming 'X_test' is your preprocessed sliding window of HRV data
predictions = hrv_detector.predict(X_test)

# Flag anomalies where the probability is high
anomalies = predictions > 0.85
print(f"Detected {np.sum(anomalies)} moments of high physiological stress!")
Enter fullscreen mode Exit fullscreen mode

Conclusion: Learning in Public πŸš€

Integrating Bi-LSTM for HRV analysis isn't just about the math; it's about understanding the human condition through data. By capturing both past and future context in a heartbeat stream, we can build tools that truly help people manage their well-being.

What's next?

  1. Try adding Accelerometry data to filter out "stress" that is actually just physical exercise.
  2. Deploy the model using TensorFlow Lite to run directly on a mobile device.

Did this help you understand HRV better? Drop a comment below or share your own "Learning in Public" journey! And don't forget to visit wellally.tech/blog for more advanced insights into health-tech engineering.

Top comments (0)