-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.py
More file actions
1735 lines (1499 loc) · 59 KB
/
benchmark.py
File metadata and controls
1735 lines (1499 loc) · 59 KB
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Benchmark script comparing multiple ECG classification models:
1. Feedforward Neural Network (Lloyd et al., 2001)
2. Transformer-based Model (Ikram et al., 2025)
3. Three-Stage Hierarchical Transformer (Tang et al., 2025)
4. 1D Convolutional Neural Network (CNN)
5. Long Short-Term Memory (LSTM)
6. Hopfield Network (ETASR, 2013)
7. Variational Autoencoder (VAE) - FactorECG (van de Leur et al., 2022)
8. Liquid Time-Constant Network (LTC) - Hasani et al. (2020)
9. Hidden Markov Model (HMM)
10. Hierarchical Hidden Markov Model (Hierarchical HMM)
11. Dynamic Bayesian Network (DBN)
12. Markov Decision Process (MDP)
13. Partially Observable MDP (PO-MDP)
14. Markov Random Field (MRF)
15. Granger Causality
"""
import numpy as np # NumPy for array operations
import torch # PyTorch
from typing import Dict, Tuple # Type hints
import time # Time measurement
import json # JSON for saving results
from neural_network import NeuralNetwork, create_sample_ecg_data # Feedforward NN
from transformer_ecg import ( # Transformer model
TransformerECGClassifier, ECGDataset, train_transformer,
evaluate_model, create_synthetic_ecg_data
)
from three_stage_former import ( # Three-Stage Former model
ThreeStageFormer, train_three_stage_former, evaluate_model as evaluate_3stage
)
from cnn_lstm_ecg import ( # CNN and LSTM models
CNN1DECGClassifier, LSTMECGClassifier, train_model, evaluate_model as evaluate_cnn_lstm
)
from hopfield_ecg import ( # Hopfield Network model
HopfieldECGClassifier, train_hopfield, evaluate_model as evaluate_hopfield
)
from vae_ecg import ( # VAE model
VAEEcgClassifier, train_vae, evaluate_model as evaluate_vae
)
from ltc_ecg import ( # LTC model
LTCEcgClassifier, train_ltc, evaluate_model as evaluate_ltc, ECGDataset as LTCECGDataset
)
from hmm_ecg import ( # HMM models
train_hmm, evaluate_model as evaluate_hmm
)
from dbn_ecg import ( # DBN model
train_dbn, evaluate_model as evaluate_dbn
)
from mdp_ecg import ( # MDP models
train_mdp, evaluate_model as evaluate_mdp
)
from mrf_ecg import ( # MRF model
train_mrf, evaluate_model as evaluate_mrf
)
from granger_ecg import ( # Granger Causality
train_granger, evaluate_model as evaluate_granger
)
from torch.utils.data import DataLoader # Data loading
import matplotlib.pyplot as plt # Plotting
from sklearn.metrics import ( # Evaluation metrics
accuracy_score, precision_score, recall_score,
f1_score, classification_report, confusion_matrix
)
import seaborn as sns # Better plots
def prepare_data_for_feedforward(
signals: np.ndarray,
labels: np.ndarray,
feature_extraction: str = 'statistical'
) -> Tuple[np.ndarray, np.ndarray]:
"""
Extract features from ECG signals for feedforward neural network.
Parameters:
-----------
signals : np.ndarray
Raw ECG signals of shape (n_samples, seq_len)
labels : np.ndarray
Class labels
feature_extraction : str
Feature extraction method
Returns:
--------
Tuple[np.ndarray, np.ndarray]
(features, labels)
"""
n_samples = signals.shape[0]
features_list = []
if feature_extraction == 'statistical':
# Extract statistical features
for i in range(n_samples):
signal = signals[i]
feat = [
np.mean(signal), # Mean
np.std(signal), # Standard deviation
np.median(signal), # Median
np.min(signal), # Minimum
np.max(signal), # Maximum
np.percentile(signal, 25), # 25th percentile
np.percentile(signal, 75), # 75th percentile
np.var(signal), # Variance
np.mean(np.abs(np.diff(signal))), # Mean absolute difference
np.std(np.diff(signal)), # Std of differences
]
# Add frequency domain features
fft = np.fft.rfft(signal) # FFT
feat.append(np.mean(np.abs(fft))) # Mean frequency magnitude
feat.append(np.std(np.abs(fft))) # Std frequency magnitude
feat.append(np.argmax(np.abs(fft))) # Dominant frequency
features_list.append(feat)
features = np.array(features_list) # Convert to array
labels_binary = (labels > 0).astype(int) # Convert to binary for comparison
return features, labels_binary.reshape(-1, 1) # Return features and binary labels
def benchmark_feedforward_nn(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
y_val: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray
) -> Dict:
"""
Benchmark feedforward neural network.
Parameters:
-----------
X_train, y_train : np.ndarray
Training data
X_val, y_val : np.ndarray
Validation data
X_test, y_test : np.ndarray
Test data
Returns:
--------
Dict
Benchmark results
"""
print("\n" + "="*60)
print("BENCHMARKING FEEDFORWARD NEURAL NETWORK")
print("="*60)
# Normalize features
mean = X_train.mean(axis=0) # Compute mean
std = X_train.std(axis=0) # Compute std
X_train_norm = (X_train - mean) / (std + 1e-8) # Normalize training
X_val_norm = (X_val - mean) / (std + 1e-8) # Normalize validation
X_test_norm = (X_test - mean) / (std + 1e-8) # Normalize test
# Initialize model
input_size = X_train.shape[1] # Input dimension
model = NeuralNetwork(
input_size=input_size,
hidden_layers=[64, 32, 16], # 3 hidden layers
output_size=1,
activation='sigmoid',
learning_rate=0.01,
random_seed=42
)
# Train model
start_time = time.time() # Start timer
history = model.train(
X_train_norm, y_train,
X_val_norm, y_val,
epochs=500, # 500 epochs
batch_size=32,
verbose=False,
early_stopping=True,
patience=20
)
train_time = time.time() - start_time # Training time
# Evaluate on test set
start_time = time.time() # Start timer
test_predictions = model.predict(X_test_norm) # Get predictions
test_probabilities = model.predict_proba(X_test_norm) # Get probabilities
inference_time = time.time() - start_time # Inference time
# Calculate metrics
accuracy = model.compute_accuracy(y_test, test_predictions) # Accuracy
precision = precision_score(y_test.flatten(), test_predictions.flatten(), zero_division=0) # Precision
recall = recall_score(y_test.flatten(), test_predictions.flatten(), zero_division=0) # Recall
f1 = f1_score(y_test.flatten(), test_predictions.flatten(), zero_division=0) # F1 score
# Count parameters (approximate)
num_params = 0
for weight in model.weights: # Count weight parameters
num_params += weight.size
for bias in model.biases: # Count bias parameters
num_params += bias.size
results = {
'model_name': 'Feedforward Neural Network',
'accuracy': float(accuracy),
'precision': float(precision),
'recall': float(recall),
'f1_score': float(f1),
'train_time': train_time,
'inference_time': inference_time,
'num_parameters': int(num_params),
'train_loss_history': history['loss_history'],
'train_acc_history': history['accuracy_history'],
'predictions': test_predictions.flatten().tolist(),
'probabilities': test_probabilities.flatten().tolist(),
'true_labels': y_test.flatten().tolist()
}
print(f"\nResults:")
print(f" Accuracy: {accuracy:.4f}")
print(f" Precision: {precision:.4f}")
print(f" Recall: {recall:.4f}")
print(f" F1 Score: {f1:.4f}")
print(f" Train Time: {train_time:.2f} seconds")
print(f" Inference Time: {inference_time:.4f} seconds")
print(f" Parameters: {num_params:,}")
return results # Return results
def benchmark_transformer(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
y_val: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
device: str = 'cpu'
) -> Dict:
"""
Benchmark Transformer model.
Parameters:
-----------
X_train, y_train : np.ndarray
Training data
X_val, y_val : np.ndarray
Validation data
X_test, y_test : np.ndarray
Test data
device : str
Device to use
Returns:
--------
Dict
Benchmark results
"""
print("\n" + "="*60)
print("BENCHMARKING TRANSFORMER-BASED MODEL")
print("="*60)
# Create datasets
train_dataset = ECGDataset(X_train, y_train, seq_len=1000) # Training dataset
val_dataset = ECGDataset(X_val, y_val, seq_len=1000) # Validation dataset
test_dataset = ECGDataset(X_test, y_test, seq_len=1000) # Test dataset
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) # Training loader
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False) # Validation loader
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) # Test loader
# Initialize model
model = TransformerECGClassifier(
input_dim=1,
d_model=128,
nhead=8,
num_layers=6,
dim_feedforward=512,
dropout=0.1,
num_classes=5,
max_seq_len=1000
)
# Count parameters
num_params = sum(p.numel() for p in model.parameters() if p.requires_grad) # Total parameters
# Train model
start_time = time.time() # Start timer
history = train_transformer(
model, train_loader, val_loader,
num_epochs=50, # 50 epochs
learning_rate=0.001,
device=device,
verbose=False
)
train_time = time.time() - start_time # Training time
# Evaluate on test set
start_time = time.time() # Start timer
results = evaluate_model(model, test_loader, device=device) # Evaluate
inference_time = time.time() - start_time # Inference time
# Convert multi-class to binary for comparison
binary_predictions = (results['predictions'] > 0).astype(int) # Convert to binary
binary_labels = (results['labels'] > 0).astype(int) # Convert to binary
# Calculate metrics
accuracy = results['accuracy'] # Accuracy
precision = precision_score(binary_labels, binary_predictions, zero_division=0) # Precision
recall = recall_score(binary_labels, binary_predictions, zero_division=0) # Recall
f1 = f1_score(binary_labels, binary_predictions, zero_division=0) # F1 score
benchmark_results = {
'model_name': 'Transformer-based ECG Classifier',
'accuracy': float(accuracy),
'precision': float(precision),
'recall': float(recall),
'f1_score': float(f1),
'train_time': train_time,
'inference_time': inference_time,
'num_parameters': int(num_params),
'train_loss_history': [float(x) for x in history['train_loss']],
'train_acc_history': [float(x) for x in history['train_acc']],
'val_loss_history': [float(x) for x in history.get('val_loss', [])],
'val_acc_history': [float(x) for x in history.get('val_acc', [])],
'predictions': binary_predictions.tolist(),
'probabilities': binary_predictions.tolist(),
'true_labels': binary_labels.tolist()
}
print(f"\nResults:")
print(f" Accuracy: {accuracy:.4f}")
print(f" Precision: {precision:.4f}")
print(f" Recall: {recall:.4f}")
print(f" F1 Score: {f1:.4f}")
print(f" Train Time: {train_time:.2f} seconds")
print(f" Inference Time: {inference_time:.4f} seconds")
print(f" Parameters: {num_params:,}")
return benchmark_results # Return results
def benchmark_three_stage_former(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
y_val: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
device: str = 'cpu'
) -> Dict:
"""
Benchmark Three-Stage Former model.
Parameters:
-----------
X_train, y_train : np.ndarray
Training data
X_val, y_val : np.ndarray
Validation data
X_test, y_test : np.ndarray
Test data
device : str
Device to use
Returns:
--------
Dict
Benchmark results
"""
print("\n" + "="*60)
print("BENCHMARKING THREE-STAGE FORMER")
print("="*60)
# Create datasets
train_dataset = ECGDataset(X_train, y_train, seq_len=1000)
val_dataset = ECGDataset(X_val, y_val, seq_len=1000)
test_dataset = ECGDataset(X_test, y_test, seq_len=1000)
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# Initialize model
model = ThreeStageFormer(
input_dim=1,
d_model=128,
nhead=8,
num_layers_per_stage=2,
dim_feedforward=512,
dropout=0.1,
num_classes=5,
max_seq_len=1000,
pooling_stride=2
)
# Count parameters
num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
# Train model
start_time = time.time()
history = train_three_stage_former(
model, train_loader, val_loader,
num_epochs=50,
learning_rate=0.001,
device=device,
verbose=False
)
train_time = time.time() - start_time
# Evaluate on test set
start_time = time.time()
results = evaluate_3stage(model, test_loader, device=device)
inference_time = time.time() - start_time
# Convert multi-class to binary for comparison
binary_predictions = (results['predictions'] > 0).astype(int)
binary_labels = (results['labels'] > 0).astype(int)
# Calculate metrics
accuracy = results['accuracy']
precision = precision_score(binary_labels, binary_predictions, zero_division=0)
recall = recall_score(binary_labels, binary_predictions, zero_division=0)
f1 = f1_score(binary_labels, binary_predictions, zero_division=0)
benchmark_results = {
'model_name': 'Three-Stage Former',
'accuracy': float(accuracy),
'precision': float(precision),
'recall': float(recall),
'f1_score': float(f1),
'train_time': train_time,
'inference_time': inference_time,
'num_parameters': int(num_params),
'train_loss_history': [float(x) for x in history['train_loss']],
'train_acc_history': [float(x) for x in history['train_acc']],
'val_loss_history': [float(x) for x in history.get('val_loss', [])],
'val_acc_history': [float(x) for x in history.get('val_acc', [])],
'predictions': binary_predictions.tolist(),
'probabilities': binary_predictions.tolist(),
'true_labels': binary_labels.tolist()
}
print(f"\nResults:")
print(f" Accuracy: {accuracy:.4f}")
print(f" Precision: {precision:.4f}")
print(f" Recall: {recall:.4f}")
print(f" F1 Score: {f1:.4f}")
print(f" Train Time: {train_time:.2f} seconds")
print(f" Inference Time: {inference_time:.4f} seconds")
print(f" Parameters: {num_params:,}")
return benchmark_results
def benchmark_cnn(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
y_val: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
device: str = 'cpu'
) -> Dict:
"""
Benchmark 1D CNN model.
Parameters:
-----------
X_train, y_train : np.ndarray
Training data
X_val, y_val : np.ndarray
Validation data
X_test, y_test : np.ndarray
Test data
device : str
Device to use
Returns:
--------
Dict
Benchmark results
"""
print("\n" + "="*60)
print("BENCHMARKING 1D CONVOLUTIONAL NEURAL NETWORK")
print("="*60)
# Create datasets
train_dataset = ECGDataset(X_train, y_train, seq_len=1000)
val_dataset = ECGDataset(X_val, y_val, seq_len=1000)
test_dataset = ECGDataset(X_test, y_test, seq_len=1000)
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# Initialize model
model = CNN1DECGClassifier(
input_channels=1,
num_classes=5,
seq_len=1000,
dropout=0.3
)
# Count parameters
num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
# Train model
start_time = time.time()
history = train_model(
model, train_loader, val_loader,
num_epochs=50,
learning_rate=0.001,
device=device,
verbose=False
)
train_time = time.time() - start_time
# Evaluate on test set
start_time = time.time()
results = evaluate_cnn_lstm(model, test_loader, device=device)
inference_time = time.time() - start_time
# Convert multi-class to binary for comparison
binary_predictions = (results['predictions'] > 0).astype(int)
binary_labels = (results['labels'] > 0).astype(int)
# Calculate metrics
accuracy = results['accuracy']
precision = precision_score(binary_labels, binary_predictions, zero_division=0)
recall = recall_score(binary_labels, binary_predictions, zero_division=0)
f1 = f1_score(binary_labels, binary_predictions, zero_division=0)
benchmark_results = {
'model_name': '1D CNN',
'accuracy': float(accuracy),
'precision': float(precision),
'recall': float(recall),
'f1_score': float(f1),
'train_time': train_time,
'inference_time': inference_time,
'num_parameters': int(num_params),
'train_loss_history': [float(x) for x in history['train_loss']],
'train_acc_history': [float(x) for x in history['train_acc']],
'val_loss_history': [float(x) for x in history.get('val_loss', [])],
'val_acc_history': [float(x) for x in history.get('val_acc', [])],
'predictions': binary_predictions.tolist(),
'probabilities': binary_predictions.tolist(),
'true_labels': binary_labels.tolist()
}
print(f"\nResults:")
print(f" Accuracy: {accuracy:.4f}")
print(f" Precision: {precision:.4f}")
print(f" Recall: {recall:.4f}")
print(f" F1 Score: {f1:.4f}")
print(f" Train Time: {train_time:.2f} seconds")
print(f" Inference Time: {inference_time:.4f} seconds")
print(f" Parameters: {num_params:,}")
return benchmark_results
def benchmark_lstm(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
y_val: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
device: str = 'cpu'
) -> Dict:
"""
Benchmark LSTM model.
Parameters:
-----------
X_train, y_train : np.ndarray
Training data
X_val, y_val : np.ndarray
Validation data
X_test, y_test : np.ndarray
Test data
device : str
Device to use
Returns:
--------
Dict
Benchmark results
"""
print("\n" + "="*60)
print("BENCHMARKING LSTM")
print("="*60)
# Create datasets
train_dataset = ECGDataset(X_train, y_train, seq_len=1000)
val_dataset = ECGDataset(X_val, y_val, seq_len=1000)
test_dataset = ECGDataset(X_test, y_test, seq_len=1000)
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# Initialize model
model = LSTMECGClassifier(
input_size=1,
hidden_size=128,
num_layers=2,
num_classes=5,
dropout=0.3,
bidirectional=True
)
# Count parameters
num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
# Train model
start_time = time.time()
history = train_model(
model, train_loader, val_loader,
num_epochs=50,
learning_rate=0.001,
device=device,
verbose=False
)
train_time = time.time() - start_time
# Evaluate on test set
start_time = time.time()
results = evaluate_cnn_lstm(model, test_loader, device=device)
inference_time = time.time() - start_time
# Convert multi-class to binary for comparison
binary_predictions = (results['predictions'] > 0).astype(int)
binary_labels = (results['labels'] > 0).astype(int)
# Calculate metrics
accuracy = results['accuracy']
precision = precision_score(binary_labels, binary_predictions, zero_division=0)
recall = recall_score(binary_labels, binary_predictions, zero_division=0)
f1 = f1_score(binary_labels, binary_predictions, zero_division=0)
benchmark_results = {
'model_name': 'LSTM',
'accuracy': float(accuracy),
'precision': float(precision),
'recall': float(recall),
'f1_score': float(f1),
'train_time': train_time,
'inference_time': inference_time,
'num_parameters': int(num_params),
'train_loss_history': [float(x) for x in history['train_loss']],
'train_acc_history': [float(x) for x in history['train_acc']],
'val_loss_history': [float(x) for x in history.get('val_loss', [])],
'val_acc_history': [float(x) for x in history.get('val_acc', [])],
'predictions': binary_predictions.tolist(),
'probabilities': binary_predictions.tolist(),
'true_labels': binary_labels.tolist()
}
print(f"\nResults:")
print(f" Accuracy: {accuracy:.4f}")
print(f" Precision: {precision:.4f}")
print(f" Recall: {recall:.4f}")
print(f" F1 Score: {f1:.4f}")
print(f" Train Time: {train_time:.2f} seconds")
print(f" Inference Time: {inference_time:.4f} seconds")
print(f" Parameters: {num_params:,}")
return benchmark_results
def benchmark_hopfield(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
y_val: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
device: str = 'cpu'
) -> Dict:
"""
Benchmark Hopfield Network model.
Parameters:
-----------
X_train, y_train : np.ndarray
Training data
X_val, y_val : np.ndarray
Validation data
X_test, y_test : np.ndarray
Test data
device : str
Device to use
Returns:
--------
Dict
Benchmark results
"""
print("\n" + "="*60)
print("BENCHMARKING HOPFIELD NETWORK")
print("="*60)
# Create datasets (using ECGDataset from transformer_ecg, compatible interface)
train_dataset = ECGDataset(X_train, y_train, seq_len=1000)
val_dataset = ECGDataset(X_val, y_val, seq_len=1000)
test_dataset = ECGDataset(X_test, y_test, seq_len=1000)
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# Initialize model
model = HopfieldECGClassifier(
input_size=1000,
feature_size=128,
hidden_size=256,
num_classes=5,
num_iterations=10,
beta=1.0
)
# Count parameters
num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
# Train model
start_time = time.time()
history = train_hopfield(
model, train_loader, val_loader,
num_epochs=50,
learning_rate=0.001,
device=device,
verbose=False
)
train_time = time.time() - start_time
# Evaluate on test set
start_time = time.time()
results = evaluate_hopfield(model, test_loader, device=device)
inference_time = time.time() - start_time
# Convert multi-class to binary for comparison
binary_predictions = (results['predictions'] > 0).astype(int)
binary_labels = (results['labels'] > 0).astype(int)
# Calculate metrics
accuracy = results['accuracy']
precision = precision_score(binary_labels, binary_predictions, zero_division=0)
recall = recall_score(binary_labels, binary_predictions, zero_division=0)
f1 = f1_score(binary_labels, binary_predictions, zero_division=0)
benchmark_results = {
'model_name': 'Hopfield Network',
'accuracy': float(accuracy),
'precision': float(precision),
'recall': float(recall),
'f1_score': float(f1),
'train_time': train_time,
'inference_time': inference_time,
'num_parameters': int(num_params),
'train_loss_history': [float(x) for x in history['train_loss']],
'train_acc_history': [float(x) for x in history['train_acc']],
'val_loss_history': [float(x) for x in history.get('val_loss', [])],
'val_acc_history': [float(x) for x in history.get('val_acc', [])],
'predictions': binary_predictions.tolist(),
'probabilities': binary_predictions.tolist(),
'true_labels': binary_labels.tolist()
}
print(f"\nResults:")
print(f" Accuracy: {accuracy:.4f}")
print(f" Precision: {precision:.4f}")
print(f" Recall: {recall:.4f}")
print(f" F1 Score: {f1:.4f}")
print(f" Train Time: {train_time:.2f} seconds")
print(f" Inference Time: {inference_time:.4f} seconds")
print(f" Parameters: {num_params:,}")
return benchmark_results
def plot_comparison(all_results: Dict, save_path: str = 'comparison.png'):
"""Plot comparison of all models."""
# Extract model names and results
model_names = []
results_list = []
for key, value in all_results.items():
if isinstance(value, dict) and 'model_name' in value:
model_names.append(value['model_name'])
results_list.append(value)
fig, axes = plt.subplots(2, 2, figsize=(18, 12))
# Metrics comparison
metrics = ['accuracy', 'precision', 'recall', 'f1_score']
metric_labels = ['Accuracy', 'Precision', 'Recall', 'F1 Score']
x = np.arange(len(metrics))
width = 0.15
colors = ['skyblue', 'lightcoral', 'lightgreen', 'lightyellow', 'lightpink']
for i, results in enumerate(results_list):
values = [results[m] for m in metrics]
offset = (i - len(results_list) / 2) * width + width / 2
axes[0, 0].bar(x + offset, values, width, label=model_names[i], alpha=0.8, color=colors[i % len(colors)])
axes[0, 0].set_ylabel('Score')
axes[0, 0].set_title('Performance Metrics Comparison')
axes[0, 0].set_xticks(x)
axes[0, 0].set_xticklabels(metric_labels)
axes[0, 0].legend(fontsize=8)
axes[0, 0].grid(True, alpha=0.3)
axes[0, 0].set_ylim([0, 1.1])
# Training time comparison
times = [r['train_time'] for r in results_list]
axes[0, 1].bar(model_names, times, alpha=0.8, color=colors[:len(model_names)])
axes[0, 1].set_ylabel('Time (seconds)')
axes[0, 1].set_title('Training Time Comparison')
axes[0, 1].grid(True, alpha=0.3)
axes[0, 1].tick_params(axis='x', rotation=15)
# Loss history
for i, results in enumerate(results_list):
axes[1, 0].plot(results['train_loss_history'], label=f"{model_names[i]} - Loss", alpha=0.7, linewidth=1.5)
axes[1, 0].set_xlabel('Epoch')
axes[1, 0].set_ylabel('Loss')
axes[1, 0].set_title('Training Loss History')
axes[1, 0].legend(fontsize=8)
axes[1, 0].grid(True, alpha=0.3)
# Accuracy history
for i, results in enumerate(results_list):
axes[1, 1].plot(results['train_acc_history'], label=f"{model_names[i]} - Accuracy", alpha=0.7, linewidth=1.5)
axes[1, 1].set_xlabel('Epoch')
axes[1, 1].set_ylabel('Accuracy')
axes[1, 1].set_title('Training Accuracy History')
axes[1, 1].legend(fontsize=8)
axes[1, 1].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"\nComparison plot saved to {save_path}")
plt.close()
def benchmark_vae(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
y_val: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
device: str = 'cpu'
) -> Dict:
"""
Benchmark VAE model.
Parameters:
-----------
X_train, y_train : np.ndarray
Training data
X_val, y_val : np.ndarray
Validation data
X_test, y_test : np.ndarray
Test data
device : str
Device to use
Returns:
--------
Dict
Benchmark results
"""
print("\n" + "="*60)
print("BENCHMARKING VARIATIONAL AUTOENCODER (VAE)")
print("="*60)
# Create datasets
train_dataset = ECGDataset(X_train, y_train, seq_len=1000)
val_dataset = ECGDataset(X_val, y_val, seq_len=1000)
test_dataset = ECGDataset(X_test, y_test, seq_len=1000)
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
# Initialize model
model = VAEEcgClassifier(
input_size=1000,
latent_dim=21, # 21 factors as in FactorECG
num_classes=5,
hidden_dims=[256, 128, 64],
beta=0.001
)
# Count parameters
num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
# Train model
start_time = time.time()
history = train_vae(
model, train_loader, val_loader,
num_epochs=50,
learning_rate=0.001,
device=device,
verbose=False
)
train_time = time.time() - start_time
# Evaluate on test set
start_time = time.time()
results = evaluate_vae(model, test_loader, device=device)
inference_time = time.time() - start_time
# Convert multi-class to binary for comparison
binary_predictions = (results['predictions'] > 0).astype(int)
binary_labels = (results['labels'] > 0).astype(int)
# Calculate metrics
accuracy = results['accuracy']
precision = precision_score(binary_labels, binary_predictions, zero_division=0)
recall = recall_score(binary_labels, binary_predictions, zero_division=0)
f1 = f1_score(binary_labels, binary_predictions, zero_division=0)
benchmark_results = {
'model_name': 'Variational Autoencoder (VAE)',
'accuracy': float(accuracy),
'precision': float(precision),
'recall': float(recall),
'f1_score': float(f1),
'train_time': train_time,
'inference_time': inference_time,
'num_parameters': int(num_params),
'train_loss_history': [float(x) for x in history['train_loss']],
'train_acc_history': [float(x) for x in history['train_acc']],
'val_loss_history': [float(x) for x in history.get('val_loss', [])],
'val_acc_history': [float(x) for x in history.get('val_acc', [])],
'predictions': binary_predictions.tolist(),
'probabilities': binary_predictions.tolist(),
'true_labels': binary_labels.tolist()
}
print(f"\nResults:")
print(f" Accuracy: {accuracy:.4f}")
print(f" Precision: {precision:.4f}")
print(f" Recall: {recall:.4f}")
print(f" F1 Score: {f1:.4f}")
print(f" Train Time: {train_time:.2f} seconds")
print(f" Inference Time: {inference_time:.4f} seconds")
print(f" Parameters: {num_params:,}")
return benchmark_results
def benchmark_ltc(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
y_val: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
device: str = 'cpu'
) -> Dict:
"""
Benchmark Liquid Time-Constant Network (LTC) model.
Parameters:
-----------
X_train, y_train : np.ndarray
Training data
X_val, y_val : np.ndarray
Validation data
X_test, y_test : np.ndarray
Test data
device : str
Device to use
Returns:
--------
Dict
Benchmark results
"""
print("\n" + "="*60)
print("BENCHMARKING LIQUID TIME-CONSTANT NETWORK (LTC)")
print("="*60)
# Create datasets
train_dataset = LTCECGDataset(X_train, y_train, seq_len=1000)
val_dataset = LTCECGDataset(X_val, y_val, seq_len=1000)
test_dataset = LTCECGDataset(X_test, y_test, seq_len=1000)