-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathEEG_level_head.py
More file actions
1604 lines (1302 loc) · 65.2 KB
/
EEG_level_head.py
File metadata and controls
1604 lines (1302 loc) · 65.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
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
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import os
from torch.utils.data import Dataset
import pandas as pd
import argparse
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from tqdm import tqdm
from sklearn.metrics import balanced_accuracy_score
from sklearn import metrics as sklearn_metrics
from utils import BinaryFocalLoss,FocalLoss
from torch.nn.utils.rnn import pad_sequence
import sys
import numpy as np
import random
import warnings
warnings.filterwarnings("ignore")
class Logger:
def __init__(self, file_path):
self.terminal = sys.stdout
self.log = open(file_path, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
self.terminal.flush()
self.log.flush()
def log_only(self, message):
self.log.write(message + "\n")
self.log.flush()
def print_only(self, message):
self.terminal.write(message + "\n")
self.terminal.flush()
def setup_logger(output_dir, filename="training_log.txt"):
log_path = os.path.join(output_dir, filename)
sys.stdout = Logger(log_path)
return sys.stdout
class ClipAndExtend:
def __init__(self):
self.transform_idx = np.random.choice([0, 1], size=3).tolist()
def __call__(self,X):
if self.transform_idx[0]==1 and len(X)>10:
X=self.clip(X)
if self.transform_idx[1]==1 and len(X)>60 and len(X)<10000:
X=self.pad(X)
if self.transform_idx[2]==1 and len(X)<20000:
X=self.repeat(X)
return X
def clip(self, X):
center = len(X) // 2
random_int1 = random.randint(0, center-5)
random_int2 = random.randint(0, center-5)
X = X[len(X) // 2 -5 - random_int1: len(X) // 2 + 5+ random_int2, :]
return X
def pad(self,X):
# padding with others
max_length = (10000 - len(X)) // 2
random_int1 = random.randint(0, max_length)
random_int2 = random.randint(0, max_length)
m = X.shape[1]
X1 = self.get_random_matrix(random_int1, m)
X2 = self.get_random_matrix(random_int2, m)
X = np.vstack((X1, X, X2))
return X
def repeat(self, X):
n = np.random.randint(2, 6)
X = np.tile(X, (n, 1))
return X
def get_random_matrix(self, n, m):
matrix = np.zeros((n, m), dtype=np.float32)
for i in range(n):
if m == 1:
row = np.random.uniform(0, 0.5, size=(1,)).astype(np.float32)
else:
a_i1 = np.random.uniform(0.5, 1)
rest = np.random.uniform(0, 1 - a_i1, m - 1)
row = np.concatenate(([a_i1], rest))
row = row / np.sum(row)
matrix[i] = row.astype(np.float32)
return matrix
class CSVDataset(Dataset):
def __init__(self, csv_dirs, class_idx, file_list_path='', transform=None, is_predict_dataset=False):
if is_predict_dataset:
self.csv_files=get_predicting_files(csv_dirs)
else:
self.file_list=pd.read_csv(file_list_path)
self.csv_files=get_training_files(csv_dirs)
self.predicting_dataset=is_predict_dataset
self.transform = transform
self.class_idx = class_idx
def __len__(self):
return len(self.csv_files)
def __getitem__(self, idx):
csv_file = self.csv_files[idx]
file_name = os.path.basename(csv_file).split('.')[0]
df = pd.read_csv(csv_file)
if 'pred_class' in df.columns:
# continuous_class=df['pred_class'].tolist()
df = df.drop(columns=['pred_class'])
if df.isna().any().any():
###########for over GPU memory, could change###########
df = df.fillna(1)
###########for over GPU memory, could change###########
X = df.values.astype('float32')
if len(X) == 0:
print(f'{file_name} is none')
return None
is_low_signal = False
if X.shape[1] == 1 and np.all(X < 0.4):
is_low_signal = True
elif X.shape[1] > 1:
if self.predicting_dataset and hasattr(self, 'class_idx') and self.class_idx is not None:
if isinstance(self.class_idx, int) and 0 <= self.class_idx < X.shape[1]:
threshold = 1.0 / X.shape[1]
column_max = np.max(X[:, self.class_idx]) if self.class_idx > 0 else 0
if column_max < threshold:
is_low_signal = True
length = len(X)
if length < 30:
mean_values = np.mean(X, axis=0)
padding = np.tile(mean_values, (30 - length, 1))
X = np.vstack([X, padding])
elif length > 300000:
X = X[10:300000]
if not is_low_signal and self.transform is not None:
X = self.transform(X)
if self.predicting_dataset:
if is_low_signal:
return X, 0, file_name, length, True
else:
return X, None, file_name, length, False
if is_low_signal:
y = 0
else:
matched = self.file_list[self.file_list['file_name'] == file_name]
if matched.empty:
# print(f'{file_name} can not localize label, not match file')
return None
else:
if self.class_idx in matched['label'].to_list():
y = 1
elif 0 in matched['label'].to_list():
y = 0
else:
# print(f'{file_name} can not localize label, no label')
return None
return X, y, file_name, length
def get_training_files(training_dirs):
files=[]
for training_dir in training_dirs:
for file in os.listdir(training_dir):
if file.endswith('.csv'):
file_path = os.path.join(training_dir, file)
if os.path.isfile(file_path):
files.append(file_path)
return files
def get_predicting_files(test_dirs):
files = []
for test_dir in test_dirs:
for file in os.listdir(test_dir):
if file.endswith('.csv'):
file_path = os.path.join(test_dir, file)
if os.path.isfile(file_path):
files.append(file_path)
return files
def collate_fn(batch):
batch = [item for item in batch if item is not None]
if not batch:
return None, None, None, None
if len(batch[0]) == 5:
X, y, file_names, lengths, is_low_signals = zip(*batch)
is_low_signals = torch.tensor(is_low_signals)
else:
X, y, file_names, lengths = zip(*batch)
is_low_signals = None
X_padded = pad_sequence([torch.tensor(x) for x in X], batch_first=True, padding_value=0)
if y[0] is not None and all(isinstance(item, (int, float)) for item in y):
y = torch.tensor(y)
else:
y = None
lengths = torch.tensor(lengths)
if is_low_signals is not None:
return X_padded, y, file_names, lengths, is_low_signals
else:
return X_padded, y, file_names, lengths
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=15000):
super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-torch.log(torch.tensor(float(max_len))) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
return x + self.pe[:, :x.size(1)] # 简化切片操作
class CNNTransformerClassifier(nn.Module):
def __init__(self, input_dim, cnn_channels=16, transformer_layers=2, transformer_heads=4,
transformer_hidden_dim=64, output_dim=1, dropout=0.1, pe_max_length=15000):
super(CNNTransformerClassifier, self).__init__()
# CNN layers
self.cnn = nn.Sequential(
nn.Conv1d(in_channels=input_dim, out_channels=cnn_channels, kernel_size=3, padding=1),
nn.ReLU(),
nn.Dropout(dropout),
nn.MaxPool1d(kernel_size=10), # combine 10s
nn.Conv1d(in_channels=cnn_channels, out_channels=cnn_channels * 2, kernel_size=3, padding=1),
nn.ReLU(),
nn.Dropout(dropout),
nn.MaxPool1d(kernel_size=3) # combine 30s
)
self.seq_len_factor = 30 # CNN reduces sequence length by a factor of 30
# Transformer layers
self.transformer_input_dim = cnn_channels * 2
encoder_layer = TransformerEncoderLayer(
d_model=self.transformer_input_dim,
nhead=transformer_heads,
dim_feedforward=transformer_hidden_dim,
dropout=dropout,
batch_first=True
)
self.transformer = TransformerEncoder(encoder_layer, num_layers=transformer_layers)
self.pe_max_length=pe_max_length
# Normalization layers
self.pre_transformer_norm = nn.LayerNorm(self.transformer_input_dim)
self.post_transformer_norm = nn.LayerNorm(self.transformer_input_dim)
# Positional encoding
self.positional_encoding = PositionalEncoding(d_model=self.transformer_input_dim, max_len=self.pe_max_length)
# Output layers
self.fc = nn.Sequential(
nn.Linear(self.transformer_input_dim, transformer_hidden_dim),
nn.BatchNorm1d(transformer_hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(transformer_hidden_dim, output_dim)
)
def forward(self, x, lengths=None):
batch_size = x.size(0)
# CNN processing
x = x.transpose(1, 2) # (batch, seq, feature) -> (batch, feature, seq)
if lengths is not None:
lengths = (lengths // self.seq_len_factor).clamp(min=1).long()
x = self.cnn(x)
x = x.transpose(1, 2) # (batch, feature, seq) -> (batch, seq, feature)
# Pre-transformer normalization
x = self.pre_transformer_norm(x)
# Position encoding
x = self.positional_encoding(x)
# Transformer processing
if lengths is not None:
padding_mask = self.create_padding_mask(lengths, x.size(1))
padding_mask = padding_mask.to(x.device)
try:
x = self.transformer(x, src_key_padding_mask=padding_mask)
except TypeError:
x = self.transformer(x, mask=None, src_key_padding_mask=padding_mask)
else:
x = self.transformer(x)
# Post-transformer normalization
x = self.post_transformer_norm(x)
# Sequence pooling
if lengths is not None:
indices = (lengths - 1).view(-1, 1, 1).expand(-1, 1, x.size(-1))
# check the valid of index
if indices.max() >= x.size(1) or indices.min() < 0:
# print(
# f"Warning:index out of bound!indices range [{indices.min()}, {indices.max()}],but x.size(1)={x.size(1)}")
indices = torch.clamp(indices, 0, x.size(1) - 1)
x = x.gather(1, indices).squeeze(1)
else:
x = x[:, -1, :]
# Dimension verification
if x.size(0) != batch_size:
raise ValueError(f"Expected batch size {batch_size}, got {x.size(0)}")
if x.size(1) != self.transformer_input_dim:
raise ValueError(f"Expected feature dim {self.transformer_input_dim}, got {x.size(1)}")
return self.fc(x)
def create_padding_mask(self, lengths, max_len):
device = lengths.device
mask = (torch.arange(max_len, device=device, dtype=torch.long)[None, :] >= lengths[:, None])
return mask
def train(args, model, device, optimizer, criterion, num_epochs,train_loader_raw, train_loader_transform=None,
test_loader=None, save_freq=5, resume_training=False):
os.makedirs(args.output_dir, exist_ok=True)
logger = setup_logger(args.output_dir)
best_accuracy = 0.0
best_model_path=os.path.join(args.output_dir, 'checkpoint-best.pth')
# If resuming training, load the last checkpoint
if resume_training:
if os.path.exists(best_model_path):
checkpoint = torch.load(best_model_path)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
start_epoch = checkpoint.get('epoch', 0)
best_accuracy = checkpoint.get('accuracy', 0.0)
logger.print_only(f"Resuming training from previous epoch {start_epoch}")
else:
logger.print_only("No checkpoint found. Starting training from scratch.")
model.train()
for epoch in range(num_epochs):
both_epoch_loss=0
both_accuracy = 0
both_balanced_accuracy=0
for train_loader in [train_loader_transform,train_loader_raw]:
if train_loader is None:
continue
epoch_loss = 0
y_true = []
y_pred = []
for batch_idx, (inputs, labels, _, lengths) in enumerate(train_loader):
if inputs is None:
continue
inputs, labels, lengths = inputs.to(device), labels.to(device), lengths.to(device)
optimizer.zero_grad()
outputs = model(inputs, lengths=lengths)
# Adjust labels based on task type
if args.n_classes == 1: # Binary classification
labels = labels.view(-1, 1).float()
else: # Multi-class classification
labels = labels.long()
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# Calculate predictions
if args.n_classes == 1: # Binary classification
probabilities = torch.sigmoid(outputs)
predicted = torch.round(probabilities).squeeze().detach()
else: # Multi-class classification
probabilities = torch.softmax(outputs, dim=1)
predicted = torch.argmax(probabilities, dim=1)
y_true_batch=labels.squeeze().cpu().numpy()
y_pred_batch= predicted.cpu().numpy()
loss_batch=loss.item()
batch_accuracy = sklearn_metrics.accuracy_score(y_true_batch, y_pred_batch)
batch_balanced_accuracy = balanced_accuracy_score(y_true_batch, y_pred_batch)
logger.print_only(
f'Epoch [{epoch + 1}/{num_epochs}] Batch [{batch_idx + 1}/{len(train_loader)}], Loss: {loss_batch:.4f}; Accuracy: {batch_accuracy:.4f}; Balanced Accuracy: {batch_balanced_accuracy:.4f}')
y_true.extend(y_true_batch)
y_pred.extend(y_pred_batch)
epoch_loss+=loss_batch
train_accuracy = sklearn_metrics.accuracy_score(y_true, y_pred)
balanced_accuracy = balanced_accuracy_score(y_true, y_pred)
epoch_loss=epoch_loss/len(train_loader)
print(f'Epoch [{epoch + 1}/{num_epochs}] Train [1] Loss: {epoch_loss:.4f}; [2] Accuracy: {train_accuracy:.4f}; [3] Balanced Accuracy: {balanced_accuracy:.4f}')
both_epoch_loss += epoch_loss
both_accuracy+=train_accuracy
both_balanced_accuracy += balanced_accuracy
both_epoch_loss=both_epoch_loss/2
both_accuracy=both_accuracy/2
both_balanced_accuracy=both_balanced_accuracy/2
print(
f'[*] Epoch [{epoch + 1}/{num_epochs}] Avg loss:{both_epoch_loss:.4f}; Avg Accuracy: {both_accuracy:.4f}; AvgBalanced Accuracy: {both_balanced_accuracy:.4f}')
# Save model at specified frequency
if (epoch + 1) % save_freq == 0:
model_save_path = os.path.join(args.output_dir,f'checkpoint-{epoch + 1}.pth')
torch.save({
'epoch': epoch + 1,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'accuracy': train_accuracy
}, model_save_path)
logger.print_only(f"Model saved at epoch {epoch + 1}")
# Evaluate on test set if available
if test_loader:
logger.print_only('test')
test_accuracy, balanced_accuracy = test(args.n_classes, model, device, test_loader)
print(
f'Epoch [{epoch + 1}/{num_epochs}], Test Accuracy: {test_accuracy:.4f}, Balanced Accuracy: {balanced_accuracy:.4f}')
# Save best model
if test_accuracy > best_accuracy:
best_accuracy = test_accuracy
torch.save({
'epoch': epoch + 1,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'accuracy': best_accuracy
}, best_model_path)
logger.print_only(f"[*] New best model saved with accuracy {best_accuracy:.4f}")
else:
if both_accuracy>best_accuracy:
best_accuracy = both_accuracy
torch.save({
'epoch': epoch + 1,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'accuracy': best_accuracy
}, best_model_path)
logger.print_only(f"[*] New best model saved with accuracy {best_accuracy:.4f}")
sys.stdout.log.close()
sys.stdout = sys.stdout.terminal
def test(n_classes, model, device, test_loader, result_dir, type, n_files, save_result=True):
os.makedirs(result_dir, exist_ok=True)
model.eval()
results = []
with torch.no_grad():
for batch_idx, batch_data in enumerate(test_loader):
if batch_data is None: # 如果 batch 为空,跳过
print('None inputs, skip')
continue
if len(batch_data) == 5:
inputs, y, csv_file, lengths, is_low_signals = batch_data
# 处理低信号样本
low_signal_indices = torch.where(is_low_signals)[0]
if len(low_signal_indices) > 0:
for idx in low_signal_indices:
i = idx.item()
if save_result:
results.append({
'file_name': csv_file[i],
'probability': 0,
'pred_class': 0,
'true': y[i].item()
})
if torch.all(is_low_signals):
print(
f'Batch [{batch_idx + 1}/{len(test_loader)}]: All samples are low signal, skipping model evaluation')
continue
non_low_indices = torch.where(~is_low_signals)[0]
inputs = inputs[non_low_indices]
y = y[non_low_indices]
lengths = lengths[non_low_indices]
csv_file = [csv_file[i.item()] for i in non_low_indices]
else:
inputs, y, csv_file, lengths = batch_data
inputs, lengths = inputs.to(device), lengths.to(device)
outputs = model(inputs, lengths=lengths)
if n_classes == 1: # Binary classification
probabilities = torch.sigmoid(outputs)
predicted = torch.round(probabilities).squeeze()
if predicted.dim() == 0 and len(y) == 1:
predicted = predicted.unsqueeze(0)
labels = y.float().view(-1, 1) if y.dim() == 1 else y.float()
else: # Multi-class classification
probabilities = torch.softmax(outputs, dim=1)
predicted = torch.argmax(probabilities, dim=1)
labels = y.long()
y_true = labels.cpu().numpy()
y_pred = predicted.cpu().numpy()
if y_true.ndim > 1 and y_true.shape[1] == 1:
y_true = y_true.ravel()
if y_pred.ndim > 1 and y_pred.shape[1] == 1:
y_pred = y_pred.ravel()
accuracy = sklearn_metrics.accuracy_score(y_true, y_pred)
balanced_accuracy = balanced_accuracy_score(y_true, y_pred)
print(
f'Batch [{batch_idx + 1}/{len(test_loader)}]: Accuracy: {accuracy:.4f}; Balanced Accuracy: {balanced_accuracy:.4f}')
if save_result:
for i in range(len(csv_file)):
prob_val = probabilities[i].item() if isinstance(probabilities[i], torch.Tensor) else probabilities[
i]
pred_val = predicted[i].item() if isinstance(predicted[i], torch.Tensor) else predicted[i]
true_val = y[i].item() if isinstance(y[i], torch.Tensor) else y[i]
results.append({
'file_name': csv_file[i],
'probability': prob_val,
'pred_class': pred_val,
'true': true_val
})
if save_result:
results_df = pd.DataFrame(results)
file_path = os.path.join(result_dir, f'pred_EEG_level_{type}.csv')
results_df.to_csv(file_path, index=False)
os.chmod(file_path, 0o777)
return accuracy, balanced_accuracy
def predict(args, input_dim,n_classes, class_idx, model, device, test_loader, result_dir, type, n_files, event_precision=1, check_signal=True):
model.eval()
results = []
with torch.no_grad():
progress_bar = tqdm(total=n_files, desc=f"{type} EEG level results")
for batch_data in test_loader:
if batch_data is None:
print('None inputs, skip')
continue
if check_signal and len(batch_data) == 5:
inputs, y, csv_file, lengths, is_low_signals = batch_data
# 处理低信号样本
low_signal_indices = torch.where(is_low_signals)[0]
if len(low_signal_indices) > 0:
for idx in low_signal_indices:
i = idx.item()
results.append({
'file_name': csv_file[i],
'probability': 0,
'pred_class_p': 0,
#'positive_count': 0,
#'positive_proportion':0,
'confidence': 0,
'pred_class': 0,
})
if check_signal and torch.all(is_low_signals):
progress_bar.update(len(csv_file))
continue
non_low_indices = torch.where(~is_low_signals)[0]
inputs = inputs[non_low_indices]
if y is not None:
y = y[non_low_indices]
lengths = lengths[non_low_indices]
csv_file = [csv_file[i.item()] for i in non_low_indices]
else:
inputs, y, csv_file, lengths = batch_data
if inputs.size(0) == 0:
continue
inputs, lengths = inputs.to(device), lengths.to(device)
outputs = model(inputs, lengths=lengths)
if n_classes == 1:
probabilities = torch.sigmoid(outputs)
predicted = torch.round(probabilities).squeeze()
if not isinstance(predicted, torch.Tensor) or predicted.dim() == 0:
predicted = predicted.view(1)
probabilities = probabilities.view(1)
else:
probabilities = torch.softmax(outputs, dim=1)
predicted = torch.argmax(probabilities, dim=1)
for i in range(len(csv_file)):
prob_val = probabilities[i].item() if isinstance(probabilities[i], torch.Tensor) else probabilities[i]
pred_val = predicted[i].item() if isinstance(predicted[i], torch.Tensor) else predicted[i]
if input_dim == 1:
mask = inputs[i] > 0.5
count = int(mask.sum().item() * event_precision)
total = inputs[i].numel()
else:
max_indices = torch.argmax(inputs[i], dim=1)
mask = (max_indices == class_idx)
count = int(mask.sum().item() * event_precision)
total = inputs[i].shape[0]
proportion = count / total
confidence = min(1, prob_val + proportion)
if type=='SPIKES':
if count >= 5:
confidence=min(1,confidence/2+0.5)
else:
if count < 10 and confidence>0.5:
confidence = 0.5
if n_classes == 1:
pred_class_p = 1 if prob_val > 0.5 else 0
pred_class = 1 if confidence > 0.5 else 0
else:
pred_class_p = pred_val
pred_class = pred_val
if type == 'NORMAL':
results.append({
'file_name': csv_file[i],
'probability': prob_val,
'pred_class_p': pred_class_p,
#'positive_count': count,
# 'positive_proportion': proportion,
'confidence': confidence,
'pred_class': pred_class,
'revised_confidence': confidence,
'revised_pred_class': pred_class,
})
else:
results.append({
'file_name': csv_file[i],
'probability': prob_val,
'pred_class_p': pred_class_p,
#'positive_count': count,
#'positive_proportion': proportion,
'confidence': confidence,
'pred_class': pred_class,
})
progress_bar.update(len(csv_file))
progress_bar.n = n_files
progress_bar.refresh()
progress_bar.close()
results_df = pd.DataFrame(results)
normal_file_path=os.path.join(result_dir, f'pred_EEG_level_NORMAL.csv')
if os.path.exists(normal_file_path) and type!='NORMAL':
normal_df = pd.read_csv(normal_file_path)
normal_df=normal_results_align(results_df, normal_df)
if normal_df is not False:
normal_df.to_csv(normal_file_path, index=False)
if type=='SPIKES' and args.align_spike_detection_and_location:
foc_spike_path=os.path.join(result_dir, f'pred_EEG_level_FOC_SPIKES.csv')
gen_spike_path=os.path.join(result_dir, f'pred_EEG_level_GEN_SPIKES.csv')
if os.path.exists(foc_spike_path):
foc_spike_df=pd.read_csv(foc_spike_path)
results_df_new,foc_spike_df=spikes_results_align(results_df,foc_spike_df)
if results_df_new is not False:
results_df=results_df_new
foc_spike_df.to_csv(foc_spike_path, index=False)
if os.path.exists(gen_spike_path):
gen_spike_df = pd.read_csv(gen_spike_path)
results_df_new,gen_spike_df = spikes_results_align(results_df, gen_spike_df)
if results_df_new is not False:
results_df=results_df_new
gen_spike_df.to_csv(gen_spike_path, index=False)
# if (type == 'FOC_SPIKES' or type == 'GEN_SPIKES') and args.align_spike_detection_and_location:
# spike_path=os.path.join(result_dir, f'pred_EEG_level_SPIKES.csv')
# if os.path.exists(spike_path):
# spike_df=pd.read_csv(spike_path)
# spike_df,results_df=spikes_results_align(spike_df, results_df)
# if spike_df is not False:
# spike_df.to_csv(spike_path, index=False)
file_path = os.path.join(result_dir, f'pred_EEG_level_{type}.csv')
results_df.to_csv(file_path, index=False)
os.chmod(file_path, 0o777)
print(f'EEG level results are saved to {file_path}')
def spikes_results_align(df_a, df_b):
# 检查必要的列
required_columns = ['file_name', 'confidence', 'pred_class']
for df in [df_a, df_b]:
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
return False,False
# 确保file_name列的类型一致
df_a['file_name'] = df_a['file_name'].astype(str)
df_b['file_name'] = df_b['file_name'].astype(str)
b_index = df_b.set_index('file_name')
common_files = set(df_a['file_name']).intersection(set(df_b['file_name']))
has_count_column = 'positive_count' in df_a.columns
for file_name in common_files:
a_idx = df_a[df_a['file_name'] == file_name].index
b_idx = df_b[df_b['file_name'] == file_name].index
a_confidence = df_a.loc[a_idx, 'confidence'].values[0]
b_confidence = b_index.loc[file_name, 'confidence']
if b_confidence > 0.5 and a_confidence < 0.5:
mean_confidence = (a_confidence + b_confidence) / 2
if mean_confidence > 0.5 and has_count_column:
a_count = df_a.loc[a_idx, 'positive_count'].values[0]
if a_count == 0:
mean_confidence = 0.5
df_a.loc[a_idx, 'confidence'] = mean_confidence
df_a.loc[a_idx, 'pred_class'] = 1 if mean_confidence > 0.5 else 0
df_b.loc[b_idx, 'confidence'] = mean_confidence
df_b.loc[b_idx, 'pred_class'] = 1 if mean_confidence > 0.5 else 0
return df_a, df_b
def normal_results_align(df_a, df_b):
# df_b is normal file
required_columns = ['file_name', 'confidence', 'pred_class']
for df in [df_a, df_b]:
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
return False
df_a['file_name'] = df_a['file_name'].astype(str)
df_b['file_name'] = df_b['file_name'].astype(str)
b_index = df_b.set_index('file_name')
common_files = set(df_a['file_name']).intersection(set(df_b['file_name']))
for file_name in common_files:
a_idx = df_a[df_a['file_name'] == file_name].index
b_idx = df_b[df_b['file_name'] == file_name].index
a_confidence = df_a.loc[a_idx, 'confidence'].values[0]
b_confidence = b_index.loc[file_name, 'confidence']
if b_confidence < 0.5 and a_confidence > 0.5:
df_b.loc[b_idx, 'revised_confidence'] = 0.5
df_b.loc[b_idx, 'revised_pred_class'] = 1
return df_b
def predict_based_10min(args,input_dim, n_classes, class_idx, model, device, test_loader, result_dir, type, n_files,event_precision=1,check_signal=True):
model.eval()
results = []
sub_sample_length = 591
min_sample_length = 30
batch_size = 64
if type == 'FOC_SPIKES' or type == 'GEN_SPIKES' or type=='FOC_SLOWING' or type=='GEN_SLOWING':
predict(args=args, input_dim=input_dim,n_classes= n_classes, class_idx=class_idx, model=model, device=device, test_loader=test_loader, result_dir=result_dir, type=type, n_files=n_files, event_precision=event_precision, check_signal=True)
with torch.no_grad():
progress_bar = tqdm(total=n_files, desc=f"{type} EEG level results")
for batch_data in test_loader:
if batch_data is None:
print('None inputs, skip')
continue
if check_signal and len(batch_data) == 5:
inputs, y, csv_file, lengths, is_low_signals = batch_data
low_signal_indices = torch.where(is_low_signals)[0]
if len(low_signal_indices) > 0:
for idx in low_signal_indices:
i = idx.item()
results.append({
'file_name': csv_file[i],
'probability': 0,
'pred_class_p': 0,
# 'positive_count': 0,
#'positive_proportion': 0,
#'high_positive_proportion':0,
#'positive_10min_count': 0,
'confidence': 0,
'pred_class': 0,
})
if check_signal and torch.all(is_low_signals):
progress_bar.update(len(csv_file))
continue
non_low_indices = torch.where(~is_low_signals)[0]
inputs = inputs[non_low_indices]
if y is not None:
y = y[non_low_indices]
lengths = lengths[non_low_indices]
csv_file = [csv_file[i.item()] for i in non_low_indices]
else:
inputs, y, csv_file, lengths = batch_data
if inputs.size(0) == 0:
continue
file_results = {}
for name in csv_file:
if n_classes == 1:
file_results[name] = {
'max_prob': 0.0,
'max_confidence': 0.0,
'total_segments': 0,
'positive_segments': 0,
'positive_count':0,
'positive_proportion': 0,
'high_positive_proportion':0,
'sequence_length':0,
}
else:
file_results[name] = {
'max_prob': [0.0] * n_classes,
'max_confidence':[0.0] * n_classes,
'total_segments': 0,
'class_counts': [0] * n_classes,
'positive_count': 0,
'positive_proportion': 0,
'high_positive_proportion': 0,
'sequence_length': 0,
}
all_sub_samples = []
sub_sample_lengths = []
sub_sample_file_indices = []
sub_sample_file_names = []
sub_positive_proportion = []
for i in range(len(csv_file)):
file_name = csv_file[i]
input_sample = inputs[i]
num_rows = input_sample.shape[0]
file_results[file_name]['sequence_length'] = num_rows
if input_dim == 1:
total = input_sample.numel()
mask = input_sample > 0.5
count = int(mask.sum().item() * event_precision)
#mask_2 = input_sample > 0.9
#count_2 = int(mask_2.sum().item() * event_precision)
else:
total = num_rows
max_indices = torch.argmax(input_sample, dim=1)
mask = (max_indices == class_idx)
count = int(mask.sum().item() * event_precision)
#mask_2 = input_sample[:,class_idx] > 0.8
#count_2 = int(mask_2.sum().item() * event_precision)
file_results[file_name]['positive_count'] = count
if count==0:
file_results[file_name]['positive_proportion'] = 0
#file_results[file_name]['high_positive_proportion'] = 0
else:
file_results[file_name]['positive_proportion'] = count / total
#file_results[file_name]['high_positive_proportion'] = count_2 / count
if input_sample.dim() == 1:
input_sample = input_sample.unsqueeze(1)
num_rows = input_sample.shape[0]
num_full_segments = num_rows // sub_sample_length
last_segment_length = num_rows % sub_sample_length
total_segments = num_full_segments + (1 if last_segment_length >= min_sample_length else 0)
file_results[file_name]['total_segments'] += total_segments
for j in range(num_full_segments):
start_row = j * sub_sample_length
end_row = (j + 1) * sub_sample_length
sub_input = input_sample[start_row:end_row]
sub_mask = mask[start_row:end_row]
sub_count = int(sub_mask.sum().item() * event_precision)
if 0 not in sub_input.shape:
all_sub_samples.append(sub_input)
sub_sample_lengths.append(sub_sample_length)
sub_sample_file_indices.append(i)
sub_sample_file_names.append(file_name)
sub_positive_proportion.append(sub_count/sub_sample_length)
else:
print(f"Warning:skip subsample with shape {sub_input.shape}")
if last_segment_length >= min_sample_length:
start_row = num_full_segments * sub_sample_length
end_row = num_rows
sub_input = input_sample[start_row:end_row]
sub_mask = mask[start_row:end_row]
sub_count = int(sub_mask.sum().item() * event_precision)
if 0 not in sub_input.shape:
mean_values = sub_input.mean(dim=0, keepdim=True)
padded_sub_input = torch.zeros((sub_sample_length, sub_input.shape[1]),
dtype=sub_input.dtype,
device=sub_input.device)
padded_sub_input[:last_segment_length] = sub_input
for row_idx in range(last_segment_length, sub_sample_length):
padded_sub_input[row_idx] = mean_values
all_sub_samples.append(padded_sub_input)
sub_sample_lengths.append(last_segment_length)
sub_sample_file_indices.append(i)
sub_sample_file_names.append(file_name)
sub_positive_proportion.append(sub_count/sub_sample_length)
else:
print(f"Warning:skip subsample with shape {sub_input.shape}")
if len(all_sub_samples) == 0:
print("Warning:no valid subsample")
progress_bar.update(len(csv_file))
continue
# 批量处理子样本
for batch_start in range(0, len(all_sub_samples), batch_size):
batch_end = min(batch_start + batch_size, len(all_sub_samples))
batch_samples = all_sub_samples[batch_start:batch_end]
batch_lengths = sub_sample_lengths[batch_start:batch_end]
batch_positive_proportion = sub_positive_proportion[batch_start:batch_end]
batch_file_indices = sub_sample_file_indices[batch_start:batch_end]
batch_file_names = sub_sample_file_names[batch_start:batch_end]
try:
batch_tensor = torch.stack(batch_samples).to(device)
batch_lengths_tensor = torch.tensor(batch_lengths, device=device)
batch_outputs = model(batch_tensor, lengths=batch_lengths_tensor)
for k in range(len(batch_samples)):