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