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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": []
|
| 7 |
+
},
|
| 8 |
+
"kernelspec": {
|
| 9 |
+
"name": "python3",
|
| 10 |
+
"display_name": "Python 3"
|
| 11 |
+
},
|
| 12 |
+
"language_info": {
|
| 13 |
+
"name": "python"
|
| 14 |
+
}
|
| 15 |
+
},
|
| 16 |
+
"cells": [
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "markdown",
|
| 19 |
+
"source": [
|
| 20 |
+
"**After Processing the raw data in the end to end pipeline matlab file, this python notebook is meant to segment and form them into .npy files which are easily lodaded into our custom deep learning model**"
|
| 21 |
+
],
|
| 22 |
+
"metadata": {
|
| 23 |
+
"id": "osl6LnrAg-Ea"
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "markdown",
|
| 28 |
+
"source": [
|
| 29 |
+
"A. Segment for Train set"
|
| 30 |
+
],
|
| 31 |
+
"metadata": {
|
| 32 |
+
"id": "NA622TQmhabM"
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"metadata": {
|
| 39 |
+
"id": "t971XYf6g4Sx"
|
| 40 |
+
},
|
| 41 |
+
"outputs": [],
|
| 42 |
+
"source": [
|
| 43 |
+
"import os\n",
|
| 44 |
+
"import numpy as np\n",
|
| 45 |
+
"from glob import glob\n",
|
| 46 |
+
"import scipy.io as sio\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"# Parameters for CWT segmentation based on time resolution\n",
|
| 49 |
+
"segment_duration = 2.5 # seconds\n",
|
| 50 |
+
"fs = 800 # sampling frequency (Hz)\n",
|
| 51 |
+
"segment_size = int(fs * segment_duration) # 800*2.5 = 2000 frames\n",
|
| 52 |
+
"overlap = 0.75\n",
|
| 53 |
+
"step_size = int(segment_size * (1 - overlap))\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"# The input and output directories for the train CWT data (can adjust the paths as needed)\n",
|
| 56 |
+
"input_path = \"/content/drive/MyDrive/my_dataset/traincwt/\" # Change to suitable path\n",
|
| 57 |
+
"output_path = \"/content/drive/MyDrive/my_dataset/traincwt_segmented/\" # Change to suitable path\n",
|
| 58 |
+
"os.makedirs(output_path, exist_ok=True)\n",
|
| 59 |
+
"\n",
|
| 60 |
+
"# Get list of all CWT amplitude files for the train set\n",
|
| 61 |
+
"amp_files = sorted(glob(os.path.join(input_path, \"trainamp_*_cwt.mat\")))\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"for amp_file in amp_files:\n",
|
| 64 |
+
" amp_filename = os.path.basename(amp_file)\n",
|
| 65 |
+
"\n",
|
| 66 |
+
" # Find corresponding phase file by replacing \"trainamp_\" with \"trainphase_\"\n",
|
| 67 |
+
" phase_filename = amp_filename.replace(\"trainamp_\", \"trainphase_\")\n",
|
| 68 |
+
" phase_file = os.path.join(input_path, phase_filename)\n",
|
| 69 |
+
"\n",
|
| 70 |
+
" if not os.path.exists(phase_file):\n",
|
| 71 |
+
" print(f\"Skipping {amp_filename} as phase file {phase_filename} not found.\")\n",
|
| 72 |
+
" continue\n",
|
| 73 |
+
"\n",
|
| 74 |
+
" # Load CWT amplitude and phase data from .mat files\n",
|
| 75 |
+
" amp_mat = sio.loadmat(amp_file)\n",
|
| 76 |
+
" phase_mat = sio.loadmat(phase_file)\n",
|
| 77 |
+
"\n",
|
| 78 |
+
" # Check for required variables\n",
|
| 79 |
+
" if \"wt_amp\" not in amp_mat or \"wt_phase\" not in phase_mat:\n",
|
| 80 |
+
" print(f\"Variables not found in {amp_filename} or {phase_filename}, skipping.\")\n",
|
| 81 |
+
" continue\n",
|
| 82 |
+
"\n",
|
| 83 |
+
" amp_data = amp_mat[\"wt_amp\"] # Expected shape: (freq_bins, time_frames)\n",
|
| 84 |
+
" phase_data = phase_mat[\"wt_phase\"]\n",
|
| 85 |
+
"\n",
|
| 86 |
+
" # Checking the dimensions\n",
|
| 87 |
+
" if amp_data.shape != phase_data.shape:\n",
|
| 88 |
+
" print(f\"Mismatch in dimensions for {amp_filename} and {phase_filename}, skipping.\")\n",
|
| 89 |
+
" continue\n",
|
| 90 |
+
"\n",
|
| 91 |
+
" freq_bins, total_frames = amp_data.shape\n",
|
| 92 |
+
" segment_num = 1\n",
|
| 93 |
+
" start_idx = 0\n",
|
| 94 |
+
"\n",
|
| 95 |
+
" # Segment along the time axis (columns)\n",
|
| 96 |
+
" while start_idx + segment_size <= total_frames:\n",
|
| 97 |
+
" amp_segment = amp_data[:, start_idx:start_idx + segment_size]\n",
|
| 98 |
+
" phase_segment = phase_data[:, start_idx:start_idx + segment_size]\n",
|
| 99 |
+
"\n",
|
| 100 |
+
" # Create output filenames (.npy format)\n",
|
| 101 |
+
" base_name = amp_filename[:-4] # Removes the '.mat' extension\n",
|
| 102 |
+
" amp_segment_name = f\"{base_name}_S{segment_num}.npy\".replace(\"trainamp\", \"segtrainamp\")\n",
|
| 103 |
+
" phase_segment_name = f\"{base_name}_S{segment_num}.npy\".replace(\"trainamp\", \"segtrainphase\")\n",
|
| 104 |
+
" amp_segment_file = os.path.join(output_path, amp_segment_name)\n",
|
| 105 |
+
" phase_segment_file = os.path.join(output_path, phase_segment_name)\n",
|
| 106 |
+
"\n",
|
| 107 |
+
" # Save segments as .npy files\n",
|
| 108 |
+
" np.save(amp_segment_file, amp_segment)\n",
|
| 109 |
+
" np.save(phase_segment_file, phase_segment)\n",
|
| 110 |
+
"\n",
|
| 111 |
+
" start_idx += step_size\n",
|
| 112 |
+
" segment_num += 1\n",
|
| 113 |
+
"\n",
|
| 114 |
+
" # Handle any leftover frames as a final segment\n",
|
| 115 |
+
" if total_frames - start_idx > 0:\n",
|
| 116 |
+
" remaining = total_frames - start_idx\n",
|
| 117 |
+
" extra_needed = segment_size - remaining\n",
|
| 118 |
+
" extra_start = max(0, start_idx - extra_needed)\n",
|
| 119 |
+
"\n",
|
| 120 |
+
" amp_segment = amp_data[:, extra_start:]\n",
|
| 121 |
+
" phase_segment = phase_data[:, extra_start:]\n",
|
| 122 |
+
"\n",
|
| 123 |
+
" base_name = amp_filename[:-4]\n",
|
| 124 |
+
" amp_segment_name = f\"{base_name}_S{segment_num}.npy\".replace(\"trainamp\", \"segtrainamp\")\n",
|
| 125 |
+
" phase_segment_name = f\"{base_name}_S{segment_num}.npy\".replace(\"trainamp\", \"segtrainphase\")\n",
|
| 126 |
+
" amp_segment_file = os.path.join(output_path, amp_segment_name)\n",
|
| 127 |
+
" phase_segment_file = os.path.join(output_path, phase_segment_name)\n",
|
| 128 |
+
"\n",
|
| 129 |
+
" np.save(amp_segment_file, amp_segment)\n",
|
| 130 |
+
" np.save(phase_segment_file, phase_segment)\n",
|
| 131 |
+
"\n",
|
| 132 |
+
" print(f\"Segmented CWT data for {amp_filename} and its phase file.\")\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"print(\"All CWT segmentation tasks for the train set completed.\")\n"
|
| 135 |
+
]
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "markdown",
|
| 139 |
+
"source": [
|
| 140 |
+
"B. Segment for test set"
|
| 141 |
+
],
|
| 142 |
+
"metadata": {
|
| 143 |
+
"id": "lMZ8xMDyhtCP"
|
| 144 |
+
}
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"source": [
|
| 149 |
+
"import os\n",
|
| 150 |
+
"import numpy as np\n",
|
| 151 |
+
"from glob import glob\n",
|
| 152 |
+
"import scipy.io as sio\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"# Parameters for CWT segmentation based on time resolution\n",
|
| 155 |
+
"segment_duration = 2.5 # seconds\n",
|
| 156 |
+
"fs = 800 # sampling frequency (Hz)\n",
|
| 157 |
+
"segment_size = int(fs * segment_duration) # 800*2.5 = 2000 frames\n",
|
| 158 |
+
"overlap = 0.75\n",
|
| 159 |
+
"step_size = int(segment_size * (1 - overlap))\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"# The input and output directories for the test CWT data (can adjust the paths as needed)\n",
|
| 162 |
+
"input_path = \"/content/drive/MyDrive/my_dataset/testcwt/\" # Change to suitable path\n",
|
| 163 |
+
"output_path = \"/content/drive/MyDrive/my_dataset/testcwt_segmented/\" # Change to suitable path\n",
|
| 164 |
+
"os.makedirs(output_path, exist_ok=True)\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"# Get list of all CWT amplitude files for the test set\n",
|
| 167 |
+
"amp_files = sorted(glob(os.path.join(input_path, \"testamp_*_cwt.mat\")))\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"for amp_file in amp_files:\n",
|
| 170 |
+
" amp_filename = os.path.basename(amp_file)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" # Find corresponding phase file by replacing \"testamp_\" with \"testphase_\"\n",
|
| 173 |
+
" phase_filename = amp_filename.replace(\"testamp_\", \"testphase_\")\n",
|
| 174 |
+
" phase_file = os.path.join(input_path, phase_filename)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" if not os.path.exists(phase_file):\n",
|
| 177 |
+
" print(f\"Skipping {amp_filename} as phase file {phase_filename} not found.\")\n",
|
| 178 |
+
" continue\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # Load CWT amplitude and phase data from .mat files\n",
|
| 181 |
+
" amp_mat = sio.loadmat(amp_file)\n",
|
| 182 |
+
" phase_mat = sio.loadmat(phase_file)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" # Check for required variables\n",
|
| 185 |
+
" if \"wt_amp\" not in amp_mat or \"wt_phase\" not in phase_mat:\n",
|
| 186 |
+
" print(f\"Variables not found in {amp_filename} or {phase_filename}, skipping.\")\n",
|
| 187 |
+
" continue\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" amp_data = amp_mat[\"wt_amp\"] # Expected shape: (freq_bins, time_frames)\n",
|
| 190 |
+
" phase_data = phase_mat[\"wt_phase\"]\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" if amp_data.shape != phase_data.shape:\n",
|
| 193 |
+
" print(f\"Mismatch in dimensions for {amp_filename} and {phase_filename}, skipping.\")\n",
|
| 194 |
+
" continue\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" freq_bins, total_frames = amp_data.shape\n",
|
| 197 |
+
" segment_num = 1\n",
|
| 198 |
+
" start_idx = 0\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # Segment along the time axis (columns)\n",
|
| 201 |
+
" while start_idx + segment_size <= total_frames:\n",
|
| 202 |
+
" amp_segment = amp_data[:, start_idx:start_idx + segment_size]\n",
|
| 203 |
+
" phase_segment = phase_data[:, start_idx:start_idx + segment_size]\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" # Create output filenames (.npy format)\n",
|
| 206 |
+
" base_name = amp_filename[:-4] # Remove '.mat' extension\n",
|
| 207 |
+
" amp_segment_name = f\"{base_name}_S{segment_num}.npy\".replace(\"testamp\", \"segtestamp\")\n",
|
| 208 |
+
" phase_segment_name = f\"{base_name}_S{segment_num}.npy\".replace(\"testamp\", \"segtestphase\")\n",
|
| 209 |
+
" amp_segment_file = os.path.join(output_path, amp_segment_name)\n",
|
| 210 |
+
" phase_segment_file = os.path.join(output_path, phase_segment_name)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" # Save segments as .npy files\n",
|
| 213 |
+
" np.save(amp_segment_file, amp_segment)\n",
|
| 214 |
+
" np.save(phase_segment_file, phase_segment)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" start_idx += step_size\n",
|
| 217 |
+
" segment_num += 1\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" # Handle any leftover frames as a final segment\n",
|
| 220 |
+
" if total_frames - start_idx > 0:\n",
|
| 221 |
+
" remaining = total_frames - start_idx\n",
|
| 222 |
+
" extra_needed = segment_size - remaining\n",
|
| 223 |
+
" extra_start = max(0, start_idx - extra_needed)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" amp_segment = amp_data[:, extra_start:]\n",
|
| 226 |
+
" phase_segment = phase_data[:, extra_start:]\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" base_name = amp_filename[:-4]\n",
|
| 229 |
+
" amp_segment_name = f\"{base_name}_S{segment_num}.npy\".replace(\"testamp\", \"segtestamp\")\n",
|
| 230 |
+
" phase_segment_name = f\"{base_name}_S{segment_num}.npy\".replace(\"testamp\", \"segtestphase\")\n",
|
| 231 |
+
" amp_segment_file = os.path.join(output_path, amp_segment_name)\n",
|
| 232 |
+
" phase_segment_file = os.path.join(output_path, phase_segment_name)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" np.save(amp_segment_file, amp_segment)\n",
|
| 235 |
+
" np.save(phase_segment_file, phase_segment)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" print(f\"Segmented CWT data for {amp_filename} and its phase file.\")\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"print(\"All CWT segmentation tasks for the test set completed.\")\n"
|
| 240 |
+
],
|
| 241 |
+
"metadata": {
|
| 242 |
+
"id": "s9rJLrPyg9SR"
|
| 243 |
+
},
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"outputs": []
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"cell_type": "markdown",
|
| 249 |
+
"source": [
|
| 250 |
+
"C. Preparing train data"
|
| 251 |
+
],
|
| 252 |
+
"metadata": {
|
| 253 |
+
"id": "qb1GR3Pfh6Ar"
|
| 254 |
+
}
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"source": [
|
| 259 |
+
"import os\n",
|
| 260 |
+
"import numpy as np\n",
|
| 261 |
+
"from glob import glob\n",
|
| 262 |
+
"from sklearn.utils import shuffle\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"segmented_dir = \"/content/drive/MyDrive/my_dataset/traincwt_segmented/\"\n",
|
| 265 |
+
"preprocessed_dir = \"/content/drive/MyDrive/my_dataset/preprocessedcwt/\"\n",
|
| 266 |
+
"os.makedirs(preprocessed_dir, exist_ok=True)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"# Files to save preprocessed training data\n",
|
| 269 |
+
"train_combined_file = os.path.join(preprocessed_dir, \"X_train_combinedcwt.npy\")\n",
|
| 270 |
+
"train_label_file = os.path.join(preprocessed_dir, \"Y_traincwt.npy\")\n",
|
| 271 |
+
"global_mean_file = os.path.join(preprocessed_dir, \"global_mean.npy\")\n",
|
| 272 |
+
"global_std_file = os.path.join(preprocessed_dir, \"global_std.npy\")\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"# ----- Function to load and combine training data -----\n",
|
| 275 |
+
"def load_train_data():\n",
|
| 276 |
+
" # retrieve all segmented amplitude files\n",
|
| 277 |
+
" amp_files = sorted(glob(os.path.join(segmented_dir, \"segtrainamp_*.npy\")))\n",
|
| 278 |
+
" X_combined = [] # store the combined amplitude-phase arrays\n",
|
| 279 |
+
" Y = [] # Labels\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" for amp_file in amp_files:\n",
|
| 282 |
+
" # Derive corresponding phase file name by replacing \"segtrainamp_\" with \"segtrainphase_\"\n",
|
| 283 |
+
" phase_file = amp_file.replace(\"segtrainamp_\", \"segtrainphase_\")\n",
|
| 284 |
+
" if not os.path.exists(phase_file):\n",
|
| 285 |
+
" print(f\"Skipping {amp_file}, corresponding phase file not found.\")\n",
|
| 286 |
+
" continue\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" # Load amplitude and phase arrays\n",
|
| 289 |
+
" amp_data = np.load(amp_file) # Expected shape: (freq_bins, time_frames)\n",
|
| 290 |
+
" phase_data = np.load(phase_file) # Expected shape: (freq_bins, time_frames)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" print(f\"Loaded amplitude file: {amp_file} with shape {amp_data.shape}\")\n",
|
| 293 |
+
" print(f\"Loaded phase file: {phase_file} with shape {phase_data.shape}\")\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" if amp_data.shape != phase_data.shape:\n",
|
| 296 |
+
" print(f\"Mismatch in dimensions for {amp_file}, skipping.\")\n",
|
| 297 |
+
" continue\n",
|
| 298 |
+
"\n",
|
| 299 |
+
" # Stack amplitude and phase along a new last axis -> shape: (freq_bins, time_frames, 2)\n",
|
| 300 |
+
" combined = np.stack([amp_data, phase_data], axis=-1)\n",
|
| 301 |
+
" X_combined.append(combined)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" # Extract label from the file name.\n",
|
| 304 |
+
" # Given \"segtrainamp_A1_P0_L1_T2_cwt_S1.npy\",\n",
|
| 305 |
+
" # we assume the activity label is encoded after \"_A\" (here, \"1\") and shift to 0-based indexing.\n",
|
| 306 |
+
" try:\n",
|
| 307 |
+
" label_str = amp_file.split(\"_A\")[1].split(\"_\")[0]\n",
|
| 308 |
+
" label = int(label_str) - 1\n",
|
| 309 |
+
" except Exception as e:\n",
|
| 310 |
+
" print(f\"Error extracting label from {amp_file}: {e}\")\n",
|
| 311 |
+
" continue\n",
|
| 312 |
+
"\n",
|
| 313 |
+
" Y.append(label)\n",
|
| 314 |
+
"\n",
|
| 315 |
+
" X_combined = np.array(X_combined) # Shape: (num_samples, freq_bins, time_frames, 2)\n",
|
| 316 |
+
" Y = np.array(Y)\n",
|
| 317 |
+
" return X_combined, Y\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"# ----- Load or Process Training Data -----\n",
|
| 320 |
+
"if os.path.exists(train_combined_file) and os.path.exists(train_label_file):\n",
|
| 321 |
+
" print(\"Loading preprocessed training data...\")\n",
|
| 322 |
+
" X_train = np.load(train_combined_file)\n",
|
| 323 |
+
" Y_train = np.load(train_label_file)\n",
|
| 324 |
+
"else:\n",
|
| 325 |
+
" print(\"Processing training data (this may take time)...\")\n",
|
| 326 |
+
" X_train, Y_train = load_train_data()\n",
|
| 327 |
+
"\n",
|
| 328 |
+
" # Computes a mean and std for each channel (amplitude and phase) over all samples.\n",
|
| 329 |
+
" global_mean = np.mean(X_train, axis=(0, 1, 2), keepdims=True)\n",
|
| 330 |
+
" global_std = np.std(X_train, axis=(0, 1, 2), keepdims=True)\n",
|
| 331 |
+
"\n",
|
| 332 |
+
" # Normalize each channel separately\n",
|
| 333 |
+
" X_train = (X_train - global_mean) / global_std\n",
|
| 334 |
+
"\n",
|
| 335 |
+
" # Save preprocessed arrays and normalization parameters for later use\n",
|
| 336 |
+
" np.save(train_combined_file, X_train)\n",
|
| 337 |
+
" np.save(train_label_file, Y_train)\n",
|
| 338 |
+
" np.save(global_mean_file, global_mean)\n",
|
| 339 |
+
" np.save(global_std_file, global_std)\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"# ----- Print Shapes -----\n",
|
| 343 |
+
"print(f\"Training combined data shape: {X_train.shape}\")\n",
|
| 344 |
+
"print(f\"Training labels shape: {Y_train.shape}\")\n",
|
| 345 |
+
"\n"
|
| 346 |
+
],
|
| 347 |
+
"metadata": {
|
| 348 |
+
"id": "yrsefr1sh8_s"
|
| 349 |
+
},
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "markdown",
|
| 355 |
+
"source": [
|
| 356 |
+
"D. Preparing test data"
|
| 357 |
+
],
|
| 358 |
+
"metadata": {
|
| 359 |
+
"id": "1vlHc1TIiRrT"
|
| 360 |
+
}
|
| 361 |
+
},
|
| 362 |
+
{
|
| 363 |
+
"cell_type": "code",
|
| 364 |
+
"source": [
|
| 365 |
+
"import os\n",
|
| 366 |
+
"import numpy as np\n",
|
| 367 |
+
"from glob import glob\n",
|
| 368 |
+
"from sklearn.utils import shuffle\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"# ----- Paths -----\n",
|
| 371 |
+
"segmented_dir = \"/content/drive/MyDrive/my_dataset/testcwt_segmented/\"\n",
|
| 372 |
+
"preprocessed_dir = \"/content/drive/MyDrive/my_dataset/preprocessedcwt/\"\n",
|
| 373 |
+
"os.makedirs(preprocessed_dir, exist_ok=True)\n",
|
| 374 |
+
"\n",
|
| 375 |
+
"# Files to save preprocessed test data\n",
|
| 376 |
+
"test_combined_file = os.path.join(preprocessed_dir, \"X_test_combinedcwt.npy\")\n",
|
| 377 |
+
"test_label_file = os.path.join(preprocessed_dir, \"Y_testcwt.npy\")\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"# Global normalization parameters from training\n",
|
| 380 |
+
"global_mean_file = os.path.join(preprocessed_dir, \"global_mean.npy\")\n",
|
| 381 |
+
"global_std_file = os.path.join(preprocessed_dir, \"global_std.npy\")\n",
|
| 382 |
+
"\n",
|
| 383 |
+
"# ----- Function to load and combine test data -----\n",
|
| 384 |
+
"def load_test_data():\n",
|
| 385 |
+
" # retrieve all segmented amplitude files for the test set\n",
|
| 386 |
+
" amp_files = sorted(glob(os.path.join(segmented_dir, \"segtestamp_*.npy\")))\n",
|
| 387 |
+
" X_combined = [] # store the combined amplitude-phase arrays\n",
|
| 388 |
+
" Y = [] # Labels\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" for amp_file in amp_files:\n",
|
| 391 |
+
" # Derive corresponding phase file name by replacing \"segtestamp_\" with \"segtestphase_\"\n",
|
| 392 |
+
" phase_file = amp_file.replace(\"segtestamp_\", \"segtestphase_\")\n",
|
| 393 |
+
" if not os.path.exists(phase_file):\n",
|
| 394 |
+
" print(f\"Skipping {amp_file}, corresponding phase file not found.\")\n",
|
| 395 |
+
" continue\n",
|
| 396 |
+
"\n",
|
| 397 |
+
" # Load amplitude and phase arrays\n",
|
| 398 |
+
" amp_data = np.load(amp_file) # Expected shape: (freq_bins, time_frames)\n",
|
| 399 |
+
" phase_data = np.load(phase_file) # Expected shape: (freq_bins, time_frames)\n",
|
| 400 |
+
"\n",
|
| 401 |
+
" print(f\"Loaded amplitude file: {amp_file} with shape {amp_data.shape}\")\n",
|
| 402 |
+
" print(f\"Loaded phase file: {phase_file} with shape {phase_data.shape}\")\n",
|
| 403 |
+
"\n",
|
| 404 |
+
" if amp_data.shape != phase_data.shape:\n",
|
| 405 |
+
" print(f\"Mismatch in dimensions for {amp_file}, skipping.\")\n",
|
| 406 |
+
" continue\n",
|
| 407 |
+
"\n",
|
| 408 |
+
" # Stack amplitude and phase along a new last axis -> shape: (freq_bins, time_frames, 2)\n",
|
| 409 |
+
" combined = np.stack([amp_data, phase_data], axis=-1)\n",
|
| 410 |
+
" X_combined.append(combined)\n",
|
| 411 |
+
"\n",
|
| 412 |
+
" # Extract label from the file name.\n",
|
| 413 |
+
" # Given \"segtestamp_A1_P0_L1_T2_cwt_S1.npy\",\n",
|
| 414 |
+
" # we assume the activity label is encoded after \"_A\" (here, \"1\") and convert to 0-based indexing.\n",
|
| 415 |
+
" try:\n",
|
| 416 |
+
" label_str = amp_file.split(\"_A\")[1].split(\"_\")[0]\n",
|
| 417 |
+
" label = int(label_str) - 1\n",
|
| 418 |
+
" except Exception as e:\n",
|
| 419 |
+
" print(f\"Error extracting label from {amp_file}: {e}\")\n",
|
| 420 |
+
" continue\n",
|
| 421 |
+
"\n",
|
| 422 |
+
" Y.append(label)\n",
|
| 423 |
+
"\n",
|
| 424 |
+
" X_combined = np.array(X_combined) # Shape: (num_samples, freq_bins, time_frames, 2)\n",
|
| 425 |
+
" Y = np.array(Y)\n",
|
| 426 |
+
" return X_combined, Y\n",
|
| 427 |
+
"\n",
|
| 428 |
+
"# ----- Load or Process Test Data -----\n",
|
| 429 |
+
"if os.path.exists(test_combined_file) and os.path.exists(test_label_file):\n",
|
| 430 |
+
" print(\"Loading preprocessed test data...\")\n",
|
| 431 |
+
" X_test = np.load(test_combined_file)\n",
|
| 432 |
+
" Y_test = np.load(test_label_file)\n",
|
| 433 |
+
"else:\n",
|
| 434 |
+
" print(\"Processing test data (this may take time)...\")\n",
|
| 435 |
+
" X_test, Y_test = load_test_data()\n",
|
| 436 |
+
"\n",
|
| 437 |
+
" # Ensure the global normalization parameters from training exist.\n",
|
| 438 |
+
" if not (os.path.exists(global_mean_file) and os.path.exists(global_std_file)):\n",
|
| 439 |
+
" raise ValueError(\"Global normalization parameters not found. Preprocess training data first.\")\n",
|
| 440 |
+
"\n",
|
| 441 |
+
" # Load training normalization parameters\n",
|
| 442 |
+
" global_mean = np.load(global_mean_file)\n",
|
| 443 |
+
" global_std = np.load(global_std_file)\n",
|
| 444 |
+
"\n",
|
| 445 |
+
" # Normalize test data using training parameters\n",
|
| 446 |
+
" X_test = (X_test - global_mean) / global_std\n",
|
| 447 |
+
"\n",
|
| 448 |
+
" # Save preprocessed test data for future use\n",
|
| 449 |
+
" np.save(test_combined_file, X_test)\n",
|
| 450 |
+
" np.save(test_label_file, Y_test)\n",
|
| 451 |
+
"\n",
|
| 452 |
+
"# ----- Print Shapes -----\n",
|
| 453 |
+
"print(f\"Test combined data shape: {X_test.shape}\")\n",
|
| 454 |
+
"print(f\"Test labels shape: {Y_test.shape}\")\n"
|
| 455 |
+
],
|
| 456 |
+
"metadata": {
|
| 457 |
+
"id": "wKn2--aEiRdE"
|
| 458 |
+
},
|
| 459 |
+
"execution_count": null,
|
| 460 |
+
"outputs": []
|
| 461 |
+
},
|
| 462 |
+
{
|
| 463 |
+
"cell_type": "markdown",
|
| 464 |
+
"source": [
|
| 465 |
+
"E. Model architecture (CNN-LSTM)"
|
| 466 |
+
],
|
| 467 |
+
"metadata": {
|
| 468 |
+
"id": "uG1nQk_GivC0"
|
| 469 |
+
}
|
| 470 |
+
},
|
| 471 |
+
{
|
| 472 |
+
"cell_type": "code",
|
| 473 |
+
"source": [
|
| 474 |
+
"import os\n",
|
| 475 |
+
"import numpy as np\n",
|
| 476 |
+
"from sklearn.utils import shuffle\n",
|
| 477 |
+
"import tensorflow as tf\n",
|
| 478 |
+
"from tensorflow.keras.models import Model\n",
|
| 479 |
+
"from tensorflow.keras.layers import (Input, Conv2D, MaxPooling2D, Flatten, Dense,\n",
|
| 480 |
+
" Dropout, BatchNormalization, Activation, Reshape, LSTM, Concatenate)\n",
|
| 481 |
+
"from tensorflow.keras.regularizers import l2\n",
|
| 482 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 483 |
+
"\n",
|
| 484 |
+
"\n",
|
| 485 |
+
"# ========== 1) Load Preprocessed CWT Data ==========\n",
|
| 486 |
+
"\n",
|
| 487 |
+
"preprocessed_dir = \"/content/drive/MyDrive/my_dataset/preprocessedcwt/\" # Adjust as needed\n",
|
| 488 |
+
"X_train_file = os.path.join(preprocessed_dir, \"X_train_combinedcwt.npy\")\n",
|
| 489 |
+
"Y_train_file = os.path.join(preprocessed_dir, \"Y_traincwt.npy\")\n",
|
| 490 |
+
"X_test_file = os.path.join(preprocessed_dir, \"X_test_combinedcwt.npy\")\n",
|
| 491 |
+
"Y_test_file = os.path.join(preprocessed_dir, \"Y_testcwt.npy\")\n",
|
| 492 |
+
"\n",
|
| 493 |
+
"X_train = np.load(X_train_file)\n",
|
| 494 |
+
"Y_train = np.load(Y_train_file)\n",
|
| 495 |
+
"X_test = np.load(X_test_file)\n",
|
| 496 |
+
"Y_test = np.load(Y_test_file)\n",
|
| 497 |
+
"\n",
|
| 498 |
+
"X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size=0.2, random_state=42)\n",
|
| 499 |
+
"\n",
|
| 500 |
+
"# ========== 2) Shuffle Training Data ==========\n",
|
| 501 |
+
"\n",
|
| 502 |
+
"X_train, Y_train = shuffle(X_train, Y_train, random_state=42)\n",
|
| 503 |
+
"print(\"X_train shape:\", X_train.shape)\n",
|
| 504 |
+
"print(\"Y_train shape:\", Y_train.shape)\n",
|
| 505 |
+
"print(\"X_val shape:\", X_val.shape)\n",
|
| 506 |
+
"print(\"Y_val shape:\", Y_val.shape)\n",
|
| 507 |
+
"print(\"X_test shape:\", X_test.shape)\n",
|
| 508 |
+
"print(\"Y_test shape:\", Y_test.shape)\n",
|
| 509 |
+
"\n",
|
| 510 |
+
"# ========== 4) Define the 2D CNN Model ==========\n",
|
| 511 |
+
"\n",
|
| 512 |
+
"l2_lambda = 1e-5\n",
|
| 513 |
+
"input_shape = (75, 2000, 2)\n",
|
| 514 |
+
"\n",
|
| 515 |
+
"input_data = Input(shape=input_shape, name=\"Input_Data\")\n",
|
| 516 |
+
"\n",
|
| 517 |
+
"\n",
|
| 518 |
+
"# ========== Global Stream ==========\n",
|
| 519 |
+
"x1 = Conv2D(8, kernel_size=(4, 16), strides=(4, 8), activation='relu',\n",
|
| 520 |
+
" padding='same', kernel_regularizer=l2(l2_lambda))(input_data)\n",
|
| 521 |
+
"x1 = BatchNormalization()(x1)\n",
|
| 522 |
+
"x1 = Dropout(0.3)(x1)\n",
|
| 523 |
+
"\n",
|
| 524 |
+
"x1 = Conv2D(16, kernel_size=(8, 32), strides=(3, 6), activation='relu',\n",
|
| 525 |
+
" padding='same', kernel_regularizer=l2(l2_lambda))(x1)\n",
|
| 526 |
+
"x1 = BatchNormalization()(x1)\n",
|
| 527 |
+
"x1 = Dropout(0.3)(x1)\n",
|
| 528 |
+
"\n",
|
| 529 |
+
"x1 = Conv2D(16, kernel_size=(4, 16), strides=(2, 4), activation='relu',\n",
|
| 530 |
+
" padding='same', kernel_regularizer=l2(l2_lambda))(x1)\n",
|
| 531 |
+
"x1 = BatchNormalization()(x1)\n",
|
| 532 |
+
"x1 = Dropout(0.4)(x1)\n",
|
| 533 |
+
"\n",
|
| 534 |
+
"x1 = Reshape((-1, x1.shape[-2] * x1.shape[-1]))(x1)\n",
|
| 535 |
+
"x1 = (LSTM(128, return_sequences=False))(x1)\n",
|
| 536 |
+
"x1 = BatchNormalization()(x1)\n",
|
| 537 |
+
"x1 = Dropout(0.4)(x1)\n",
|
| 538 |
+
"\n",
|
| 539 |
+
"\n",
|
| 540 |
+
"# ========== Local Stream ==========\n",
|
| 541 |
+
"x2 = Conv2D(8, kernel_size=(2, 2), strides=(1, 2), activation='relu',\n",
|
| 542 |
+
" padding='same', kernel_regularizer=l2(l2_lambda))(input_data)\n",
|
| 543 |
+
"x2 = BatchNormalization()(x2)\n",
|
| 544 |
+
"x2 = Dropout(0.3)(x2)\n",
|
| 545 |
+
"\n",
|
| 546 |
+
"x2 = Conv2D(16, kernel_size=(2, 2), strides=(1, 2), activation='relu',\n",
|
| 547 |
+
" padding='same', kernel_regularizer=l2(l2_lambda))(x2)\n",
|
| 548 |
+
"x2 = BatchNormalization()(x2)\n",
|
| 549 |
+
"x2 = Dropout(0.3)(x2)\n",
|
| 550 |
+
"\n",
|
| 551 |
+
"x2 = Conv2D(16, kernel_size=(2, 2), strides=(1, 2), activation='relu',\n",
|
| 552 |
+
" padding='same', kernel_regularizer=l2(l2_lambda))(x2)\n",
|
| 553 |
+
"x2 = BatchNormalization()(x2)\n",
|
| 554 |
+
"x2 = Dropout(0.4)(x2)\n",
|
| 555 |
+
"\n",
|
| 556 |
+
"x2 = Reshape((-1, x2.shape[-2] * x2.shape[-1]))(x2)\n",
|
| 557 |
+
"x2 = (LSTM(128, return_sequences=False))(x2)\n",
|
| 558 |
+
"x2 = BatchNormalization()(x2)\n",
|
| 559 |
+
"x2 = Dropout(0.4)(x2)\n",
|
| 560 |
+
"\n",
|
| 561 |
+
"\n",
|
| 562 |
+
"# ========== Merge Streams ==========\n",
|
| 563 |
+
"x = Concatenate()([x1, x2])\n",
|
| 564 |
+
"\n",
|
| 565 |
+
"# ========== Dense Layers ==========\n",
|
| 566 |
+
"x = Dense(128, activation='relu', kernel_regularizer=l2(l2_lambda))(x)\n",
|
| 567 |
+
"x = BatchNormalization()(x)\n",
|
| 568 |
+
"x = Dropout(0.5)(x)\n",
|
| 569 |
+
"\n",
|
| 570 |
+
"\n",
|
| 571 |
+
"num_classes = 13\n",
|
| 572 |
+
"output = Dense(num_classes, activation='softmax')(x)\n",
|
| 573 |
+
"\n",
|
| 574 |
+
"model = Model(inputs=input_data, outputs=output)\n",
|
| 575 |
+
"model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n",
|
| 576 |
+
"model.summary()"
|
| 577 |
+
],
|
| 578 |
+
"metadata": {
|
| 579 |
+
"id": "uF2l1YP5iylW"
|
| 580 |
+
},
|
| 581 |
+
"execution_count": null,
|
| 582 |
+
"outputs": []
|
| 583 |
+
},
|
| 584 |
+
{
|
| 585 |
+
"cell_type": "markdown",
|
| 586 |
+
"source": [
|
| 587 |
+
"F. Training"
|
| 588 |
+
],
|
| 589 |
+
"metadata": {
|
| 590 |
+
"id": "qopjpFdmkTe-"
|
| 591 |
+
}
|
| 592 |
+
},
|
| 593 |
+
{
|
| 594 |
+
"cell_type": "code",
|
| 595 |
+
"source": [
|
| 596 |
+
"import numpy as np\n",
|
| 597 |
+
"from sklearn.metrics import classification_report, confusion_matrix\n",
|
| 598 |
+
"from tensorflow.keras.callbacks import EarlyStopping\n",
|
| 599 |
+
"\n",
|
| 600 |
+
"# ----- Early Stopping -----\n",
|
| 601 |
+
"early_stopping = EarlyStopping(\n",
|
| 602 |
+
" monitor='val_loss',\n",
|
| 603 |
+
" patience=10,\n",
|
| 604 |
+
" restore_best_weights=True\n",
|
| 605 |
+
")\n",
|
| 606 |
+
"\n",
|
| 607 |
+
"\n",
|
| 608 |
+
"batch_size = 32\n",
|
| 609 |
+
"epochs = 200\n",
|
| 610 |
+
"\n",
|
| 611 |
+
"history = model.fit(\n",
|
| 612 |
+
" X_train,\n",
|
| 613 |
+
" Y_train,\n",
|
| 614 |
+
" batch_size=batch_size,\n",
|
| 615 |
+
" epochs=epochs,\n",
|
| 616 |
+
" validation_data=(X_val, Y_val),\n",
|
| 617 |
+
" callbacks=[early_stopping],\n",
|
| 618 |
+
" verbose=1\n",
|
| 619 |
+
")\n",
|
| 620 |
+
"\n",
|
| 621 |
+
"# ----- Evaluate the Model on the Test Set -----\n",
|
| 622 |
+
"test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=1)\n",
|
| 623 |
+
"print(f\"Test Loss: {test_loss:.4f}, Test Accuracy: {test_accuracy:.4f}\")\n",
|
| 624 |
+
"\n",
|
| 625 |
+
"# ----- Get Predictions on the Test Set -----\n",
|
| 626 |
+
"predictions = model.predict(X_test)\n",
|
| 627 |
+
"predicted_labels = np.argmax(predictions, axis=1)\n",
|
| 628 |
+
"\n",
|
| 629 |
+
"# ----- Compute and Display the Confusion Matrix -----\n",
|
| 630 |
+
"conf_matrix = confusion_matrix(Y_test, predicted_labels)\n",
|
| 631 |
+
"print(\"Confusion Matrix:\")\n",
|
| 632 |
+
"print(conf_matrix)\n",
|
| 633 |
+
"\n",
|
| 634 |
+
"# ----- Display the Classification Report -----\n",
|
| 635 |
+
"print(\"Classification Report:\")\n",
|
| 636 |
+
"print(classification_report(Y_test, predicted_labels))"
|
| 637 |
+
],
|
| 638 |
+
"metadata": {
|
| 639 |
+
"id": "4kLALP8-jH8Z"
|
| 640 |
+
},
|
| 641 |
+
"execution_count": null,
|
| 642 |
+
"outputs": []
|
| 643 |
+
},
|
| 644 |
+
{
|
| 645 |
+
"cell_type": "markdown",
|
| 646 |
+
"source": [
|
| 647 |
+
"G. Merging of static activities"
|
| 648 |
+
],
|
| 649 |
+
"metadata": {
|
| 650 |
+
"id": "8CXrcrP0jNY-"
|
| 651 |
+
}
|
| 652 |
+
},
|
| 653 |
+
{
|
| 654 |
+
"cell_type": "code",
|
| 655 |
+
"source": [
|
| 656 |
+
"import numpy as np\n",
|
| 657 |
+
"from sklearn.metrics import accuracy_score, confusion_matrix, classification_report\n",
|
| 658 |
+
"\n",
|
| 659 |
+
"# Group classes 2, 3, 4 into a single label \"2\" as the standing/sitting/lying falls under those classes respetively\n",
|
| 660 |
+
"\n",
|
| 661 |
+
"def group_label(label):\n",
|
| 662 |
+
" if label in [1, 2, 3]:\n",
|
| 663 |
+
" return 2\n",
|
| 664 |
+
" else:\n",
|
| 665 |
+
" return label\n",
|
| 666 |
+
"\n",
|
| 667 |
+
"y_true_grouped = [group_label(l) for l in Y_test]\n",
|
| 668 |
+
"y_pred_grouped = [group_label(l) for l in predicted_labels]\n",
|
| 669 |
+
"\n",
|
| 670 |
+
"# Compute new accuracy\n",
|
| 671 |
+
"new_accuracy = accuracy_score(y_true_grouped, y_pred_grouped)\n",
|
| 672 |
+
"print(\"New Accuracy (with static activities merged):\", new_accuracy)\n",
|
| 673 |
+
"\n",
|
| 674 |
+
"conf_matrix_grouped = confusion_matrix(y_true_grouped, y_pred_grouped)\n",
|
| 675 |
+
"print(\"Grouped Confusion Matrix:\\n\", conf_matrix_grouped)\n",
|
| 676 |
+
"\n",
|
| 677 |
+
"print(\"Grouped Classification Report:\")\n",
|
| 678 |
+
"print(classification_report(y_true_grouped, y_pred_grouped))"
|
| 679 |
+
],
|
| 680 |
+
"metadata": {
|
| 681 |
+
"id": "qYtwhbXLjQQe"
|
| 682 |
+
},
|
| 683 |
+
"execution_count": null,
|
| 684 |
+
"outputs": []
|
| 685 |
+
}
|
| 686 |
+
]
|
| 687 |
+
}
|