Repository navigation
Expand file tree
/
Copy pathscript.py
More file actions
736 lines (591 loc) · 30.2 KB
/
Copy pathscript.py
File metadata and controls
736 lines (591 loc) · 30.2 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
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import KFold
from sklearn.metrics import classification_report, accuracy_score,roc_auc_score,precision_score,recall_score,f1_score,confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import optuna
from scipy.stats import entropy
import pywt
# Imports for additional models:
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import ExtraTreesClassifier, AdaBoostClassifier, VotingClassifier, StackingClassifier
from sklearn.linear_model import SGDClassifier
# From your original code:
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from catboost import CatBoostClassifier
from xgboost import XGBClassifier
import pickle
def preproc_dataset(df):
df = df.iloc[:, 1:].T.reset_index(drop=True)
df = df.iloc[0::2, :]
return df
def gaussian_modulated_vlp(signal, amplitude_range, fs=500, num_sine_waves=4):
"""
Apply Gaussian-modulated sinusoidal VLP with white noise to a signal.
Parameters:
signal: ndarray
QRS data for one beat.
amplitude_range: tuple
Range of amplitudes (min, max) for the VLP.
fs: int
Sampling frequency in Hz.
num_sine_waves: int
Number of sinusoidal components.
Returns:
ndarray: Signal with VLP applied.
"""
signal_length = len(signal)
r_peak = 100 * fs / 1000 # R peak at 100 ms
frequencies = np.random.normal(125, 70, num_sine_waves)
frequencies = np.clip(frequencies, 40, 250)
# frequencies = np.clip(frequencies, 0, 10000000000000)
duration_mean = 35 * fs / 1000
duration_sd = 10 * fs / 1000
durations = np.random.normal(duration_mean, duration_sd, num_sine_waves)
durations = np.clip(durations, 5 * fs / 1000, 50 * fs / 1000)
# durations = np.clip(durations, 0 * fs / 1000, 5000000000 * fs / 1000)
start_mean = r_peak + 35 * fs / 1000 # R-peak + offset
start_sd = 5 * fs / 1000
start_positions = np.random.normal(start_mean, start_sd, num_sine_waves)
start_positions = np.clip(start_positions, r_peak + 20 * fs / 1000, r_peak + 80 * fs / 1000)
# start_positions = np.clip(start_positions, r_peak + 0 * fs / 1000, r_peak + 30000 * fs / 1000)
phases = np.random.uniform(0, 2 * np.pi, num_sine_waves)
amplitudes = np.random.normal(np.mean(amplitude_range), np.std(amplitude_range), num_sine_waves)
amplitudes = np.clip(amplitudes, amplitude_range[0], amplitude_range[1])
# amplitudes = np.clip(amplitudes,0, 10000000000)
amplitudes *= 1e-3 / num_sine_waves
vlp_signal = np.zeros(signal_length)
for i in range(num_sine_waves):
t = np.arange(signal_length)
modulating_gaussian = np.exp(-((t - start_positions[i]) ** 2) / (2 * (durations[i] ** 2)))
sinusoidal_wave = np.sin(2 * np.pi * frequencies[i] * (t - start_positions[i]) + phases[i])
white_noise = np.random.normal(0, amplitudes[i] / 4, signal_length)
vlp_signal += amplitudes[i] / 4 * modulating_gaussian * sinusoidal_wave
vlp_signal += white_noise
# Restrict the VLP to the specified range only
start = int(np.min(start_positions))
duration = int(np.max(durations))
vlp_signal[:start] = 0
vlp_signal[start + duration:] = 0
# return signal + vlp_signal, frequencies, durations, phases, amplitudes, start_positions
return signal + vlp_signal # , frequencies, durations, phases, amplitudes, start_positions
def extract_features(df):
# Statistical features
features = pd.DataFrame()
features['mean'] = df.mean(axis=1)
features['std'] = df.std(axis=1)
features['max'] = df.max(axis=1)
features['min'] = df.min(axis=1)
features['median'] = df.median(axis=1)
features['skew'] = df.skew(axis=1)
features['kurtosis'] = df.kurtosis(axis=1)
features['quantile_25'] = df.quantile(0.25, axis=1)
features['quantile_75'] = df.quantile(0.75, axis=1)
features['iqr'] = features['quantile_75'] - features['quantile_25']
features['rms'] = np.sqrt(np.mean(np.square(df), axis=1))
features['energy'] = np.sum(np.square(df), axis=1)
features['entropy'] = df.apply(lambda x: entropy(x.value_counts(), base=2), axis=1)
fft_features = np.abs(np.fft.rfft(df, axis=1))
fft_df = pd.DataFrame(fft_features)
features['fft_mean'] = fft_df.mean(axis=1).values
features['fft_std'] = fft_df.std(axis=1).values
features['fft_max'] = fft_df.max(axis=1).values
# Derivative of Fourier transform features
fft_derivative = np.diff(fft_features, axis=1)
fft_derivative_df = pd.DataFrame(fft_derivative)
features['fft_derivative_mean'] = fft_derivative_df.mean(axis=1).values
features['fft_derivative_std'] = fft_derivative_df.std(axis=1).values
features['fft_derivative_max'] = fft_derivative_df.max(axis=1).values
# FFT high-frequency features (e.g., top 50% frequencies)
high_freq_fft = fft_features[:, fft_features.shape[1] // 2:]
high_freq_df = pd.DataFrame(high_freq_fft)
features['fft_high_mean'] = high_freq_df.mean(axis=1).values
features['fft_high_std'] = high_freq_df.std(axis=1).values
features['fft_high_max'] = high_freq_df.max(axis=1).values
# Wavelet Transform features
def wavelet_features(row, wavelet='db4', level=1):
coeffs = pywt.wavedec(row, wavelet, level=level)
detail_coeffs = coeffs[1:] # Skip approximation coefficients
detail_features = {}
for i, coeff in enumerate(detail_coeffs):
detail_features[f'wavelet_level_{i + 1}_mean'] = np.mean(np.abs(coeff))
detail_features[f'wavelet_level_{i + 1}_std'] = np.std(coeff)
detail_features[f'wavelet_level_{i + 1}_max'] = np.max(np.abs(coeff))
return detail_features
wavelet_results = df.apply(lambda row: wavelet_features(row.values), axis=1)
wavelet_features_df = pd.DataFrame(list(wavelet_results))
for col in wavelet_features_df.columns:
features[col] = wavelet_features_df[col].values
# features = pd.concat([features, wavelet_features_df], axis=1)
# # Autocorrelation features
def autocorr(x, lag=1):
return x.autocorr(lag=lag)
features['autocorr_1'] = df.apply(lambda x: autocorr(x, lag=1), axis=1)
features['autocorr_2'] = df.apply(lambda x: autocorr(x, lag=2), axis=1)
features['autocorr_5'] = df.apply(lambda x: autocorr(x, lag=5), axis=1)
features['autocorr_10'] = df.apply(lambda x: autocorr(x, lag=10), axis=1)
features['autocorr_30'] = df.apply(lambda x: autocorr(x, lag=30), axis=1)
features['autocorr_50'] = df.apply(lambda x: autocorr(x, lag=50), axis=1)
# Peak features
features['num_peaks'] = df.apply(lambda x: ((x.shift(1) < x) & (x.shift(-1) < x)).sum(), axis=1)
# Features for non-overlapping windows
def windowed_features(df, window_size):
windowed = []
for i in range(0, len(df.columns), window_size):
chunk = df.iloc[:, i:i + window_size]
window_stats = pd.DataFrame({
f'window_{i // window_size}_mean': chunk.mean(axis=1),
f'window_{i // window_size}_std': chunk.std(axis=1),
f'window_{i // window_size}_max': chunk.max(axis=1),
f'window_{i // window_size}_min': chunk.min(axis=1),
f'window_{i // window_size}_median': chunk.median(axis=1),
f'window_{i // window_size}_skew': chunk.skew(axis=1),
f'window_{i // window_size}_kurtosis': chunk.kurtosis(axis=1),
f'window_{i // window_size}_entropy': chunk.apply(lambda x: entropy(x.value_counts(), base=2), axis=1)
})
windowed.append(window_stats)
return pd.concat(windowed, axis=1)
for window_size in [10, 30, 50]:
windowed_features_df = windowed_features(df, window_size)
windowed_features_df.columns = [f'w{window_size}_{col}' for col in windowed_features_df.columns]
features = pd.concat([features, windowed_features_df], axis=1)
return features
def run_experiment(X_cleaned, y_cleaned, models_dict):
# 2) We create a master dictionary to store results for each model
all_model_results = {}
# 3) Outer KFold
outer_kf = KFold(n_splits=5, shuffle=True, random_state=42)
for model_name, model_info in models_dict.items():
print(f"\n{'=' * 40}\nRunning model: {model_name}\n{'=' * 40}")
all_model_results[model_name] = {} # store fold results here
fold_num = 1
for train_index, test_index in outer_kf.split(X_cleaned):
print(f"\n Fold {fold_num}")
# Split data
X_train, X_test = X_cleaned.iloc[train_index], X_cleaned.iloc[test_index]
y_train, y_test = y_cleaned.iloc[train_index], y_cleaned.iloc[test_index]
# -----------------------------
# Define the objective function
# -----------------------------
def objective(trial):
# Collect the proposed hyperparameters
trial_params = {}
for param_name, param_fn in model_info["param_space"].items():
trial_params[param_name] = param_fn(trial)
print(trial_params)
# Build the model with those hyperparameters
# For CatBoost, note that we typically pass params to the constructor or .fit()
if model_name == "CatBoost":
# typical usage: CatBoostClassifier(verbose=0, **trial_params)
clf = model_info["model"](verbose=0, **trial_params)
elif model_name == 'LDA' or model_name == 'GaussianNB' or model_name == 'QDA':
clf = model_info["model"](**trial_params)
else:
clf = model_info["model"](**trial_params, random_state=42)
# Construct pipeline
if model_info["requires_scaling"]:
pipeline = Pipeline([
('scaler', StandardScaler()),
('clf', clf)
])
else:
pipeline = Pipeline([
('clf', clf)
])
# Inner cross-validation on X_train
inner_kf = KFold(n_splits=3, shuffle=True, random_state=42)
cv_scores = []
for inner_train_idx, inner_valid_idx in inner_kf.split(X_train):
X_inner_train, X_inner_valid = X_train.iloc[inner_train_idx], X_train.iloc[inner_valid_idx]
y_inner_train, y_inner_valid = y_train.iloc[inner_train_idx], y_train.iloc[inner_valid_idx]
pipeline.fit(X_inner_train, y_inner_train)
y_pred_inner = pipeline.predict(X_inner_valid)
acc_inner = accuracy_score(y_inner_valid, y_pred_inner)
cv_scores.append(acc_inner)
return np.mean(cv_scores)
# -----------------------------
# Run Optuna
# -----------------------------
study = optuna.create_study(direction="maximize")
# Adjust n_trials or timeout as needed
study.optimize(objective, n_trials=5, timeout=300)
best_params = study.best_params
if 'probability' in list(model_info['param_space'].keys()):
best_params['probability'] = True
# print(" Best Hyperparameters:", best_params)
# Build final pipeline using best hyperparameters
if model_name == "CatBoost":
final_clf = model_info["model"](verbose=0, **best_params)
elif model_name == 'LDA' or model_name == 'GaussianNB' or model_name == 'QDA':
# best_params.pop('iterations')
# best_params.pop('depth')
final_clf = model_info["model"](**best_params)
else:
final_clf = model_info["model"](**best_params, random_state=42)
if model_info["requires_scaling"]:
final_pipeline = Pipeline([
('scaler', StandardScaler()),
('clf', final_clf)
])
else:
final_pipeline = Pipeline([
('clf', final_clf)
])
# Fit the final pipeline on the entire outer-train fold
final_pipeline.fit(X_train, y_train)
# Evaluate on the outer-test fold
y_pred_test = final_pipeline.predict(X_test)
# For AUC, we need predict_proba (or decision_function).
# Some models (SVC with certain kernels) may not provide predict_proba unless probability=True
# which we forced above. For CatBoost, XGBoost, RandomForest, etc. it's standard.
y_pred_prob_test = final_pipeline.predict_proba(X_test)
acc = accuracy_score(y_test, y_pred_test)
roc_auc = roc_auc_score(y_test, y_pred_prob_test[:, 1]) # use second column for positive class
prec = precision_score(y_test, y_pred_test)
rec = recall_score(y_test, y_pred_test)
f1_ = f1_score(y_test, y_pred_test)
confusion_mat = confusion_matrix(y_test, y_pred_test)
fold_result = {
'accuracy': acc,
'auc_score': roc_auc,
'precision': prec,
'recall': rec,
'f1_score': f1_,
'opt_params': best_params,
'confusion_matrix': confusion_mat
}
# Save fold result
all_model_results[model_name][fold_num] = fold_result
fold_num += 1
return all_model_results
def run_experiment_sktime(X_cleaned, y_cleaned, models_dict):
# Master dictionary to store results for each model
all_model_results = {}
# Outer KFold
outer_kf = KFold(n_splits=5, shuffle=True, random_state=42)
for model_name, model_info in models_dict.items():
print(f"\n{'=' * 40}\nRunning model: {model_name}\n{'=' * 40}")
all_model_results[model_name] = {} # Store fold results here
fold_num = 1
for train_index, test_index in outer_kf.split(X_cleaned):
print(f"\n Fold {fold_num}")
# Split data
X_train, X_test = X_cleaned.iloc[train_index], X_cleaned.iloc[test_index]
y_train, y_test = y_cleaned.iloc[train_index], y_cleaned.iloc[test_index]
# -----------------------------
# Define the objective function
# -----------------------------
def objective(trial):
# Collect the proposed hyperparameters
trial_params = {}
for param_name, param_fn in model_info["param_space"].items():
trial_params[param_name] = param_fn(trial)
print(trial_params)
# Build the model with those hyperparameters
clf = model_info["model"](**trial_params)
# # Construct pipeline
# if model_info["requires_scaling"]:
# pipeline = make_pipeline(
# ('scaler', StandardScaler()),
# ('clf', clf)
# )
# else:
# pipeline = make_pipeline(('clf', clf))
# Inner cross-validation on X_train
inner_kf = KFold(n_splits=3, shuffle=True, random_state=42)
cv_scores = []
for inner_train_idx, inner_valid_idx in inner_kf.split(X_train):
X_inner_train, X_inner_valid = X_train.iloc[inner_train_idx], X_train.iloc[inner_valid_idx]
y_inner_train, y_inner_valid = y_train.iloc[inner_train_idx], y_train.iloc[inner_valid_idx]
X_inner_train = np.expand_dims(X_inner_train.values, axis=1)
X_inner_valid = np.expand_dims(X_inner_valid.values, axis=1)
clf.fit(X_inner_train, y_inner_train)
y_pred_inner = clf.predict(X_inner_valid)
acc_inner = accuracy_score(y_inner_valid, y_pred_inner)
cv_scores.append(acc_inner)
return np.mean(cv_scores)
# -----------------------------
# Run Optuna
# -----------------------------
study = optuna.create_study(direction="maximize")
print('start')
study.optimize(objective, n_trials=1, timeout=10, n_jobs=-1)
best_params = study.best_params
print(" Best Hyperparameters:", best_params)
# Build final pipeline using best hyperparameters
final_clf = model_info["model"](**best_params)
X_train = np.expand_dims(X_train.values, axis=1)
X_test = np.expand_dims(X_test.values, axis=1)
# if model_info["requires_scaling"]:
# final_pipeline = make_pipeline(
# ('scaler', StandardScaler()),
# ('clf', final_clf)
# )
# else:
# final_pipeline = make_pipeline(('clf', final_clf))
# Fit the final pipeline on the entire outer-train fold
final_clf.fit(X_train, y_train)
# Evaluate on the outer-test fold
y_pred_test = final_clf.predict(X_test)
acc = accuracy_score(y_test, y_pred_test)
prec = precision_score(y_test, y_pred_test, zero_division=0)
rec = recall_score(y_test, y_pred_test, zero_division=0)
f1_ = f1_score(y_test, y_pred_test, zero_division=0)
confusion_mat = confusion_matrix(y_test, y_pred_test)
fold_result = {
'accuracy': acc,
'precision': prec,
'recall': rec,
'f1_score': f1_,
'opt_params': best_params,
'confusion_matrix': confusion_mat
}
# Save fold result
all_model_results[model_name][fold_num] = fold_result
fold_num += 1
return all_model_results
from copy import deepcopy
classical_models_to_test = {
# -------------------------------------------------------------------------
# 1) Logistic Regression
# -------------------------------------------------------------------------
"LogisticRegression": {
"model": LogisticRegression,
"requires_scaling": True,
"param_space": {
"C": lambda trial: trial.suggest_float("C", 1e-3, 1e3, log=True),
"penalty": lambda trial: trial.suggest_categorical("penalty", ["l1", "l2"]),
"solver": lambda trial: trial.suggest_categorical("solver", ["liblinear", "saga"]),
"max_iter":lambda trial: 200 # You can also tune this if you want
}
},
# -------------------------------------------------------------------------
# 2) Decision Tree
# -------------------------------------------------------------------------
"DecisionTree": {
"model": DecisionTreeClassifier,
"requires_scaling": False,
"param_space": {
"criterion": lambda trial: trial.suggest_categorical("criterion", ["gini", "entropy", "log_loss"]),
"max_depth": lambda trial: trial.suggest_int("max_depth", 2, 32, log=True),
"min_samples_split": lambda trial: trial.suggest_int("min_samples_split", 2, 10),
"min_samples_leaf": lambda trial: trial.suggest_int("min_samples_leaf", 1, 10),
"max_features": lambda trial: trial.suggest_categorical("max_features", [None, "sqrt", "log2"])
}
},
# -------------------------------------------------------------------------
# 3) Random Forest
# -------------------------------------------------------------------------
"RandomForest": {
"model": RandomForestClassifier,
"requires_scaling": False,
"param_space": {
"n_estimators": lambda trial: trial.suggest_int("n_estimators", 50, 500),
"max_depth": lambda trial: trial.suggest_int("max_depth", 2, 32, log=True),
"min_samples_split": lambda trial: trial.suggest_int("min_samples_split", 2, 10),
"min_samples_leaf": lambda trial: trial.suggest_int("min_samples_leaf", 1, 10),
"max_features": lambda trial: trial.suggest_float("max_features", 0.1, 1.0)
}
},
# -------------------------------------------------------------------------
# 5) XGBoost
# -------------------------------------------------------------------------
"XGBoost": {
"model": XGBClassifier,
"requires_scaling": False, # Tree-based, typically no scaling needed
"param_space": {
"n_estimators": lambda trial: trial.suggest_int("n_estimators", 50, 500),
"max_depth": lambda trial: trial.suggest_int("max_depth", 2, 16),
"learning_rate": lambda trial: trial.suggest_float("learning_rate", 1e-4, 0.3, log=True),
"subsample": lambda trial: trial.suggest_float("subsample", 0.5, 1.0),
"colsample_bytree": lambda trial: trial.suggest_float("colsample_bytree", 0.5, 1.0)
}
},
# -------------------------------------------------------------------------
# 6) CatBoost
# -------------------------------------------------------------------------
"CatBoost": {
"model": CatBoostClassifier,
"requires_scaling": False, # Tree-based
"param_space": {
"iterations": lambda trial: trial.suggest_int("iterations", 50, 500),
"depth": lambda trial: trial.suggest_int("depth", 2, 10),
"learning_rate": lambda trial: trial.suggest_float("learning_rate", 1e-4, 0.3, log=True),
"l2_leaf_reg": lambda trial: trial.suggest_float("l2_leaf_reg", 1e-3, 10, log=True)
}
},
# -------------------------------------------------------------------------
# 7) Linear Discriminant Analysis (LDA)
# -------------------------------------------------------------------------
# "LDA": {
# "model": LinearDiscriminantAnalysis,
# "requires_scaling": True,
# "param_space": {
# # solver can be one of: ['svd', 'lsqr', 'eigen']
# "solver": lambda trial: trial.suggest_categorical("solver", ["svd", "lsqr", "eigen"]),
# # shrinkage only applies to 'lsqr' or 'eigen'
# "shrinkage": lambda trial: trial.suggest_categorical("shrinkage", [None, "auto"]),
# # LDA doesn’t have many other parameters commonly tuned.
# # You might do param_grid for 'n_components' if relevant for dimensionality reduction, etc.
# }
# },
# -------------------------------------------------------------------------
# 8) Extra Trees (Extremely Randomized Trees)
# -------------------------------------------------------------------------
"ExtraTrees": {
"model": ExtraTreesClassifier,
"requires_scaling": False,
"param_space": {
"n_estimators": lambda trial: trial.suggest_int("n_estimators", 50, 500),
"max_depth": lambda trial: trial.suggest_int("max_depth", 2, 32, log=True),
"min_samples_split": lambda trial: trial.suggest_int("min_samples_split", 2, 10),
"min_samples_leaf": lambda trial: trial.suggest_int("min_samples_leaf", 1, 10),
"max_features": lambda trial: trial.suggest_float("max_features", 0.1, 1.0)
}
},
# -------------------------------------------------------------------------
# 9) AdaBoost
# -------------------------------------------------------------------------
"AdaBoost": {
"model": AdaBoostClassifier,
"requires_scaling": False,
"param_space": {
"n_estimators": lambda trial: trial.suggest_int("n_estimators", 50, 500),
"learning_rate": lambda trial: trial.suggest_float("learning_rate", 1e-3, 1.0, log=True),
# algorithm can be "SAMME" or "SAMME.R"
"algorithm": lambda trial: trial.suggest_categorical("algorithm", ["SAMME", "SAMME.R"])
}
},
# -------------------------------------------------------------------------
# 10) VotingClassifier
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# 11) Bayesian model (GaussianNB)
# -------------------------------------------------------------------------
"GaussianNB": {
"model": GaussianNB,
"requires_scaling": False, # Typically doesn't require scaling
"param_space": {
# 'var_smoothing' is the main hyperparameter for GaussianNB
"var_smoothing": lambda trial: trial.suggest_float("var_smoothing", 1e-12, 1e-5, log=True)
}
},
# -------------------------------------------------------------------------
# 13) QDA (Quadratic Discriminant Analysis)
# -------------------------------------------------------------------------
"QDA": {
"model": QuadraticDiscriminantAnalysis,
"requires_scaling": True,
"param_space": {
# Commonly tuned parameter is reg_param
"reg_param": lambda trial: trial.suggest_float("reg_param", 0.0, 1.0)
}
},
# -------------------------------------------------------------------------
# 14) SGDClassifier
# -------------------------------------------------------------------------
"SGD": {
"model": SGDClassifier,
"requires_scaling": True, # Usually beneficial
"param_space": {
"loss": lambda trial: trial.suggest_categorical("loss", ["log_loss", "modified_huber"]),
"penalty": lambda trial: trial.suggest_categorical("penalty", ["l2", "l1", "elasticnet"]),
"alpha": lambda trial: trial.suggest_float("alpha", 1e-6, 1e-1, log=True),
"max_iter":lambda trial: 1000, # or trial.suggest_int("max_iter", 100, 2000)
"tol": lambda trial: 1e-3 # or trial.suggest_float("tol", 1e-5, 1e-1, log=True)
}
},
}
def exp():
lead_2 = pd.read_csv('../data/Healthy_ECG_Data/healthy_leadV2.csv')
lead_6 = pd.read_csv('../data/Healthy_ECG_Data/healthy_leadV6.csv')
lead_II = pd.read_csv('../data/Healthy_ECG_Data/healthy_leadII.csv')
lead_2 = preproc_dataset(lead_2)
lead_6 = preproc_dataset(lead_6)
lead_II = preproc_dataset(lead_II)
healthy_df1 = deepcopy(lead_6)
healthy_df2 = deepcopy(lead_II)
vlp_df = deepcopy(lead_2)
random_indices = np.random.permutation(healthy_df1.shape[0])
sample_len = healthy_df1.shape[0] // 3
healthy_df1 = healthy_df1.iloc[:sample_len]
healthy_df2 = healthy_df2.iloc[sample_len:2 * sample_len]
vlp_df = vlp_df.iloc[2 * sample_len:3 * sample_len]
healthy_df = pd.concat([healthy_df1, healthy_df2])
for i in range(0, vlp_df.shape[0]):
vlp_df.iloc[i, :] = gaussian_modulated_vlp(vlp_df.iloc[i, :], (10, 40), 500).T
#### Here add code to add vlp to vlp_df
# vlp_df=func(vlp_df)
healthy_df['label'] = 0
vlp_df['label'] = 1
# Combine the two DataFrames
data = pd.concat([healthy_df, vlp_df], ignore_index=True)
# Separate features and labels
X = data.drop('label', axis=1)
y = data['label']
X_features = extract_features(X)
X_features_without_na = X_features.dropna()
# Align y to the cleaned X by using the index of X_cleaned
y_without_na = y.loc[X_features.index]
X_without_na = X.loc[X_features.index]
result = run_experiment(X_features_without_na, y_without_na, classical_models_to_test)
open('result_exp2_lead_2.pkl', 'wb').write(pickle.dumps(result))
healthy_df1 = deepcopy(lead_2)
healthy_df2 = deepcopy(lead_II)
vlp_df = deepcopy(lead_6)
random_indices = np.random.permutation(healthy_df1.shape[0])
sample_len = healthy_df1.shape[0] // 3
healthy_df1 = healthy_df1.iloc[:sample_len]
healthy_df2 = healthy_df2.iloc[sample_len:2 * sample_len]
vlp_df = vlp_df.iloc[2 * sample_len:3 * sample_len]
healthy_df = pd.concat([healthy_df1, healthy_df2])
for i in range(0, vlp_df.shape[0]):
vlp_df.iloc[i, :] = gaussian_modulated_vlp(vlp_df.iloc[i, :], (10, 40), 500).T
#### Here add code to add vlp to vlp_df
# vlp_df=func(vlp_df)
healthy_df['label'] = 0
vlp_df['label'] = 1
# Combine the two DataFrames
data = pd.concat([healthy_df, vlp_df], ignore_index=True)
# Separate features and labels
X = data.drop('label', axis=1)
y = data['label']
X_features = extract_features(X)
X_features_without_na = X_features.dropna()
# Align y to the cleaned X by using the index of X_cleaned
y_without_na = y.loc[X_features.index]
X_without_na = X.loc[X_features.index]
result = run_experiment(X_features_without_na, y_without_na, classical_models_to_test)
open('result_exp2_lead_6.pkl', 'wb').write(pickle.dumps(result))
healthy_df1 = deepcopy(lead_6)
healthy_df2 = deepcopy(lead_2)
vlp_df = deepcopy(lead_II)
random_indices = np.random.permutation(healthy_df1.shape[0])
sample_len = healthy_df1.shape[0] // 3
healthy_df1 = healthy_df1.iloc[:sample_len]
healthy_df2 = healthy_df2.iloc[sample_len:2 * sample_len]
vlp_df = vlp_df.iloc[2 * sample_len:3 * sample_len]
healthy_df = pd.concat([healthy_df1, healthy_df2])
for i in range(0, vlp_df.shape[0]):
vlp_df.iloc[i, :] = gaussian_modulated_vlp(vlp_df.iloc[i, :], (10, 40), 500).T
#### Here add code to add vlp to vlp_df
# vlp_df=func(vlp_df)
healthy_df['label'] = 0
vlp_df['label'] = 1
# Combine the two DataFrames
data = pd.concat([healthy_df, vlp_df], ignore_index=True)
# Separate features and labels
X = data.drop('label', axis=1)
y = data['label']
X_features = extract_features(X)
X_features_without_na = X_features.dropna()
# Align y to the cleaned X by using the index of X_cleaned
y_without_na = y.loc[X_features.index]
X_without_na = X.loc[X_features.index]
result = run_experiment(X_features_without_na, y_without_na, classical_models_to_test)
open('result_exp2_lead_II.pkl', 'wb').write(pickle.dumps(result))