Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- external/CBraMod/.gitignore +1 -0
- external/CBraMod/LICENSE +21 -0
- external/CBraMod/README.md +118 -0
- external/CBraMod/datasets/__init__.py +0 -0
- external/CBraMod/datasets/bciciv2a_dataset.py +68 -0
- external/CBraMod/datasets/chb_dataset.py +70 -0
- external/CBraMod/datasets/faced_dataset.py +69 -0
- external/CBraMod/datasets/isruc_dataset.py +107 -0
- external/CBraMod/datasets/mumtaz_dataset.py +70 -0
- external/CBraMod/datasets/physio_dataset.py +72 -0
- external/CBraMod/datasets/pretraining_dataset.py +34 -0
- external/CBraMod/datasets/seedv_dataset.py +73 -0
- external/CBraMod/datasets/seedvig_dataset.py +70 -0
- external/CBraMod/datasets/shu_dataset.py +70 -0
- external/CBraMod/datasets/speech_dataset.py +71 -0
- external/CBraMod/datasets/stress_dataset.py +70 -0
- external/CBraMod/datasets/tuab_dataset.py +70 -0
- external/CBraMod/datasets/tuev_dataset.py +77 -0
- external/CBraMod/finetune_evaluator.py +79 -0
- external/CBraMod/finetune_main.py +153 -0
- external/CBraMod/finetune_trainer.py +285 -0
- external/CBraMod/models/__init__.py +0 -0
- external/CBraMod/models/cbramod.py +119 -0
- external/CBraMod/models/criss_cross_transformer.py +219 -0
- external/CBraMod/models/model_for_bciciv2a.py +56 -0
- external/CBraMod/models/model_for_chb.py +60 -0
- external/CBraMod/models/model_for_faced.py +61 -0
- external/CBraMod/models/model_for_isruc.py +43 -0
- external/CBraMod/models/model_for_mumtaz.py +60 -0
- external/CBraMod/models/model_for_physio.py +57 -0
- external/CBraMod/models/model_for_seedv.py +58 -0
- external/CBraMod/models/model_for_seedvig.py +61 -0
- external/CBraMod/models/model_for_shu.py +61 -0
- external/CBraMod/models/model_for_speech.py +57 -0
- external/CBraMod/models/model_for_stress.py +60 -0
- external/CBraMod/models/model_for_tuab.py +60 -0
- external/CBraMod/models/model_for_tuev.py +58 -0
- external/CBraMod/preprocessing/README.md +42 -0
- external/CBraMod/preprocessing/__init__.py +0 -0
- external/CBraMod/pretrain_main.py +69 -0
- external/CBraMod/pretrain_trainer.py +95 -0
- external/CBraMod/quick_example.py +27 -0
- external/CBraMod/requirements.txt +14 -0
- external/T3A/CODE_OF_CONDUCT.md +5 -0
- external/T3A/CONTRIBUTING.md +32 -0
- external/T3A/LICENSE +9 -0
- external/T3A/Pipfile +29 -0
- external/T3A/Pipfile.lock +0 -0
- external/T3A/README.md +116 -0
- repo/outputs/budgeted_risk/risk_decisions/stage0_random_eval_batch/eegmmidb/fold_4/seed_0/b10_eegmmidb_029.json +326 -0
external/CBraMod/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
.idea
|
external/CBraMod/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Jiquan Wang
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
external/CBraMod/README.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<div align="center">
|
| 2 |
+
|
| 3 |
+
# CBraMod
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
_A Criss-Cross Brain Foundation Model for EEG Decoding_
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
[](https://arxiv.org/abs/2412.07236)
|
| 10 |
+
[](https://openreview.net/forum?id=NPNUHgHF2w)
|
| 11 |
+
[](https://huggingface.co/weighting666/CBraMod)
|
| 12 |
+

|
| 13 |
+
|
| 14 |
+
</div>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
<div align="center">
|
| 18 |
+
<img src="figure/CBraMod_logo.png" style="width: 15%;" />
|
| 19 |
+
</div>
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
<p align="center">
|
| 23 |
+
🔍 <a href="#-about">About</a>
|
| 24 |
+
| 🔨 <a href="#-setup">Setup</a>
|
| 25 |
+
| 🚢 <a href="#-pretrain">Pretrain</a>
|
| 26 |
+
| ⛵ <a href="#-finetune">Finetune</a>
|
| 27 |
+
| 🚀 <a href="#-quick-start">Quick Start</a>
|
| 28 |
+
| 🔗 <a href="#-citation">Citation</a>
|
| 29 |
+
</p>
|
| 30 |
+
🔥 NEWS: Thanks to over 100 stars! We've further refined the code for improved stability. Appreciate your patience as we refine the implementation — ongoing EEG research continues to shape the development of a standardized pipeline.
|
| 31 |
+
|
| 32 |
+
🔥 NEWS: The paper "_CBraMod: A Criss-Cross Brain Foundation Model for EEG Decoding_" has been accepted by ICLR 2025!
|
| 33 |
+
|
| 34 |
+
## 🔍 About
|
| 35 |
+
We propose **CBraMod**, a novel EEG foundation model, for EEG decoding on various clinical and BCI application.
|
| 36 |
+
The preprint version of our paper is available at [arXiv](https://arxiv.org/abs/2412.07236).
|
| 37 |
+
The camera-ready version of the paper will be available at [OpenReview](https://openreview.net/forum?id=NPNUHgHF2w).
|
| 38 |
+
<div align="center">
|
| 39 |
+
<img src="figure/model.png" style="width:100%;" />
|
| 40 |
+
</div>
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
## 🔨 Setup
|
| 45 |
+
Install [Python](https://www.python.org/downloads/).
|
| 46 |
+
|
| 47 |
+
Install [PyTorch](https://pytorch.org/get-started/locally/).
|
| 48 |
+
|
| 49 |
+
Install other requirements:
|
| 50 |
+
```commandline
|
| 51 |
+
pip install -r requirements.txt
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
## 🚢 Pretrain
|
| 56 |
+
You can pretrain CBraMod on our pretraining dataset or your custom pretraining dataset using the following code:
|
| 57 |
+
```commandline
|
| 58 |
+
python pretrain_main.py
|
| 59 |
+
```
|
| 60 |
+
We have released a pretrained checkpoint on [Hugginface🤗](https://huggingface.co/weighting666/CBraMod).
|
| 61 |
+
|
| 62 |
+
## ⛵ Finetune
|
| 63 |
+
You can finetune CBraMod on our selected downstream datasets using the following code:
|
| 64 |
+
```commandline
|
| 65 |
+
python finetune_main.py
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
## 🚀 Quick Start
|
| 70 |
+
You can fine-tune the pretrained CBraMod on your custom downstream dataset using the following example code:
|
| 71 |
+
```python
|
| 72 |
+
import torch
|
| 73 |
+
import torch.nn as nn
|
| 74 |
+
from models.cbramod import CBraMod
|
| 75 |
+
from einops.layers.torch import Rearrange
|
| 76 |
+
|
| 77 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 78 |
+
model = CBraMod().to(device)
|
| 79 |
+
model.load_state_dict(torch.load('pretrained_weights/pretrained_weights.pth', map_location=device))
|
| 80 |
+
model.proj_out = nn.Identity()
|
| 81 |
+
classifier = nn.Sequential(
|
| 82 |
+
Rearrange('b c s p -> b (c s p)'),
|
| 83 |
+
nn.Linear(22*4*200, 4*200),
|
| 84 |
+
nn.ELU(),
|
| 85 |
+
nn.Dropout(0.1),
|
| 86 |
+
nn.Linear(4 * 200, 200),
|
| 87 |
+
nn.ELU(),
|
| 88 |
+
nn.Dropout(0.1),
|
| 89 |
+
nn.Linear(200, 4),
|
| 90 |
+
).to(device)
|
| 91 |
+
|
| 92 |
+
# mock_eeg.shape = (batch_size, num_of_channels, time_segments, points_per_patch)
|
| 93 |
+
mock_eeg = torch.randn((8, 22, 4, 200)).to(device)
|
| 94 |
+
|
| 95 |
+
# logits.shape = (batch_size, num_of_classes)
|
| 96 |
+
logits = classifier(model(mock_eeg))
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
## 🔗 Citation
|
| 102 |
+
If you're using this repository in your research or applications, please cite using the following BibTeX:
|
| 103 |
+
```bibtex
|
| 104 |
+
@inproceedings{wang2025cbramod,
|
| 105 |
+
title={{CB}raMod: A Criss-Cross Brain Foundation Model for {EEG} Decoding},
|
| 106 |
+
author={Jiquan Wang and Sha Zhao and Zhiling Luo and Yangxuan Zhou and Haiteng Jiang and Shijian Li and Tao Li and Gang Pan},
|
| 107 |
+
booktitle={The Thirteenth International Conference on Learning Representations},
|
| 108 |
+
year={2025},
|
| 109 |
+
url={https://openreview.net/forum?id=NPNUHgHF2w}
|
| 110 |
+
}
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
## ⭐ Star History
|
| 114 |
+
<div align="center">
|
| 115 |
+
<a href="https://star-history.com/#wjq-learning/CBraMod&Date">
|
| 116 |
+
<img src="https://api.star-history.com/svg?repos=wjq-learning/CBraMod&type=Date" style="width: 80%;" />
|
| 117 |
+
</a>
|
| 118 |
+
</div>
|
external/CBraMod/datasets/__init__.py
ADDED
|
File without changes
|
external/CBraMod/datasets/bciciv2a_dataset.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
data_dir,
|
| 14 |
+
mode='train',
|
| 15 |
+
):
|
| 16 |
+
super(CustomDataset, self).__init__()
|
| 17 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 18 |
+
with self.db.begin(write=False) as txn:
|
| 19 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.keys))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
key = self.keys[idx]
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
data = pair['sample']
|
| 29 |
+
label = pair['label']
|
| 30 |
+
return data/100, label
|
| 31 |
+
|
| 32 |
+
def collate(self, batch):
|
| 33 |
+
x_data = np.array([x[0] for x in batch])
|
| 34 |
+
y_label = np.array([x[1] for x in batch])
|
| 35 |
+
return to_tensor(x_data), to_tensor(y_label).long()
|
| 36 |
+
|
| 37 |
+
class LoadDataset(object):
|
| 38 |
+
def __init__(self, params):
|
| 39 |
+
self.params = params
|
| 40 |
+
self.datasets_dir = params.datasets_dir
|
| 41 |
+
|
| 42 |
+
def get_data_loader(self):
|
| 43 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 44 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 45 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 46 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 47 |
+
print(len(train_set)+len(val_set)+len(test_set))
|
| 48 |
+
data_loader = {
|
| 49 |
+
'train': DataLoader(
|
| 50 |
+
train_set,
|
| 51 |
+
batch_size=self.params.batch_size,
|
| 52 |
+
collate_fn=train_set.collate,
|
| 53 |
+
shuffle=True,
|
| 54 |
+
),
|
| 55 |
+
'val': DataLoader(
|
| 56 |
+
val_set,
|
| 57 |
+
batch_size=self.params.batch_size,
|
| 58 |
+
collate_fn=val_set.collate,
|
| 59 |
+
shuffle=False,
|
| 60 |
+
),
|
| 61 |
+
'test': DataLoader(
|
| 62 |
+
test_set,
|
| 63 |
+
batch_size=self.params.batch_size,
|
| 64 |
+
collate_fn=test_set.collate,
|
| 65 |
+
shuffle=False,
|
| 66 |
+
),
|
| 67 |
+
}
|
| 68 |
+
return data_loader
|
external/CBraMod/datasets/chb_dataset.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
from scipy import signal
|
| 10 |
+
|
| 11 |
+
class CustomDataset(Dataset):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
data_dir,
|
| 15 |
+
mode='train',
|
| 16 |
+
):
|
| 17 |
+
super(CustomDataset, self).__init__()
|
| 18 |
+
self.files = [os.path.join(data_dir, mode, file) for file in os.listdir(os.path.join(data_dir, mode))]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.files))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
file = self.files[idx]
|
| 26 |
+
data_dict = pickle.load(open(file, 'rb'))
|
| 27 |
+
data = data_dict['X']
|
| 28 |
+
label = data_dict['y']
|
| 29 |
+
data = signal.resample(data, 2000, axis=1)
|
| 30 |
+
data = data.reshape(16, 10, 200)
|
| 31 |
+
return data/100, label
|
| 32 |
+
|
| 33 |
+
def collate(self, batch):
|
| 34 |
+
x_data = np.array([x[0] for x in batch])
|
| 35 |
+
y_label = np.array([x[1] for x in batch])
|
| 36 |
+
return to_tensor(x_data), to_tensor(y_label)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class LoadDataset(object):
|
| 40 |
+
def __init__(self, params):
|
| 41 |
+
self.params = params
|
| 42 |
+
self.datasets_dir = params.datasets_dir
|
| 43 |
+
|
| 44 |
+
def get_data_loader(self):
|
| 45 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 46 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 47 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 48 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 49 |
+
print(len(train_set) + len(val_set) + len(test_set))
|
| 50 |
+
data_loader = {
|
| 51 |
+
'train': DataLoader(
|
| 52 |
+
train_set,
|
| 53 |
+
batch_size=self.params.batch_size,
|
| 54 |
+
collate_fn=train_set.collate,
|
| 55 |
+
shuffle=True,
|
| 56 |
+
),
|
| 57 |
+
'val': DataLoader(
|
| 58 |
+
val_set,
|
| 59 |
+
batch_size=self.params.batch_size,
|
| 60 |
+
collate_fn=val_set.collate,
|
| 61 |
+
shuffle=False,
|
| 62 |
+
),
|
| 63 |
+
'test': DataLoader(
|
| 64 |
+
test_set,
|
| 65 |
+
batch_size=self.params.batch_size,
|
| 66 |
+
collate_fn=test_set.collate,
|
| 67 |
+
shuffle=False,
|
| 68 |
+
),
|
| 69 |
+
}
|
| 70 |
+
return data_loader
|
external/CBraMod/datasets/faced_dataset.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
data_dir,
|
| 14 |
+
mode='train',
|
| 15 |
+
):
|
| 16 |
+
super(CustomDataset, self).__init__()
|
| 17 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 18 |
+
with self.db.begin(write=False) as txn:
|
| 19 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.keys))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
key = self.keys[idx]
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
data = pair['sample']
|
| 29 |
+
label = pair['label']
|
| 30 |
+
return data/100, label
|
| 31 |
+
|
| 32 |
+
def collate(self, batch):
|
| 33 |
+
x_data = np.array([x[0] for x in batch])
|
| 34 |
+
y_label = np.array([x[1] for x in batch])
|
| 35 |
+
return to_tensor(x_data), to_tensor(y_label).long()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class LoadDataset(object):
|
| 39 |
+
def __init__(self, params):
|
| 40 |
+
self.params = params
|
| 41 |
+
self.datasets_dir = params.datasets_dir
|
| 42 |
+
|
| 43 |
+
def get_data_loader(self):
|
| 44 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 45 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 46 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 47 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 48 |
+
print(len(train_set)+len(val_set)+len(test_set))
|
| 49 |
+
data_loader = {
|
| 50 |
+
'train': DataLoader(
|
| 51 |
+
train_set,
|
| 52 |
+
batch_size=self.params.batch_size,
|
| 53 |
+
collate_fn=train_set.collate,
|
| 54 |
+
shuffle=True,
|
| 55 |
+
),
|
| 56 |
+
'val': DataLoader(
|
| 57 |
+
val_set,
|
| 58 |
+
batch_size=self.params.batch_size,
|
| 59 |
+
collate_fn=val_set.collate,
|
| 60 |
+
shuffle=False,
|
| 61 |
+
),
|
| 62 |
+
'test': DataLoader(
|
| 63 |
+
test_set,
|
| 64 |
+
batch_size=self.params.batch_size,
|
| 65 |
+
collate_fn=test_set.collate,
|
| 66 |
+
shuffle=False,
|
| 67 |
+
),
|
| 68 |
+
}
|
| 69 |
+
return data_loader
|
external/CBraMod/datasets/isruc_dataset.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
seqs_labels_path_pair
|
| 14 |
+
):
|
| 15 |
+
super(CustomDataset, self).__init__()
|
| 16 |
+
self.seqs_labels_path_pair = seqs_labels_path_pair
|
| 17 |
+
|
| 18 |
+
def __len__(self):
|
| 19 |
+
return len((self.seqs_labels_path_pair))
|
| 20 |
+
|
| 21 |
+
def __getitem__(self, idx):
|
| 22 |
+
seq_path = self.seqs_labels_path_pair[idx][0]
|
| 23 |
+
label_path = self.seqs_labels_path_pair[idx][1]
|
| 24 |
+
# print(seq_path)
|
| 25 |
+
# print(label_path)
|
| 26 |
+
seq = np.load(seq_path)
|
| 27 |
+
label = np.load(label_path)
|
| 28 |
+
return seq/100, label
|
| 29 |
+
|
| 30 |
+
def collate(self, batch):
|
| 31 |
+
x_seq = np.array([x[0] for x in batch])
|
| 32 |
+
y_label = np.array([x[1] for x in batch])
|
| 33 |
+
return to_tensor(x_seq), to_tensor(y_label).long()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class LoadDataset(object):
|
| 37 |
+
def __init__(self, params):
|
| 38 |
+
self.params = params
|
| 39 |
+
self.seqs_dir = os.path.join(params.datasets_dir, 'seq')
|
| 40 |
+
self.labels_dir = os.path.join(params.datasets_dir, 'labels')
|
| 41 |
+
self.seqs_labels_path_pair = self.load_path()
|
| 42 |
+
|
| 43 |
+
def get_data_loader(self):
|
| 44 |
+
train_pairs, val_pairs, test_pairs = self.split_dataset(self.seqs_labels_path_pair)
|
| 45 |
+
train_set = CustomDataset(train_pairs)
|
| 46 |
+
val_set = CustomDataset(val_pairs)
|
| 47 |
+
test_set = CustomDataset(test_pairs)
|
| 48 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 49 |
+
print(len(train_set) + len(val_set) + len(test_set))
|
| 50 |
+
data_loader = {
|
| 51 |
+
'train': DataLoader(
|
| 52 |
+
train_set,
|
| 53 |
+
batch_size=self.params.batch_size,
|
| 54 |
+
collate_fn=train_set.collate,
|
| 55 |
+
shuffle=True,
|
| 56 |
+
),
|
| 57 |
+
'val': DataLoader(
|
| 58 |
+
val_set,
|
| 59 |
+
batch_size=1,
|
| 60 |
+
collate_fn=val_set.collate,
|
| 61 |
+
shuffle=False,
|
| 62 |
+
),
|
| 63 |
+
'test': DataLoader(
|
| 64 |
+
test_set,
|
| 65 |
+
batch_size=1,
|
| 66 |
+
collate_fn=test_set.collate,
|
| 67 |
+
shuffle=False,
|
| 68 |
+
),
|
| 69 |
+
}
|
| 70 |
+
return data_loader
|
| 71 |
+
|
| 72 |
+
def load_path(self):
|
| 73 |
+
seqs_labels_path_pair = []
|
| 74 |
+
# subject_nums = os.listdir(self.seqs_dir)
|
| 75 |
+
# print(subject_nums)
|
| 76 |
+
subject_dirs_seq = []
|
| 77 |
+
subject_dirs_labels = []
|
| 78 |
+
for subject_num in range(1, 101):
|
| 79 |
+
subject_dirs_seq.append(os.path.join(self.seqs_dir, f'ISRUC-group1-{subject_num}'))
|
| 80 |
+
subject_dirs_labels.append(os.path.join(self.labels_dir, f'ISRUC-group1-{subject_num}'))
|
| 81 |
+
|
| 82 |
+
for subject_seq, subject_label in zip(subject_dirs_seq, subject_dirs_labels):
|
| 83 |
+
# print(subject_seq, subject_label)
|
| 84 |
+
subject_pairs = []
|
| 85 |
+
seq_fnames = os.listdir(subject_seq)
|
| 86 |
+
label_fnames = os.listdir(subject_label)
|
| 87 |
+
# print(seq_fnames)
|
| 88 |
+
for seq_fname, label_fname in zip(seq_fnames, label_fnames):
|
| 89 |
+
subject_pairs.append((os.path.join(subject_seq, seq_fname), os.path.join(subject_label, label_fname)))
|
| 90 |
+
seqs_labels_path_pair.append(subject_pairs)
|
| 91 |
+
# print(seqs_labels_path_pair)
|
| 92 |
+
return seqs_labels_path_pair
|
| 93 |
+
|
| 94 |
+
def split_dataset(self, seqs_labels_path_pair):
|
| 95 |
+
train_pairs = []
|
| 96 |
+
val_pairs = []
|
| 97 |
+
test_pairs = []
|
| 98 |
+
|
| 99 |
+
for i in range(100):
|
| 100 |
+
if i < 80:
|
| 101 |
+
train_pairs.extend(seqs_labels_path_pair[i])
|
| 102 |
+
elif i < 90:
|
| 103 |
+
val_pairs.extend(seqs_labels_path_pair[i])
|
| 104 |
+
else:
|
| 105 |
+
test_pairs.extend(seqs_labels_path_pair[i])
|
| 106 |
+
# print(train_pairs, val_pairs, test_pairs)
|
| 107 |
+
return train_pairs, val_pairs, test_pairs
|
external/CBraMod/datasets/mumtaz_dataset.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
data_dir,
|
| 14 |
+
mode='train',
|
| 15 |
+
):
|
| 16 |
+
super(CustomDataset, self).__init__()
|
| 17 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 18 |
+
with self.db.begin(write=False) as txn:
|
| 19 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.keys))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
key = self.keys[idx]
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
data = pair['sample']
|
| 29 |
+
label = pair['label']
|
| 30 |
+
# print(label)
|
| 31 |
+
return data/100, label
|
| 32 |
+
|
| 33 |
+
def collate(self, batch):
|
| 34 |
+
x_data = np.array([x[0] for x in batch])
|
| 35 |
+
y_label = np.array([x[1] for x in batch])
|
| 36 |
+
return to_tensor(x_data), to_tensor(y_label)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class LoadDataset(object):
|
| 40 |
+
def __init__(self, params):
|
| 41 |
+
self.params = params
|
| 42 |
+
self.datasets_dir = params.datasets_dir
|
| 43 |
+
|
| 44 |
+
def get_data_loader(self):
|
| 45 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 46 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 47 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 48 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 49 |
+
print(len(train_set) + len(val_set) + len(test_set))
|
| 50 |
+
data_loader = {
|
| 51 |
+
'train': DataLoader(
|
| 52 |
+
train_set,
|
| 53 |
+
batch_size=self.params.batch_size,
|
| 54 |
+
collate_fn=train_set.collate,
|
| 55 |
+
shuffle=True,
|
| 56 |
+
),
|
| 57 |
+
'val': DataLoader(
|
| 58 |
+
val_set,
|
| 59 |
+
batch_size=self.params.batch_size,
|
| 60 |
+
collate_fn=val_set.collate,
|
| 61 |
+
shuffle=True,
|
| 62 |
+
),
|
| 63 |
+
'test': DataLoader(
|
| 64 |
+
test_set,
|
| 65 |
+
batch_size=self.params.batch_size,
|
| 66 |
+
collate_fn=test_set.collate,
|
| 67 |
+
shuffle=True,
|
| 68 |
+
),
|
| 69 |
+
}
|
| 70 |
+
return data_loader
|
external/CBraMod/datasets/physio_dataset.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
data_dir,
|
| 14 |
+
mode='train',
|
| 15 |
+
):
|
| 16 |
+
super(CustomDataset, self).__init__()
|
| 17 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 18 |
+
with self.db.begin(write=False) as txn:
|
| 19 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.keys))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
key = self.keys[idx]
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
data = pair['sample']
|
| 29 |
+
label = pair['label']
|
| 30 |
+
# print(key)
|
| 31 |
+
# print(data)
|
| 32 |
+
# print(label)
|
| 33 |
+
return data/100, label
|
| 34 |
+
|
| 35 |
+
def collate(self, batch):
|
| 36 |
+
x_data = np.array([x[0] for x in batch])
|
| 37 |
+
y_label = np.array([x[1] for x in batch])
|
| 38 |
+
return to_tensor(x_data), to_tensor(y_label).long()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class LoadDataset(object):
|
| 42 |
+
def __init__(self, params):
|
| 43 |
+
self.params = params
|
| 44 |
+
self.datasets_dir = params.datasets_dir
|
| 45 |
+
|
| 46 |
+
def get_data_loader(self):
|
| 47 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 48 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 49 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 50 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 51 |
+
print(len(train_set)+len(val_set)+len(test_set))
|
| 52 |
+
data_loader = {
|
| 53 |
+
'train': DataLoader(
|
| 54 |
+
train_set,
|
| 55 |
+
batch_size=self.params.batch_size,
|
| 56 |
+
collate_fn=train_set.collate,
|
| 57 |
+
shuffle=True,
|
| 58 |
+
),
|
| 59 |
+
'val': DataLoader(
|
| 60 |
+
val_set,
|
| 61 |
+
batch_size=self.params.batch_size,
|
| 62 |
+
collate_fn=val_set.collate,
|
| 63 |
+
shuffle=False,
|
| 64 |
+
),
|
| 65 |
+
'test': DataLoader(
|
| 66 |
+
test_set,
|
| 67 |
+
batch_size=self.params.batch_size,
|
| 68 |
+
collate_fn=test_set.collate,
|
| 69 |
+
shuffle=False,
|
| 70 |
+
),
|
| 71 |
+
}
|
| 72 |
+
return data_loader
|
external/CBraMod/datasets/pretraining_dataset.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
|
| 3 |
+
import lmdb
|
| 4 |
+
from torch.utils.data import Dataset
|
| 5 |
+
|
| 6 |
+
from utils.util import to_tensor
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class PretrainingDataset(Dataset):
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
dataset_dir
|
| 13 |
+
):
|
| 14 |
+
super(PretrainingDataset, self).__init__()
|
| 15 |
+
self.db = lmdb.open(dataset_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 16 |
+
with self.db.begin(write=False) as txn:
|
| 17 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))
|
| 18 |
+
# self.keys = self.keys[:100000]
|
| 19 |
+
|
| 20 |
+
def __len__(self):
|
| 21 |
+
return len(self.keys)
|
| 22 |
+
|
| 23 |
+
def __getitem__(self, idx):
|
| 24 |
+
key = self.keys[idx]
|
| 25 |
+
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
patch = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
|
| 29 |
+
patch = to_tensor(patch)
|
| 30 |
+
# print(patch.shape)
|
| 31 |
+
return patch
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
|
external/CBraMod/datasets/seedv_dataset.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CustomDataset(Dataset):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
data_dir,
|
| 15 |
+
mode='train',
|
| 16 |
+
):
|
| 17 |
+
super(CustomDataset, self).__init__()
|
| 18 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 19 |
+
with self.db.begin(write=False) as txn:
|
| 20 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 21 |
+
|
| 22 |
+
def __len__(self):
|
| 23 |
+
return len((self.keys))
|
| 24 |
+
|
| 25 |
+
def __getitem__(self, idx):
|
| 26 |
+
key = self.keys[idx]
|
| 27 |
+
with self.db.begin(write=False) as txn:
|
| 28 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 29 |
+
data = pair['sample']
|
| 30 |
+
label = pair['label']
|
| 31 |
+
# print(key)
|
| 32 |
+
# print(data)
|
| 33 |
+
# print(label)
|
| 34 |
+
return data / 100, label
|
| 35 |
+
|
| 36 |
+
def collate(self, batch):
|
| 37 |
+
x_data = np.array([x[0] for x in batch])
|
| 38 |
+
y_label = np.array([x[1] for x in batch])
|
| 39 |
+
return to_tensor(x_data), to_tensor(y_label).long()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class LoadDataset(object):
|
| 43 |
+
def __init__(self, params):
|
| 44 |
+
self.params = params
|
| 45 |
+
self.datasets_dir = params.datasets_dir
|
| 46 |
+
|
| 47 |
+
def get_data_loader(self):
|
| 48 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 49 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 50 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 51 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 52 |
+
print(len(train_set) + len(val_set) + len(test_set))
|
| 53 |
+
data_loader = {
|
| 54 |
+
'train': DataLoader(
|
| 55 |
+
train_set,
|
| 56 |
+
batch_size=self.params.batch_size,
|
| 57 |
+
collate_fn=train_set.collate,
|
| 58 |
+
shuffle=True,
|
| 59 |
+
),
|
| 60 |
+
'val': DataLoader(
|
| 61 |
+
val_set,
|
| 62 |
+
batch_size=self.params.batch_size,
|
| 63 |
+
collate_fn=val_set.collate,
|
| 64 |
+
shuffle=False,
|
| 65 |
+
),
|
| 66 |
+
'test': DataLoader(
|
| 67 |
+
test_set,
|
| 68 |
+
batch_size=self.params.batch_size,
|
| 69 |
+
collate_fn=test_set.collate,
|
| 70 |
+
shuffle=False,
|
| 71 |
+
),
|
| 72 |
+
}
|
| 73 |
+
return data_loader
|
external/CBraMod/datasets/seedvig_dataset.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
data_dir,
|
| 14 |
+
mode='train',
|
| 15 |
+
):
|
| 16 |
+
super(CustomDataset, self).__init__()
|
| 17 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 18 |
+
with self.db.begin(write=False) as txn:
|
| 19 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.keys))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
key = self.keys[idx]
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
data = pair['sample']
|
| 29 |
+
label = pair['label']
|
| 30 |
+
# print(key)
|
| 31 |
+
# print(data.shape)
|
| 32 |
+
return data/100, label
|
| 33 |
+
|
| 34 |
+
def collate(self, batch):
|
| 35 |
+
x_data = np.array([x[0] for x in batch])
|
| 36 |
+
y_label = np.array([x[1] for x in batch])
|
| 37 |
+
return to_tensor(x_data), to_tensor(y_label)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class LoadDataset(object):
|
| 41 |
+
def __init__(self, params):
|
| 42 |
+
self.params = params
|
| 43 |
+
self.datasets_dir = params.datasets_dir
|
| 44 |
+
|
| 45 |
+
def get_data_loader(self):
|
| 46 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 47 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 48 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 49 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 50 |
+
data_loader = {
|
| 51 |
+
'train': DataLoader(
|
| 52 |
+
train_set,
|
| 53 |
+
batch_size=self.params.batch_size,
|
| 54 |
+
collate_fn=train_set.collate,
|
| 55 |
+
shuffle=True,
|
| 56 |
+
),
|
| 57 |
+
'val': DataLoader(
|
| 58 |
+
val_set,
|
| 59 |
+
batch_size=self.params.batch_size,
|
| 60 |
+
collate_fn=val_set.collate,
|
| 61 |
+
shuffle=False,
|
| 62 |
+
),
|
| 63 |
+
'test': DataLoader(
|
| 64 |
+
test_set,
|
| 65 |
+
batch_size=self.params.batch_size,
|
| 66 |
+
collate_fn=test_set.collate,
|
| 67 |
+
shuffle=False,
|
| 68 |
+
),
|
| 69 |
+
}
|
| 70 |
+
return data_loader
|
external/CBraMod/datasets/shu_dataset.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
data_dir,
|
| 14 |
+
mode='train',
|
| 15 |
+
):
|
| 16 |
+
super(CustomDataset, self).__init__()
|
| 17 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 18 |
+
with self.db.begin(write=False) as txn:
|
| 19 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.keys))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
key = self.keys[idx]
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
data = pair['sample']
|
| 29 |
+
label = pair['label']
|
| 30 |
+
# print(label)
|
| 31 |
+
return data/100, label
|
| 32 |
+
|
| 33 |
+
def collate(self, batch):
|
| 34 |
+
x_data = np.array([x[0] for x in batch])
|
| 35 |
+
y_label = np.array([x[1] for x in batch])
|
| 36 |
+
return to_tensor(x_data), to_tensor(y_label)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class LoadDataset(object):
|
| 40 |
+
def __init__(self, params):
|
| 41 |
+
self.params = params
|
| 42 |
+
self.datasets_dir = params.datasets_dir
|
| 43 |
+
|
| 44 |
+
def get_data_loader(self):
|
| 45 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 46 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 47 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 48 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 49 |
+
print(len(train_set)+len(val_set)+len(test_set))
|
| 50 |
+
data_loader = {
|
| 51 |
+
'train': DataLoader(
|
| 52 |
+
train_set,
|
| 53 |
+
batch_size=self.params.batch_size,
|
| 54 |
+
collate_fn=train_set.collate,
|
| 55 |
+
shuffle=True,
|
| 56 |
+
),
|
| 57 |
+
'val': DataLoader(
|
| 58 |
+
val_set,
|
| 59 |
+
batch_size=self.params.batch_size,
|
| 60 |
+
collate_fn=val_set.collate,
|
| 61 |
+
shuffle=True,
|
| 62 |
+
),
|
| 63 |
+
'test': DataLoader(
|
| 64 |
+
test_set,
|
| 65 |
+
batch_size=self.params.batch_size,
|
| 66 |
+
collate_fn=test_set.collate,
|
| 67 |
+
shuffle=True,
|
| 68 |
+
),
|
| 69 |
+
}
|
| 70 |
+
return data_loader
|
external/CBraMod/datasets/speech_dataset.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
data_dir,
|
| 14 |
+
mode='train',
|
| 15 |
+
):
|
| 16 |
+
super(CustomDataset, self).__init__()
|
| 17 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 18 |
+
with self.db.begin(write=False) as txn:
|
| 19 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.keys))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
key = self.keys[idx]
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
data = pair['sample']
|
| 29 |
+
label = pair['label']
|
| 30 |
+
# print(key)
|
| 31 |
+
# print(data.shape)
|
| 32 |
+
# print(label)
|
| 33 |
+
return data/100, label
|
| 34 |
+
|
| 35 |
+
def collate(self, batch):
|
| 36 |
+
x_data = np.array([x[0] for x in batch])
|
| 37 |
+
y_label = np.array([x[1] for x in batch])
|
| 38 |
+
return to_tensor(x_data), to_tensor(y_label).long()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class LoadDataset(object):
|
| 42 |
+
def __init__(self, params):
|
| 43 |
+
self.params = params
|
| 44 |
+
self.datasets_dir = params.datasets_dir
|
| 45 |
+
|
| 46 |
+
def get_data_loader(self):
|
| 47 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 48 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 49 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 50 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 51 |
+
data_loader = {
|
| 52 |
+
'train': DataLoader(
|
| 53 |
+
train_set,
|
| 54 |
+
batch_size=self.params.batch_size,
|
| 55 |
+
collate_fn=train_set.collate,
|
| 56 |
+
shuffle=True,
|
| 57 |
+
),
|
| 58 |
+
'val': DataLoader(
|
| 59 |
+
val_set,
|
| 60 |
+
batch_size=self.params.batch_size,
|
| 61 |
+
collate_fn=val_set.collate,
|
| 62 |
+
shuffle=False,
|
| 63 |
+
),
|
| 64 |
+
'test': DataLoader(
|
| 65 |
+
test_set,
|
| 66 |
+
batch_size=self.params.batch_size,
|
| 67 |
+
collate_fn=test_set.collate,
|
| 68 |
+
shuffle=False,
|
| 69 |
+
),
|
| 70 |
+
}
|
| 71 |
+
return data_loader
|
external/CBraMod/datasets/stress_dataset.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
class CustomDataset(Dataset):
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
data_dir,
|
| 14 |
+
mode='train',
|
| 15 |
+
):
|
| 16 |
+
super(CustomDataset, self).__init__()
|
| 17 |
+
self.db = lmdb.open(data_dir, readonly=True, lock=False, readahead=True, meminit=False)
|
| 18 |
+
with self.db.begin(write=False) as txn:
|
| 19 |
+
self.keys = pickle.loads(txn.get('__keys__'.encode()))[mode]
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.keys))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
key = self.keys[idx]
|
| 26 |
+
with self.db.begin(write=False) as txn:
|
| 27 |
+
pair = pickle.loads(txn.get(key.encode()))
|
| 28 |
+
data = pair['sample']
|
| 29 |
+
label = pair['label']
|
| 30 |
+
# print(label)
|
| 31 |
+
return data/100, label
|
| 32 |
+
|
| 33 |
+
def collate(self, batch):
|
| 34 |
+
x_data = np.array([x[0] for x in batch])
|
| 35 |
+
y_label = np.array([x[1] for x in batch])
|
| 36 |
+
return to_tensor(x_data), to_tensor(y_label)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class LoadDataset(object):
|
| 40 |
+
def __init__(self, params):
|
| 41 |
+
self.params = params
|
| 42 |
+
self.datasets_dir = params.datasets_dir
|
| 43 |
+
|
| 44 |
+
def get_data_loader(self):
|
| 45 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 46 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 47 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 48 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 49 |
+
print(len(train_set)+len(val_set)+len(test_set))
|
| 50 |
+
data_loader = {
|
| 51 |
+
'train': DataLoader(
|
| 52 |
+
train_set,
|
| 53 |
+
batch_size=self.params.batch_size,
|
| 54 |
+
collate_fn=train_set.collate,
|
| 55 |
+
shuffle=True,
|
| 56 |
+
),
|
| 57 |
+
'val': DataLoader(
|
| 58 |
+
val_set,
|
| 59 |
+
batch_size=self.params.batch_size,
|
| 60 |
+
collate_fn=val_set.collate,
|
| 61 |
+
shuffle=True,
|
| 62 |
+
),
|
| 63 |
+
'test': DataLoader(
|
| 64 |
+
test_set,
|
| 65 |
+
batch_size=self.params.batch_size,
|
| 66 |
+
collate_fn=test_set.collate,
|
| 67 |
+
shuffle=True,
|
| 68 |
+
),
|
| 69 |
+
}
|
| 70 |
+
return data_loader
|
external/CBraMod/datasets/tuab_dataset.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
from scipy import signal
|
| 10 |
+
|
| 11 |
+
class CustomDataset(Dataset):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
data_dir,
|
| 15 |
+
mode='train',
|
| 16 |
+
):
|
| 17 |
+
super(CustomDataset, self).__init__()
|
| 18 |
+
self.files = [os.path.join(data_dir, mode, file) for file in os.listdir(os.path.join(data_dir, mode))]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def __len__(self):
|
| 22 |
+
return len((self.files))
|
| 23 |
+
|
| 24 |
+
def __getitem__(self, idx):
|
| 25 |
+
file = self.files[idx]
|
| 26 |
+
data_dict = pickle.load(open(file, 'rb'))
|
| 27 |
+
data = data_dict['X']
|
| 28 |
+
label = data_dict['y']
|
| 29 |
+
# data = signal.resample(data, 2000, axis=-1)
|
| 30 |
+
data = data.reshape(16, 10, 200)
|
| 31 |
+
return data/100, label
|
| 32 |
+
|
| 33 |
+
def collate(self, batch):
|
| 34 |
+
x_data = np.array([x[0] for x in batch])
|
| 35 |
+
y_label = np.array([x[1] for x in batch])
|
| 36 |
+
return to_tensor(x_data), to_tensor(y_label)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class LoadDataset(object):
|
| 40 |
+
def __init__(self, params):
|
| 41 |
+
self.params = params
|
| 42 |
+
self.datasets_dir = params.datasets_dir
|
| 43 |
+
|
| 44 |
+
def get_data_loader(self):
|
| 45 |
+
train_set = CustomDataset(self.datasets_dir, mode='train')
|
| 46 |
+
val_set = CustomDataset(self.datasets_dir, mode='val')
|
| 47 |
+
test_set = CustomDataset(self.datasets_dir, mode='test')
|
| 48 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 49 |
+
print(len(train_set) + len(val_set) + len(test_set))
|
| 50 |
+
data_loader = {
|
| 51 |
+
'train': DataLoader(
|
| 52 |
+
train_set,
|
| 53 |
+
batch_size=self.params.batch_size,
|
| 54 |
+
collate_fn=train_set.collate,
|
| 55 |
+
shuffle=True,
|
| 56 |
+
),
|
| 57 |
+
'val': DataLoader(
|
| 58 |
+
val_set,
|
| 59 |
+
batch_size=self.params.batch_size,
|
| 60 |
+
collate_fn=val_set.collate,
|
| 61 |
+
shuffle=False,
|
| 62 |
+
),
|
| 63 |
+
'test': DataLoader(
|
| 64 |
+
test_set,
|
| 65 |
+
batch_size=self.params.batch_size,
|
| 66 |
+
collate_fn=test_set.collate,
|
| 67 |
+
shuffle=False,
|
| 68 |
+
),
|
| 69 |
+
}
|
| 70 |
+
return data_loader
|
external/CBraMod/datasets/tuev_dataset.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.utils.data import Dataset, DataLoader
|
| 3 |
+
import numpy as np
|
| 4 |
+
from utils.util import to_tensor
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import lmdb
|
| 8 |
+
import pickle
|
| 9 |
+
from scipy import signal
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class CustomDataset(Dataset):
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
data_dir,
|
| 16 |
+
files,
|
| 17 |
+
):
|
| 18 |
+
super(CustomDataset, self).__init__()
|
| 19 |
+
self.data_dir = data_dir
|
| 20 |
+
self.files = files
|
| 21 |
+
|
| 22 |
+
def __len__(self):
|
| 23 |
+
return len((self.files))
|
| 24 |
+
|
| 25 |
+
def __getitem__(self, idx):
|
| 26 |
+
file = self.files[idx]
|
| 27 |
+
data_dict = pickle.load(open(os.path.join(self.data_dir, file), "rb"))
|
| 28 |
+
data = data_dict['signal']
|
| 29 |
+
label = int(data_dict['label'][0]-1)
|
| 30 |
+
# data = signal.resample(data, 1000, axis=-1)
|
| 31 |
+
data = data.reshape(16, 5, 200)
|
| 32 |
+
return data/100, label
|
| 33 |
+
|
| 34 |
+
def collate(self, batch):
|
| 35 |
+
x_data = np.array([x[0] for x in batch])
|
| 36 |
+
y_label = np.array([x[1] for x in batch])
|
| 37 |
+
return to_tensor(x_data), to_tensor(y_label).long()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class LoadDataset(object):
|
| 41 |
+
def __init__(self, params):
|
| 42 |
+
self.params = params
|
| 43 |
+
self.datasets_dir = params.datasets_dir
|
| 44 |
+
|
| 45 |
+
def get_data_loader(self):
|
| 46 |
+
train_files = os.listdir(os.path.join(self.datasets_dir, "processed_train"))
|
| 47 |
+
val_files = os.listdir(os.path.join(self.datasets_dir, "processed_eval"))
|
| 48 |
+
test_files = os.listdir(os.path.join(self.datasets_dir, "processed_test"))
|
| 49 |
+
|
| 50 |
+
train_set = CustomDataset(os.path.join(self.datasets_dir, "processed_train"), train_files)
|
| 51 |
+
val_set = CustomDataset(os.path.join(self.datasets_dir, "processed_eval"), val_files)
|
| 52 |
+
test_set = CustomDataset(os.path.join(self.datasets_dir, "processed_test"), test_files)
|
| 53 |
+
|
| 54 |
+
print(len(train_set), len(val_set), len(test_set))
|
| 55 |
+
print(len(train_set)+len(val_set)+len(test_set))
|
| 56 |
+
|
| 57 |
+
data_loader = {
|
| 58 |
+
'train': DataLoader(
|
| 59 |
+
train_set,
|
| 60 |
+
batch_size=self.params.batch_size,
|
| 61 |
+
collate_fn=train_set.collate,
|
| 62 |
+
shuffle=True,
|
| 63 |
+
),
|
| 64 |
+
'val': DataLoader(
|
| 65 |
+
val_set,
|
| 66 |
+
batch_size=self.params.batch_size,
|
| 67 |
+
collate_fn=val_set.collate,
|
| 68 |
+
shuffle=False,
|
| 69 |
+
),
|
| 70 |
+
'test': DataLoader(
|
| 71 |
+
test_set,
|
| 72 |
+
batch_size=self.params.batch_size,
|
| 73 |
+
collate_fn=test_set.collate,
|
| 74 |
+
shuffle=False,
|
| 75 |
+
),
|
| 76 |
+
}
|
| 77 |
+
return data_loader
|
external/CBraMod/finetune_evaluator.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from sklearn.metrics import balanced_accuracy_score, f1_score, confusion_matrix, cohen_kappa_score, roc_auc_score, \
|
| 4 |
+
precision_recall_curve, auc, r2_score, mean_squared_error
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Evaluator:
|
| 9 |
+
def __init__(self, params, data_loader):
|
| 10 |
+
self.params = params
|
| 11 |
+
self.data_loader = data_loader
|
| 12 |
+
|
| 13 |
+
def get_metrics_for_multiclass(self, model):
|
| 14 |
+
model.eval()
|
| 15 |
+
|
| 16 |
+
truths = []
|
| 17 |
+
preds = []
|
| 18 |
+
for x, y in tqdm(self.data_loader, mininterval=1):
|
| 19 |
+
x = x.cuda()
|
| 20 |
+
y = y.cuda()
|
| 21 |
+
|
| 22 |
+
pred = model(x)
|
| 23 |
+
pred_y = torch.max(pred, dim=-1)[1]
|
| 24 |
+
|
| 25 |
+
truths += y.cpu().squeeze().numpy().tolist()
|
| 26 |
+
preds += pred_y.cpu().squeeze().numpy().tolist()
|
| 27 |
+
|
| 28 |
+
truths = np.array(truths)
|
| 29 |
+
preds = np.array(preds)
|
| 30 |
+
acc = balanced_accuracy_score(truths, preds)
|
| 31 |
+
f1 = f1_score(truths, preds, average='weighted')
|
| 32 |
+
kappa = cohen_kappa_score(truths, preds)
|
| 33 |
+
cm = confusion_matrix(truths, preds)
|
| 34 |
+
return acc, kappa, f1, cm
|
| 35 |
+
|
| 36 |
+
def get_metrics_for_binaryclass(self, model):
|
| 37 |
+
model.eval()
|
| 38 |
+
|
| 39 |
+
truths = []
|
| 40 |
+
preds = []
|
| 41 |
+
scores = []
|
| 42 |
+
for x, y in tqdm(self.data_loader, mininterval=1):
|
| 43 |
+
x = x.cuda()
|
| 44 |
+
y = y.cuda()
|
| 45 |
+
pred = model(x)
|
| 46 |
+
score_y = torch.sigmoid(pred)
|
| 47 |
+
pred_y = torch.gt(score_y, 0.5).long()
|
| 48 |
+
truths += y.long().cpu().squeeze().numpy().tolist()
|
| 49 |
+
preds += pred_y.cpu().squeeze().numpy().tolist()
|
| 50 |
+
scores += score_y.cpu().numpy().tolist()
|
| 51 |
+
|
| 52 |
+
truths = np.array(truths)
|
| 53 |
+
preds = np.array(preds)
|
| 54 |
+
scores = np.array(scores)
|
| 55 |
+
acc = balanced_accuracy_score(truths, preds)
|
| 56 |
+
roc_auc = roc_auc_score(truths, scores)
|
| 57 |
+
precision, recall, thresholds = precision_recall_curve(truths, scores, pos_label=1)
|
| 58 |
+
pr_auc = auc(recall, precision)
|
| 59 |
+
cm = confusion_matrix(truths, preds)
|
| 60 |
+
return acc, pr_auc, roc_auc, cm
|
| 61 |
+
|
| 62 |
+
def get_metrics_for_regression(self, model):
|
| 63 |
+
model.eval()
|
| 64 |
+
|
| 65 |
+
truths = []
|
| 66 |
+
preds = []
|
| 67 |
+
for x, y in tqdm(self.data_loader, mininterval=1):
|
| 68 |
+
x = x.cuda()
|
| 69 |
+
y = y.cuda()
|
| 70 |
+
pred = model(x)
|
| 71 |
+
truths += y.cpu().squeeze().numpy().tolist()
|
| 72 |
+
preds += pred.cpu().squeeze().numpy().tolist()
|
| 73 |
+
|
| 74 |
+
truths = np.array(truths)
|
| 75 |
+
preds = np.array(preds)
|
| 76 |
+
corrcoef = np.corrcoef(truths, preds)[0, 1]
|
| 77 |
+
r2 = r2_score(truths, preds)
|
| 78 |
+
rmse = mean_squared_error(truths, preds) ** 0.5
|
| 79 |
+
return corrcoef, r2, rmse
|
external/CBraMod/finetune_main.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import random
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from datasets import faced_dataset, seedv_dataset, physio_dataset, shu_dataset, isruc_dataset, chb_dataset, \
|
| 8 |
+
speech_dataset, mumtaz_dataset, seedvig_dataset, stress_dataset, tuev_dataset, tuab_dataset, bciciv2a_dataset
|
| 9 |
+
from finetune_trainer import Trainer
|
| 10 |
+
from models import model_for_faced, model_for_seedv, model_for_physio, model_for_shu, model_for_isruc, model_for_chb, \
|
| 11 |
+
model_for_speech, model_for_mumtaz, model_for_seedvig, model_for_stress, model_for_tuev, model_for_tuab, \
|
| 12 |
+
model_for_bciciv2a
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def main():
|
| 16 |
+
parser = argparse.ArgumentParser(description='Big model downstream')
|
| 17 |
+
parser.add_argument('--seed', type=int, default=3407, help='random seed (default: 0)')
|
| 18 |
+
parser.add_argument('--cuda', type=int, default=1, help='cuda number (default: 1)')
|
| 19 |
+
parser.add_argument('--epochs', type=int, default=50, help='number of epochs (default: 5)')
|
| 20 |
+
parser.add_argument('--batch_size', type=int, default=64, help='batch size for training (default: 32)')
|
| 21 |
+
parser.add_argument('--lr', type=float, default=1e-4, help='learning rate (default: 1e-3)')
|
| 22 |
+
parser.add_argument('--weight_decay', type=float, default=5e-2, help='weight decay (default: 1e-2)')
|
| 23 |
+
parser.add_argument('--optimizer', type=str, default='AdamW', help='optimizer (AdamW, SGD)')
|
| 24 |
+
parser.add_argument('--clip_value', type=float, default=1, help='clip_value')
|
| 25 |
+
parser.add_argument('--dropout', type=float, default=0.1, help='dropout')
|
| 26 |
+
parser.add_argument('--classifier', type=str, default='all_patch_reps',
|
| 27 |
+
help='[all_patch_reps, all_patch_reps_twolayer, '
|
| 28 |
+
'all_patch_reps_onelayer, avgpooling_patch_reps]')
|
| 29 |
+
# all_patch_reps: use all patch features with a three-layer classifier;
|
| 30 |
+
# all_patch_reps_twolayer: use all patch features with a two-layer classifier;
|
| 31 |
+
# all_patch_reps_onelayer: use all patch features with a one-layer classifier;
|
| 32 |
+
# avgpooling_patch_reps: use average pooling for patch features;
|
| 33 |
+
|
| 34 |
+
"""############ Downstream dataset settings ############"""
|
| 35 |
+
parser.add_argument('--downstream_dataset', type=str, default='MentalArithmetic',
|
| 36 |
+
help='[FACED, SEED-V, PhysioNet-MI, SHU-MI, ISRUC, CHB-MIT, BCIC2020-3, Mumtaz2016, '
|
| 37 |
+
'SEED-VIG, MentalArithmetic, TUEV, TUAB, BCIC-IV-2a]')
|
| 38 |
+
parser.add_argument('--datasets_dir', type=str,
|
| 39 |
+
default='/data/datasets/BigDownstream/mental-arithmetic/processed',
|
| 40 |
+
help='datasets_dir')
|
| 41 |
+
parser.add_argument('--num_of_classes', type=int, default=2, help='number of classes')
|
| 42 |
+
parser.add_argument('--model_dir', type=str, default='/data/wjq/models_weights/Big/BigFaced', help='model_dir')
|
| 43 |
+
"""############ Downstream dataset settings ############"""
|
| 44 |
+
|
| 45 |
+
parser.add_argument('--num_workers', type=int, default=16, help='num_workers')
|
| 46 |
+
parser.add_argument('--label_smoothing', type=float, default=0.1, help='label_smoothing')
|
| 47 |
+
parser.add_argument('--multi_lr', type=bool, default=True,
|
| 48 |
+
help='multi_lr') # set different learning rates for different modules
|
| 49 |
+
parser.add_argument('--frozen', type=bool,
|
| 50 |
+
default=False, help='frozen')
|
| 51 |
+
parser.add_argument('--use_pretrained_weights', type=bool,
|
| 52 |
+
default=True, help='use_pretrained_weights')
|
| 53 |
+
parser.add_argument('--foundation_dir', type=str,
|
| 54 |
+
default='pretrained_weights/pretrained_weights.pth',
|
| 55 |
+
help='foundation_dir')
|
| 56 |
+
|
| 57 |
+
params = parser.parse_args()
|
| 58 |
+
print(params)
|
| 59 |
+
|
| 60 |
+
setup_seed(params.seed)
|
| 61 |
+
torch.cuda.set_device(params.cuda)
|
| 62 |
+
print('The downstream dataset is {}'.format(params.downstream_dataset))
|
| 63 |
+
if params.downstream_dataset == 'FACED':
|
| 64 |
+
load_dataset = faced_dataset.LoadDataset(params)
|
| 65 |
+
data_loader = load_dataset.get_data_loader()
|
| 66 |
+
model = model_for_faced.Model(params)
|
| 67 |
+
t = Trainer(params, data_loader, model)
|
| 68 |
+
t.train_for_multiclass()
|
| 69 |
+
elif params.downstream_dataset == 'SEED-V':
|
| 70 |
+
load_dataset = seedv_dataset.LoadDataset(params)
|
| 71 |
+
data_loader = load_dataset.get_data_loader()
|
| 72 |
+
model = model_for_seedv.Model(params)
|
| 73 |
+
t = Trainer(params, data_loader, model)
|
| 74 |
+
t.train_for_multiclass()
|
| 75 |
+
elif params.downstream_dataset == 'PhysioNet-MI':
|
| 76 |
+
load_dataset = physio_dataset.LoadDataset(params)
|
| 77 |
+
data_loader = load_dataset.get_data_loader()
|
| 78 |
+
model = model_for_physio.Model(params)
|
| 79 |
+
t = Trainer(params, data_loader, model)
|
| 80 |
+
t.train_for_multiclass()
|
| 81 |
+
elif params.downstream_dataset == 'SHU-MI':
|
| 82 |
+
load_dataset = shu_dataset.LoadDataset(params)
|
| 83 |
+
data_loader = load_dataset.get_data_loader()
|
| 84 |
+
model = model_for_shu.Model(params)
|
| 85 |
+
t = Trainer(params, data_loader, model)
|
| 86 |
+
t.train_for_binaryclass()
|
| 87 |
+
elif params.downstream_dataset == 'ISRUC':
|
| 88 |
+
load_dataset = isruc_dataset.LoadDataset(params)
|
| 89 |
+
data_loader = load_dataset.get_data_loader()
|
| 90 |
+
model = model_for_isruc.Model(params)
|
| 91 |
+
t = Trainer(params, data_loader, model)
|
| 92 |
+
t.train_for_multiclass()
|
| 93 |
+
elif params.downstream_dataset == 'CHB-MIT':
|
| 94 |
+
load_dataset = chb_dataset.LoadDataset(params)
|
| 95 |
+
data_loader = load_dataset.get_data_loader()
|
| 96 |
+
model = model_for_chb.Model(params)
|
| 97 |
+
t = Trainer(params, data_loader, model)
|
| 98 |
+
t.train_for_binaryclass()
|
| 99 |
+
elif params.downstream_dataset == 'BCIC2020-3':
|
| 100 |
+
load_dataset = speech_dataset.LoadDataset(params)
|
| 101 |
+
data_loader = load_dataset.get_data_loader()
|
| 102 |
+
model = model_for_speech.Model(params)
|
| 103 |
+
t = Trainer(params, data_loader, model)
|
| 104 |
+
t.train_for_multiclass()
|
| 105 |
+
elif params.downstream_dataset == 'Mumtaz2016':
|
| 106 |
+
load_dataset = mumtaz_dataset.LoadDataset(params)
|
| 107 |
+
data_loader = load_dataset.get_data_loader()
|
| 108 |
+
model = model_for_mumtaz.Model(params)
|
| 109 |
+
t = Trainer(params, data_loader, model)
|
| 110 |
+
t.train_for_binaryclass()
|
| 111 |
+
elif params.downstream_dataset == 'SEED-VIG':
|
| 112 |
+
load_dataset = seedvig_dataset.LoadDataset(params)
|
| 113 |
+
data_loader = load_dataset.get_data_loader()
|
| 114 |
+
model = model_for_seedvig.Model(params)
|
| 115 |
+
t = Trainer(params, data_loader, model)
|
| 116 |
+
t.train_for_regression()
|
| 117 |
+
elif params.downstream_dataset == 'MentalArithmetic':
|
| 118 |
+
load_dataset = stress_dataset.LoadDataset(params)
|
| 119 |
+
data_loader = load_dataset.get_data_loader()
|
| 120 |
+
model = model_for_stress.Model(params)
|
| 121 |
+
t = Trainer(params, data_loader, model)
|
| 122 |
+
t.train_for_binaryclass()
|
| 123 |
+
elif params.downstream_dataset == 'TUEV':
|
| 124 |
+
load_dataset = tuev_dataset.LoadDataset(params)
|
| 125 |
+
data_loader = load_dataset.get_data_loader()
|
| 126 |
+
model = model_for_tuev.Model(params)
|
| 127 |
+
t = Trainer(params, data_loader, model)
|
| 128 |
+
t.train_for_multiclass()
|
| 129 |
+
elif params.downstream_dataset == 'TUAB':
|
| 130 |
+
load_dataset = tuab_dataset.LoadDataset(params)
|
| 131 |
+
data_loader = load_dataset.get_data_loader()
|
| 132 |
+
model = model_for_tuab.Model(params)
|
| 133 |
+
t = Trainer(params, data_loader, model)
|
| 134 |
+
t.train_for_binaryclass()
|
| 135 |
+
elif params.downstream_dataset == 'BCIC-IV-2a':
|
| 136 |
+
load_dataset = bciciv2a_dataset.LoadDataset(params)
|
| 137 |
+
data_loader = load_dataset.get_data_loader()
|
| 138 |
+
model = model_for_bciciv2a.Model(params)
|
| 139 |
+
t = Trainer(params, data_loader, model)
|
| 140 |
+
t.train_for_multiclass()
|
| 141 |
+
print('Done!!!!!')
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def setup_seed(seed):
|
| 145 |
+
torch.manual_seed(seed)
|
| 146 |
+
torch.cuda.manual_seed_all(seed)
|
| 147 |
+
np.random.seed(seed)
|
| 148 |
+
random.seed(seed)
|
| 149 |
+
torch.backends.cudnn.deterministic = True
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if __name__ == '__main__':
|
| 153 |
+
main()
|
external/CBraMod/finetune_trainer.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import os
|
| 3 |
+
from timeit import default_timer as timer
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss, MSELoss
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
|
| 10 |
+
from finetune_evaluator import Evaluator
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Trainer(object):
|
| 14 |
+
def __init__(self, params, data_loader, model):
|
| 15 |
+
self.params = params
|
| 16 |
+
self.data_loader = data_loader
|
| 17 |
+
|
| 18 |
+
self.val_eval = Evaluator(params, self.data_loader['val'])
|
| 19 |
+
self.test_eval = Evaluator(params, self.data_loader['test'])
|
| 20 |
+
|
| 21 |
+
self.model = model.cuda()
|
| 22 |
+
if self.params.downstream_dataset in ['FACED', 'SEED-V', 'PhysioNet-MI', 'ISRUC', 'BCIC2020-3', 'TUEV', 'BCIC-IV-2a']:
|
| 23 |
+
self.criterion = CrossEntropyLoss(label_smoothing=self.params.label_smoothing).cuda()
|
| 24 |
+
elif self.params.downstream_dataset in ['SHU-MI', 'CHB-MIT', 'Mumtaz2016', 'MentalArithmetic', 'TUAB']:
|
| 25 |
+
self.criterion = BCEWithLogitsLoss().cuda()
|
| 26 |
+
elif self.params.downstream_dataset == 'SEED-VIG':
|
| 27 |
+
self.criterion = MSELoss().cuda()
|
| 28 |
+
|
| 29 |
+
self.best_model_states = None
|
| 30 |
+
|
| 31 |
+
backbone_params = []
|
| 32 |
+
other_params = []
|
| 33 |
+
for name, param in self.model.named_parameters():
|
| 34 |
+
if "backbone" in name:
|
| 35 |
+
backbone_params.append(param)
|
| 36 |
+
|
| 37 |
+
if params.frozen:
|
| 38 |
+
param.requires_grad = False
|
| 39 |
+
else:
|
| 40 |
+
param.requires_grad = True
|
| 41 |
+
else:
|
| 42 |
+
other_params.append(param)
|
| 43 |
+
|
| 44 |
+
if self.params.optimizer == 'AdamW':
|
| 45 |
+
if self.params.multi_lr: # set different learning rates for different modules
|
| 46 |
+
self.optimizer = torch.optim.AdamW([
|
| 47 |
+
{'params': backbone_params, 'lr': self.params.lr},
|
| 48 |
+
{'params': other_params, 'lr': 0.001*(self.params.batch_size/256)**0.5}
|
| 49 |
+
], weight_decay=self.params.weight_decay)
|
| 50 |
+
else:
|
| 51 |
+
self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.params.lr,
|
| 52 |
+
weight_decay=self.params.weight_decay)
|
| 53 |
+
else:
|
| 54 |
+
if self.params.multi_lr:
|
| 55 |
+
self.optimizer = torch.optim.SGD([
|
| 56 |
+
{'params': backbone_params, 'lr': self.params.lr},
|
| 57 |
+
{'params': other_params, 'lr': self.params.lr * 5}
|
| 58 |
+
], momentum=0.9, weight_decay=self.params.weight_decay)
|
| 59 |
+
else:
|
| 60 |
+
self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.params.lr, momentum=0.9,
|
| 61 |
+
weight_decay=self.params.weight_decay)
|
| 62 |
+
|
| 63 |
+
self.data_length = len(self.data_loader['train'])
|
| 64 |
+
self.optimizer_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
|
| 65 |
+
self.optimizer, T_max=self.params.epochs * self.data_length, eta_min=1e-6
|
| 66 |
+
)
|
| 67 |
+
print(self.model)
|
| 68 |
+
|
| 69 |
+
def train_for_multiclass(self):
|
| 70 |
+
f1_best = 0
|
| 71 |
+
kappa_best = 0
|
| 72 |
+
acc_best = 0
|
| 73 |
+
cm_best = None
|
| 74 |
+
for epoch in range(self.params.epochs):
|
| 75 |
+
self.model.train()
|
| 76 |
+
start_time = timer()
|
| 77 |
+
losses = []
|
| 78 |
+
for x, y in tqdm(self.data_loader['train'], mininterval=10):
|
| 79 |
+
self.optimizer.zero_grad()
|
| 80 |
+
x = x.cuda()
|
| 81 |
+
y = y.cuda()
|
| 82 |
+
pred = self.model(x)
|
| 83 |
+
if self.params.downstream_dataset == 'ISRUC':
|
| 84 |
+
loss = self.criterion(pred.transpose(1, 2), y)
|
| 85 |
+
else:
|
| 86 |
+
loss = self.criterion(pred, y)
|
| 87 |
+
|
| 88 |
+
loss.backward()
|
| 89 |
+
losses.append(loss.data.cpu().numpy())
|
| 90 |
+
if self.params.clip_value > 0:
|
| 91 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.params.clip_value)
|
| 92 |
+
# torch.nn.utils.clip_grad_value_(self.model.parameters(), self.params.clip_value)
|
| 93 |
+
self.optimizer.step()
|
| 94 |
+
self.optimizer_scheduler.step()
|
| 95 |
+
|
| 96 |
+
optim_state = self.optimizer.state_dict()
|
| 97 |
+
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
acc, kappa, f1, cm = self.val_eval.get_metrics_for_multiclass(self.model)
|
| 100 |
+
print(
|
| 101 |
+
"Epoch {} : Training Loss: {:.5f}, acc: {:.5f}, kappa: {:.5f}, f1: {:.5f}, LR: {:.5f}, Time elapsed {:.2f} mins".format(
|
| 102 |
+
epoch + 1,
|
| 103 |
+
np.mean(losses),
|
| 104 |
+
acc,
|
| 105 |
+
kappa,
|
| 106 |
+
f1,
|
| 107 |
+
optim_state['param_groups'][0]['lr'],
|
| 108 |
+
(timer() - start_time) / 60
|
| 109 |
+
)
|
| 110 |
+
)
|
| 111 |
+
print(cm)
|
| 112 |
+
if kappa > kappa_best:
|
| 113 |
+
print("kappa increasing....saving weights !! ")
|
| 114 |
+
print("Val Evaluation: acc: {:.5f}, kappa: {:.5f}, f1: {:.5f}".format(
|
| 115 |
+
acc,
|
| 116 |
+
kappa,
|
| 117 |
+
f1,
|
| 118 |
+
))
|
| 119 |
+
best_f1_epoch = epoch + 1
|
| 120 |
+
acc_best = acc
|
| 121 |
+
kappa_best = kappa
|
| 122 |
+
f1_best = f1
|
| 123 |
+
cm_best = cm
|
| 124 |
+
self.best_model_states = copy.deepcopy(self.model.state_dict())
|
| 125 |
+
self.model.load_state_dict(self.best_model_states)
|
| 126 |
+
with torch.no_grad():
|
| 127 |
+
print("***************************Test************************")
|
| 128 |
+
acc, kappa, f1, cm = self.test_eval.get_metrics_for_multiclass(self.model)
|
| 129 |
+
print("***************************Test results************************")
|
| 130 |
+
print(
|
| 131 |
+
"Test Evaluation: acc: {:.5f}, kappa: {:.5f}, f1: {:.5f}".format(
|
| 132 |
+
acc,
|
| 133 |
+
kappa,
|
| 134 |
+
f1,
|
| 135 |
+
)
|
| 136 |
+
)
|
| 137 |
+
print(cm)
|
| 138 |
+
if not os.path.isdir(self.params.model_dir):
|
| 139 |
+
os.makedirs(self.params.model_dir)
|
| 140 |
+
model_path = self.params.model_dir + "/epoch{}_acc_{:.5f}_kappa_{:.5f}_f1_{:.5f}.pth".format(best_f1_epoch, acc, kappa, f1)
|
| 141 |
+
torch.save(self.model.state_dict(), model_path)
|
| 142 |
+
print("model save in " + model_path)
|
| 143 |
+
|
| 144 |
+
def train_for_binaryclass(self):
|
| 145 |
+
acc_best = 0
|
| 146 |
+
roc_auc_best = 0
|
| 147 |
+
pr_auc_best = 0
|
| 148 |
+
cm_best = None
|
| 149 |
+
for epoch in range(self.params.epochs):
|
| 150 |
+
self.model.train()
|
| 151 |
+
start_time = timer()
|
| 152 |
+
losses = []
|
| 153 |
+
for x, y in tqdm(self.data_loader['train'], mininterval=10):
|
| 154 |
+
self.optimizer.zero_grad()
|
| 155 |
+
x = x.cuda()
|
| 156 |
+
y = y.cuda()
|
| 157 |
+
pred = self.model(x)
|
| 158 |
+
|
| 159 |
+
loss = self.criterion(pred, y)
|
| 160 |
+
|
| 161 |
+
loss.backward()
|
| 162 |
+
losses.append(loss.data.cpu().numpy())
|
| 163 |
+
if self.params.clip_value > 0:
|
| 164 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.params.clip_value)
|
| 165 |
+
# torch.nn.utils.clip_grad_value_(self.model.parameters(), self.params.clip_value)
|
| 166 |
+
self.optimizer.step()
|
| 167 |
+
self.optimizer_scheduler.step()
|
| 168 |
+
|
| 169 |
+
optim_state = self.optimizer.state_dict()
|
| 170 |
+
|
| 171 |
+
with torch.no_grad():
|
| 172 |
+
acc, pr_auc, roc_auc, cm = self.val_eval.get_metrics_for_binaryclass(self.model)
|
| 173 |
+
print(
|
| 174 |
+
"Epoch {} : Training Loss: {:.5f}, acc: {:.5f}, pr_auc: {:.5f}, roc_auc: {:.5f}, LR: {:.5f}, Time elapsed {:.2f} mins".format(
|
| 175 |
+
epoch + 1,
|
| 176 |
+
np.mean(losses),
|
| 177 |
+
acc,
|
| 178 |
+
pr_auc,
|
| 179 |
+
roc_auc,
|
| 180 |
+
optim_state['param_groups'][0]['lr'],
|
| 181 |
+
(timer() - start_time) / 60
|
| 182 |
+
)
|
| 183 |
+
)
|
| 184 |
+
print(cm)
|
| 185 |
+
if roc_auc > roc_auc_best:
|
| 186 |
+
print("roc_auc increasing....saving weights !! ")
|
| 187 |
+
print("Val Evaluation: acc: {:.5f}, pr_auc: {:.5f}, roc_auc: {:.5f}".format(
|
| 188 |
+
acc,
|
| 189 |
+
pr_auc,
|
| 190 |
+
roc_auc,
|
| 191 |
+
))
|
| 192 |
+
best_f1_epoch = epoch + 1
|
| 193 |
+
acc_best = acc
|
| 194 |
+
pr_auc_best = pr_auc
|
| 195 |
+
roc_auc_best = roc_auc
|
| 196 |
+
cm_best = cm
|
| 197 |
+
self.best_model_states = copy.deepcopy(self.model.state_dict())
|
| 198 |
+
self.model.load_state_dict(self.best_model_states)
|
| 199 |
+
with torch.no_grad():
|
| 200 |
+
print("***************************Test************************")
|
| 201 |
+
acc, pr_auc, roc_auc, cm = self.test_eval.get_metrics_for_binaryclass(self.model)
|
| 202 |
+
print("***************************Test results************************")
|
| 203 |
+
print(
|
| 204 |
+
"Test Evaluation: acc: {:.5f}, pr_auc: {:.5f}, roc_auc: {:.5f}".format(
|
| 205 |
+
acc,
|
| 206 |
+
pr_auc,
|
| 207 |
+
roc_auc,
|
| 208 |
+
)
|
| 209 |
+
)
|
| 210 |
+
print(cm)
|
| 211 |
+
if not os.path.isdir(self.params.model_dir):
|
| 212 |
+
os.makedirs(self.params.model_dir)
|
| 213 |
+
model_path = self.params.model_dir + "/epoch{}_acc_{:.5f}_pr_{:.5f}_roc_{:.5f}.pth".format(best_f1_epoch, acc, pr_auc, roc_auc)
|
| 214 |
+
torch.save(self.model.state_dict(), model_path)
|
| 215 |
+
print("model save in " + model_path)
|
| 216 |
+
|
| 217 |
+
def train_for_regression(self):
|
| 218 |
+
corrcoef_best = 0
|
| 219 |
+
r2_best = 0
|
| 220 |
+
rmse_best = 0
|
| 221 |
+
for epoch in range(self.params.epochs):
|
| 222 |
+
self.model.train()
|
| 223 |
+
start_time = timer()
|
| 224 |
+
losses = []
|
| 225 |
+
for x, y in tqdm(self.data_loader['train'], mininterval=10):
|
| 226 |
+
self.optimizer.zero_grad()
|
| 227 |
+
x = x.cuda()
|
| 228 |
+
y = y.cuda()
|
| 229 |
+
pred = self.model(x)
|
| 230 |
+
loss = self.criterion(pred, y)
|
| 231 |
+
|
| 232 |
+
loss.backward()
|
| 233 |
+
losses.append(loss.data.cpu().numpy())
|
| 234 |
+
if self.params.clip_value > 0:
|
| 235 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.params.clip_value)
|
| 236 |
+
# torch.nn.utils.clip_grad_value_(self.model.parameters(), self.params.clip_value)
|
| 237 |
+
self.optimizer.step()
|
| 238 |
+
self.optimizer_scheduler.step()
|
| 239 |
+
|
| 240 |
+
optim_state = self.optimizer.state_dict()
|
| 241 |
+
|
| 242 |
+
with torch.no_grad():
|
| 243 |
+
corrcoef, r2, rmse = self.val_eval.get_metrics_for_regression(self.model)
|
| 244 |
+
print(
|
| 245 |
+
"Epoch {} : Training Loss: {:.5f}, corrcoef: {:.5f}, r2: {:.5f}, rmse: {:.5f}, LR: {:.5f}, Time elapsed {:.2f} mins".format(
|
| 246 |
+
epoch + 1,
|
| 247 |
+
np.mean(losses),
|
| 248 |
+
corrcoef,
|
| 249 |
+
r2,
|
| 250 |
+
rmse,
|
| 251 |
+
optim_state['param_groups'][0]['lr'],
|
| 252 |
+
(timer() - start_time) / 60
|
| 253 |
+
)
|
| 254 |
+
)
|
| 255 |
+
if r2 > r2_best:
|
| 256 |
+
print("r2 increasing....saving weights !! ")
|
| 257 |
+
print("Val Evaluation: corrcoef: {:.5f}, r2: {:.5f}, rmse: {:.5f}".format(
|
| 258 |
+
corrcoef,
|
| 259 |
+
r2,
|
| 260 |
+
rmse,
|
| 261 |
+
))
|
| 262 |
+
best_r2_epoch = epoch + 1
|
| 263 |
+
corrcoef_best = corrcoef
|
| 264 |
+
r2_best = r2
|
| 265 |
+
rmse_best = rmse
|
| 266 |
+
self.best_model_states = copy.deepcopy(self.model.state_dict())
|
| 267 |
+
|
| 268 |
+
self.model.load_state_dict(self.best_model_states)
|
| 269 |
+
with torch.no_grad():
|
| 270 |
+
print("***************************Test************************")
|
| 271 |
+
corrcoef, r2, rmse = self.test_eval.get_metrics_for_regression(self.model)
|
| 272 |
+
print("***************************Test results************************")
|
| 273 |
+
print(
|
| 274 |
+
"Test Evaluation: corrcoef: {:.5f}, r2: {:.5f}, rmse: {:.5f}".format(
|
| 275 |
+
corrcoef,
|
| 276 |
+
r2,
|
| 277 |
+
rmse,
|
| 278 |
+
)
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
if not os.path.isdir(self.params.model_dir):
|
| 282 |
+
os.makedirs(self.params.model_dir)
|
| 283 |
+
model_path = self.params.model_dir + "/epoch{}_corrcoef_{:.5f}_r2_{:.5f}_rmse_{:.5f}.pth".format(best_r2_epoch, corrcoef, r2, rmse)
|
| 284 |
+
torch.save(self.model.state_dict(), model_path)
|
| 285 |
+
print("model save in " + model_path)
|
external/CBraMod/models/__init__.py
ADDED
|
File without changes
|
external/CBraMod/models/cbramod.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
from models.criss_cross_transformer import TransformerEncoderLayer, TransformerEncoder
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class CBraMod(nn.Module):
|
| 9 |
+
def __init__(self, in_dim=200, out_dim=200, d_model=200, dim_feedforward=800, seq_len=30, n_layer=12,
|
| 10 |
+
nhead=8):
|
| 11 |
+
super().__init__()
|
| 12 |
+
self.patch_embedding = PatchEmbedding(in_dim, out_dim, d_model, seq_len)
|
| 13 |
+
encoder_layer = TransformerEncoderLayer(
|
| 14 |
+
d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, batch_first=True, norm_first=True,
|
| 15 |
+
activation=F.gelu
|
| 16 |
+
)
|
| 17 |
+
self.encoder = TransformerEncoder(encoder_layer, num_layers=n_layer, enable_nested_tensor=False)
|
| 18 |
+
self.proj_out = nn.Sequential(
|
| 19 |
+
# nn.Linear(d_model, d_model*2),
|
| 20 |
+
# nn.GELU(),
|
| 21 |
+
# nn.Linear(d_model*2, d_model),
|
| 22 |
+
# nn.GELU(),
|
| 23 |
+
nn.Linear(d_model, out_dim),
|
| 24 |
+
)
|
| 25 |
+
self.apply(_weights_init)
|
| 26 |
+
|
| 27 |
+
def forward(self, x, mask=None):
|
| 28 |
+
patch_emb = self.patch_embedding(x, mask)
|
| 29 |
+
feats = self.encoder(patch_emb)
|
| 30 |
+
|
| 31 |
+
out = self.proj_out(feats)
|
| 32 |
+
|
| 33 |
+
return out
|
| 34 |
+
|
| 35 |
+
class PatchEmbedding(nn.Module):
|
| 36 |
+
def __init__(self, in_dim, out_dim, d_model, seq_len):
|
| 37 |
+
super().__init__()
|
| 38 |
+
self.d_model = d_model
|
| 39 |
+
self.positional_encoding = nn.Sequential(
|
| 40 |
+
nn.Conv2d(in_channels=d_model, out_channels=d_model, kernel_size=(19, 7), stride=(1, 1), padding=(9, 3),
|
| 41 |
+
groups=d_model),
|
| 42 |
+
)
|
| 43 |
+
self.mask_encoding = nn.Parameter(torch.zeros(in_dim), requires_grad=False)
|
| 44 |
+
# self.mask_encoding = nn.Parameter(torch.randn(in_dim), requires_grad=True)
|
| 45 |
+
|
| 46 |
+
self.proj_in = nn.Sequential(
|
| 47 |
+
nn.Conv2d(in_channels=1, out_channels=25, kernel_size=(1, 49), stride=(1, 25), padding=(0, 24)),
|
| 48 |
+
nn.GroupNorm(5, 25),
|
| 49 |
+
nn.GELU(),
|
| 50 |
+
|
| 51 |
+
nn.Conv2d(in_channels=25, out_channels=25, kernel_size=(1, 3), stride=(1, 1), padding=(0, 1)),
|
| 52 |
+
nn.GroupNorm(5, 25),
|
| 53 |
+
nn.GELU(),
|
| 54 |
+
|
| 55 |
+
nn.Conv2d(in_channels=25, out_channels=25, kernel_size=(1, 3), stride=(1, 1), padding=(0, 1)),
|
| 56 |
+
nn.GroupNorm(5, 25),
|
| 57 |
+
nn.GELU(),
|
| 58 |
+
)
|
| 59 |
+
self.spectral_proj = nn.Sequential(
|
| 60 |
+
nn.Linear(101, d_model),
|
| 61 |
+
nn.Dropout(0.1),
|
| 62 |
+
# nn.LayerNorm(d_model, eps=1e-5),
|
| 63 |
+
)
|
| 64 |
+
# self.norm1 = nn.LayerNorm(d_model, eps=1e-5)
|
| 65 |
+
# self.norm2 = nn.LayerNorm(d_model, eps=1e-5)
|
| 66 |
+
# self.proj_in = nn.Sequential(
|
| 67 |
+
# nn.Linear(in_dim, d_model, bias=False),
|
| 68 |
+
# )
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def forward(self, x, mask=None):
|
| 72 |
+
bz, ch_num, patch_num, patch_size = x.shape
|
| 73 |
+
if mask == None:
|
| 74 |
+
mask_x = x
|
| 75 |
+
else:
|
| 76 |
+
mask_x = x.clone()
|
| 77 |
+
mask_x[mask == 1] = self.mask_encoding
|
| 78 |
+
|
| 79 |
+
mask_x = mask_x.contiguous().view(bz, 1, ch_num * patch_num, patch_size)
|
| 80 |
+
patch_emb = self.proj_in(mask_x)
|
| 81 |
+
patch_emb = patch_emb.permute(0, 2, 1, 3).contiguous().view(bz, ch_num, patch_num, self.d_model)
|
| 82 |
+
|
| 83 |
+
mask_x = mask_x.contiguous().view(bz*ch_num*patch_num, patch_size)
|
| 84 |
+
spectral = torch.fft.rfft(mask_x, dim=-1, norm='forward')
|
| 85 |
+
spectral = torch.abs(spectral).contiguous().view(bz, ch_num, patch_num, 101)
|
| 86 |
+
spectral_emb = self.spectral_proj(spectral)
|
| 87 |
+
# print(patch_emb[5, 5, 5, :])
|
| 88 |
+
# print(spectral_emb[5, 5, 5, :])
|
| 89 |
+
patch_emb = patch_emb + spectral_emb
|
| 90 |
+
|
| 91 |
+
positional_embedding = self.positional_encoding(patch_emb.permute(0, 3, 1, 2))
|
| 92 |
+
positional_embedding = positional_embedding.permute(0, 2, 3, 1)
|
| 93 |
+
|
| 94 |
+
patch_emb = patch_emb + positional_embedding
|
| 95 |
+
|
| 96 |
+
return patch_emb
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _weights_init(m):
|
| 100 |
+
if isinstance(m, nn.Linear):
|
| 101 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 102 |
+
if isinstance(m, nn.Conv1d):
|
| 103 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 104 |
+
elif isinstance(m, nn.BatchNorm1d):
|
| 105 |
+
nn.init.constant_(m.weight, 1)
|
| 106 |
+
nn.init.constant_(m.bias, 0)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
if __name__ == '__main__':
|
| 111 |
+
|
| 112 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 113 |
+
model = CBraMod(in_dim=200, out_dim=200, d_model=200, dim_feedforward=800, seq_len=30, n_layer=12,
|
| 114 |
+
nhead=8).to(device)
|
| 115 |
+
model.load_state_dict(torch.load('pretrained_weights/pretrained_weights.pth',
|
| 116 |
+
map_location=device))
|
| 117 |
+
a = torch.randn((8, 16, 10, 200)).cuda()
|
| 118 |
+
b = model(a)
|
| 119 |
+
print(a.shape, b.shape)
|
external/CBraMod/models/criss_cross_transformer.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from typing import Optional, Any, Union, Callable
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
# import torch.nn.functional as F
|
| 7 |
+
import warnings
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TransformerEncoder(nn.Module):
|
| 13 |
+
def __init__(self, encoder_layer, num_layers, norm=None, enable_nested_tensor=True, mask_check=True):
|
| 14 |
+
super().__init__()
|
| 15 |
+
torch._C._log_api_usage_once(f"torch.nn.modules.{self.__class__.__name__}")
|
| 16 |
+
self.layers = _get_clones(encoder_layer, num_layers)
|
| 17 |
+
self.num_layers = num_layers
|
| 18 |
+
self.norm = norm
|
| 19 |
+
|
| 20 |
+
def forward(
|
| 21 |
+
self,
|
| 22 |
+
src: Tensor,
|
| 23 |
+
mask: Optional[Tensor] = None,
|
| 24 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 25 |
+
is_causal: Optional[bool] = None) -> Tensor:
|
| 26 |
+
|
| 27 |
+
output = src
|
| 28 |
+
for mod in self.layers:
|
| 29 |
+
output = mod(output, src_mask=mask)
|
| 30 |
+
if self.norm is not None:
|
| 31 |
+
output = self.norm(output)
|
| 32 |
+
return output
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class TransformerEncoderLayer(nn.Module):
|
| 36 |
+
__constants__ = ['norm_first']
|
| 37 |
+
|
| 38 |
+
def __init__(self, d_model: int, nhead: int, dim_feedforward: int = 2048, dropout: float = 0.1,
|
| 39 |
+
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
|
| 40 |
+
layer_norm_eps: float = 1e-5, batch_first: bool = False, norm_first: bool = False,
|
| 41 |
+
bias: bool = True, device=None, dtype=None) -> None:
|
| 42 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.self_attn_s = nn.MultiheadAttention(d_model//2, nhead // 2, dropout=dropout,
|
| 45 |
+
bias=bias, batch_first=batch_first,
|
| 46 |
+
**factory_kwargs)
|
| 47 |
+
self.self_attn_t = nn.MultiheadAttention(d_model//2, nhead // 2, dropout=dropout,
|
| 48 |
+
bias=bias, batch_first=batch_first,
|
| 49 |
+
**factory_kwargs)
|
| 50 |
+
|
| 51 |
+
# Implementation of Feedforward model
|
| 52 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward, bias=bias, **factory_kwargs)
|
| 53 |
+
self.dropout = nn.Dropout(dropout)
|
| 54 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model, bias=bias, **factory_kwargs)
|
| 55 |
+
|
| 56 |
+
self.norm_first = norm_first
|
| 57 |
+
self.norm1 = nn.LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
|
| 58 |
+
self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
|
| 59 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 60 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 61 |
+
|
| 62 |
+
# Legacy string support for activation function.
|
| 63 |
+
if isinstance(activation, str):
|
| 64 |
+
activation = _get_activation_fn(activation)
|
| 65 |
+
|
| 66 |
+
# We can't test self.activation in forward() in TorchScript,
|
| 67 |
+
# so stash some information about it instead.
|
| 68 |
+
if activation is F.relu or isinstance(activation, torch.nn.ReLU):
|
| 69 |
+
self.activation_relu_or_gelu = 1
|
| 70 |
+
elif activation is F.gelu or isinstance(activation, torch.nn.GELU):
|
| 71 |
+
self.activation_relu_or_gelu = 2
|
| 72 |
+
else:
|
| 73 |
+
self.activation_relu_or_gelu = 0
|
| 74 |
+
self.activation = activation
|
| 75 |
+
|
| 76 |
+
def __setstate__(self, state):
|
| 77 |
+
super().__setstate__(state)
|
| 78 |
+
if not hasattr(self, 'activation'):
|
| 79 |
+
self.activation = F.relu
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def forward(
|
| 83 |
+
self,
|
| 84 |
+
src: Tensor,
|
| 85 |
+
src_mask: Optional[Tensor] = None,
|
| 86 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 87 |
+
is_causal: bool = False) -> Tensor:
|
| 88 |
+
|
| 89 |
+
x = src
|
| 90 |
+
x = x + self._sa_block(self.norm1(x), src_mask, src_key_padding_mask, is_causal=is_causal)
|
| 91 |
+
x = x + self._ff_block(self.norm2(x))
|
| 92 |
+
return x
|
| 93 |
+
|
| 94 |
+
# self-attention block
|
| 95 |
+
def _sa_block(self, x: Tensor,
|
| 96 |
+
attn_mask: Optional[Tensor], key_padding_mask: Optional[Tensor], is_causal: bool = False) -> Tensor:
|
| 97 |
+
bz, ch_num, patch_num, patch_size = x.shape
|
| 98 |
+
xs = x[:, :, :, :patch_size // 2]
|
| 99 |
+
xt = x[:, :, :, patch_size // 2:]
|
| 100 |
+
xs = xs.transpose(1, 2).contiguous().view(bz*patch_num, ch_num, patch_size // 2)
|
| 101 |
+
xt = xt.contiguous().view(bz*ch_num, patch_num, patch_size // 2)
|
| 102 |
+
xs = self.self_attn_s(xs, xs, xs,
|
| 103 |
+
attn_mask=attn_mask,
|
| 104 |
+
key_padding_mask=key_padding_mask,
|
| 105 |
+
need_weights=False)[0]
|
| 106 |
+
xs = xs.contiguous().view(bz, patch_num, ch_num, patch_size//2).transpose(1, 2)
|
| 107 |
+
xt = self.self_attn_t(xt, xt, xt,
|
| 108 |
+
attn_mask=attn_mask,
|
| 109 |
+
key_padding_mask=key_padding_mask,
|
| 110 |
+
need_weights=False)[0]
|
| 111 |
+
xt = xt.contiguous().view(bz, ch_num, patch_num, patch_size//2)
|
| 112 |
+
x = torch.concat((xs, xt), dim=3)
|
| 113 |
+
return self.dropout1(x)
|
| 114 |
+
|
| 115 |
+
# feed forward block
|
| 116 |
+
def _ff_block(self, x: Tensor) -> Tensor:
|
| 117 |
+
x = self.linear2(self.dropout(self.activation(self.linear1(x))))
|
| 118 |
+
return self.dropout2(x)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _get_activation_fn(activation: str) -> Callable[[Tensor], Tensor]:
|
| 123 |
+
if activation == "relu":
|
| 124 |
+
return F.relu
|
| 125 |
+
elif activation == "gelu":
|
| 126 |
+
return F.gelu
|
| 127 |
+
|
| 128 |
+
raise RuntimeError(f"activation should be relu/gelu, not {activation}")
|
| 129 |
+
|
| 130 |
+
def _get_clones(module, N):
|
| 131 |
+
# FIXME: copy.deepcopy() is not defined on nn.module
|
| 132 |
+
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _get_seq_len(
|
| 136 |
+
src: Tensor,
|
| 137 |
+
batch_first: bool
|
| 138 |
+
) -> Optional[int]:
|
| 139 |
+
|
| 140 |
+
if src.is_nested:
|
| 141 |
+
return None
|
| 142 |
+
else:
|
| 143 |
+
src_size = src.size()
|
| 144 |
+
if len(src_size) == 2:
|
| 145 |
+
# unbatched: S, E
|
| 146 |
+
return src_size[0]
|
| 147 |
+
else:
|
| 148 |
+
# batched: B, S, E if batch_first else S, B, E
|
| 149 |
+
seq_len_pos = 1 if batch_first else 0
|
| 150 |
+
return src_size[seq_len_pos]
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _detect_is_causal_mask(
|
| 154 |
+
mask: Optional[Tensor],
|
| 155 |
+
is_causal: Optional[bool] = None,
|
| 156 |
+
size: Optional[int] = None,
|
| 157 |
+
) -> bool:
|
| 158 |
+
"""Return whether the given attention mask is causal.
|
| 159 |
+
|
| 160 |
+
Warning:
|
| 161 |
+
If ``is_causal`` is not ``None``, its value will be returned as is. If a
|
| 162 |
+
user supplies an incorrect ``is_causal`` hint,
|
| 163 |
+
|
| 164 |
+
``is_causal=False`` when the mask is in fact a causal attention.mask
|
| 165 |
+
may lead to reduced performance relative to what would be achievable
|
| 166 |
+
with ``is_causal=True``;
|
| 167 |
+
``is_causal=True`` when the mask is in fact not a causal attention.mask
|
| 168 |
+
may lead to incorrect and unpredictable execution - in some scenarios,
|
| 169 |
+
a causal mask may be applied based on the hint, in other execution
|
| 170 |
+
scenarios the specified mask may be used. The choice may not appear
|
| 171 |
+
to be deterministic, in that a number of factors like alignment,
|
| 172 |
+
hardware SKU, etc influence the decision whether to use a mask or
|
| 173 |
+
rely on the hint.
|
| 174 |
+
``size`` if not None, check whether the mask is a causal mask of the provided size
|
| 175 |
+
Otherwise, checks for any causal mask.
|
| 176 |
+
"""
|
| 177 |
+
# Prevent type refinement
|
| 178 |
+
make_causal = (is_causal is True)
|
| 179 |
+
|
| 180 |
+
if is_causal is None and mask is not None:
|
| 181 |
+
sz = size if size is not None else mask.size(-2)
|
| 182 |
+
causal_comparison = _generate_square_subsequent_mask(
|
| 183 |
+
sz, device=mask.device, dtype=mask.dtype)
|
| 184 |
+
|
| 185 |
+
# Do not use `torch.equal` so we handle batched masks by
|
| 186 |
+
# broadcasting the comparison.
|
| 187 |
+
if mask.size() == causal_comparison.size():
|
| 188 |
+
make_causal = bool((mask == causal_comparison).all())
|
| 189 |
+
else:
|
| 190 |
+
make_causal = False
|
| 191 |
+
|
| 192 |
+
return make_causal
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _generate_square_subsequent_mask(
|
| 196 |
+
sz: int,
|
| 197 |
+
device: torch.device = torch.device(torch._C._get_default_device()), # torch.device('cpu'),
|
| 198 |
+
dtype: torch.dtype = torch.get_default_dtype(),
|
| 199 |
+
) -> Tensor:
|
| 200 |
+
r"""Generate a square causal mask for the sequence. The masked positions are filled with float('-inf').
|
| 201 |
+
Unmasked positions are filled with float(0.0).
|
| 202 |
+
"""
|
| 203 |
+
return torch.triu(
|
| 204 |
+
torch.full((sz, sz), float('-inf'), dtype=dtype, device=device),
|
| 205 |
+
diagonal=1,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
if __name__ == '__main__':
|
| 210 |
+
encoder_layer = TransformerEncoderLayer(
|
| 211 |
+
d_model=256, nhead=4, dim_feedforward=1024, batch_first=True, norm_first=True,
|
| 212 |
+
activation=F.gelu
|
| 213 |
+
)
|
| 214 |
+
encoder = TransformerEncoder(encoder_layer, num_layers=2, enable_nested_tensor=False)
|
| 215 |
+
encoder = encoder.cuda()
|
| 216 |
+
|
| 217 |
+
a = torch.randn((4, 19, 30, 256)).cuda()
|
| 218 |
+
b = encoder(a)
|
| 219 |
+
print(a.shape, b.shape)
|
external/CBraMod/models/model_for_bciciv2a.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
from .cbramod import CBraMod
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Model(nn.Module):
|
| 8 |
+
def __init__(self, param):
|
| 9 |
+
super(Model, self).__init__()
|
| 10 |
+
self.backbone = CBraMod(
|
| 11 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 12 |
+
dim_feedforward=800, seq_len=30,
|
| 13 |
+
n_layer=12, nhead=8
|
| 14 |
+
)
|
| 15 |
+
if param.use_pretrained_weights:
|
| 16 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 17 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 18 |
+
self.backbone.proj_out = nn.Identity()
|
| 19 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 20 |
+
self.classifier = nn.Sequential(
|
| 21 |
+
Rearrange('b c s d -> b d c s'),
|
| 22 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 23 |
+
nn.Flatten(),
|
| 24 |
+
nn.Linear(200, param.num_of_classes),
|
| 25 |
+
)
|
| 26 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 27 |
+
self.classifier = nn.Sequential(
|
| 28 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 29 |
+
nn.Linear(22 * 4 * 200, param.num_of_classes),
|
| 30 |
+
)
|
| 31 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 32 |
+
self.classifier = nn.Sequential(
|
| 33 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 34 |
+
nn.Linear(22 * 4 * 200, 200),
|
| 35 |
+
nn.ELU(),
|
| 36 |
+
nn.Dropout(param.dropout),
|
| 37 |
+
nn.Linear(200, param.num_of_classes),
|
| 38 |
+
)
|
| 39 |
+
elif param.classifier == 'all_patch_reps':
|
| 40 |
+
self.classifier = nn.Sequential(
|
| 41 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 42 |
+
nn.Linear(22 * 4 * 200, 4 * 200),
|
| 43 |
+
nn.ELU(),
|
| 44 |
+
nn.Dropout(param.dropout),
|
| 45 |
+
nn.Linear(4 * 200, 200),
|
| 46 |
+
nn.ELU(),
|
| 47 |
+
nn.Dropout(param.dropout),
|
| 48 |
+
nn.Linear(200, param.num_of_classes),
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def forward(self, x):
|
| 52 |
+
# x = x / 100
|
| 53 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 54 |
+
feats = self.backbone(x)
|
| 55 |
+
out = self.classifier(feats)
|
| 56 |
+
return out
|
external/CBraMod/models/model_for_chb.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
from .cbramod import CBraMod
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Model(nn.Module):
|
| 8 |
+
def __init__(self, param):
|
| 9 |
+
super(Model, self).__init__()
|
| 10 |
+
self.backbone = CBraMod(
|
| 11 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 12 |
+
dim_feedforward=800, seq_len=30,
|
| 13 |
+
n_layer=12, nhead=8
|
| 14 |
+
)
|
| 15 |
+
if param.use_pretrained_weights:
|
| 16 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 17 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 18 |
+
self.backbone.proj_out = nn.Identity()
|
| 19 |
+
|
| 20 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 21 |
+
self.classifier = nn.Sequential(
|
| 22 |
+
Rearrange('b c s d -> b d c s'),
|
| 23 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 24 |
+
nn.Flatten(),
|
| 25 |
+
nn.Linear(200, 1),
|
| 26 |
+
Rearrange('b 1 -> (b 1)'),
|
| 27 |
+
)
|
| 28 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 29 |
+
self.classifier = nn.Sequential(
|
| 30 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 31 |
+
nn.Linear(16*10*200, 1),
|
| 32 |
+
Rearrange('b 1 -> (b 1)'),
|
| 33 |
+
)
|
| 34 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 35 |
+
self.classifier = nn.Sequential(
|
| 36 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 37 |
+
nn.Linear(16*10*200, 200),
|
| 38 |
+
nn.ELU(),
|
| 39 |
+
nn.Dropout(param.dropout),
|
| 40 |
+
nn.Linear(200, 1),
|
| 41 |
+
Rearrange('b 1 -> (b 1)'),
|
| 42 |
+
)
|
| 43 |
+
elif param.classifier == 'all_patch_reps':
|
| 44 |
+
self.classifier = nn.Sequential(
|
| 45 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 46 |
+
nn.Linear(16*10*200, 10*200),
|
| 47 |
+
nn.ELU(),
|
| 48 |
+
nn.Dropout(param.dropout),
|
| 49 |
+
nn.Linear(10*200, 200),
|
| 50 |
+
nn.ELU(),
|
| 51 |
+
nn.Dropout(param.dropout),
|
| 52 |
+
nn.Linear(200, 1),
|
| 53 |
+
Rearrange('b 1 -> (b 1)'),
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 58 |
+
feats = self.backbone(x)
|
| 59 |
+
out = self.classifier(feats)
|
| 60 |
+
return out
|
external/CBraMod/models/model_for_faced.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
if param.use_pretrained_weights:
|
| 18 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 19 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 20 |
+
self.backbone.proj_out = nn.Identity()
|
| 21 |
+
|
| 22 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 23 |
+
self.classifier = nn.Sequential(
|
| 24 |
+
Rearrange('b c s d -> b d c s'),
|
| 25 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 26 |
+
nn.Flatten(),
|
| 27 |
+
nn.Linear(200, param.num_of_classes),
|
| 28 |
+
)
|
| 29 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 30 |
+
self.classifier = nn.Sequential(
|
| 31 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 32 |
+
nn.Linear(32 * 10 * 200, param.num_of_classes),
|
| 33 |
+
)
|
| 34 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 35 |
+
self.classifier = nn.Sequential(
|
| 36 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 37 |
+
nn.Linear(32 * 10 * 200, 200),
|
| 38 |
+
nn.ELU(),
|
| 39 |
+
nn.Dropout(param.dropout),
|
| 40 |
+
nn.Linear(200, param.num_of_classes),
|
| 41 |
+
)
|
| 42 |
+
elif param.classifier == 'all_patch_reps':
|
| 43 |
+
self.classifier = nn.Sequential(
|
| 44 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 45 |
+
nn.Linear(32 * 10 * 200, 10 * 200),
|
| 46 |
+
nn.ELU(),
|
| 47 |
+
nn.Dropout(param.dropout),
|
| 48 |
+
nn.Linear(10 * 200, 200),
|
| 49 |
+
nn.ELU(),
|
| 50 |
+
nn.Dropout(param.dropout),
|
| 51 |
+
nn.Linear(200, param.num_of_classes),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def forward(self, x):
|
| 55 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 56 |
+
feats = self.backbone(x)
|
| 57 |
+
out = self.classifier(feats)
|
| 58 |
+
return out
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
|
external/CBraMod/models/model_for_isruc.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
|
| 21 |
+
self.head = nn.Sequential(
|
| 22 |
+
nn.Linear(6*30*200, 512),
|
| 23 |
+
nn.GELU(),
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
encoder_layer = nn.TransformerEncoderLayer(
|
| 27 |
+
d_model=512, nhead=4, dim_feedforward=2048, batch_first=True, activation=F.gelu, norm_first=True
|
| 28 |
+
)
|
| 29 |
+
self.sequence_encoder = nn.TransformerEncoder(encoder_layer, num_layers=1, enable_nested_tensor=False)
|
| 30 |
+
self.classifier = nn.Linear(512, param.num_of_classes)
|
| 31 |
+
|
| 32 |
+
# self.apply(_weights_init)
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
bz, seq_len, ch_num, epoch_size = x.shape
|
| 36 |
+
|
| 37 |
+
x = x.contiguous().view(bz * seq_len, ch_num, 30, 200)
|
| 38 |
+
epoch_features = self.backbone(x)
|
| 39 |
+
epoch_features = epoch_features.contiguous().view(bz, seq_len, ch_num*30*200)
|
| 40 |
+
epoch_features = self.head(epoch_features)
|
| 41 |
+
seq_features = self.sequence_encoder(epoch_features)
|
| 42 |
+
out = self.classifier(seq_features)
|
| 43 |
+
return out
|
external/CBraMod/models/model_for_mumtaz.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 21 |
+
self.classifier = nn.Sequential(
|
| 22 |
+
Rearrange('b c s d -> b d c s'),
|
| 23 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 24 |
+
nn.Flatten(),
|
| 25 |
+
nn.Linear(200, 1),
|
| 26 |
+
Rearrange('b 1 -> (b 1)'),
|
| 27 |
+
)
|
| 28 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 29 |
+
self.classifier = nn.Sequential(
|
| 30 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 31 |
+
nn.Linear(19 * 5 * 200, 1),
|
| 32 |
+
Rearrange('b 1 -> (b 1)'),
|
| 33 |
+
)
|
| 34 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 35 |
+
self.classifier = nn.Sequential(
|
| 36 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 37 |
+
nn.Linear(19 * 5 * 200, 200),
|
| 38 |
+
nn.ELU(),
|
| 39 |
+
nn.Dropout(param.dropout),
|
| 40 |
+
nn.Linear(200, 1),
|
| 41 |
+
Rearrange('b 1 -> (b 1)'),
|
| 42 |
+
)
|
| 43 |
+
elif param.classifier == 'all_patch_reps':
|
| 44 |
+
self.classifier = nn.Sequential(
|
| 45 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 46 |
+
nn.Linear(19 * 5 * 200, 5 * 200),
|
| 47 |
+
nn.ELU(),
|
| 48 |
+
nn.Dropout(param.dropout),
|
| 49 |
+
nn.Linear(5 * 200, 200),
|
| 50 |
+
nn.ELU(),
|
| 51 |
+
nn.Dropout(param.dropout),
|
| 52 |
+
nn.Linear(200, 1),
|
| 53 |
+
Rearrange('b 1 -> (b 1)'),
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 58 |
+
feats = self.backbone(x)
|
| 59 |
+
out = self.classifier(feats)
|
| 60 |
+
return out
|
external/CBraMod/models/model_for_physio.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 21 |
+
self.classifier = nn.Sequential(
|
| 22 |
+
Rearrange('b c s d -> b d c s'),
|
| 23 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 24 |
+
nn.Flatten(),
|
| 25 |
+
nn.Linear(200, param.num_of_classes),
|
| 26 |
+
)
|
| 27 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 28 |
+
self.classifier = nn.Sequential(
|
| 29 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 30 |
+
nn.Linear(64 * 4 * 200, param.num_of_classes),
|
| 31 |
+
)
|
| 32 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 33 |
+
self.classifier = nn.Sequential(
|
| 34 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 35 |
+
nn.Linear(64 * 4 * 200, 200),
|
| 36 |
+
nn.ELU(),
|
| 37 |
+
nn.Dropout(param.dropout),
|
| 38 |
+
nn.Linear(200, param.num_of_classes),
|
| 39 |
+
)
|
| 40 |
+
elif param.classifier == 'all_patch_reps':
|
| 41 |
+
self.classifier = nn.Sequential(
|
| 42 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 43 |
+
nn.Linear(64 * 4 * 200, 4 * 200),
|
| 44 |
+
nn.ELU(),
|
| 45 |
+
nn.Dropout(param.dropout),
|
| 46 |
+
nn.Linear(4 * 200, 200),
|
| 47 |
+
nn.ELU(),
|
| 48 |
+
nn.Dropout(param.dropout),
|
| 49 |
+
nn.Linear(200, param.num_of_classes),
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 55 |
+
feats = self.backbone(x)
|
| 56 |
+
out = self.classifier(feats)
|
| 57 |
+
return out
|
external/CBraMod/models/model_for_seedv.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 21 |
+
self.classifier = nn.Sequential(
|
| 22 |
+
Rearrange('b c s d -> b d c s'),
|
| 23 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 24 |
+
nn.Flatten(),
|
| 25 |
+
nn.Linear(200, param.num_of_classes),
|
| 26 |
+
)
|
| 27 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 28 |
+
self.classifier = nn.Sequential(
|
| 29 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 30 |
+
nn.Linear(62 * 1 * 200, param.num_of_classes),
|
| 31 |
+
)
|
| 32 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 33 |
+
self.classifier = nn.Sequential(
|
| 34 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 35 |
+
nn.Linear(62 * 1 * 200, 200),
|
| 36 |
+
nn.ELU(),
|
| 37 |
+
nn.Dropout(param.dropout),
|
| 38 |
+
nn.Linear(200, param.num_of_classes),
|
| 39 |
+
)
|
| 40 |
+
elif param.classifier == 'all_patch_reps':
|
| 41 |
+
self.classifier = nn.Sequential(
|
| 42 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 43 |
+
nn.Linear(62 * 1 * 200, 4 * 200),
|
| 44 |
+
nn.ELU(),
|
| 45 |
+
nn.Dropout(param.dropout),
|
| 46 |
+
nn.Linear(4 * 200, 200),
|
| 47 |
+
nn.ELU(),
|
| 48 |
+
nn.Dropout(param.dropout),
|
| 49 |
+
nn.Linear(200, param.num_of_classes),
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
# x = x / 100
|
| 54 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 55 |
+
feats = self.backbone(x)
|
| 56 |
+
feats = feats.contiguous().view(bz, ch_num*seq_len*200)
|
| 57 |
+
out = self.classifier(feats)
|
| 58 |
+
return out
|
external/CBraMod/models/model_for_seedvig.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 21 |
+
self.classifier = nn.Sequential(
|
| 22 |
+
Rearrange('b c s d -> b d c s'),
|
| 23 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 24 |
+
nn.Flatten(),
|
| 25 |
+
nn.Linear(200, 1),
|
| 26 |
+
Rearrange('b 1 -> (b 1)'),
|
| 27 |
+
)
|
| 28 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 29 |
+
self.classifier = nn.Sequential(
|
| 30 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 31 |
+
nn.Linear(17 * 8 * 200, 1),
|
| 32 |
+
Rearrange('b 1 -> (b 1)'),
|
| 33 |
+
)
|
| 34 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 35 |
+
self.classifier = nn.Sequential(
|
| 36 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 37 |
+
nn.Linear(17 * 8 * 200, 200),
|
| 38 |
+
nn.ELU(),
|
| 39 |
+
nn.Dropout(param.dropout),
|
| 40 |
+
nn.Linear(200, 1),
|
| 41 |
+
Rearrange('b 1 -> (b 1)'),
|
| 42 |
+
)
|
| 43 |
+
elif param.classifier == 'all_patch_reps':
|
| 44 |
+
self.classifier = nn.Sequential(
|
| 45 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 46 |
+
nn.Linear(17 * 8 * 200, 8 * 200),
|
| 47 |
+
nn.ELU(),
|
| 48 |
+
nn.Dropout(param.dropout),
|
| 49 |
+
nn.Linear(8 * 200, 200),
|
| 50 |
+
nn.ELU(),
|
| 51 |
+
nn.Dropout(param.dropout),
|
| 52 |
+
nn.Linear(200, 1),
|
| 53 |
+
Rearrange('b 1 -> (b 1)'),
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 58 |
+
feats = self.backbone(x)
|
| 59 |
+
out = self.classifier(feats)
|
| 60 |
+
return out
|
| 61 |
+
|
external/CBraMod/models/model_for_shu.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 21 |
+
self.classifier = nn.Sequential(
|
| 22 |
+
Rearrange('b c s d -> b d c s'),
|
| 23 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 24 |
+
nn.Flatten(),
|
| 25 |
+
nn.Linear(200, 1),
|
| 26 |
+
Rearrange('b 1 -> (b 1)'),
|
| 27 |
+
)
|
| 28 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 29 |
+
self.classifier = nn.Sequential(
|
| 30 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 31 |
+
nn.Linear(32 * 4 * 200, 1),
|
| 32 |
+
Rearrange('b 1 -> (b 1)'),
|
| 33 |
+
)
|
| 34 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 35 |
+
self.classifier = nn.Sequential(
|
| 36 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 37 |
+
nn.Linear(32 * 4 * 200, 200),
|
| 38 |
+
nn.ELU(),
|
| 39 |
+
nn.Dropout(param.dropout),
|
| 40 |
+
nn.Linear(200, 1),
|
| 41 |
+
Rearrange('b 1 -> (b 1)'),
|
| 42 |
+
)
|
| 43 |
+
elif param.classifier == 'all_patch_reps':
|
| 44 |
+
self.classifier = nn.Sequential(
|
| 45 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 46 |
+
nn.Linear(32 * 4 * 200, 4 * 200),
|
| 47 |
+
nn.ELU(),
|
| 48 |
+
nn.Dropout(param.dropout),
|
| 49 |
+
nn.Linear(4 * 200, 200),
|
| 50 |
+
nn.ELU(),
|
| 51 |
+
nn.Dropout(param.dropout),
|
| 52 |
+
nn.Linear(200, 1),
|
| 53 |
+
Rearrange('b 1 -> (b 1)'),
|
| 54 |
+
)
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 57 |
+
feats = self.backbone(x)
|
| 58 |
+
out = self.classifier(feats)
|
| 59 |
+
return out
|
| 60 |
+
|
| 61 |
+
|
external/CBraMod/models/model_for_speech.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 21 |
+
self.classifier = nn.Sequential(
|
| 22 |
+
Rearrange('b c s d -> b d c s'),
|
| 23 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 24 |
+
nn.Flatten(),
|
| 25 |
+
nn.Linear(200, param.num_of_classes)
|
| 26 |
+
)
|
| 27 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 28 |
+
self.classifier = nn.Sequential(
|
| 29 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 30 |
+
nn.Linear(64*3*200, param.num_of_classes),
|
| 31 |
+
)
|
| 32 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 33 |
+
self.classifier = nn.Sequential(
|
| 34 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 35 |
+
nn.Linear(64*3*200, 200),
|
| 36 |
+
nn.ELU(),
|
| 37 |
+
nn.Dropout(param.dropout),
|
| 38 |
+
nn.Linear(200, param.num_of_classes),
|
| 39 |
+
)
|
| 40 |
+
elif param.classifier == 'all_patch_reps':
|
| 41 |
+
self.classifier = nn.Sequential(
|
| 42 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 43 |
+
nn.Linear(64*3*200, 3*200),
|
| 44 |
+
nn.ELU(),
|
| 45 |
+
nn.Dropout(param.dropout),
|
| 46 |
+
nn.Linear(3*200, 200),
|
| 47 |
+
nn.ELU(),
|
| 48 |
+
nn.Dropout(param.dropout),
|
| 49 |
+
nn.Linear(200, param.num_of_classes),
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 54 |
+
feats = self.backbone(x)
|
| 55 |
+
out = self.classifier(feats)
|
| 56 |
+
return out
|
| 57 |
+
|
external/CBraMod/models/model_for_stress.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
class Model(nn.Module):
|
| 8 |
+
def __init__(self, param):
|
| 9 |
+
super(Model, self).__init__()
|
| 10 |
+
self.backbone = CBraMod(
|
| 11 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 12 |
+
dim_feedforward=800, seq_len=30,
|
| 13 |
+
n_layer=12, nhead=8
|
| 14 |
+
)
|
| 15 |
+
if param.use_pretrained_weights:
|
| 16 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 17 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 18 |
+
self.backbone.proj_out = nn.Identity()
|
| 19 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 20 |
+
self.classifier = nn.Sequential(
|
| 21 |
+
Rearrange('b c s d -> b d c s'),
|
| 22 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 23 |
+
nn.Flatten(),
|
| 24 |
+
nn.Linear(200, 1),
|
| 25 |
+
Rearrange('b 1 -> (b 1)'),
|
| 26 |
+
)
|
| 27 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 28 |
+
self.classifier = nn.Sequential(
|
| 29 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 30 |
+
nn.Linear(20 * 5 * 200, 1),
|
| 31 |
+
Rearrange('b 1 -> (b 1)'),
|
| 32 |
+
)
|
| 33 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 34 |
+
self.classifier = nn.Sequential(
|
| 35 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 36 |
+
nn.Linear(20 * 5 * 200, 200),
|
| 37 |
+
nn.ELU(),
|
| 38 |
+
nn.Dropout(param.dropout),
|
| 39 |
+
nn.Linear(200, 1),
|
| 40 |
+
Rearrange('b 1 -> (b 1)'),
|
| 41 |
+
)
|
| 42 |
+
elif param.classifier == 'all_patch_reps':
|
| 43 |
+
self.classifier = nn.Sequential(
|
| 44 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 45 |
+
nn.Linear(20 * 5 * 200, 5 * 200),
|
| 46 |
+
nn.ELU(),
|
| 47 |
+
nn.Dropout(param.dropout),
|
| 48 |
+
nn.Linear(5 * 200, 200),
|
| 49 |
+
nn.ELU(),
|
| 50 |
+
nn.Dropout(param.dropout),
|
| 51 |
+
nn.Linear(200, 1),
|
| 52 |
+
Rearrange('b 1 -> (b 1)'),
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 57 |
+
feats = self.backbone(x)
|
| 58 |
+
out = self.classifier(feats)
|
| 59 |
+
return out
|
| 60 |
+
|
external/CBraMod/models/model_for_tuab.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 21 |
+
self.classifier = nn.Sequential(
|
| 22 |
+
Rearrange('b c s d -> b d c s'),
|
| 23 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 24 |
+
nn.Flatten(),
|
| 25 |
+
nn.Linear(200, 1),
|
| 26 |
+
Rearrange('b 1 -> (b 1)'),
|
| 27 |
+
)
|
| 28 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 29 |
+
self.classifier = nn.Sequential(
|
| 30 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 31 |
+
nn.Linear(16 * 10 * 200, 1),
|
| 32 |
+
Rearrange('b 1 -> (b 1)'),
|
| 33 |
+
)
|
| 34 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 35 |
+
self.classifier = nn.Sequential(
|
| 36 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 37 |
+
nn.Linear(16 * 10 * 200, 200),
|
| 38 |
+
nn.ELU(),
|
| 39 |
+
nn.Dropout(param.dropout),
|
| 40 |
+
nn.Linear(200, 1),
|
| 41 |
+
Rearrange('b 1 -> (b 1)'),
|
| 42 |
+
)
|
| 43 |
+
elif param.classifier == 'all_patch_reps':
|
| 44 |
+
self.classifier = nn.Sequential(
|
| 45 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 46 |
+
nn.Linear(16 * 10 * 200, 10 * 200),
|
| 47 |
+
nn.ELU(),
|
| 48 |
+
nn.Dropout(param.dropout),
|
| 49 |
+
nn.Linear(10 * 200, 200),
|
| 50 |
+
nn.ELU(),
|
| 51 |
+
nn.Dropout(param.dropout),
|
| 52 |
+
nn.Linear(200, 1),
|
| 53 |
+
Rearrange('b 1 -> (b 1)'),
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 58 |
+
feats = self.backbone(x)
|
| 59 |
+
out = self.classifier(feats)
|
| 60 |
+
return out
|
external/CBraMod/models/model_for_tuev.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops.layers.torch import Rearrange
|
| 4 |
+
|
| 5 |
+
from .cbramod import CBraMod
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Model(nn.Module):
|
| 9 |
+
def __init__(self, param):
|
| 10 |
+
super(Model, self).__init__()
|
| 11 |
+
self.backbone = CBraMod(
|
| 12 |
+
in_dim=200, out_dim=200, d_model=200,
|
| 13 |
+
dim_feedforward=800, seq_len=30,
|
| 14 |
+
n_layer=12, nhead=8
|
| 15 |
+
)
|
| 16 |
+
if param.use_pretrained_weights:
|
| 17 |
+
map_location = torch.device(f'cuda:{param.cuda}')
|
| 18 |
+
self.backbone.load_state_dict(torch.load(param.foundation_dir, map_location=map_location))
|
| 19 |
+
self.backbone.proj_out = nn.Identity()
|
| 20 |
+
|
| 21 |
+
if param.classifier == 'avgpooling_patch_reps':
|
| 22 |
+
self.classifier = nn.Sequential(
|
| 23 |
+
Rearrange('b c s d -> b d c s'),
|
| 24 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 25 |
+
nn.Flatten(),
|
| 26 |
+
nn.Linear(200, param.num_of_classes),
|
| 27 |
+
)
|
| 28 |
+
elif param.classifier == 'all_patch_reps_onelayer':
|
| 29 |
+
self.classifier = nn.Sequential(
|
| 30 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 31 |
+
nn.Linear(16 * 5 * 200, param.num_of_classes),
|
| 32 |
+
)
|
| 33 |
+
elif param.classifier == 'all_patch_reps_twolayer':
|
| 34 |
+
self.classifier = nn.Sequential(
|
| 35 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 36 |
+
nn.Linear(16 * 5 * 200, 200),
|
| 37 |
+
nn.ELU(),
|
| 38 |
+
nn.Dropout(param.dropout),
|
| 39 |
+
nn.Linear(200, param.num_of_classes),
|
| 40 |
+
)
|
| 41 |
+
elif param.classifier == 'all_patch_reps':
|
| 42 |
+
self.classifier = nn.Sequential(
|
| 43 |
+
Rearrange('b c s d -> b (c s d)'),
|
| 44 |
+
nn.Linear(16 * 5 * 200, 5 * 200),
|
| 45 |
+
nn.ELU(),
|
| 46 |
+
nn.Dropout(param.dropout),
|
| 47 |
+
nn.Linear(5 * 200, 200),
|
| 48 |
+
nn.ELU(),
|
| 49 |
+
nn.Dropout(param.dropout),
|
| 50 |
+
nn.Linear(200, param.num_of_classes),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
bz, ch_num, seq_len, patch_size = x.shape
|
| 55 |
+
feats = self.backbone(x)
|
| 56 |
+
out = self.classifier(feats)
|
| 57 |
+
return out
|
| 58 |
+
|
external/CBraMod/preprocessing/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dataset Preprocessing README
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
## 🔥 June 2, 2025 Update for TUAB and TUEV
|
| 5 |
+
|
| 6 |
+
The previous preprocessing code for the **TUAB** and **TUEV** datasets was inherited from the [BIOT](https://github.com/ycq091044/BIOT) and [LaBraM](https://github.com/935963004/LaBraM) repositories. These original implementations included **random elements** in the data splitting process. Even with fixed random seeds, different hardware environments could lead to **inconsistent Train/Val/Test splits**. This issue has been carried forward into **CBraMod**.
|
| 7 |
+
|
| 8 |
+
In the performance comparison presented in the **CBraMod paper**, I directly cited the results reported in the **BIOT** and **LaBraM** papers without having access to their exact dataset splits. Therefore, I cannot guarantee that the comparisons were made using the **same dataset partitions**. As a result, the evaluation may **not be entirely fair**.
|
| 9 |
+
|
| 10 |
+
Moreover, others may also be unable to reproduce a **fair comparison** with **CBraMod** on **TUAB** and **TUEV** under the same conditions.
|
| 11 |
+
|
| 12 |
+
To fully address this issue, I have updated the preprocessing code for **TUAB** and **TUEV** to ensure **fixed, deterministic dataset splits**. If you are conducting experiments on these two datasets, please use the **latest version of the preprocessing code** to generate the splits.
|
| 13 |
+
|
| 14 |
+
For accurate and fair comparisons, it is **strongly recommended** to re-implement existing methods such as **BIOT**, **LaBraM**, and **CBraMod** **on the same fixed splits**.
|
| 15 |
+
|
| 16 |
+
> ⚠️ **Please note**: The **TUAB version** used in our experiments is **3.0.1**, and the **TUEV version** is **2.0.0**. Updates to the datasets may result in changes to the total number of samples.
|
| 17 |
+
>
|
| 18 |
+
> 📌 If you are using **different versions** of these datasets, **do not refer to our sample counts**. Instead, **reproduce the results directly on your own data splits**.
|
| 19 |
+
>
|
| 20 |
+
> ✅ We also provide **dataset splits** for **TUEV v2.0.1**. Please refer to the sample counts below for details.
|
| 21 |
+
|
| 22 |
+
### 📊 Current Sample Counts (Updated Preprocessing)
|
| 23 |
+
|
| 24 |
+
#### **TUAB (v3.0.1):**
|
| 25 |
+
- **Train:** 297,103
|
| 26 |
+
- **Validation:** 75,407
|
| 27 |
+
- **Test:** 36,945
|
| 28 |
+
- **Total:** 409,455
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
#### **TUEV (v2.0.0):**
|
| 32 |
+
- **Train:** 67,436
|
| 33 |
+
- **Validation:** 15,634
|
| 34 |
+
- **Test:** 29,421
|
| 35 |
+
- **Total:** 112,491
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
#### **TUEV (v2.0.1):**
|
| 39 |
+
- **Train:** 68,445
|
| 40 |
+
- **Validation:** 15,487
|
| 41 |
+
- **Test:** 29,421
|
| 42 |
+
- **Total:** 113,353
|
external/CBraMod/preprocessing/__init__.py
ADDED
|
File without changes
|
external/CBraMod/pretrain_main.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import random
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from torch.utils.data import DataLoader
|
| 6 |
+
|
| 7 |
+
from datasets.pretraining_dataset import PretrainingDataset
|
| 8 |
+
from models.cbramod import CBraMod
|
| 9 |
+
from pretrain_trainer import Trainer
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def setup_seed(seed):
|
| 13 |
+
torch.manual_seed(seed)
|
| 14 |
+
torch.cuda.manual_seed_all(seed)
|
| 15 |
+
np.random.seed(seed)
|
| 16 |
+
random.seed(seed)
|
| 17 |
+
torch.backends.cudnn.deterministic = True
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def main():
|
| 21 |
+
parser = argparse.ArgumentParser(description='EEG Foundation Model')
|
| 22 |
+
parser.add_argument('--seed', type=int, default=42, help='random seed (default: 0)')
|
| 23 |
+
parser.add_argument('--cuda', type=int, default=3, help='cuda number (default: 1)')
|
| 24 |
+
parser.add_argument('--parallel', type=bool, default=False, help='parallel')
|
| 25 |
+
parser.add_argument('--epochs', type=int, default=40, help='number of epochs (default: 5)')
|
| 26 |
+
parser.add_argument('--batch_size', type=int, default=128, help='batch size for training (default: 32)')
|
| 27 |
+
parser.add_argument('--lr', type=float, default=5e-4, help='learning rate (default: 1e-3)')
|
| 28 |
+
parser.add_argument('--weight_decay', type=float, default=5e-2, help='weight_decay')
|
| 29 |
+
parser.add_argument('--clip_value', type=float, default=1, help='clip_value')
|
| 30 |
+
parser.add_argument('--lr_scheduler', type=str, default='CosineAnnealingLR',
|
| 31 |
+
help='lr_scheduler: CosineAnnealingLR, ExponentialLR, StepLR, MultiStepLR, CyclicLR')
|
| 32 |
+
|
| 33 |
+
# parser.add_argument('--project_mode', type=str, default='cnn', help='project_mode')
|
| 34 |
+
parser.add_argument('--dropout', type=float, default=0.1, help='dropout')
|
| 35 |
+
parser.add_argument('--in_dim', type=int, default=200, help='in_dim')
|
| 36 |
+
parser.add_argument('--out_dim', type=int, default=200, help='out_dim')
|
| 37 |
+
parser.add_argument('--d_model', type=int, default=200, help='d_model')
|
| 38 |
+
parser.add_argument('--dim_feedforward', type=int, default=800, help='dim_feedforward')
|
| 39 |
+
parser.add_argument('--seq_len', type=int, default=30, help='seq_len')
|
| 40 |
+
parser.add_argument('--n_layer', type=int, default=12, help='n_layer')
|
| 41 |
+
parser.add_argument('--nhead', type=int, default=8, help='nhead')
|
| 42 |
+
parser.add_argument('--need_mask', type=bool, default=True, help='need_mask')
|
| 43 |
+
parser.add_argument('--mask_ratio', type=float, default=0.5, help='mask_ratio')
|
| 44 |
+
|
| 45 |
+
parser.add_argument('--dataset_dir', type=str, default='dataset_dir',
|
| 46 |
+
help='dataset_dir')
|
| 47 |
+
parser.add_argument('--model_dir', type=str, default='model_dir', help='model_dir')
|
| 48 |
+
params = parser.parse_args()
|
| 49 |
+
print(params)
|
| 50 |
+
setup_seed(params.seed)
|
| 51 |
+
pretrained_dataset = PretrainingDataset(dataset_dir=params.dataset_dir)
|
| 52 |
+
print(len(pretrained_dataset))
|
| 53 |
+
data_loader = DataLoader(
|
| 54 |
+
pretrained_dataset,
|
| 55 |
+
batch_size=params.batch_size,
|
| 56 |
+
num_workers=8,
|
| 57 |
+
shuffle=True,
|
| 58 |
+
)
|
| 59 |
+
model = CBraMod(
|
| 60 |
+
params.in_dim, params.out_dim, params.d_model, params.dim_feedforward, params.seq_len, params.n_layer,
|
| 61 |
+
params.nhead
|
| 62 |
+
)
|
| 63 |
+
trainer = Trainer(params, data_loader, model)
|
| 64 |
+
trainer.train()
|
| 65 |
+
pretrained_dataset.db.close()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == '__main__':
|
| 69 |
+
main()
|
external/CBraMod/pretrain_trainer.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from ptflops import get_model_complexity_info
|
| 4 |
+
from torch.nn import MSELoss
|
| 5 |
+
from torchinfo import summary
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
from utils.util import generate_mask
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Trainer(object):
|
| 12 |
+
def __init__(self, params, data_loader, model):
|
| 13 |
+
self.params = params
|
| 14 |
+
self.device = torch.device(f"cuda:{self.params.cuda}" if torch.cuda.is_available() else "cpu")
|
| 15 |
+
self.data_loader = data_loader
|
| 16 |
+
self.model = model.to(self.device)
|
| 17 |
+
self.criterion = MSELoss(reduction='mean').to(self.device)
|
| 18 |
+
|
| 19 |
+
if self.params.parallel:
|
| 20 |
+
device_ids = [0, 1, 2, 3, 4, 5, 6, 7]
|
| 21 |
+
self.model = torch.nn.DataParallel(self.model, device_ids=device_ids)
|
| 22 |
+
|
| 23 |
+
self.data_length = len(self.data_loader)
|
| 24 |
+
|
| 25 |
+
summary(self.model, input_size=(1, 19, 30, 200))
|
| 26 |
+
|
| 27 |
+
macs, params = get_model_complexity_info(self.model, (19, 30, 200), as_strings=True,
|
| 28 |
+
print_per_layer_stat=True, verbose=True)
|
| 29 |
+
print('{:<30} {:<8}'.format('Computational complexity: ', macs))
|
| 30 |
+
print('{:<30} {:<8}'.format('Number of parameters: ', params))
|
| 31 |
+
|
| 32 |
+
self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.params.lr,
|
| 33 |
+
weight_decay=self.params.weight_decay)
|
| 34 |
+
|
| 35 |
+
if self.params.lr_scheduler=='CosineAnnealingLR':
|
| 36 |
+
self.optimizer_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
|
| 37 |
+
self.optimizer, T_max=40*self.data_length, eta_min=1e-5
|
| 38 |
+
)
|
| 39 |
+
elif self.params.lr_scheduler=='ExponentialLR':
|
| 40 |
+
self.optimizer_scheduler = torch.optim.lr_scheduler.ExponentialLR(
|
| 41 |
+
self.optimizer, gamma=0.999999999
|
| 42 |
+
)
|
| 43 |
+
elif self.params.lr_scheduler=='StepLR':
|
| 44 |
+
self.optimizer_scheduler = torch.optim.lr_scheduler.StepLR(
|
| 45 |
+
self.optimizer, step_size=5*self.data_length, gamma=0.5
|
| 46 |
+
)
|
| 47 |
+
elif self.params.lr_scheduler=='MultiStepLR':
|
| 48 |
+
self.optimizer_scheduler = torch.optim.lr_scheduler.MultiStepLR(
|
| 49 |
+
self.optimizer, milestones=[10*self.data_length, 20*self.data_length, 30*self.data_length], gamma=0.1
|
| 50 |
+
)
|
| 51 |
+
elif self.params.lr_scheduler=='CyclicLR':
|
| 52 |
+
self.optimizer_scheduler = torch.optim.lr_scheduler.CyclicLR(
|
| 53 |
+
self.optimizer, base_lr=1e-6, max_lr=0.001, step_size_up=self.data_length*5,
|
| 54 |
+
step_size_down=self.data_length*2, mode='exp_range', gamma=0.9, cycle_momentum=False
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def train(self):
|
| 59 |
+
best_loss = 10000
|
| 60 |
+
for epoch in range(self.params.epochs):
|
| 61 |
+
losses = []
|
| 62 |
+
for x in tqdm(self.data_loader, mininterval=10):
|
| 63 |
+
self.optimizer.zero_grad()
|
| 64 |
+
x = x.to(self.device)/100
|
| 65 |
+
if self.params.need_mask:
|
| 66 |
+
bz, ch_num, patch_num, patch_size = x.shape
|
| 67 |
+
mask = generate_mask(
|
| 68 |
+
bz, ch_num, patch_num, mask_ratio=self.params.mask_ratio, device=self.device,
|
| 69 |
+
)
|
| 70 |
+
y = self.model(x, mask=mask)
|
| 71 |
+
masked_x = x[mask == 1]
|
| 72 |
+
masked_y = y[mask == 1]
|
| 73 |
+
loss = self.criterion(masked_y, masked_x)
|
| 74 |
+
|
| 75 |
+
# non_masked_x = x[mask == 0]
|
| 76 |
+
# non_masked_y = y[mask == 0]
|
| 77 |
+
# non_masked_loss = self.criterion(non_masked_y, non_masked_x)
|
| 78 |
+
# loss = 0.8 * masked_loss + 0.2 * non_masked_loss
|
| 79 |
+
else:
|
| 80 |
+
y = self.model(x)
|
| 81 |
+
loss = self.criterion(y, x)
|
| 82 |
+
loss.backward()
|
| 83 |
+
if self.params.clip_value > 0:
|
| 84 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.params.clip_value)
|
| 85 |
+
self.optimizer.step()
|
| 86 |
+
self.optimizer_scheduler.step()
|
| 87 |
+
losses.append(loss.data.cpu().numpy())
|
| 88 |
+
mean_loss = np.mean(losses)
|
| 89 |
+
learning_rate = self.optimizer.state_dict()['param_groups'][0]['lr']
|
| 90 |
+
print(f'Epoch {epoch+1}: Training Loss: {mean_loss:.6f}, Learning Rate: {learning_rate:.6f}')
|
| 91 |
+
if mean_loss < best_loss:
|
| 92 |
+
model_path = rf'{self.params.model_dir}/epoch{epoch+1}_loss{mean_loss}.pth'
|
| 93 |
+
torch.save(self.model.state_dict(), model_path)
|
| 94 |
+
print("model save in " + model_path)
|
| 95 |
+
best_loss = mean_loss
|
external/CBraMod/quick_example.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from models.cbramod import CBraMod
|
| 4 |
+
from einops.layers.torch import Rearrange
|
| 5 |
+
|
| 6 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 7 |
+
model = CBraMod().to(device)
|
| 8 |
+
model.load_state_dict(torch.load('pretrained_weights/pretrained_weights.pth', map_location=device))
|
| 9 |
+
model.proj_out = nn.Identity()
|
| 10 |
+
classifier = nn.Sequential(
|
| 11 |
+
Rearrange('b c s p -> b (c s p)'),
|
| 12 |
+
nn.Linear(22*4*200, 4*200),
|
| 13 |
+
nn.ELU(),
|
| 14 |
+
nn.Dropout(0.1),
|
| 15 |
+
nn.Linear(4 * 200, 200),
|
| 16 |
+
nn.ELU(),
|
| 17 |
+
nn.Dropout(0.1),
|
| 18 |
+
nn.Linear(200, 4),
|
| 19 |
+
).to(device)
|
| 20 |
+
|
| 21 |
+
# mock_eeg.shape = (batch_size, num_of_channels, time_segments, points_per_patch)
|
| 22 |
+
mock_eeg = torch.randn((8, 22, 4, 200)).to(device)
|
| 23 |
+
|
| 24 |
+
# logits.shape = (batch_size, num_of_classes)
|
| 25 |
+
logits = classifier(model(mock_eeg))
|
| 26 |
+
|
| 27 |
+
print(logits.shape)
|
external/CBraMod/requirements.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
einops
|
| 2 |
+
h5py
|
| 3 |
+
lmdb
|
| 4 |
+
matplotlib
|
| 5 |
+
mne
|
| 6 |
+
numpy
|
| 7 |
+
pandas
|
| 8 |
+
ptflops
|
| 9 |
+
pyEDFlib
|
| 10 |
+
scikit_learn
|
| 11 |
+
scipy
|
| 12 |
+
torchinfo
|
| 13 |
+
tqdm
|
| 14 |
+
umap_learn
|
external/T3A/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code of Conduct
|
| 2 |
+
|
| 3 |
+
Facebook has adopted a Code of Conduct that we expect project participants to adhere to.
|
| 4 |
+
Please read the [full text](https://code.fb.com/codeofconduct/)
|
| 5 |
+
so that you can understand what actions will and will not be tolerated.
|
external/T3A/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributing to `DomainBed`
|
| 2 |
+
We want to make contributing to this project as easy and transparent as
|
| 3 |
+
possible.
|
| 4 |
+
|
| 5 |
+
## Pull Requests
|
| 6 |
+
We actively welcome your pull requests.
|
| 7 |
+
|
| 8 |
+
1. Fork the repo and create your branch from `master`.
|
| 9 |
+
2. If you've added code that should be tested, add tests.
|
| 10 |
+
3. If you've changed APIs, update the documentation.
|
| 11 |
+
4. Ensure the test suite passes.
|
| 12 |
+
5. Make sure your code lints.
|
| 13 |
+
6. If you haven't already, complete the Contributor License Agreement ("CLA").
|
| 14 |
+
|
| 15 |
+
## Contributor License Agreement ("CLA")
|
| 16 |
+
In order to accept your pull request, we need you to submit a CLA. You only need
|
| 17 |
+
to do this once to work on any of Facebook's open source projects.
|
| 18 |
+
|
| 19 |
+
Complete your CLA here: <https://code.facebook.com/cla>
|
| 20 |
+
|
| 21 |
+
## Issues
|
| 22 |
+
We use GitHub issues to track public bugs. Please ensure your description is
|
| 23 |
+
clear and has sufficient instructions to be able to reproduce the issue.
|
| 24 |
+
|
| 25 |
+
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
|
| 26 |
+
disclosure of security bugs. In those cases, please go through the process
|
| 27 |
+
outlined on that page and do not file a public issue.
|
| 28 |
+
|
| 29 |
+
## License
|
| 30 |
+
By contributing to `DomainBed`, you agree that your contributions
|
| 31 |
+
will be licensed under the LICENSE file in the root directory of this source
|
| 32 |
+
tree.
|
external/T3A/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) Facebook, Inc. and its affiliates.
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
| 6 |
+
|
| 7 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
| 8 |
+
|
| 9 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
external/T3A/Pipfile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[[source]]
|
| 2 |
+
url = "https://pypi.org/simple"
|
| 3 |
+
verify_ssl = true
|
| 4 |
+
name = "pypi"
|
| 5 |
+
|
| 6 |
+
[packages]
|
| 7 |
+
torch = "*"
|
| 8 |
+
torchvision = "*"
|
| 9 |
+
torchaudio = "*"
|
| 10 |
+
tqdm = "*"
|
| 11 |
+
einops = "*"
|
| 12 |
+
python-dotenv = "*"
|
| 13 |
+
rarfile = "*"
|
| 14 |
+
scipy = "*"
|
| 15 |
+
jupyterlab = "*"
|
| 16 |
+
wilds = "*"
|
| 17 |
+
gdown = "*"
|
| 18 |
+
wget = "*"
|
| 19 |
+
timm = "*"
|
| 20 |
+
|
| 21 |
+
[dev-packages]
|
| 22 |
+
pipenv = "*"
|
| 23 |
+
flake8 = "*"
|
| 24 |
+
autopep8 = "*"
|
| 25 |
+
wandb = "*"
|
| 26 |
+
jupyter = "*"
|
| 27 |
+
|
| 28 |
+
[requires]
|
| 29 |
+
python_version = "3.7"
|
external/T3A/Pipfile.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
external/T3A/README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Test-Time Classifier Adjustment Module for Model-Agnostic Domain Generalization
|
| 2 |
+
|
| 3 |
+
This codebase is the official implementation of `Test-Time Classifier Adjustment Module for Model-Agnostic Domain Generalization` (NeurIPS2021, Spotlight, [url](<https://openreview.net/forum?id=e_yvNqkJKAW&referrer=%5BAuthor%20Console%5D(%2Fgroup%3Fid%3DNeurIPS.cc%2F2021%2FConference%2FAuthors%23your-submissions)>).
|
| 4 |
+
This codebase is mainly based on [DomainBed](https://github.com/facebookresearch/DomainBed), with following modifications:
|
| 5 |
+
|
| 6 |
+
* enable to use various backbone networks including Big Transfer (BiT), Vision Transformers (ViT, DeiT, HViT), and MLP-Mixer.
|
| 7 |
+
* enable to test test-time adaptation method (T3A and [Tent](https://github.com/DequanWang/tent)).
|
| 8 |
+
|
| 9 |
+
## Installation
|
| 10 |
+
|
| 11 |
+
#### CUDA/Python
|
| 12 |
+
```
|
| 13 |
+
git clone git@github.com:matsuolab/Domainbed_contrib.git
|
| 14 |
+
cd Domainbed_contrib/docker
|
| 15 |
+
docker build -t {image_name} .
|
| 16 |
+
docker run -it -h `hostname` --runtime=nvidia -v /path/to/Domainbed_contrib /path/to/anyware --shm-size=40gb --name {container_name} {image_name}
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
#### Python libralies
|
| 20 |
+
We use `pipenv` for package management.
|
| 21 |
+
```
|
| 22 |
+
cd /path/to/Domainbed_contrib
|
| 23 |
+
pip install pipenv
|
| 24 |
+
pipenv install
|
| 25 |
+
pipenv shell
|
| 26 |
+
pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.8.0+cu102.html
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## Quick start
|
| 30 |
+
#### (1) Downlload the datasets
|
| 31 |
+
|
| 32 |
+
```sh
|
| 33 |
+
python -m domainbed.scripts.download --data_dir=/my/datasets/path --dataset pacs
|
| 34 |
+
```
|
| 35 |
+
Note: change `--dataset pacs` for downloading other datasets (e.g., `vlcs`, `office_home`, `terra_incognita`).
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
#### (2) Train a model on source domains
|
| 39 |
+
```sh
|
| 40 |
+
python -m domainbed.scripts.train\
|
| 41 |
+
--data_dir /my/datasets/path\
|
| 42 |
+
--output_dir /my/pretrain/path\
|
| 43 |
+
--algorithm ERM\
|
| 44 |
+
--dataset PACS\
|
| 45 |
+
--hparams "{\"backbone\": \"resnet50\"}"
|
| 46 |
+
```
|
| 47 |
+
This scripts will produce new directory `/my/pretrain/path`, which include the full training log.
|
| 48 |
+
|
| 49 |
+
Note: change `--dataset PACS` for training on other datasets (e.g., `VLCS`, `OfficeHome`, `TerraIncognita`).
|
| 50 |
+
|
| 51 |
+
Note: change `--hparams "{\"backbone\": \"resnet50\"}"` for using other backbones (e.g., `resnet18`, `ViT-B16`, `HViT`).
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
#### (3) Evaluate model with test time adaptation (Table 1, Table 2, Figure 2)
|
| 55 |
+
```sh
|
| 56 |
+
python -m domainbed.scripts.unsupervised_adaptation\
|
| 57 |
+
--input_dir=/my/pretrain/path\
|
| 58 |
+
--adapt_algorithm=T3A
|
| 59 |
+
```
|
| 60 |
+
This scripts will produce a new file in `/my/pretrain/path`, whose name is `results_{adapt_algorithm}.jsonl`.
|
| 61 |
+
|
| 62 |
+
Note: change `--adapt_algorithm=T3A` for using other test time adaptation methods (`T3A`, `Tent`, or `TentClf`).
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
#### (4) Evaluate model with fine-tuning classifier(Figure 1)
|
| 67 |
+
```sh
|
| 68 |
+
python -m domainbed.scripts.supervised_adaptation\
|
| 69 |
+
--input_dir=/my/pretrain/path\
|
| 70 |
+
--ft_mode=clf
|
| 71 |
+
```
|
| 72 |
+
This scripts will produce a new file in `/my/pretrain/path`, whose name is `results_{ft_mode}.jsonl`.
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
## Available backbones
|
| 76 |
+
|
| 77 |
+
* resnet18
|
| 78 |
+
* resnet50
|
| 79 |
+
* BiT-M-R50x3
|
| 80 |
+
* BiT-M-R101x3
|
| 81 |
+
* BiT-M-R152x2
|
| 82 |
+
* ViT-B16
|
| 83 |
+
* ViT-L16
|
| 84 |
+
* DeiT
|
| 85 |
+
* Hybrid ViT (HViT)
|
| 86 |
+
* MLP-Mixer (Mixer-L16)
|
| 87 |
+
|
| 88 |
+
## Reproducing results
|
| 89 |
+
#### Table 1 and Figure 2 (Tuned ERM and CORAL)
|
| 90 |
+
|
| 91 |
+
You can use `scripts/hparam_search.sh`. Specifically, for each dataset and base algorithm, you can just type a following command.
|
| 92 |
+
```
|
| 93 |
+
sh scripts/hparam_search.sh resnet50 PACS ERM
|
| 94 |
+
```
|
| 95 |
+
Note that, it automatically starts 240 jobs, and take many times to finish.
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
#### Table 2 and Figure 1 (ERM with various backbone)
|
| 99 |
+
|
| 100 |
+
You can use `scripts/launch.sh`. Specifically, for each backbone, you can just type following three commands.
|
| 101 |
+
```
|
| 102 |
+
sh scripts/launch.sh pretrain resnet50 10 3 local
|
| 103 |
+
sh scripts/launch.sh sup resnet50 10 3 local
|
| 104 |
+
sh scripts/launch.sh unsup resnet50 10 3 local
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
#### Other results
|
| 109 |
+
For table 1, we used scores reported by [In Search of Lost Domain Generalization](https://arxiv.org/abs/2007.01434).
|
| 110 |
+
Full results for the reported scores in LaTeX format available [here](domainbed/results/2020_10_06_7df6f06/results.tex).
|
| 111 |
+
Note: We only used scores for VLCS, PACS, OfficeHome, and TerraIncognita. We used the resutls with `IIDAccuracySelectionMethod`.
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
## License
|
| 115 |
+
|
| 116 |
+
This source code is released under the MIT license, included [here](LICENSE).
|
repo/outputs/budgeted_risk/risk_decisions/stage0_random_eval_batch/eegmmidb/fold_4/seed_0/b10_eegmmidb_029.json
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"batch_hash": "b984cc53016c7232032ac8f4026c8e2c02eb993fa85bd504266ce7b458c68b43",
|
| 3 |
+
"decisions": [
|
| 4 |
+
{
|
| 5 |
+
"alpha": 0.1,
|
| 6 |
+
"budget": 10,
|
| 7 |
+
"certified_index": 20,
|
| 8 |
+
"dataset": "eegmmidb",
|
| 9 |
+
"decision_hash": "6e5164374b0a8883c238cb677413de0e10b2b053372e3bf56c4818e9c11a06e8",
|
| 10 |
+
"delta": 0.1,
|
| 11 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 12 |
+
"query_hash": "2071d3c4bff25b84331c4ee43af9045d384f5b238619c70b50da100225d7b182",
|
| 13 |
+
"repeat": 0,
|
| 14 |
+
"role": "evaluation",
|
| 15 |
+
"seed": 0,
|
| 16 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 17 |
+
"strategy": "random",
|
| 18 |
+
"subject_id": "eegmmidb:029"
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"alpha": 0.1,
|
| 22 |
+
"budget": 10,
|
| 23 |
+
"certified_index": 18,
|
| 24 |
+
"dataset": "eegmmidb",
|
| 25 |
+
"decision_hash": "b3af3756ac33832e8efdf06e496458d9e9337440d8d1d9300068e4c4e5d7f857",
|
| 26 |
+
"delta": 0.1,
|
| 27 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 28 |
+
"query_hash": "c4388b996ee81a7fc54156bfe3a113a0ddbb41a22fcbffba31e20dc9e69ecf9d",
|
| 29 |
+
"repeat": 1,
|
| 30 |
+
"role": "evaluation",
|
| 31 |
+
"seed": 0,
|
| 32 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 33 |
+
"strategy": "random",
|
| 34 |
+
"subject_id": "eegmmidb:029"
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"alpha": 0.1,
|
| 38 |
+
"budget": 10,
|
| 39 |
+
"certified_index": 17,
|
| 40 |
+
"dataset": "eegmmidb",
|
| 41 |
+
"decision_hash": "87a63c6f35e0aad0466d53ed6789158caaa0db666d73a6fe195c0699e554f354",
|
| 42 |
+
"delta": 0.1,
|
| 43 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 44 |
+
"query_hash": "b84266c2c265ca593a1c4fb3295f6e2acfe0f31cd3fa1dcc40a2105a9e6b3424",
|
| 45 |
+
"repeat": 2,
|
| 46 |
+
"role": "evaluation",
|
| 47 |
+
"seed": 0,
|
| 48 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 49 |
+
"strategy": "random",
|
| 50 |
+
"subject_id": "eegmmidb:029"
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"alpha": 0.1,
|
| 54 |
+
"budget": 10,
|
| 55 |
+
"certified_index": 15,
|
| 56 |
+
"dataset": "eegmmidb",
|
| 57 |
+
"decision_hash": "c91d48da8a1ea672edf4b4a1605919dcccd06f0d66e6da6cf67a33560a35b362",
|
| 58 |
+
"delta": 0.1,
|
| 59 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 60 |
+
"query_hash": "3734a29e5d2d56dcfc7c94d63d5959bf527308af895047df8e729b909943d59b",
|
| 61 |
+
"repeat": 3,
|
| 62 |
+
"role": "evaluation",
|
| 63 |
+
"seed": 0,
|
| 64 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 65 |
+
"strategy": "random",
|
| 66 |
+
"subject_id": "eegmmidb:029"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"alpha": 0.1,
|
| 70 |
+
"budget": 10,
|
| 71 |
+
"certified_index": 20,
|
| 72 |
+
"dataset": "eegmmidb",
|
| 73 |
+
"decision_hash": "17f8b78b5823de89921244ffc9acf31d222b5c9cd6b0a1b8eff49e04636ab644",
|
| 74 |
+
"delta": 0.1,
|
| 75 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 76 |
+
"query_hash": "12312319c188d6a5002d31cb1783760c70ff6349ded1b7fa07ff51fddba14927",
|
| 77 |
+
"repeat": 4,
|
| 78 |
+
"role": "evaluation",
|
| 79 |
+
"seed": 0,
|
| 80 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 81 |
+
"strategy": "random",
|
| 82 |
+
"subject_id": "eegmmidb:029"
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"alpha": 0.1,
|
| 86 |
+
"budget": 10,
|
| 87 |
+
"certified_index": 20,
|
| 88 |
+
"dataset": "eegmmidb",
|
| 89 |
+
"decision_hash": "1706b5cf86d4b924f98403b7139974ec40b7fa85648082c16f48cf91e206e908",
|
| 90 |
+
"delta": 0.1,
|
| 91 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 92 |
+
"query_hash": "efe4098d881f8c51fa9b5d3a7a10ad8028e8cd611ab41f16846c51ffa979985e",
|
| 93 |
+
"repeat": 5,
|
| 94 |
+
"role": "evaluation",
|
| 95 |
+
"seed": 0,
|
| 96 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 97 |
+
"strategy": "random",
|
| 98 |
+
"subject_id": "eegmmidb:029"
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"alpha": 0.1,
|
| 102 |
+
"budget": 10,
|
| 103 |
+
"certified_index": 19,
|
| 104 |
+
"dataset": "eegmmidb",
|
| 105 |
+
"decision_hash": "63fc4da4d7ac1a17b2008bd2f33a2a948add5d11d572b912a59f215e2e8ec81b",
|
| 106 |
+
"delta": 0.1,
|
| 107 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 108 |
+
"query_hash": "e3a9f3e904ac592828fac34bc7ae2e9dd349e03d980df45ee014c3778e625144",
|
| 109 |
+
"repeat": 6,
|
| 110 |
+
"role": "evaluation",
|
| 111 |
+
"seed": 0,
|
| 112 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 113 |
+
"strategy": "random",
|
| 114 |
+
"subject_id": "eegmmidb:029"
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"alpha": 0.1,
|
| 118 |
+
"budget": 10,
|
| 119 |
+
"certified_index": 15,
|
| 120 |
+
"dataset": "eegmmidb",
|
| 121 |
+
"decision_hash": "37c73754029f242d8cd446a9674c426da704d892b5d721dc613f170fbc832fcf",
|
| 122 |
+
"delta": 0.1,
|
| 123 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 124 |
+
"query_hash": "e824932cc8698ffb0f55cc0a5385b6fe5b31d0922f840b7e56811833d091c6ee",
|
| 125 |
+
"repeat": 7,
|
| 126 |
+
"role": "evaluation",
|
| 127 |
+
"seed": 0,
|
| 128 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 129 |
+
"strategy": "random",
|
| 130 |
+
"subject_id": "eegmmidb:029"
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"alpha": 0.1,
|
| 134 |
+
"budget": 10,
|
| 135 |
+
"certified_index": 17,
|
| 136 |
+
"dataset": "eegmmidb",
|
| 137 |
+
"decision_hash": "96a4ee94c9773e31357f665201bfc1bc3b1d64ddb81cb7582cf4fa0fcbcf1335",
|
| 138 |
+
"delta": 0.1,
|
| 139 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 140 |
+
"query_hash": "b926b40d79cd477c730efca2db4595dc67ad8ce97d7ccf2907fb1e14a262d28a",
|
| 141 |
+
"repeat": 8,
|
| 142 |
+
"role": "evaluation",
|
| 143 |
+
"seed": 0,
|
| 144 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 145 |
+
"strategy": "random",
|
| 146 |
+
"subject_id": "eegmmidb:029"
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"alpha": 0.1,
|
| 150 |
+
"budget": 10,
|
| 151 |
+
"certified_index": 20,
|
| 152 |
+
"dataset": "eegmmidb",
|
| 153 |
+
"decision_hash": "53a6d2ef080d9f4d279ea1c9597292c347ea87832bb2528dfb82b10224ac30c2",
|
| 154 |
+
"delta": 0.1,
|
| 155 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 156 |
+
"query_hash": "9394f9363bbcf4b312171ac4f2871c8ef64cda1b53a5cfa687f457efe3565ecc",
|
| 157 |
+
"repeat": 9,
|
| 158 |
+
"role": "evaluation",
|
| 159 |
+
"seed": 0,
|
| 160 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 161 |
+
"strategy": "random",
|
| 162 |
+
"subject_id": "eegmmidb:029"
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"alpha": 0.1,
|
| 166 |
+
"budget": 10,
|
| 167 |
+
"certified_index": 18,
|
| 168 |
+
"dataset": "eegmmidb",
|
| 169 |
+
"decision_hash": "fe5db362a72223d7fac9534e827faf93a1dd6b393965826f328e92ca15b9448e",
|
| 170 |
+
"delta": 0.1,
|
| 171 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 172 |
+
"query_hash": "395bc405d43442ccef51969069b9a6340209650e4f4ee5765bab51a9fac664a0",
|
| 173 |
+
"repeat": 10,
|
| 174 |
+
"role": "evaluation",
|
| 175 |
+
"seed": 0,
|
| 176 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 177 |
+
"strategy": "random",
|
| 178 |
+
"subject_id": "eegmmidb:029"
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"alpha": 0.1,
|
| 182 |
+
"budget": 10,
|
| 183 |
+
"certified_index": 15,
|
| 184 |
+
"dataset": "eegmmidb",
|
| 185 |
+
"decision_hash": "0c14b99cf8bde029e3326c34ff865c0030a49ecc8c364a2bf3548ef2c392562d",
|
| 186 |
+
"delta": 0.1,
|
| 187 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 188 |
+
"query_hash": "3497f71549578546958f0fb68a9ab4b249bbe5003101a4c89fd02e1bf056d3a9",
|
| 189 |
+
"repeat": 11,
|
| 190 |
+
"role": "evaluation",
|
| 191 |
+
"seed": 0,
|
| 192 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 193 |
+
"strategy": "random",
|
| 194 |
+
"subject_id": "eegmmidb:029"
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"alpha": 0.1,
|
| 198 |
+
"budget": 10,
|
| 199 |
+
"certified_index": 18,
|
| 200 |
+
"dataset": "eegmmidb",
|
| 201 |
+
"decision_hash": "b5001867eb717109111e7d24726d9a354bac9aafca5820bbe8da4b5e28666558",
|
| 202 |
+
"delta": 0.1,
|
| 203 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 204 |
+
"query_hash": "bdfb5aed68f89462c32bb81e17dc3c2f6e156390e130111badc8550b6b8ec4c7",
|
| 205 |
+
"repeat": 12,
|
| 206 |
+
"role": "evaluation",
|
| 207 |
+
"seed": 0,
|
| 208 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 209 |
+
"strategy": "random",
|
| 210 |
+
"subject_id": "eegmmidb:029"
|
| 211 |
+
},
|
| 212 |
+
{
|
| 213 |
+
"alpha": 0.1,
|
| 214 |
+
"budget": 10,
|
| 215 |
+
"certified_index": 20,
|
| 216 |
+
"dataset": "eegmmidb",
|
| 217 |
+
"decision_hash": "e5e716d0f1b95422b90aef497d1a739d428251851167fc060cb430372a350607",
|
| 218 |
+
"delta": 0.1,
|
| 219 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 220 |
+
"query_hash": "656c344c22ee3b7879b743b3fc1337c8c3372b5877a1b555207651212d0322b2",
|
| 221 |
+
"repeat": 13,
|
| 222 |
+
"role": "evaluation",
|
| 223 |
+
"seed": 0,
|
| 224 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 225 |
+
"strategy": "random",
|
| 226 |
+
"subject_id": "eegmmidb:029"
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"alpha": 0.1,
|
| 230 |
+
"budget": 10,
|
| 231 |
+
"certified_index": 15,
|
| 232 |
+
"dataset": "eegmmidb",
|
| 233 |
+
"decision_hash": "8c0d8ab97ef2044b8c8091e0b384085af7a6927ba8717d40ef1dde675aa30bf0",
|
| 234 |
+
"delta": 0.1,
|
| 235 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 236 |
+
"query_hash": "90143bbb710dd398989f4a10c3fd036422ed1898d8107ec3dd9e89043e144d72",
|
| 237 |
+
"repeat": 14,
|
| 238 |
+
"role": "evaluation",
|
| 239 |
+
"seed": 0,
|
| 240 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 241 |
+
"strategy": "random",
|
| 242 |
+
"subject_id": "eegmmidb:029"
|
| 243 |
+
},
|
| 244 |
+
{
|
| 245 |
+
"alpha": 0.1,
|
| 246 |
+
"budget": 10,
|
| 247 |
+
"certified_index": 15,
|
| 248 |
+
"dataset": "eegmmidb",
|
| 249 |
+
"decision_hash": "c338821bf97455b200f1228bcebc67ce8c1e4babf0913f537bec0f2987263eb5",
|
| 250 |
+
"delta": 0.1,
|
| 251 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 252 |
+
"query_hash": "fea5c7a4a20071b5114c42d334f677b308a00bbdf34e7095dd6995435b3f3bda",
|
| 253 |
+
"repeat": 15,
|
| 254 |
+
"role": "evaluation",
|
| 255 |
+
"seed": 0,
|
| 256 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 257 |
+
"strategy": "random",
|
| 258 |
+
"subject_id": "eegmmidb:029"
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"alpha": 0.1,
|
| 262 |
+
"budget": 10,
|
| 263 |
+
"certified_index": 19,
|
| 264 |
+
"dataset": "eegmmidb",
|
| 265 |
+
"decision_hash": "680449eee1572031e5bf8ef941fa5db0bde860a168de93b68f76f41ef5033770",
|
| 266 |
+
"delta": 0.1,
|
| 267 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 268 |
+
"query_hash": "37b804f8231dc6382bed75a59cd3a2c6b8931709a8bfe172b042a5c8c8e6004b",
|
| 269 |
+
"repeat": 16,
|
| 270 |
+
"role": "evaluation",
|
| 271 |
+
"seed": 0,
|
| 272 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 273 |
+
"strategy": "random",
|
| 274 |
+
"subject_id": "eegmmidb:029"
|
| 275 |
+
},
|
| 276 |
+
{
|
| 277 |
+
"alpha": 0.1,
|
| 278 |
+
"budget": 10,
|
| 279 |
+
"certified_index": 15,
|
| 280 |
+
"dataset": "eegmmidb",
|
| 281 |
+
"decision_hash": "1ed7ff5b08778dceb294ffc1e7a33ef248ba246d4cd8741cbd483dd37d59110b",
|
| 282 |
+
"delta": 0.1,
|
| 283 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 284 |
+
"query_hash": "f5364b63c289182d5c8056f8c07bacd1a9ec97dfba96a3e0ba62ff1251dc82a9",
|
| 285 |
+
"repeat": 17,
|
| 286 |
+
"role": "evaluation",
|
| 287 |
+
"seed": 0,
|
| 288 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 289 |
+
"strategy": "random",
|
| 290 |
+
"subject_id": "eegmmidb:029"
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"alpha": 0.1,
|
| 294 |
+
"budget": 10,
|
| 295 |
+
"certified_index": 17,
|
| 296 |
+
"dataset": "eegmmidb",
|
| 297 |
+
"decision_hash": "8fcd561487cf7eff3a773c679506dcbc601fac1b75bc27766adc1ae6a9107c26",
|
| 298 |
+
"delta": 0.1,
|
| 299 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 300 |
+
"query_hash": "faec179143d2fa98848429afa982074e2cb13133047e1943a23121b9ae6a4b76",
|
| 301 |
+
"repeat": 18,
|
| 302 |
+
"role": "evaluation",
|
| 303 |
+
"seed": 0,
|
| 304 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 305 |
+
"strategy": "random",
|
| 306 |
+
"subject_id": "eegmmidb:029"
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
"alpha": 0.1,
|
| 310 |
+
"budget": 10,
|
| 311 |
+
"certified_index": 20,
|
| 312 |
+
"dataset": "eegmmidb",
|
| 313 |
+
"decision_hash": "3389d41155ad02bec82e375e34ad8d65d5406c5cd205283305e4dc78c73dcdcb",
|
| 314 |
+
"delta": 0.1,
|
| 315 |
+
"episode_hash": "cc728c588c3fe108a7529effa80262ed1ed989041eb9917f7c3f894626019053",
|
| 316 |
+
"query_hash": "f8e3380911c3cdd9ec98c2b0b447581c9b365eefb70e270cf3966e2b559cfb31",
|
| 317 |
+
"repeat": 19,
|
| 318 |
+
"role": "evaluation",
|
| 319 |
+
"seed": 0,
|
| 320 |
+
"source_model_hash": "e3ff1372a811e8eb9532e4030c3d343fd0e496860900ac7742718fe94fe0446d",
|
| 321 |
+
"strategy": "random",
|
| 322 |
+
"subject_id": "eegmmidb:029"
|
| 323 |
+
}
|
| 324 |
+
],
|
| 325 |
+
"schema_version": "budgeted-risk-decision-batch-v1"
|
| 326 |
+
}
|