DeboraJ1 commited on
Commit
ec99ce1
·
2 Parent(s): 70ecc3f94602e8

merge to include data

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # auto_detect_breast_mri
2
 
3
  Malignancy classification on breast MRI, comparing an **abbreviated protocol (AP)** against the
@@ -210,5 +224,4 @@ tests/ unit tests only
210
  `pip install pre-commit && pre-commit install`; CI runs it on every push.
211
  - Weights & Biases: run configs and names are visible to everyone with access to the project, and
212
  heatmap captions contain patient keys. Set `wandb_mode: offline` (or `disabled`) in your config
213
- when that is not acceptable.
214
-
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ metrics:
6
+ - roc_auc
7
+ pipeline_tag: image-classification
8
+ tags:
9
+ - breast
10
+ - mri
11
+ - classification
12
+ - resnet18
13
+ - resnet50
14
+ ---
15
  # auto_detect_breast_mri
16
 
17
  Malignancy classification on breast MRI, comparing an **abbreviated protocol (AP)** against the
 
224
  `pip install pre-commit && pre-commit install`; CI runs it on every push.
225
  - Weights & Biases: run configs and names are visible to everyone with access to the project, and
226
  heatmap captions contain patient keys. Set `wandb_mode: offline` (or `disabled`) in your config
227
+ when that is not acceptable.
 
auto_detect_breast_mri/evaluation/__init__.py CHANGED
@@ -1 +0,0 @@
1
- """Metrics, statistics, GradCAM and the analyses built on predictions."""
 
 
auto_detect_breast_mri/evaluation/cluster_bootstrap.py CHANGED
@@ -277,10 +277,8 @@ def bca_interval(replications, observed, jackknife_values, confidence):
277
  def noninferiority_p_value(replications, margin):
278
  """
279
  One sided bootstrap p value for H0: delta <= -margin against H1: delta > -margin.
280
-
281
- Delta is AUC(AP) - AUC(FDP), so the abbreviated protocol is non-inferior when delta stays
282
- *above* the negative margin. Uses the same percentile scale as the reported intervals, so a two
283
- sided 95% interval whose lower bound exceeds -margin corresponds to p < 0.025.
284
  :return: p value in (0, 1]
285
  """
286
  replications = np.asarray(replications)
 
277
  def noninferiority_p_value(replications, margin):
278
  """
279
  One sided bootstrap p value for H0: delta <= -margin against H1: delta > -margin.
280
+ Uses the same percentile scale as the reported intervals, so a two sided 95% interval whose
281
+ lower bound exceeds -margin corresponds to p < 0.025.
 
 
282
  :return: p value in (0, 1]
283
  """
284
  replications = np.asarray(replications)
auto_detect_breast_mri/evaluation/gradcam.py CHANGED
@@ -284,11 +284,10 @@ def render_heatmap(model, model_name, volume, output_png, device=None):
284
  grayscale = cam(input_tensor=volume) # (1, W, H, D) or (1, W, H)
285
  heat = np.asarray(grayscale)[0]
286
  # torchio hands over volumes as (C, W, H, D), so the slice axis is the LAST one, not the
287
- # first spatial one.
288
- # k defines the slice with the strongest response -> ensure we do not output a "cold" slice where the lesion is not
289
- k = int(heat.sum(axis=(0, 1)).argmax()) if heat.ndim == 3 else None
290
- img_slice = volume[0, 0, :, :, k].detach().cpu().numpy()
291
- heat_slice = heat[..., k] if heat.ndim == 3 else heat
292
  fig, ax = plt.subplots()
293
  # .T so height runs down the image and width across it, the usual in-plane orientation
294
  ax.imshow(img_slice.T, cmap="gray")
 
284
  grayscale = cam(input_tensor=volume) # (1, W, H, D) or (1, W, H)
285
  heat = np.asarray(grayscale)[0]
286
  # torchio hands over volumes as (C, W, H, D), so the slice axis is the LAST one, not the
287
+ # first spatial one. Cutting along dim 2 gives a W x D strip (e.g. 256 x 32), which is why
288
+ # the overlay came out as a squeezed sliver instead of an in-plane image.
289
+ img_slice = volume[0, 0, :, :, volume.shape[-1] // 2].detach().cpu().numpy()
290
+ heat_slice = heat[..., heat.shape[-1] // 2] if heat.ndim == 3 else heat
 
291
  fig, ax = plt.subplots()
292
  # .T so height runs down the image and width across it, the usual in-plane orientation
293
  ax.imshow(img_slice.T, cmap="gray")
auto_detect_breast_mri/evaluation/subgroups.py CHANGED
@@ -238,6 +238,193 @@ def analyse_by_group(table, group_column, architectures, replications=2000, weig
238
  return results
239
 
240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  def to_frame(results, architectures):
242
  """
243
  The per subgroup results as a flat table, one row per (subgroup, architecture).
 
238
  return results
239
 
240
 
241
+ def to_frame(results, architectures):
242
+ """
243
+ The per subgroup results as a flat table, one row per (subgroup, architecture).
244
+ :return: list of dicts, ready for pandas
245
+ """
246
+ rows = []
247
+ for key, entry in results.items():
248
+ counts = entry['counts']
249
+ for architecture in architectures:
250
+ row = {'subgroup': key, 'label': entry.get('label', str(key)),
251
+ 'architecture': architecture, **counts}
252
+ values = entry['architectures'].get(architecture)
253
+ if values is None:
254
+ row['skipped'] = entry.get('skipped', '')
255
+ else:
256
+ row.update({'auc_AP': values['auc_ap'], 'auc_FDP': values['auc_fdp'],
257
+ 'delta_AP_minus_FDP': values['observed_delta'],
258
+ 'ci95_low': values['ci_95'][0], 'ci95_high': values['ci_95'][1],
259
+ 'bootstrap_se': values['bootstrap_se'],
260
+ 'folds_used': values['folds_used'], 'skipped': ''})
261
+ rows.append(row)
262
+ return rows
263
+
264
+ """
265
+ Performance within a subgroup of the out-of-fold table, e.g. per indication.
266
+
267
+ This is an exploratory companion to the primary AP vs FDP analysis, not a second confirmatory one.
268
+ Each subgroup is analysed with exactly the machinery of the primary analysis, only restricted to its
269
+ own rows: AUCs are computed *within* an outer fold and combined with weights that are fixed before
270
+ resampling, and the bootstrap redraws whole women so that both breasts and all repeated examinations
271
+ of one woman move together.
272
+
273
+ Three things are worth keeping in mind when reading the output:
274
+
275
+ * The fold weights are recomputed inside the subgroup. A subgroup's weights are therefore not the
276
+ weights of the primary analysis, and its delta is not a decomposition of the overall delta.
277
+ * Subgroups are small. A fold that holds only benign breasts has no AUC, is dropped, and the
278
+ remaining folds are renormalized; `folds_used` reports how many actually carried information.
279
+ * Nothing here is multiplicity adjusted across subgroups, and no non-inferiority verdict is derived.
280
+ A wide interval in a small subgroup means "not measurable here", never "inferior".
281
+ """
282
+
283
+ import numpy as np
284
+
285
+ from auto_detect_breast_mri.evaluation.cluster_bootstrap import (FoldClusterBootstrap, auc,
286
+ percentile_interval,
287
+ weighted_fold_difference)
288
+ from auto_detect_breast_mri.evaluation.oof_table import score_columns
289
+
290
+ # A subgroup below this many breasts, or with fewer than this many of either class, is reported with
291
+ # its counts but without a bootstrap: the interval would be an artefact of a handful of cases.
292
+ MIN_BREASTS = 20
293
+ MIN_PER_CLASS = 5
294
+
295
+
296
+ def weighted_fold_auc(rows_of_fold, labels, scores, weights):
297
+ """
298
+ One AUC per fold, combined with the fixed weights, folds without both classes dropped.
299
+ :return: (combined AUC, dict fold -> AUC, number of folds that contributed)
300
+ """
301
+ per_fold, combined, total_weight = {}, 0.0, 0.0
302
+ for fold, rows in rows_of_fold.items():
303
+ value = auc(labels[rows], scores[rows])
304
+ per_fold[fold] = value
305
+ if not np.isnan(value):
306
+ combined += weights[fold] * value
307
+ total_weight += weights[fold]
308
+ if total_weight == 0:
309
+ return np.nan, per_fold, 0
310
+ return combined / total_weight, per_fold, int(sum(not np.isnan(v) for v in per_fold.values()))
311
+
312
+
313
+ def describe_subgroup(rows, table):
314
+ """Counts that decide whether a subgroup can carry an analysis at all."""
315
+ part = table.iloc[rows]
316
+ labels = part['label'].to_numpy()
317
+ return {'breasts': len(part),
318
+ 'women': int(part['patient_id'].nunique()),
319
+ 'examinations': int(part['examination_id'].nunique()),
320
+ 'malignant': int((labels == 1).sum()),
321
+ 'benign': int((labels == 0).sum()),
322
+ 'folds_with_both_classes': int(sum(
323
+ 1 for _, fold_part in part.groupby('outer_fold')
324
+ if 0 < fold_part['label'].sum() < len(fold_part)))}
325
+
326
+
327
+ def analysable(counts, min_breasts=MIN_BREASTS, min_per_class=MIN_PER_CLASS):
328
+ """
329
+ Whether a subgroup is worth bootstrapping at all.
330
+ :return: (bool, reason) with reason empty when it is analysable
331
+ """
332
+ if counts['breasts'] < min_breasts:
333
+ return False, f"only {counts['breasts']} breasts (minimum {min_breasts})"
334
+ if counts['malignant'] < min_per_class or counts['benign'] < min_per_class:
335
+ return False, (f"only {counts['malignant']} malignant / {counts['benign']} benign "
336
+ f"(minimum {min_per_class} each)")
337
+ if counts['folds_with_both_classes'] == 0:
338
+ return False, "no outer fold holds both classes, every fold level AUC is undefined"
339
+ return True, ""
340
+
341
+
342
+ def analyse_subgroup(table, rows, architectures, replications, weighting, seed, stratify):
343
+ """
344
+ AUC of every model and the paired AP minus FDP difference inside one subgroup.
345
+
346
+ :param table: the wide out-of-fold table
347
+ :param rows: positional row indices of the subgroup within `table`
348
+ :param architectures: architecture labels to analyse
349
+ :return: dict with the counts, the per architecture results and, if the subgroup is too small,
350
+ a 'skipped' reason instead of the bootstrap results
351
+ """
352
+ counts = describe_subgroup(rows, table)
353
+ usable, reason = analysable(counts)
354
+ result = {'counts': counts, 'architectures': {}}
355
+ if not usable:
356
+ result['skipped'] = reason
357
+ return result
358
+
359
+ part = table.iloc[rows].reset_index(drop=True)
360
+ labels = part['label'].to_numpy()
361
+ bootstrap = FoldClusterBootstrap(part['outer_fold'].to_numpy(), part['patient_id'].to_numpy(),
362
+ labels, stratify_by_outcome=stratify)
363
+ weights = bootstrap.fold_weights(weighting)
364
+ observed_rows = bootstrap.observed_rows()
365
+ scores = {architecture: tuple(part[name].to_numpy() for name in score_columns(architecture))
366
+ for architecture in architectures}
367
+
368
+ for architecture in architectures:
369
+ ap_scores, fdp_scores = scores[architecture]
370
+ auc_ap, per_fold_ap, folds_ap = weighted_fold_auc(observed_rows, labels, ap_scores, weights)
371
+ auc_fdp, per_fold_fdp, _ = weighted_fold_auc(observed_rows, labels, fdp_scores, weights)
372
+ delta, _ = weighted_fold_difference(observed_rows, labels, ap_scores, fdp_scores, weights)
373
+ result['architectures'][architecture] = {
374
+ 'auc_ap': auc_ap, 'auc_fdp': auc_fdp, 'observed_delta': delta,
375
+ 'folds_used': folds_ap,
376
+ 'per_fold': {fold: (per_fold_ap[fold], per_fold_fdp[fold]) for fold in per_fold_ap},
377
+ 'replications': np.full(replications, np.nan)}
378
+
379
+ # one rng for the whole subgroup, so all architectures see the same resampled women
380
+ rng = np.random.default_rng(seed)
381
+ degenerate = 0
382
+ for replication in range(replications):
383
+ rows_of_fold = bootstrap.resample_rows(rng)
384
+ for architecture in architectures:
385
+ ap_scores, fdp_scores = scores[architecture]
386
+ delta, _ = weighted_fold_difference(rows_of_fold, labels, ap_scores, fdp_scores, weights)
387
+ result['architectures'][architecture]['replications'][replication] = delta
388
+ degenerate += int(np.isnan(delta))
389
+
390
+ for architecture in architectures:
391
+ entry = result['architectures'][architecture]
392
+ entry['ci_95'] = percentile_interval(entry['replications'], 0.95)
393
+ entry['bootstrap_se'] = float(np.nanstd(entry['replications'], ddof=1))
394
+ entry['degenerate_replications'] = int(np.isnan(entry['replications']).sum())
395
+ result['weights'] = weights
396
+ result['degenerate_replications'] = degenerate
397
+ return result
398
+
399
+
400
+ def analyse_by_group(table, group_column, architectures, replications=2000, weighting='pairs',
401
+ seed=0, stratify=True, label_column=None):
402
+ """
403
+ Run analyse_subgroup for every value of `group_column`, plus one 'all' row over the whole table.
404
+
405
+ :param table: the wide out-of-fold table
406
+ :param group_column: column holding the subgroup key, e.g. 'indication'
407
+ :param label_column: optional column holding a readable name of the subgroup
408
+ :return: dict subgroup key -> result of analyse_subgroup, 'all' first
409
+ """
410
+ results = {}
411
+ everything = np.arange(len(table))
412
+ results['all'] = analyse_subgroup(table, everything, architectures, replications, weighting,
413
+ seed, stratify)
414
+ results['all']['label'] = 'all breasts'
415
+
416
+ positions = {key: np.flatnonzero((table[group_column] == key).to_numpy())
417
+ for key in table[group_column].unique()}
418
+ for key in sorted(positions, key=lambda k: (-len(positions[k]), str(k))):
419
+ print(f" subgroup {key}: {len(positions[key])} breasts", flush=True)
420
+ entry = analyse_subgroup(table, positions[key], architectures, replications, weighting,
421
+ seed, stratify)
422
+ entry['label'] = (table.iloc[positions[key]][label_column].iloc[0]
423
+ if label_column else str(key))
424
+ results[key] = entry
425
+ return results
426
+
427
+
428
  def to_frame(results, architectures):
429
  """
430
  The per subgroup results as a flat table, one row per (subgroup, architecture).
auto_detect_breast_mri/models/checkpoints.py CHANGED
@@ -4,6 +4,60 @@ import torch
4
  from torch import nn
5
 
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  def save_model(model: nn.Module, parent_dir: str, filename: str):
8
  if all([model, parent_dir, filename]):
9
  torch.save(model.state_dict(), parent_dir + '/' + filename + '.pth')
 
4
  from torch import nn
5
 
6
 
7
+ def save_model(model: nn.Module, parent_dir: str, filename: str):
8
+ if all([model, parent_dir, filename]):
9
+ torch.save(model.state_dict(), parent_dir + '/' + filename + '.pth')
10
+
11
+
12
+ def load_pretrained_model(model, model_path, DEVICE):
13
+ '''
14
+ Load a model from '.pth' file to use the pretrained model in our later training loop or only evaluate it.
15
+ '''
16
+ checkpoint = torch.load(model_path, torch.device(DEVICE), weights_only=True)
17
+ state_dict = {}
18
+ if 'state_dict' in checkpoint.keys():
19
+ for k, v in checkpoint['state_dict'].items():
20
+ if k.startswith('module.'):
21
+ key = k.replace('module.', '')
22
+ else:
23
+ key = k
24
+ # check dimension of checkpoint value:
25
+ desired_shape = model.state_dict()[key].shape
26
+ if desired_shape != v.shape:
27
+ pretrained_layer_tensor = torch.empty(desired_shape)
28
+ (l, m, n, o, p) = desired_shape
29
+ (a, b, c, d, e) = v.shape # given pretrained parameters shape
30
+ pretrained_layer_tensor[:a, :b, :c, :d, :e] = v
31
+
32
+ # Duplicate values along the additional dimensions
33
+ if a < l:
34
+ for i in range(l):
35
+ pretrained_layer_tensor[a + i:a + i + 1, :, :, :, :] = pretrained_layer_tensor[:a, :, :, :, :]
36
+ if b < m:
37
+ for j in range(m):
38
+ pretrained_layer_tensor[:, b + j:b + j + 1, :, :, :] = pretrained_layer_tensor[:, :b, :, :, :]
39
+ if c < n:
40
+ for k in range(n):
41
+ pretrained_layer_tensor[:, :, c + k:c + k + 1, :, :] = pretrained_layer_tensor[:, :, :c, :, :]
42
+ if d < o:
43
+ for l in range(o):
44
+ pretrained_layer_tensor[:, :, :, d + l:d + l + 1, :] = pretrained_layer_tensor[:, :, :, :d, :]
45
+ if e < p:
46
+ for m in range(p):
47
+ pretrained_layer_tensor[:, :, :, :, e + m:e + m + 1] = pretrained_layer_tensor[:, :, :, :, :e]
48
+ for k, v in model.state_dict().items():
49
+ if k not in state_dict.keys():
50
+ state_dict[k] = model.state_dict()[k]
51
+ return state_dict
52
+ else:
53
+ return checkpoint
54
+
55
+ """Saving and loading model checkpoints."""
56
+
57
+ import torch
58
+ from torch import nn
59
+
60
+
61
  def save_model(model: nn.Module, parent_dir: str, filename: str):
62
  if all([model, parent_dir, filename]):
63
  torch.save(model.state_dict(), parent_dir + '/' + filename + '.pth')
auto_detect_breast_mri/training/__init__.py CHANGED
@@ -1 +1 @@
1
- """Training and evaluation loops, LR schedules and the shared CLI."""
 
1
+ """Training and evaluation loops, LR schedules and the shared CLI."""
auto_detect_breast_mri/training/cli.py CHANGED
@@ -62,4 +62,3 @@ def generate_parser():
62
  "Otherwise, parameter model_path must be specified or testing will evaluate untrained model.")
63
  return parser
64
 
65
-
 
62
  "Otherwise, parameter model_path must be specified or testing will evaluate untrained model.")
63
  return parser
64
 
 
jobs/cross_validation.sbatch.example CHANGED
@@ -47,7 +47,7 @@ if [[ -n "${VENV:-}" ]]; then
47
  fi
48
 
49
  cd "$REPO_ROOT"
50
- export AIMRI_CONFIG=/rwthfs/rz/cluster/home/it336446/Project/auto_detect_breast_mri/config.example.yaml
51
  # Python puts the script's own directory on sys.path, never the working directory, so the checkout
52
  # has to be on PYTHONPATH for `import auto_detect_breast_mri` to work. Harmless when the package is
53
  # pip installed into $VENV as well.
 
47
  fi
48
 
49
  cd "$REPO_ROOT"
50
+
51
  # Python puts the script's own directory on sys.path, never the working directory, so the checkout
52
  # has to be on PYTHONPATH for `import auto_detect_breast_mri` to work. Harmless when the package is
53
  # pip installed into $VENV as well.
requirements.txt CHANGED
@@ -24,3 +24,30 @@ opencv-python~=4.10.0.84
24
  torchmetrics~=1.4.2
25
  grad-cam~=1.5.4
26
  PyYAML~=6.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  torchmetrics~=1.4.2
25
  grad-cam~=1.5.4
26
  PyYAML~=6.0
27
+
28
+ numpy~=1.26.4
29
+ matplotlib~=3.9.2
30
+ pandas~=2.2.2
31
+ monai
32
+ setuptools~=75.5.0
33
+ torchvision~=0.19.1
34
+ torchio
35
+ wandb~=0.18.0
36
+ scikit-learn~=1.5.2
37
+ scikit-image~=0.24.0
38
+ pillow~=11.0.0
39
+ nibabel
40
+ openpyxl
41
+
42
+ torch~=2.4.1
43
+ pydicom~=2.4.3
44
+ SimpleITK~=2.4.0
45
+ tqdm~=4.67.0
46
+ scipy~=1.14.1
47
+ sympy~=1.13.2
48
+ tcia_utils~=2.2.1
49
+ imageio~=2.36.0
50
+ opencv-python~=4.10.0.84
51
+ torchmetrics~=1.4.2
52
+ grad-cam~=1.5.4
53
+ PyYAML~=6.0
scripts/validation/__pycache__/read_pkl.cpython-312.pyc ADDED
Binary file (5.5 kB). View file
 
scripts/validation/generate_fraction_performance_curve.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Learning curve of AP and FDP models over the size of the training set.
3
+
4
+ python scripts/validation/generate_fraction_performance_curve.py <results_dir> [<results_dir> ...]
5
+
6
+ Every training run pickles the test set predictions of its fold as
7
+
8
+ results_<architecture>_<protocol>_fold=<k>_frac=<fraction>
9
+
10
+ so one point of the curve is the mean test AUC of the five outer folds of one
11
+ (architecture, protocol, fraction), and the error bar is the spread over those five folds. The
12
+ folds are separate models on disjoint test sets, so this is the fold to fold variability of the
13
+ whole training procedure, not a confidence interval of a single model.
14
+
15
+ Several result folders may be given, which is the usual case once a fraction has been retrained:
16
+ a (architecture, protocol, fold, fraction) found twice is taken from the folder named last, and
17
+ every override is listed in the output.
18
+
19
+ The x axis is the number of training samples behind each fraction, counted from the split files
20
+ under --split_root (they differ slightly between folds, so the mean is used). Without --split_root
21
+ the fractions themselves are plotted.
22
+
23
+ Writes <output>/fraction_performance_curve.{png,pdf} and the underlying numbers as
24
+ fraction_performance_curve.csv.
25
+ """
26
+
27
+ import argparse
28
+ import pickle
29
+ import re
30
+ from collections import defaultdict
31
+ from pathlib import Path
32
+
33
+ import numpy as np
34
+
35
+ from auto_detect_breast_mri.config import resolve_path
36
+ from auto_detect_breast_mri.evaluation.cluster_bootstrap import auc
37
+
38
+ # results_<architecture>_<protocol>_fold=<k>_frac=<fraction>, as written by train.py and
39
+ # compare_protocols.py. The per epoch files use 'fold<k>' without the '=', so they do not match.
40
+ RESULT_PATTERN = re.compile(r'^results_(?P<architecture>resnet\d+)_(?P<protocol>abrv|full)'
41
+ r'_fold=(?P<fold>\d+)_frac=(?P<fraction>[0-9.]+)$')
42
+
43
+ PROTOCOL_LABELS = {'abrv': 'AP', 'full': 'FDP'}
44
+ ARCHITECTURE_LABELS = {'resnet18': 'ResNet18', 'resnet50': 'ResNet50'}
45
+
46
+ # Categorical slots in fixed order, validated for colour vision deficiency separation against the
47
+ # light chart surface. Protocol is additionally carried by the line style and the marker, so the
48
+ # series stay distinguishable in greyscale and for colourblind readers.
49
+ SERIES_STYLE = {
50
+ ('resnet18', 'abrv'): {'color': '#2a78d6', 'marker': 'o', 'linestyle': '-'},
51
+ ('resnet18', 'full'): {'color': '#eb6834', 'marker': 's', 'linestyle': '--'},
52
+ ('resnet50', 'abrv'): {'color': '#1baf7a', 'marker': '^', 'linestyle': '-'},
53
+ ('resnet50', 'full'): {'color': '#eda100', 'marker': 'D', 'linestyle': '--'},
54
+ }
55
+ SURFACE, GRIDLINE, MUTED_INK, PRIMARY_INK = '#fcfcfb', '#e1e0d9', '#898781', '#0b0b0b'
56
+
57
+
58
+ def as_array(values):
59
+ """Flat numpy array from a list, numpy array or torch tensor."""
60
+ if hasattr(values, 'detach'):
61
+ values = values.detach().cpu().numpy()
62
+ return np.asarray(values).ravel()
63
+
64
+
65
+ def read_results(directories):
66
+ """
67
+ Test set AUC of every result file found.
68
+
69
+ :param directories: list of folders holding the pickled result files
70
+ :return: (dict (architecture, protocol, fraction) -> {fold: auc}, list of override notes)
71
+ """
72
+ per_series, source_of, overrides = defaultdict(dict), {}, []
73
+ for directory in directories:
74
+ directory = Path(directory)
75
+ if not directory.is_dir():
76
+ raise FileNotFoundError(f"{directory} is not a directory.")
77
+ for path in sorted(directory.iterdir()):
78
+ parsed = RESULT_PATTERN.match(path.name)
79
+ if parsed is None or not path.is_file():
80
+ continue
81
+ key = (parsed['architecture'], parsed['protocol'], float(parsed['fraction']))
82
+ fold = int(parsed['fold'])
83
+
84
+ with open(path, 'rb') as handle:
85
+ results = pickle.load(handle)
86
+ # train.py stores 'y_prob', compare_protocols.py stores 'y_probs'
87
+ scores = results.get('y_prob', results.get('y_probs'))
88
+ if scores is None:
89
+ raise KeyError(f"{path} has neither 'y_prob' nor 'y_probs'; keys: {sorted(results)}")
90
+ labels, scores = as_array(results['y_true']), as_array(scores)
91
+ if len(labels) != len(scores):
92
+ raise ValueError(f"{path}: {len(labels)} labels but {len(scores)} scores.")
93
+
94
+ if fold in per_series[key]:
95
+ overrides.append(f"{key[0]}_{key[1]} fold {fold} frac {key[2]}: "
96
+ f"{source_of[(key, fold)]} -> {path}")
97
+ per_series[key][fold] = float(auc(labels, scores))
98
+ source_of[(key, fold)] = path
99
+ return dict(per_series), overrides
100
+
101
+
102
+ def training_set_sizes(split_root, fractions, folds=range(5), subfold=0):
103
+ """
104
+ Number of training rows behind each fraction, averaged over the folds.
105
+
106
+ The split files are the ground truth here: a fraction file holds the cases that fraction was
107
+ actually trained on, which is not exactly `fraction * full size` after stratified rounding.
108
+
109
+ :return: dict fraction -> mean number of rows, fractions with no split file left out
110
+ """
111
+ split_root = Path(split_root)
112
+ sizes = {}
113
+ for fraction in fractions:
114
+ per_fold = []
115
+ for fold in folds:
116
+ suffix = '' if fraction >= 1 else f'_frac{fraction:g}'
117
+ path = split_root / f"fold{fold}" / f"stratified_training_set-f{fold}-{subfold}{suffix}.csv"
118
+ if path.exists():
119
+ with open(path) as handle:
120
+ per_fold.append(sum(1 for _ in handle) - 1) # minus the header
121
+ if per_fold:
122
+ sizes[fraction] = float(np.mean(per_fold))
123
+ return sizes
124
+
125
+
126
+ def summarise(per_series, error):
127
+ """
128
+ Mean and error bar per (architecture, protocol, fraction).
129
+
130
+ :param error: 'std' (spread over folds), 'sem' or 'ci95' (t based, needs >= 2 folds)
131
+ :return: list of row dicts
132
+ """
133
+ rows = []
134
+ for (architecture, protocol, fraction), per_fold in sorted(per_series.items()):
135
+ values = np.array([per_fold[fold] for fold in sorted(per_fold)], dtype=float)
136
+ values = values[~np.isnan(values)]
137
+ mean = float(values.mean()) if len(values) else np.nan
138
+ deviation = float(values.std(ddof=1)) if len(values) > 1 else 0.0
139
+ if error == 'std' or len(values) < 2:
140
+ bar = deviation
141
+ else:
142
+ standard_error = deviation / np.sqrt(len(values))
143
+ if error == 'sem':
144
+ bar = standard_error
145
+ else:
146
+ from scipy.stats import t
147
+ bar = float(t.ppf(0.975, len(values) - 1) * standard_error)
148
+ rows.append({'architecture': architecture, 'protocol': protocol, 'fraction': fraction,
149
+ 'folds': len(values), 'mean_auc': mean, 'error': bar,
150
+ 'std_auc': deviation, 'min_auc': float(values.min()) if len(values) else np.nan,
151
+ 'max_auc': float(values.max()) if len(values) else np.nan,
152
+ 'per_fold': {fold: per_fold[fold] for fold in sorted(per_fold)}})
153
+ return rows
154
+
155
+
156
+ def plot(rows, sizes, output_base, error_label, title, expected_folds=5):
157
+ """Draw the curve, one series per (architecture, protocol), with an error bar per point."""
158
+ import matplotlib
159
+ matplotlib.use('Agg')
160
+ import matplotlib.pyplot as plt
161
+
162
+ figure, axes = plt.subplots(figsize=(9, 4.6), facecolor=SURFACE)
163
+ axes.set_facecolor(SURFACE)
164
+
165
+ by_series = defaultdict(list)
166
+ for row in rows:
167
+ by_series[(row['architecture'], row['protocol'])].append(row)
168
+
169
+ for key in sorted(by_series, key=lambda k: list(SERIES_STYLE).index(k)
170
+ if k in SERIES_STYLE else 99):
171
+ series = sorted(by_series[key], key=lambda r: r['fraction'])
172
+ x = [sizes.get(r['fraction'], r['fraction']) for r in series]
173
+ y = [r['mean_auc'] for r in series]
174
+ yerr = [r['error'] for r in series]
175
+ style = SERIES_STYLE.get(key, {'color': MUTED_INK, 'marker': 'o', 'linestyle': '-'})
176
+ label = f"{ARCHITECTURE_LABELS.get(key[0], key[0])} {PROTOCOL_LABELS.get(key[1], key[1])}"
177
+ axes.errorbar(x, y, yerr=yerr, label=label, capsize=3, capthick=1.2,
178
+ linewidth=2, markersize=7, markeredgecolor=SURFACE, markeredgewidth=1.0,
179
+ elinewidth=1.2, **style)
180
+
181
+ axes.set_xlabel("N training samples" if sizes else "fraction of the training data",
182
+ color=PRIMARY_INK)
183
+ axes.set_ylabel("AUC", color=PRIMARY_INK)
184
+ axes.set_title(title, color=PRIMARY_INK, fontsize=13, pad=12)
185
+ axes.grid(axis='y', color=GRIDLINE, linewidth=0.8)
186
+ axes.set_axisbelow(True)
187
+ for side in ('top', 'right'):
188
+ axes.spines[side].set_visible(False)
189
+ for side in ('left', 'bottom'):
190
+ axes.spines[side].set_color(GRIDLINE)
191
+ axes.tick_params(colors=MUTED_INK)
192
+ legend = axes.legend(loc='center left', bbox_to_anchor=(1.01, 0.5), frameon=False)
193
+ for text in legend.get_texts():
194
+ text.set_color(PRIMARY_INK)
195
+
196
+ incomplete = [r for r in rows if r['folds'] != expected_folds]
197
+ caption = f"error bars: {error_label} over the outer folds"
198
+ if incomplete:
199
+ caption += f"; {len(incomplete)} point(s) rest on fewer than {expected_folds} folds"
200
+ figure.text(0.01, 0.01, caption, color=MUTED_INK, fontsize=8)
201
+
202
+ figure.tight_layout(rect=(0, 0.03, 1, 1))
203
+ written = []
204
+ for extension in ('png', 'pdf'):
205
+ path = output_base.with_suffix(f'.{extension}')
206
+ figure.savefig(path, dpi=200, facecolor=SURFACE)
207
+ written.append(path)
208
+ plt.close(figure)
209
+ return written
210
+
211
+
212
+ def build_parser():
213
+ parser = argparse.ArgumentParser(prog="generate_fraction_performance_curve", description=__doc__,
214
+ formatter_class=argparse.RawDescriptionHelpFormatter)
215
+ parser.add_argument("results_dirs", nargs='+',
216
+ help="Folder(s) holding results_<arch>_<protocol>_fold=<k>_frac=<f> files. "
217
+ "A run found in several folders is taken from the last one given.")
218
+ parser.add_argument("-o", "--output_path", default=None,
219
+ help="Folder the figure and the CSV are written to.")
220
+ parser.add_argument("--split_root", default=None,
221
+ help="Split file root, used to label the x axis with the real number of "
222
+ "training samples. Without it the fractions are plotted.")
223
+ parser.add_argument("--subfold", type=int, default=0,
224
+ help="Inner fold of the training split files. Default: 0")
225
+ parser.add_argument("--folds", type=int, nargs='+', default=list(range(5)),
226
+ help="Outer folds expected per point. Default: 0 1 2 3 4")
227
+ parser.add_argument("-e", "--error", choices=['std', 'sem', 'ci95'], default='std',
228
+ help="Error bar: standard deviation over the folds (default), standard "
229
+ "error of the mean, or a t based 95%% interval.")
230
+ parser.add_argument("--title", default="Performance of models trained on AP and FDP")
231
+ return parser
232
+
233
+
234
+ def main():
235
+ args = build_parser().parse_args()
236
+
237
+ output_dir = Path(resolve_path(args.output_path, "output_root", "output folder")) / "figures"
238
+ output_dir.mkdir(parents=True, exist_ok=True)
239
+
240
+ per_series, overrides = read_results(args.results_dirs)
241
+ if not per_series:
242
+ raise FileNotFoundError(f"No results_<arch>_<protocol>_fold=<k>_frac=<f> files in "
243
+ f"{', '.join(map(str, args.results_dirs))}.")
244
+ for note in overrides:
245
+ print(f" overridden by a later folder: {note}")
246
+
247
+ rows = summarise(per_series, args.error)
248
+ fractions = sorted({row['fraction'] for row in rows})
249
+ sizes = training_set_sizes(args.split_root, fractions, args.folds, args.subfold) \
250
+ if args.split_root else {}
251
+ if args.split_root and len(sizes) < len(fractions):
252
+ print(f" WARNING: no split file for fraction(s) "
253
+ f"{sorted(set(fractions) - set(sizes))}; those points keep the fraction as x.")
254
+
255
+ error_label = {'std': 'standard deviation', 'sem': 'standard error of the mean',
256
+ 'ci95': '95% interval'}[args.error]
257
+ print(f"\n{'architecture':<12} {'protocol':<9} {'fraction':>8} {'n_train':>8} {'folds':>6} "
258
+ f"{'mean AUC':>9} {'+/-':>7} per fold")
259
+ for row in sorted(rows, key=lambda r: (r['architecture'], r['protocol'], r['fraction'])):
260
+ size = sizes.get(row['fraction'])
261
+ per_fold = ' '.join(f"{value:.3f}" for _, value in sorted(row['per_fold'].items()))
262
+ flag = '' if row['folds'] == len(args.folds) else ' <- incomplete'
263
+ print(f"{row['architecture']:<12} {row['protocol']:<9} {row['fraction']:>8g} "
264
+ f"{(f'{size:.0f}' if size else '-'):>8} {row['folds']:>6} {row['mean_auc']:>9.4f} "
265
+ f"{row['error']:>7.4f} {per_fold}{flag}")
266
+
267
+ import pandas as pd
268
+ table = pd.DataFrame([{**{k: v for k, v in row.items() if k != 'per_fold'},
269
+ 'n_training_samples': sizes.get(row['fraction']),
270
+ **{f'auc_fold{fold}': value for fold, value in row['per_fold'].items()}}
271
+ for row in rows])
272
+ csv_path = output_dir / "fraction_performance_curve.csv"
273
+ table.to_csv(csv_path, index=False)
274
+
275
+ written = plot(rows, sizes, output_dir / "fraction_performance_curve", error_label,
276
+ args.title, expected_folds=len(args.folds))
277
+ print(f"\nWrote {csv_path}")
278
+ for path in written:
279
+ print(f"Wrote {path}")
280
+
281
+
282
+ if __name__ == '__main__':
283
+ main()
scripts/validation/generate_heatmaps.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torchio as tio
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+
10
+ from auto_detect_breast_mri.config import resolve_path
11
+ from auto_detect_breast_mri.models.resnets import model_names
12
+ from auto_detect_breast_mri.data.breast_mri_dataset import BreastMRISubjects
13
+ # Paths come from the site config (see config.example.yaml).
14
+ path_base = resolve_path(None, "data_root", "root folder of the NIfTI data")
15
+ split_root = resolve_path(None, "split_root", "folder holding the split files")
16
+ model_root = resolve_path(None, "model_root", "folder holding the checkpoints", required=False) \
17
+ or resolve_path(None, "output_root", "folder holding the checkpoints")
18
+
19
+ batch_size = 1
20
+ pre_image_shape = (32, 512, 512)
21
+ heatmap_size = (32, 256, 256)
22
+
23
+ # Get Model
24
+ model_name = 'resnet18_abrv'
25
+ protocol = ['Dyn_0', 'Sub_1']
26
+ model_path = str(Path(model_root) / "malignity_{}.pth".format(model_name))
27
+
28
+ model = model_names.get(model_name)
29
+
30
+ checkpoint = torch.load(model_path)
31
+ model.load_state_dict(checkpoint)
32
+ model.eval()
33
+
34
+ # Register forward hook
35
+ target_layer = model.layer4[-1] # Choose the target layer
36
+ activation = {}
37
+
38
+
39
+ def get_activation(name):
40
+ def hook(model, input, output):
41
+ activation[name] = output.detach()
42
+
43
+ return hook
44
+
45
+
46
+ target_layer.register_forward_hook(get_activation('target_layer'))
47
+
48
+ # forward pass
49
+ data_set = BreastMRISubjects(path_base, str(Path(split_root) / "fold0" / "stratified_evaluation_set-f0-0.csv"),
50
+ protocol=protocol)
51
+ data_loader = tio.SubjectsLoader(data_set, batch_size=batch_size, shuffle=False, num_workers=16)
52
+
53
+ for batch_id, batch in enumerate(data_loader):
54
+ data = batch['image']['data']
55
+ ground_truth = batch['label']
56
+ path = batch['path']
57
+ output = model(data)
58
+
59
+ # Calculate gradients
60
+ model.zero_grad()
61
+ one_hot = torch.zeros_like(output)
62
+ one_hot[0, output.argmax()] = 1.0
63
+ output.backward(gradient=one_hot, retain_graph=True)
64
+
65
+ # Weighted sum of feature maps
66
+ grads = activation['target_layer'].grad.mean(dim=(2, 3), keepdim=True)
67
+ heatmap = torch.sum(grads * activation['target_layer'], dim=1, keepdim=True)
68
+ heatmap = nn.functional.relu(heatmap)
69
+
70
+ # Resize the heatmap to match the original image size
71
+ heatmap = nn.functional.interpolate(heatmap, size=heatmap_size, mode="bilinear", align_corners=False)
72
+
73
+ heatmap = heatmap / heatmap.max() # Normalize
74
+ heatmap = heatmap.squeeze().numpy() # transform to numpy array
75
+
76
+ # Display the original image and Grad-CAM heatmap
77
+ plt.figure(figsize=(10, 5))
78
+ plt.subplot(1, 2, 1)
79
+ plt.imshow(np.transpose(data[0, 0, 16].squeeze().numpy(), (1, 2, 0)))
80
+ plt.title('Original Image')
81
+
82
+ plt.subplot(1, 2, 2)
83
+ plt.imshow(heatmap[0, 0, 16], cmap='viridis') # TODO maybe only 0, 16 ?
84
+ plt.title('Grad-CAM Heatmap')
85
+
86
+ plt.show()
scripts/validation/plot_auc_curves.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import PurePath
2
+
3
+ import wandb
4
+ import torch
5
+ import torch.utils.data
6
+ import torch.nn as nn
7
+ from torch.amp import GradScaler
8
+ from torchmetrics import AUROC, Accuracy, Precision, Specificity, ROC
9
+
10
+ from auto_detect_breast_mri.config import get_config, resolve_path
11
+ from auto_detect_breast_mri.data.metadata import get_uka_metatensor
12
+ from auto_detect_breast_mri.data import loaders
13
+ from auto_detect_breast_mri.models.resnets import model_names
14
+ from auto_detect_breast_mri.data.transforms import pre_image_shape, minimalAugmentation
15
+ from auto_detect_breast_mri.models.checkpoints import load_pretrained_model
16
+ from auto_detect_breast_mri.training.cli import generate_parser
17
+ from auto_detect_breast_mri.training.loops import eval_epoch_subjects
18
+ CPU = "cpu"
19
+ GPU = "cuda"
20
+
21
+ torch.manual_seed(31)
22
+
23
+ DEVICE = GPU
24
+ if not torch.cuda.is_available():
25
+ DEVICE = CPU
26
+
27
+ transform = minimalAugmentation
28
+ t = 'basic'
29
+ batch_size = 32
30
+ fraction = 1.0
31
+ fold = 0
32
+
33
+ parser = generate_parser()
34
+ args = parser.parse_args()
35
+ model_name = args.model_name
36
+ path_base = resolve_path(args.data_path, "data_root", "root folder of the NIfTI data")
37
+ feature_path = resolve_path(args.feature_path, "metadata_file", "metadata export")
38
+ split_files_folder = resolve_path(args.split_files_folder, "split_root",
39
+ "folder holding the split files")
40
+ model_path = args.model_path
41
+ # only the leaf folder name, so no local path ends up in the run config
42
+ split_files_folder_name = PurePath(split_files_folder.rstrip('/')).name
43
+
44
+
45
+ split_file_path = split_files_folder + f"fold{fold}/stratified_test_set"
46
+ feature_dataframe = get_uka_metatensor(0, feature_path)
47
+ test_loader_abrv = loaders.get_subjects_dataloader(path_base,
48
+ feature_dataframe,
49
+ pre_image_shape,
50
+ transform,
51
+ 'abbreviated',
52
+ split_file_path,
53
+ batch_size,
54
+ fraction,
55
+ fold,
56
+ subfold=0)
57
+
58
+ test_loader_full = loaders.get_subjects_dataloader(path_base,
59
+ feature_dataframe,
60
+ pre_image_shape,
61
+ transform,
62
+ 'full',
63
+ split_file_path,
64
+ batch_size,
65
+ fraction,
66
+ fold,
67
+ subfold=0)
68
+
69
+ criterion = nn.BCEWithLogitsLoss()
70
+ auc_roc = nn.ModuleDict({state: AUROC(**{"task": "binary"}).to(DEVICE) for state in [model_name + "_abrv", model_name + "_full"]})
71
+ roc = nn.ModuleDict({state: ROC(**{"task": "binary"}).to(DEVICE) for state in [model_name + "_abrv", model_name + "_full"]})
72
+ acc = nn.ModuleDict({state: Accuracy(**{"task": "binary"}).to(DEVICE) for state in [model_name + "_abrv", model_name + "_full"]})
73
+ sens = nn.ModuleDict({state: Precision(**{"task": "binary"}).to(DEVICE) for state in [model_name + "_abrv", model_name + "_full"]})
74
+ spec = nn.ModuleDict({state: Specificity(**{"task": "binary"}).to(DEVICE) for state in [model_name + "_abrv", model_name + "_full"]})
75
+ values = (auc_roc, roc, acc, sens, spec)
76
+
77
+ model_abrv = model_names.get(model_name + '_abrv')
78
+ model_full = model_names.get(model_name + '_full')
79
+
80
+ scaler = GradScaler()
81
+ used_mixed_precision = True
82
+
83
+ wandb.init(**get_config().wandb_init_kwargs(), config={
84
+ "learning-rate": lr,
85
+ "model": model_name,
86
+ "number of test samples abrv": len(test_loader_abrv.dataset),
87
+ "number of test samples full": len(test_loader_full.dataset),
88
+ "batch size": batch_size,
89
+ "Augmentation": t + str(transform),
90
+ "Machine": "HPC",
91
+ "Mixed Precision": used_mixed_precision,
92
+ "Fold": fold,
93
+ "splits": split_files_folder_name,
94
+ }, name="{}_comparison_split={}".format(model_name, fold))
95
+
96
+
97
+ model_abrv.to(DEVICE)
98
+ model_full.to(DEVICE)
99
+
100
+
101
+ # load pretrained model:
102
+ abrv_model_path = model_path.format(model_name + "_abrv", fold)
103
+ print("load " + abrv_model_path)
104
+ checkpoint_abrv = load_pretrained_model(model_abrv, abrv_model_path, DEVICE)
105
+ model_abrv = model_abrv.load_state_dict(checkpoint_abrv)
106
+ model_abrv.eval()
107
+
108
+ full_model_path = model_path.format(model_name + "_full", fold)
109
+ print("load " + full_model_path)
110
+ checkpoint_full = load_pretrained_model(model_full, full_model_path, DEVICE)
111
+ model_full = model_abrv.load_state_dict(checkpoint_full)
112
+ model_full.eval()
113
+
114
+ abrv_loss, abrv_results_dict = eval_epoch_subjects(model_abrv, criterion, test_loader_abrv, DEVICE, values, model_name + '_abrv', plot_tpr_fpr=True, scaler=scaler, title_suffix="ABRV")
115
+ full_loss, full_results_dict = eval_epoch_subjects(model_full, criterion, test_loader_full, DEVICE, values, model_name + '_full', plot_tpr_fpr=True, scaler=scaler, title_suffix="FULL")
116
+
117
+ filename = f"AUC_ROC-{model_name}_{fold}.png"
118
+ fpr_abrv, tpr_abrv, thresholds_abrv = roc[model_name + '_abrv'].to('cpu').compute()
119
+ fpr_full, tpr_full, thresholds_full = roc[model_name + '_full'].to('cpu').compute()
120
+ y_pred = {model_name + '_abrv': tpr_abrv, model_name + '_full': tpr_full}
121
+ results['fpr'] = fpr
122
+ results['thresholds'] = thresholds
123
+ plot_roc_curve(modelname, filename)