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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train a real DANCE checkpoint on BI2014a for the braindecode tutorial.
|
| 2 |
+
|
| 3 |
+
Reuses the *exact* data pipeline, target builder and model construction from
|
| 4 |
+
``examples/applied_examples/plot_dance_event_detection.py`` so the resulting
|
| 5 |
+
``model.pt`` (a plain ``state_dict``) loads with ``strict=True`` into the model
|
| 6 |
+
the tutorial builds. The only differences from the tutorial are training scale:
|
| 7 |
+
more subjects, more epochs, a OneCycle schedule, minibatches, and keeping the
|
| 8 |
+
best checkpoint by held-out F1-event.
|
| 9 |
+
|
| 10 |
+
Usage:
|
| 11 |
+
python train_checkpoint.py --train 1 2 4 5 6 7 8 9 --test 3 --epochs 100
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from sklearn.metrics import f1_score
|
| 19 |
+
from sklearn.preprocessing import robust_scale
|
| 20 |
+
from torch.utils.data import DataLoader
|
| 21 |
+
|
| 22 |
+
from braindecode.datasets import MOABBDataset
|
| 23 |
+
from braindecode.models import DANCE
|
| 24 |
+
from braindecode.preprocessing import (
|
| 25 |
+
Preprocessor,
|
| 26 |
+
create_fixed_length_windows,
|
| 27 |
+
preprocess,
|
| 28 |
+
)
|
| 29 |
+
from braindecode.training import DanceLoss, f1_event
|
| 30 |
+
from braindecode.util import set_random_seeds
|
| 31 |
+
|
| 32 |
+
SFREQ = 128.0
|
| 33 |
+
WINDOW_S, N_CLASSES, NUM_LATENTS, MAX_EVENTS = 32.0, 3, 256, 150
|
| 34 |
+
WINDOW_SAMPLES = int(WINDOW_S * SFREQ)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# --- tutorial helpers (verbatim) -------------------------------------------
|
| 38 |
+
def robust_scale_clamp(data):
|
| 39 |
+
return np.clip(robust_scale(data, axis=1), -16, 16)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def bi_annotations_to_events(raw):
|
| 43 |
+
label_to_class = {"NonTarget": 1, "Target": 2}
|
| 44 |
+
events = []
|
| 45 |
+
for ann in raw.annotations:
|
| 46 |
+
cls = label_to_class.get(str(ann["description"]))
|
| 47 |
+
if cls is None:
|
| 48 |
+
continue
|
| 49 |
+
events.append((float(ann["onset"]), float(ann["onset"] + ann["duration"]), cls))
|
| 50 |
+
return events
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def dance_target_builder(annotations, window_onset, window_duration, max_events, num_latents):
|
| 54 |
+
start = torch.zeros(max_events)
|
| 55 |
+
end = torch.zeros(max_events)
|
| 56 |
+
cls = torch.zeros(max_events, dtype=torch.long)
|
| 57 |
+
w0, wd = window_onset, window_duration
|
| 58 |
+
kept = 0
|
| 59 |
+
for s, e, c in annotations:
|
| 60 |
+
s_c, e_c = max(s, w0), min(e, w0 + wd)
|
| 61 |
+
if e_c <= s_c or int(c) == 0 or kept >= max_events:
|
| 62 |
+
continue
|
| 63 |
+
start[kept] = (s_c - w0) / wd
|
| 64 |
+
end[kept] = (e_c - w0) / wd
|
| 65 |
+
cls[kept] = int(c)
|
| 66 |
+
kept += 1
|
| 67 |
+
dense = torch.zeros(num_latents, dtype=torch.long)
|
| 68 |
+
s_tok = (start * num_latents).clamp(0, num_latents).long()
|
| 69 |
+
e_tok = (end * num_latents).clamp(0, num_latents).long()
|
| 70 |
+
for i in range(kept):
|
| 71 |
+
a, b = int(s_tok[i]), int(e_tok[i])
|
| 72 |
+
if a < b:
|
| 73 |
+
dense[a:b] = int(cls[i])
|
| 74 |
+
return {"start": start, "end": end, "class": cls, "dense": dense}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def dance_collate(batch):
|
| 78 |
+
eeg = torch.stack([b[0] for b in batch])
|
| 79 |
+
out = {"eeg": eeg}
|
| 80 |
+
for key in ("start", "end", "class", "dense"):
|
| 81 |
+
out[key] = torch.stack([b[1][key] for b in batch])
|
| 82 |
+
return out
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def detections_to_events(detections, duration):
|
| 86 |
+
probs = torch.softmax(detections["class"], dim=-1)
|
| 87 |
+
confidence, label = probs.max(dim=-1)
|
| 88 |
+
start = detections["start"] * duration
|
| 89 |
+
end = detections["end"] * duration
|
| 90 |
+
events = []
|
| 91 |
+
for bi in range(label.shape[0]):
|
| 92 |
+
keep = label[bi] != 0
|
| 93 |
+
events.append(
|
| 94 |
+
list(
|
| 95 |
+
zip(
|
| 96 |
+
start[bi, keep].tolist(),
|
| 97 |
+
end[bi, keep].tolist(),
|
| 98 |
+
label[bi, keep].tolist(),
|
| 99 |
+
confidence[bi, keep].tolist(),
|
| 100 |
+
)
|
| 101 |
+
)
|
| 102 |
+
)
|
| 103 |
+
return events
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def build_samples(subject_ids):
|
| 107 |
+
dataset = MOABBDataset(dataset_name="BI2014a", subject_ids=subject_ids)
|
| 108 |
+
preprocess(
|
| 109 |
+
dataset,
|
| 110 |
+
[
|
| 111 |
+
Preprocessor("pick_types", eeg=True, stim=False),
|
| 112 |
+
Preprocessor("filter", l_freq=0.1, h_freq=100.0),
|
| 113 |
+
Preprocessor("resample", sfreq=SFREQ),
|
| 114 |
+
Preprocessor(robust_scale_clamp, apply_on_array=True),
|
| 115 |
+
],
|
| 116 |
+
)
|
| 117 |
+
windows_ds = create_fixed_length_windows(
|
| 118 |
+
dataset,
|
| 119 |
+
window_size_samples=WINDOW_SAMPLES,
|
| 120 |
+
window_stride_samples=WINDOW_SAMPLES,
|
| 121 |
+
drop_last_window=True,
|
| 122 |
+
preload=True,
|
| 123 |
+
use_mne_epochs=False,
|
| 124 |
+
)
|
| 125 |
+
raw_events = {
|
| 126 |
+
ds.description["subject"]: bi_annotations_to_events(ds.raw)
|
| 127 |
+
for ds in windows_ds.datasets
|
| 128 |
+
}
|
| 129 |
+
metadata = windows_ds.get_metadata()
|
| 130 |
+
samples, subjects = [], []
|
| 131 |
+
for i in range(len(windows_ds)):
|
| 132 |
+
x, _, crop_inds = windows_ds[i]
|
| 133 |
+
eeg = torch.as_tensor(np.asarray(x), dtype=torch.float32)
|
| 134 |
+
subject = int(metadata.iloc[i]["subject"])
|
| 135 |
+
window_onset = float(crop_inds[1]) / SFREQ
|
| 136 |
+
target = dance_target_builder(
|
| 137 |
+
raw_events[subject], window_onset, WINDOW_S, MAX_EVENTS, NUM_LATENTS
|
| 138 |
+
)
|
| 139 |
+
samples.append((eeg, target))
|
| 140 |
+
subjects.append(subject)
|
| 141 |
+
chs_info = windows_ds.datasets[0].raw.info["chs"]
|
| 142 |
+
return samples, np.asarray(subjects), chs_info
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@torch.no_grad()
|
| 146 |
+
def evaluate(model, loader, device):
|
| 147 |
+
model.eval()
|
| 148 |
+
ev_f1s, dense_preds, dense_targets = [], [], []
|
| 149 |
+
for batch in loader:
|
| 150 |
+
batch = {k: v.to(device) for k, v in batch.items()}
|
| 151 |
+
out = model.detect(batch["eeg"])
|
| 152 |
+
pred_events = detections_to_events(out, duration=WINDOW_S)
|
| 153 |
+
for bi in range(batch["eeg"].shape[0]):
|
| 154 |
+
gt = [
|
| 155 |
+
(float(s) * WINDOW_S, float(e) * WINDOW_S, int(c))
|
| 156 |
+
for s, e, c in zip(batch["start"][bi], batch["end"][bi], batch["class"][bi])
|
| 157 |
+
if int(c) != 0
|
| 158 |
+
]
|
| 159 |
+
preds = [(s, e, c) for (s, e, c, _c) in pred_events[bi]]
|
| 160 |
+
ev_f1s.append(f1_event(preds, gt, iou_threshold=0.5))
|
| 161 |
+
dense_preds.append(out["dense"].argmax(-1).reshape(-1).cpu())
|
| 162 |
+
dense_targets.append(batch["dense"].reshape(-1).cpu())
|
| 163 |
+
dp = torch.cat(dense_preds).numpy()
|
| 164 |
+
dt = torch.cat(dense_targets).numpy()
|
| 165 |
+
sample_f1 = f1_score(dt, dp, labels=list(range(N_CLASSES)), average="macro")
|
| 166 |
+
return float(np.mean(ev_f1s)), float(sample_f1)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def main():
|
| 170 |
+
ap = argparse.ArgumentParser()
|
| 171 |
+
ap.add_argument("--train", type=int, nargs="+", default=[1, 2, 4, 5, 6, 7, 8, 9])
|
| 172 |
+
ap.add_argument("--test", type=int, default=3)
|
| 173 |
+
ap.add_argument("--epochs", type=int, default=100)
|
| 174 |
+
ap.add_argument("--batch-size", type=int, default=8)
|
| 175 |
+
ap.add_argument("--max-lr", type=float, default=5e-4)
|
| 176 |
+
ap.add_argument("--onecycle", action="store_true", help="use OneCycle LR (else constant)")
|
| 177 |
+
ap.add_argument("--out", type=str, default="/private/home/jarod/dance_ckpt/model.pt")
|
| 178 |
+
args = ap.parse_args()
|
| 179 |
+
|
| 180 |
+
set_random_seeds(seed=0, cuda=torch.cuda.is_available())
|
| 181 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 182 |
+
|
| 183 |
+
all_subjects = sorted(set(args.train) | {args.test})
|
| 184 |
+
print(f"Loading BI2014a subjects {all_subjects} (test={args.test}) ...", flush=True)
|
| 185 |
+
samples, subjects, chs_info = build_samples(all_subjects)
|
| 186 |
+
train_idx = np.flatnonzero(subjects != args.test)
|
| 187 |
+
test_idx = np.flatnonzero(subjects == args.test)
|
| 188 |
+
train_samples = [samples[i] for i in train_idx]
|
| 189 |
+
test_samples = [samples[i] for i in test_idx]
|
| 190 |
+
print(f"{len(train_samples)} train windows, {len(test_samples)} test windows, "
|
| 191 |
+
f"n_chans={len(chs_info)}", flush=True)
|
| 192 |
+
|
| 193 |
+
train_loader = DataLoader(train_samples, batch_size=args.batch_size, shuffle=True,
|
| 194 |
+
collate_fn=dance_collate, drop_last=True)
|
| 195 |
+
test_loader = DataLoader(test_samples, batch_size=len(test_samples),
|
| 196 |
+
collate_fn=dance_collate)
|
| 197 |
+
|
| 198 |
+
model = DANCE(
|
| 199 |
+
n_outputs=N_CLASSES, n_chans=len(chs_info), chs_info=chs_info,
|
| 200 |
+
n_times=WINDOW_SAMPLES, sfreq=SFREQ, input_window_seconds=WINDOW_S,
|
| 201 |
+
).to(device)
|
| 202 |
+
criterion = DanceLoss(num_latents=NUM_LATENTS)
|
| 203 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=args.max_lr)
|
| 204 |
+
steps = max(1, len(train_loader))
|
| 205 |
+
if args.onecycle:
|
| 206 |
+
sched = torch.optim.lr_scheduler.OneCycleLR(
|
| 207 |
+
optimizer, max_lr=args.max_lr, total_steps=args.epochs * steps, pct_start=0.1
|
| 208 |
+
)
|
| 209 |
+
else:
|
| 210 |
+
sched = None
|
| 211 |
+
|
| 212 |
+
best_f1, best_state = -1.0, None
|
| 213 |
+
for epoch in range(args.epochs):
|
| 214 |
+
model.train()
|
| 215 |
+
ep_loss = 0.0
|
| 216 |
+
for batch in train_loader:
|
| 217 |
+
batch = {k: v.to(device) for k, v in batch.items()}
|
| 218 |
+
optimizer.zero_grad()
|
| 219 |
+
out = model.detect(batch["eeg"])
|
| 220 |
+
loss, _ = criterion(out, batch, duration=WINDOW_S)
|
| 221 |
+
loss.backward()
|
| 222 |
+
optimizer.step()
|
| 223 |
+
if sched is not None:
|
| 224 |
+
sched.step()
|
| 225 |
+
ep_loss += float(loss)
|
| 226 |
+
ev_f1, samp_f1 = evaluate(model, test_loader, device)
|
| 227 |
+
if ev_f1 > best_f1:
|
| 228 |
+
best_f1 = ev_f1
|
| 229 |
+
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
|
| 230 |
+
torch.save(best_state, args.out)
|
| 231 |
+
if epoch % 5 == 0 or epoch == args.epochs - 1:
|
| 232 |
+
print(f"ep{epoch:03d} loss={ep_loss/steps:.3f} "
|
| 233 |
+
f"F1-event={ev_f1:.3f} F1-sample={samp_f1:.3f} (best={best_f1:.3f})",
|
| 234 |
+
flush=True)
|
| 235 |
+
|
| 236 |
+
print(f"\nBEST held-out F1-event={best_f1:.3f}; checkpoint saved to {args.out}", flush=True)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
if __name__ == "__main__":
|
| 240 |
+
main()
|