-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper_functions.py
130 lines (105 loc) · 5.22 KB
/
helper_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""
helper_functions.py
Author: Muhammad Uzair Zahid
Created: 07/10/2021
Edited: 11/08/2024
Description: This module provides helper functions to prepare and load ECG data for training and testing,
including data segmentation, feature extraction, and normalization.
"""
import numpy as np
import pickle
from sklearn.preprocessing import RobustScaler
def prepare_ecg_data(data, wavelet_type, scales, sampling_period):
"""
Prepares ECG data for model training by segmenting heartbeats, calculating RR intervals, and
extracting features from wavelet coefficients.
Parameters:
data (dict): A dictionary containing ECG record data with keys 'coeffs', 'r_peaks', 'categories', and 'record'.
wavelet_type (str): Wavelet type used for the wavelet transform.
scales (list): List of scales for wavelet transformation.
sampling_period (float): Sampling period for the ECG signal.
Returns:
tuple: (x1, x2, y, groups) where:
- x1: List of wavelet-scaled beats.
- x2: List of RR interval features.
- y: List of heartbeat categories.
- groups: List of patient identifiers.
"""
# Define segmentation interval around R-peak
before, after = 90, 126
# Retrieve necessary data
coeffs = data["coeffs"]
r_peaks, categories = data["r_peaks"], data["categories"]
# Calculate average RR interval to normalize inter-patient variation
avg_rri = np.mean(np.diff(r_peaks))
# Initialize lists for features and labels
x1, x2, y, groups = [], [], [], []
# Process each heartbeat except the first two and last two
for i in range(2, len(r_peaks) - 2):
if categories[i] in {3, 4}: # Skip undesired categories
continue
# Calculate local RR interval for recent beats
local_RR = np.mean(np.diff(r_peaks[max(i - 10, 0):i + 1]))
# Extract heartbeat segment around R-peak using wavelet coefficients
beat_segment = coeffs[:, r_peaks[i] - before : r_peaks[i] + after]
# Append wavelet-scaled heartbeat and RR interval features
x1.append(beat_segment)
x2.append([
r_peaks[i] - r_peaks[i - 1] - avg_rri, # Previous RR Interval
r_peaks[i + 1] - r_peaks[i] - avg_rri, # Post RR Interval
(r_peaks[i] - r_peaks[i - 1]) / (r_peaks[i + 1] - r_peaks[i]), # RR Interval Ratio
local_RR - avg_rri # Local RR Interval
])
# Append labels and patient record identifier
y.append(categories[i])
groups.append(data["record"])
return x1, x2, y, groups
def load_data(wavelet_type, scales, sampling_rate, processed_data_path):
"""
Loads and processes ECG data for training and testing, including feature extraction and normalization.
Parameters:
wavelet_type (str): Wavelet type used for continuous wavelet transform.
scales (list): List of scales for wavelet transformation.
sampling_rate (int): Sampling rate of the ECG signals.
processed_data_path (str): Path to the pickle file containing the processed data.
Returns:
tuple: (train_data, test_data) where each is a tuple containing:
- x1: Wavelet-scaled beats.
- x2: RR interval features.
- y: Labels for each heartbeat.
- groups: Patient identifiers.
"""
# Load data from pickle file
with open(processed_data_path, "rb") as f:
train_data, test_data = pickle.load(f)
# Prepare training data
x1_train, x2_train, y_train, groups_train = [], [], [], []
for data in train_data:
x1, x2, y, groups = prepare_ecg_data(data=data, wavelet_type=wavelet_type, scales=scales, sampling_period=1.0 / sampling_rate)
x1_train.append(x1)
x2_train.append(x2)
y_train.append(y)
groups_train.append(groups)
# Concatenate and format training data
x1_train = np.concatenate(x1_train, axis=0).astype(np.float32)
x2_train = np.concatenate(x2_train, axis=0).astype(np.float32)
y_train = np.concatenate(y_train, axis=0).astype(np.int64)
groups_train = np.concatenate(groups_train, axis=0)
# Prepare testing data
x1_test, x2_test, y_test, groups_test = [], [], [], []
for data in test_data:
x1, x2, y, groups = prepare_ecg_data(data=data, wavelet_type=wavelet_type, scales=scales, sampling_period=1.0 / sampling_rate)
x1_test.append(x1)
x2_test.append(x2)
y_test.append(y)
groups_test.append(groups)
# Concatenate and format testing data
x1_test = np.concatenate(x1_test, axis=0).astype(np.float32)
x2_test = np.concatenate(x2_test, axis=0).astype(np.float32)
y_test = np.concatenate(y_test, axis=0).astype(np.int64)
groups_test = np.concatenate(groups_test, axis=0)
# Normalize x2 data using RobustScaler for training and testing
scaler = RobustScaler()
x2_train = scaler.fit_transform(x2_train)
x2_test = scaler.transform(x2_test)
return (x1_train, x2_train, y_train, groups_train), (x1_test, x2_test, y_test, groups_test)