Evaluating a detector
Understand exactly how the training code scores a spindle detector, translate precision, recall and F1 into the language of closed-loop experiments, choose a threshold, compare sample-level and event-level scores, evaluate a trained model on its held-out test subjects, and report the results.
In this tutorial you will
- Read the two functions that compute every score you see during training.
- See why accuracy is misleading when spindles are rare, and why F1 is used.
- Move the decision threshold of the real network and watch the confusion matrix and the precision/recall curve.
- Compare sample-level and event-level scores on the same detections.
- Compute test-set scores for your model, across several subject splits, and report them completely.
1. How the training code scores a model
At the end of every epoch, run() calls run_inference on the validation subjects (tutorial 05, section 4.5) and then get_metrics. Both are short; here are their essential lines.
if classification:
batch_labels = (batch_labels > THRESHOLD)
batch_labels = batch_labels.float()
output, h1, h2, max_value = net_copy(batch_samples_input1, batch_samples_input2, batch_samples_input3, h1, h2, max_value)
output = output.view(-1)
loss_py = criterion(output, batch_labels).mean()
loss += loss_py.item()
if not classification:
output = (output > THRESHOLD)
batch_labels = (batch_labels > THRESHOLD)
else:
output = (output >= 0.5)
batch_labels_list.append(batch_labels)
output_list.append(output)
n += 1
batch_labels_total = torch.cat(batch_labels_list)
output_total = torch.cat(output_list)
loss /= n
acc = (output_total == batch_labels_total).float().mean()
output_total = output_total.float()
batch_labels_total = batch_labels_total.float()
tp = (batch_labels_total * output_total)
tn = ((1 - batch_labels_total) * (1 - output_total))
fp = ((1 - batch_labels_total) * output_total)
fn = (batch_labels_total * (1 - output_total))
return output_total, batch_labels_total, loss, acc, tp, tn, fp, fn
def get_metrics(tp, fp, fn):
tp_sum = tp.sum().to(torch.float32).item()
fp_sum = fp.sum().to(torch.float32).item()
fn_sum = fn.sum().to(torch.float32).item()
epsilon = 1e-7
precision = tp_sum / (tp_sum + fp_sum + epsilon)
recall = tp_sum / (tp_sum + fn_sum + epsilon)
f1 = 2 * (precision * recall) / (precision + recall + epsilon)
return f1, precision, recall
In words:
- Unit of evaluation: the sample. Each evaluated position (every labeled sample of the validation subjects, since
validation_network_stride= 1) is one decision. Scores are counts of samples, pooled over all subjects and segments; they are not averaged per subject. - Fixed threshold. In classification the network output is turned into a decision with
output >= 0.5, hard-coded. Labels are classes via> THRESHOLD(exactly 0/1 in the classification file, so the value does not matter there). In regression both output and label are binarized atTHRESHOLD(0.2 for phasefullon the command line, 0.5 when the module is imported; see tutorial 05). - Loss is averaged per batch, then over batches. Accuracy is the fraction of samples where decision and label agree.
- The epsilon (\(10^{-7}\)) avoids a division by zero: a detector that never says "spindle" gets precision 0 rather than an error.
2. Precision, recall and F1 for neuroscientists
Every evaluated sample falls in one of four cells:
| Label: spindle | Label: no spindle | |
|---|---|---|
| Detector says "spindle" | True positive (TP): a stimulation would be delivered during a spindle, as intended. | False positive (FP), a false alarm: a stimulation at the wrong time, outside any spindle. |
| Detector says "no spindle" | False negative (FN), a miss: a spindle that is not stimulated. | True negative (TN): silence when silence is wanted. |
Precision answers "when the device stimulates, how often is it really during a spindle?". Low precision means many stimuli land at the wrong time: your experimental condition is diluted, and the extra stimuli may themselves perturb sleep.
Recall (sensitivity, hit rate) answers "of all spindles, how many are caught?". Low recall means a lower stimulation "dose" and a sample of stimulated spindles that may be biased (for example toward the largest ones).
F1 is the harmonic mean of the two: it is high only when both are high, and it ignores true negatives entirely, which is what you want when the "nothing happens" class is huge. It is the same score used by MODA and by most spindle-detector comparisons [2, 3].
Remember that these are sample scores: a recall of 0.6 means 60% of spindle samples are detected, not 60% of spindles. Section 5 shows the difference.
3. The accuracy trap
Accuracy (the fraction of correct decisions) looks like the natural score, but it is dominated by the true negatives. In the paper's dataset "only about 5% of the signal is labeled as sleep spindles" [1]; a "detector" that always answers "no spindle" is then 95% accurate, and completely useless.
The arithmetic: per unit of recording, the detector has \(TP = R\,p\), \(FN = (1-R)\,p\) and \(FP = TP\,(1-P)/P\), where \(p\) is the prevalence, \(R\) the recall and \(P\) the precision; accuracy is \(1 - FN - FP\). With the paper's values and 5% prevalence, the real detector is about 96% accurate, barely more than the useless one. This is why the training code logs accuracy but selects models on F1 and loss.
4. The threshold, the confusion matrix and the precision/recall curve
The network outputs a number between 0 and 1. The threshold turns it into a decision, and it sets the trade-off: a low threshold catches more spindles (recall up) but also more noise (precision down). The training code always uses 0.5, but nothing forces you to deploy with 0.5. The paper's supplementary figure for the classification model is annotated "Threshold 0.55 / F1 score 0.61", and for real-time stimulation the authors write that "the best such trade-off is attained at a threshold of 0.84 with our model, yielding a precision and a recall of 0.71 both" [1] (with the event-based definitions of section 5).
5. Sample-level versus event-level scores
Experimenters think in spindles, not samples. An event-level (by-event) evaluation first turns the labels and the detections into events (onset, offset), then matches detected events to labeled ones. The standard criterion in the spindle literature was defined by Warby and colleagues: "The best match is determined by the ED pair with the maximum intersection/union score (max OED) that exceeds the overlap threshold (Toverlap) ... Throughout this study, we used a relaxed overlap threshold value of Toverlap = 0.2, unless stated otherwise" [2]. The intersection over union (IoU) of two events is the duration of their overlap divided by the duration covered by either. The same criterion with a threshold of 0.2 is used by the A7 detector paper ("For performance evaluation, we used an OvT of 0.2" [4]) and by MODA [3]. Kaulen and colleagues, while also reporting 0.2, "recommend future studies to evaluate spindle detectors at larger overlap thresholds (e.g., at 40%)" [5]; the DOSED detector paper reports its event scores at an IoU of 0.3 [6]. Always state the criterion you used.
The two levels can disagree strongly. One long detection that covers two spindles gives good sample recall but only one event match; a detection that starts late but overlaps most of a spindle is a true positive by event and a partial miss by sample; many short flickers of the output can each count as a separate false event.
Scores in both readouts are pooled over the three recordings. Detections are aligned to the labels by removing the 10-sample (40 ms) delay of the input filter, as in the previous widget.
Closed-loop scores: what matters for stimulation
For a stimulation device, an even more relevant question is "did the stimulus arrive during the spindle, and how late?". The paper redefines the counts for its real-time analysis: "(a) True positive: the first stimulus sent within the duration of a spindle, taking all delays into account; (b) False positive: any other stimulus; (c) False negative: any spindle that does not receive a stimulus within its labeled duration" [1]. The simulation notebook notebooks/simulate_Portiloop_1_input_classification.ipynb (function stimulation_analysis) computes, for each labeled spindle, the delay between its onset and the nearest stimulation (plus a constant 64 ms hardware delay), and counts stimulations falling within 0.25 s and 0.5 s of the onset. Tutorial 08 runs this analysis in your browser.
6. Evaluating on the test set
The validation scores logged during training are optimistic: the validation subjects were used to pick the best epoch. The honest estimate comes from the test subjects, which training never touches. They exist only if the model was trained with a test set (the default; --no_test_set removes it).
The split is reproducible: subjects are split with train_test_split(..., train_size=0.8, random_state=split_i) and the remaining 20% halved into test and validation with the same random_state; in phase full, phase 1 and phase 2 subject lists are split separately, then merged. Calling generate_dataloader with seq_len=None returns a test loader for the same split:
else:
nb_segment_test = len(np.hstack([range(int(s[1]), int(s[2])) for s in test_subject]))
batch_size_test = len(list(range(0, (seq_stride // network_stride) * network_stride, network_stride))) * nb_segment_test
ds_test = SignalDataset(filename=filename,
path=path_dataset,
window_size=window_size,
fe=fe,
seq_len=1,
seq_stride=1, # just to be sure, fixed value
list_subject=test_subject,
len_segment=len_segment)
- Check that you use the training split. A checkpoint must be evaluated with the
split_idxit was trained with; with another split, some "test" subjects may have been training subjects and the score is meaningless. The command line trains split 0 (even--experiment_index) or 2 (odd);train_custom.pyuses--split. - Run this script from the repository root (it needs the dataset and the checkpoint in
portiloop_software/dataset/; it runs on the CPU). It loads the checkpoint, builds the test loader, collects the raw network outputs with the GRU state carried along each segment (the same loop asrun_inference, but keeping the output before thresholding), and computes scores at several thresholds, plus the training code's own scores for comparison:import numpy as np import torch import torch.nn as nn from portiloop_software.portiloop_python.ANN import portiloop_detector_training as pdt cfg = pdt.get_final_model_config_dict(split_i=0) # the split MUST be the one used for training cfg["experiment_name"] = "my_variant" # checkpoint file name in the dataset folder # if you changed the architecture for training, set the same keys here (hidden_size, nb_channel, ...) fe = cfg["fe"] window = int(cfg["window_size_s"] * fe) # 54 samples seq_stride = int(cfg["seq_stride_s"] * fe) # 42 samples net = pdt.get_trained_model(cfg, pdt.path_dataset) # loads the weights on cfg["device_inference"] ('cpu') _, _, _, test_loader, batch_size_test, test_subjects = pdt.generate_dataloader( window_size=window, fe=fe, seq_len=None, seq_stride=seq_stride, distribution_mode=None, batch_size=None, nb_batch_per_epoch=None, classification=True, split_i=cfg["split_idx"], network_stride=1) print("test subjects:", list(test_subjects[:, 0])) def raw_outputs(loader, net, batch_size, hidden_size, nb_rnn_layers): """Same loop as run_inference, but keeps the network output before thresholding.""" net = net.eval() h = torch.zeros((nb_rnn_layers, batch_size, hidden_size)) ys, labels = [], [] with torch.no_grad(): for x1, x2, x3, lab in loader: y, h, _, _ = net(x1.float(), x2.float(), x3.float(), h, None) ys.append(y.view(-1)); labels.append(lab.float()) return torch.cat(ys).numpy(), (torch.cat(labels) > pdt.THRESHOLD).numpy() y, truth = raw_outputs(test_loader, net, batch_size_test, cfg["hidden_size"], cfg["nb_rnn_layers"]) for thr in [0.3, 0.5, 0.7]: # report the threshold chosen on VALIDATION data det = y >= thr tp = np.sum(det & truth); fp = np.sum(det & ~truth); fn = np.sum(~det & truth) p = tp / (tp + fp + 1e-7); r = tp / (tp + fn + 1e-7) print(f"threshold {thr:.1f}: precision {p:.3f} recall {r:.3f} F1 {2 * p * r / (p + r + 1e-7):.3f}") # the training code's own metrics (threshold 0.5), for comparison _, _, loss, acc, tp, tn, fp, fn = pdt.run_inference(test_loader, nn.BCELoss(reduction="none"), net, "cpu", cfg["hidden_size"], cfg["nb_rnn_layers"], True, batch_size_test) f1, precision, recall = pdt.get_metrics(tp, fp, fn) print(f"run_inference + get_metrics: F1 {f1:.3f} precision {precision:.3f} recall {recall:.3f} accuracy {acc.item():.3f}") - Read the output. We tested this script on the synthetic practice dataset with the model of the short CPU run of tutorial 05 (2 epochs of 10 batches, so a very poor model); the numbers below only show the format, they say nothing about real performance. The two lines at threshold 0.5 must agree, which checks that the raw-output loop reproduces
run_inference:test subjects: ['syn-p1-002', 'syn-p2-014', 'syn-p1-020'] threshold 0.3: precision 0.070 recall 1.000 F1 0.131 threshold 0.5: precision 0.120 recall 0.893 F1 0.211 threshold 0.7: precision 1.000 recall 0.023 F1 0.044 run_inference + get_metrics: F1 0.211 precision 0.120 recall 0.893 accuracy 0.530
TEST_SET is True and PHASE is 'full' (tutorial 05). With TEST_SET = False there is no test subject list and generate_dataloader(seq_len=None, ...) fails. To evaluate a p1 or p2 model, set the phase globals first (the set_phase helper of docs/tools/train_custom.py does it).The simulation notebook
The notebook notebooks/simulate_Portiloop_1_input_classification.ipynb does the same on the test set, but the way the device runs: its simulate() function builds the test loader with a network stride of 5 samples (8 interleaved hidden states, 20 ms between outputs) instead of 1, keeps the raw outputs (its own copy of run_inference has the thresholding commented out), applies THRESHOLD (0.5) and calls get_metrics:
_, _, _, test_loader, batch_size_test, test_subject = generate_dataloader(window_size=window_size, fe=fe, seq_len=None, seq_stride=seq_stride,
distribution_mode=None, batch_size=None, nb_batch_per_epoch=None,
classification=classification, split_i=split_idx,
network_stride=stride_between_runs)
...
f1_test, precision_test, recall_test = get_metrics(tp, fp, fn)
Its cell 8 (the cell you edit, tutorial 08) pairs the ten released checkpoints with splits 0 to 9, exp_name = [f"pareto_search_15_35_v4_{i}" for i in [0,11,12,3,14,15,16,7,18,9]], and loops over the splits; note that the loop ends with break, so as distributed it evaluates only the first one (pareto_search_15_35_v4_0 on split 0). Remove the break to evaluate all ten. The notebook is covered in tutorial 08.
7. Variability across splits
A test set of 10% of the subjects is small, so the test score depends on which subjects it contains. Train one model per split (split_idx 0, 1, 2, ...; see the SLURM array in tutorial 05), evaluate each on its own test subjects, and report the mean and the standard deviation across splits. The notebook already contains (commented out) the lines to do so:
# res = np.array(res)
# std_f1_test, std_precision_test, std_recall_test = np.std(res, axis=0)
# mean_f1_test, mean_precision_test, mean_recall_test = np.mean(res, axis=0)
8. How the paper evaluated and reported
The Portiloop paper [1] describes its protocol as follows (section 6, "Validation and performance"): "we choose to use only 10% of subjects as our validation set (for model selection), and another 10% of subjects as our test set (for final model evaluation)"; "we shuffle all subjects 10 times and compute a different training/validation/test split of the dataset each time (sets are thus made of separate subjects)"; "for each split, we use the training set to train 3 models, the validation set being used to estimate their f1-score. We select the best of these 3 models by its best f1-score on the validation set. We then report the performance of this model in terms of its f1-score on the test set"; and "we report the average test f1-score in Table 1, with the corresponding standard deviation being indicated in parenthesis."
Table 1 of the paper gives, for the final 1-input network (row 6), mean (standard deviation) over the ten splits:
| Cohort | Recall | Precision | F1 |
|---|---|---|---|
| Phase 1 (younger) | 0.7 (0.04) | 0.59 (0.05) | 0.64 (0.03) |
| Phase 2 (older) | 0.54 (0.09) | 0.58 (0.05) | 0.55 (0.05) |
| Whole cohort | 0.64 (0.05) | 0.59 (0.05) | 0.61 (0.03) |
The paper states that these metrics describe detection "on average over all data points", that is, sample-level scores like those of section 1. The same table lists the experts' inter-rater agreement (whole cohort F1 0.72 (0.12)) and offline detectors whose values are "taken from [28]", the MODA paper [3], which evaluates by event with an overlap threshold of 0.2. Sample-level and event-level F1 are different quantities (section 5), so compare rows of such tables with care, and in your own work state which one you report.
9. A reporting checklist
- Data: dataset and annotation source (for example MODA on MASS [3, 7]), phases or age groups, number of subjects in training, validation and test, and how subjects were assigned (per subject, random seed or
split_idx). - Labels: how labels were obtained (consensus threshold, 0.2 or 0.35 in MODA), and any post-processing of events (merging, minimum and maximum duration).
- Model: architecture and number of parameters (25,679 for the published network), configuration (or a link to it), code version (git commit).
- Training: sampling (balanced or natural), loss, optimizer and learning rate, number of epochs, early-stopping rule, and which checkpoint was kept (best F1 or best loss).
- Threshold: its value and how it was chosen (on validation data, never on the test set).
- Unit of evaluation: sample-level or event-level; for event-level, the matching rule and IoU threshold; the evaluation stride (every sample, or every 5 samples as on the device).
- Scores: precision, recall and F1 (not accuracy alone), on the test set, as mean and standard deviation over splits, overall and per phase or group.
- For closed-loop use: the stimulation-level scores and the distribution of stimulation delays relative to spindle onset (tutorial 08).
- Generalization: if you apply the model to your own recordings (tutorial 09), say whether you validated it on manually scored data from your setup.
Exercises
Best threshold versus 0.5
In the threshold widget, press "Go to best F1". How much F1 is gained relative to 0.5, and how do precision and recall change? Would you use this threshold in an experiment where extra stimuli are costly?
Answer
The gain depends on the synthetic recordings; read it from the readouts. The important point is the direction: moving the threshold trades precision against recall. If off-target stimuli are costly (for example because they could wake the participant or blur the contrast with a sham condition), choose a threshold above the F1 optimum, on validation data, and accept a lower recall.
Accuracy of "always no"
With 10% spindle samples, what are the accuracy, precision, recall and F1 of a detector that never says "spindle", using the formulas of get_metrics?
Answer
Accuracy 0.90; TP = 0 and FP = 0, so precision = 0 / (0 + 0 + 10-7) = 0; recall = 0; F1 = 0. The epsilon is what makes precision 0 instead of an error.
How strict should the event match be?
In the event-level widget, keep the threshold at 0.5 and raise the IoU criterion from 0.2 to 0.6. Which score changes and which does not? Why might a detector used for stimulation care less about the IoU than an offline spindle-density analysis?
Answer
Event-level precision and recall drop as matches require more overlap; sample-level scores do not change, because they do not use events. A stimulation device needs the onset to be detected early enough, not the whole spindle to be outlined; an offline analysis of spindle duration or density needs accurate boundaries, which a strict IoU rewards.
References
- Valenchon N, Bouteiller Y, Jourde HR, L'Heureux X, Sobral M, Coffey EBJ, Beltrame G (2022). The Portiloop: a deep learning-based open science tool for closed-loop brain stimulation. PLOS ONE 17(8): e0270696. doi:10.1371/journal.pone.0270696 (sections 5.1, 6, 6.1, Table 1 and S1 File).
- Warby SC, Wendt SL, Welinder P, et al. (2014). Sleep-spindle detection: crowdsourcing and evaluating performance of experts, non-experts and automated methods. Nature Methods 11(4): 385 to 392. doi:10.1038/nmeth.2855 (Online Methods, "By-Event Performance Analysis").
- Lacourse K, Yetton B, Mednick S, Warby SC (2020). Massive online data annotation, crowdsourcing to generate high quality sleep spindle annotations from EEG data. Scientific Data 7: 190. doi:10.1038/s41597-020-0533-4
- Lacourse K, Delfrate J, Beaudry J, Peppard P, Warby SC (2019). A sleep spindle detection algorithm that emulates human expert spindle scoring. Journal of Neuroscience Methods 316: 3 to 11. doi:10.1016/j.jneumeth.2018.08.014
- Kaulen L, Schwabedal JTC, Schneider J, Ritter P, Bialonski S (2022). Advanced sleep spindle identification with neural networks. Scientific Reports 12: 7686. doi:10.1038/s41598-022-11210-y
- Chambon S, Thorey V, Arnal PJ, Mignot E, Gramfort A (2019). DOSED: a deep learning approach to detect multiple sleep micro-events in EEG signal. Journal of Neuroscience Methods 321: 64 to 78. doi:10.1016/j.jneumeth.2019.03.017
- O'Reilly C, Gosselin N, Carrier J, Nielsen T (2014). Montreal Archive of Sleep Studies: an open-access resource for instrument benchmarking and exploratory research. Journal of Sleep Research 23(6): 628 to 635. doi:10.1111/jsr.12169