synapse_net.training.cristae

Training of the cristae model for electron tomography (cristae5).

  1"""Training of the cristae model for electron tomography (`cristae5`)."""
  2
  3from typing import List, Mapping, Optional, Sequence, Tuple
  4
  5import torch_em
  6from torch_em.data import MinInstanceSampler
  7
  8from .loss import MaskedDiceLossPerSample
  9from .supervised_training import _get_split_paths, _read_split, supervised_training
 10from .transform import AugmentedMitoStateMaskTransform, standardize_channel
 11
 12
 13def get_cristae_test_paths(split_file: str, data_roots: Optional[Mapping[str, str]] = None) -> List[str]:
 14    """Get the test data of a split file for cristae training.
 15
 16    Args:
 17        split_file: The json file with the split.
 18        data_roots: Folders that override the data roots stored in the split file, by root name.
 19
 20    Returns:
 21        The filepaths for testing.
 22    """
 23    return _read_split(split_file, data_roots, "test")
 24
 25
 26def get_cristae_paths(
 27    data_roots: Optional[Mapping[str, str]] = None,
 28    split_file: Optional[str] = None,
 29    exclude: Sequence[str] = (),
 30    val_fraction: float = 0.1,
 31    seed: int = 42,
 32) -> Tuple[List[str], List[str]]:
 33    """Get the training and validation data for cristae training.
 34
 35    Args:
 36        data_roots: The folders with the training data, by root name. The '*_combined.h5' files are found
 37            recursively in them. If a `split_file` is given, they override the roots stored in it.
 38        split_file: A json file with the keys 'train' and 'val', and optionally 'test' and 'roots', whose
 39            entries have the form '<root name>/<relative path>'. By default the files are split randomly.
 40        exclude: Substrings of the filepaths to leave out of a random split.
 41        val_fraction: The fraction of the files used for validation in a random split.
 42        seed: The seed for the random split.
 43
 44    Returns:
 45        The filepaths for training.
 46        The filepaths for validation.
 47    """
 48    return _get_split_paths(data_roots, split_file, "*_combined.h5", val_fraction, seed, exclude=exclude)
 49
 50
 51def cristae_training(
 52    name: str,
 53    train_paths: Sequence[str],
 54    val_paths: Sequence[str],
 55    save_root: Optional[str] = None,
 56    patch_shape: Tuple[int, int, int] = (32, 256, 256),
 57    batch_size: int = 24,
 58    lr: float = 1.7e-4,
 59    n_iterations: int = int(1e5),
 60    early_stopping: int = 25,
 61    membrane_w_pos: float = 3.0,
 62    membrane_w_neg: float = 2.0,
 63    membrane_band_nm: float = 12.0,
 64    num_workers: int = 8,
 65    checkpoint_path: Optional[str] = None,
 66    resume: bool = False,
 67    check: bool = False,
 68) -> None:
 69    """Train the cristae model for electron tomography, with the recipe of `cristae5`.
 70
 71    The network gets two input channels, the tomogram and the mitochondria state, which is 0 for background, 1 for
 72    mitochondria with cristae annotations and 2 for mitochondria without. The mitochondria without annotations are
 73    excluded from the loss, and the loss is weighted towards the membrane of the annotated mitochondria, which
 74    improves the detection of cristae junctions. The default batch size and patch shape need an 80 GB GPU.
 75
 76    Args:
 77        name: The name of the checkpoint.
 78        train_paths: The hdf5 files for training, with the tomogram and the mitochondria state in
 79            'raw_mitos_combined' and the cristae in 'labels/cristae'.
 80        val_paths: The hdf5 files for validation.
 81        save_root: The folder for the checkpoint and the logs.
 82        patch_shape: The patch shape for training.
 83        batch_size: The batch size for training.
 84        lr: The initial learning rate.
 85        n_iterations: The maximal number of iterations.
 86        early_stopping: The number of epochs without improvement after which training is stopped.
 87        membrane_w_pos: The loss weight for cristae within `membrane_band_nm` of the membrane.
 88        membrane_w_neg: The loss weight for the other voxels within the band. Pass 1.0 for both weights to
 89            train without the membrane weighting.
 90        membrane_band_nm: The thickness of the membrane band in nanometer.
 91        num_workers: The number of workers for the dataloaders.
 92        checkpoint_path: A checkpoint to initialize the weights from.
 93        resume: Whether to continue the previous run with this name, see `supervised_training`.
 94        check: Whether to check the dataloaders instead of training.
 95    """
 96    transform = AugmentedMitoStateMaskTransform(
 97        torch_em.transform.get_augmentations(3), band_nm=membrane_band_nm, w_pos=membrane_w_pos, w_neg=membrane_w_neg,
 98    )
 99    # These are only valid for multi-process loading.
100    worker_kwargs = dict(persistent_workers=True, prefetch_factor=4) if num_workers > 0 else {}
101    supervised_training(
102        name=name, train_paths=tuple(train_paths), val_paths=tuple(val_paths), save_root=save_root,
103        raw_key="raw_mitos_combined", label_key="labels/cristae", patch_shape=patch_shape, batch_size=batch_size,
104        lr=lr, n_iterations=n_iterations, sampler=MinInstanceSampler(p_reject=0.95), loss_fn=MaskedDiceLossPerSample(),
105        in_channels=2, out_channels=2, norm=None, transform=transform, raw_transform=standardize_channel,
106        with_channels=True, early_stopping=early_stopping, mixed_precision=True, log_image_interval=50,
107        checkpoint_path=checkpoint_path, resume=resume, check=check, num_workers=num_workers, shuffle=False,
108        **worker_kwargs,
109    )
def get_cristae_test_paths( split_file: str, data_roots: Optional[Mapping[str, str]] = None) -> List[str]:
14def get_cristae_test_paths(split_file: str, data_roots: Optional[Mapping[str, str]] = None) -> List[str]:
15    """Get the test data of a split file for cristae training.
16
17    Args:
18        split_file: The json file with the split.
19        data_roots: Folders that override the data roots stored in the split file, by root name.
20
21    Returns:
22        The filepaths for testing.
23    """
24    return _read_split(split_file, data_roots, "test")

Get the test data of a split file for cristae training.

Arguments:
  • split_file: The json file with the split.
  • data_roots: Folders that override the data roots stored in the split file, by root name.
Returns:

The filepaths for testing.

def get_cristae_paths( data_roots: Optional[Mapping[str, str]] = None, split_file: Optional[str] = None, exclude: Sequence[str] = (), val_fraction: float = 0.1, seed: int = 42) -> Tuple[List[str], List[str]]:
27def get_cristae_paths(
28    data_roots: Optional[Mapping[str, str]] = None,
29    split_file: Optional[str] = None,
30    exclude: Sequence[str] = (),
31    val_fraction: float = 0.1,
32    seed: int = 42,
33) -> Tuple[List[str], List[str]]:
34    """Get the training and validation data for cristae training.
35
36    Args:
37        data_roots: The folders with the training data, by root name. The '*_combined.h5' files are found
38            recursively in them. If a `split_file` is given, they override the roots stored in it.
39        split_file: A json file with the keys 'train' and 'val', and optionally 'test' and 'roots', whose
40            entries have the form '<root name>/<relative path>'. By default the files are split randomly.
41        exclude: Substrings of the filepaths to leave out of a random split.
42        val_fraction: The fraction of the files used for validation in a random split.
43        seed: The seed for the random split.
44
45    Returns:
46        The filepaths for training.
47        The filepaths for validation.
48    """
49    return _get_split_paths(data_roots, split_file, "*_combined.h5", val_fraction, seed, exclude=exclude)

Get the training and validation data for cristae training.

Arguments:
  • data_roots: The folders with the training data, by root name. The '*_combined.h5' files are found recursively in them. If a split_file is given, they override the roots stored in it.
  • split_file: A json file with the keys 'train' and 'val', and optionally 'test' and 'roots', whose entries have the form '/'. By default the files are split randomly.
  • exclude: Substrings of the filepaths to leave out of a random split.
  • val_fraction: The fraction of the files used for validation in a random split.
  • seed: The seed for the random split.
Returns:

The filepaths for training. The filepaths for validation.

def cristae_training( name: str, train_paths: Sequence[str], val_paths: Sequence[str], save_root: Optional[str] = None, patch_shape: Tuple[int, int, int] = (32, 256, 256), batch_size: int = 24, lr: float = 0.00017, n_iterations: int = 100000, early_stopping: int = 25, membrane_w_pos: float = 3.0, membrane_w_neg: float = 2.0, membrane_band_nm: float = 12.0, num_workers: int = 8, checkpoint_path: Optional[str] = None, resume: bool = False, check: bool = False) -> None:
 52def cristae_training(
 53    name: str,
 54    train_paths: Sequence[str],
 55    val_paths: Sequence[str],
 56    save_root: Optional[str] = None,
 57    patch_shape: Tuple[int, int, int] = (32, 256, 256),
 58    batch_size: int = 24,
 59    lr: float = 1.7e-4,
 60    n_iterations: int = int(1e5),
 61    early_stopping: int = 25,
 62    membrane_w_pos: float = 3.0,
 63    membrane_w_neg: float = 2.0,
 64    membrane_band_nm: float = 12.0,
 65    num_workers: int = 8,
 66    checkpoint_path: Optional[str] = None,
 67    resume: bool = False,
 68    check: bool = False,
 69) -> None:
 70    """Train the cristae model for electron tomography, with the recipe of `cristae5`.
 71
 72    The network gets two input channels, the tomogram and the mitochondria state, which is 0 for background, 1 for
 73    mitochondria with cristae annotations and 2 for mitochondria without. The mitochondria without annotations are
 74    excluded from the loss, and the loss is weighted towards the membrane of the annotated mitochondria, which
 75    improves the detection of cristae junctions. The default batch size and patch shape need an 80 GB GPU.
 76
 77    Args:
 78        name: The name of the checkpoint.
 79        train_paths: The hdf5 files for training, with the tomogram and the mitochondria state in
 80            'raw_mitos_combined' and the cristae in 'labels/cristae'.
 81        val_paths: The hdf5 files for validation.
 82        save_root: The folder for the checkpoint and the logs.
 83        patch_shape: The patch shape for training.
 84        batch_size: The batch size for training.
 85        lr: The initial learning rate.
 86        n_iterations: The maximal number of iterations.
 87        early_stopping: The number of epochs without improvement after which training is stopped.
 88        membrane_w_pos: The loss weight for cristae within `membrane_band_nm` of the membrane.
 89        membrane_w_neg: The loss weight for the other voxels within the band. Pass 1.0 for both weights to
 90            train without the membrane weighting.
 91        membrane_band_nm: The thickness of the membrane band in nanometer.
 92        num_workers: The number of workers for the dataloaders.
 93        checkpoint_path: A checkpoint to initialize the weights from.
 94        resume: Whether to continue the previous run with this name, see `supervised_training`.
 95        check: Whether to check the dataloaders instead of training.
 96    """
 97    transform = AugmentedMitoStateMaskTransform(
 98        torch_em.transform.get_augmentations(3), band_nm=membrane_band_nm, w_pos=membrane_w_pos, w_neg=membrane_w_neg,
 99    )
100    # These are only valid for multi-process loading.
101    worker_kwargs = dict(persistent_workers=True, prefetch_factor=4) if num_workers > 0 else {}
102    supervised_training(
103        name=name, train_paths=tuple(train_paths), val_paths=tuple(val_paths), save_root=save_root,
104        raw_key="raw_mitos_combined", label_key="labels/cristae", patch_shape=patch_shape, batch_size=batch_size,
105        lr=lr, n_iterations=n_iterations, sampler=MinInstanceSampler(p_reject=0.95), loss_fn=MaskedDiceLossPerSample(),
106        in_channels=2, out_channels=2, norm=None, transform=transform, raw_transform=standardize_channel,
107        with_channels=True, early_stopping=early_stopping, mixed_precision=True, log_image_interval=50,
108        checkpoint_path=checkpoint_path, resume=resume, check=check, num_workers=num_workers, shuffle=False,
109        **worker_kwargs,
110    )

Train the cristae model for electron tomography, with the recipe of cristae5.

The network gets two input channels, the tomogram and the mitochondria state, which is 0 for background, 1 for mitochondria with cristae annotations and 2 for mitochondria without. The mitochondria without annotations are excluded from the loss, and the loss is weighted towards the membrane of the annotated mitochondria, which improves the detection of cristae junctions. The default batch size and patch shape need an 80 GB GPU.

Arguments:
  • name: The name of the checkpoint.
  • train_paths: The hdf5 files for training, with the tomogram and the mitochondria state in 'raw_mitos_combined' and the cristae in 'labels/cristae'.
  • val_paths: The hdf5 files for validation.
  • save_root: The folder for the checkpoint and the logs.
  • patch_shape: The patch shape for training.
  • batch_size: The batch size for training.
  • lr: The initial learning rate.
  • n_iterations: The maximal number of iterations.
  • early_stopping: The number of epochs without improvement after which training is stopped.
  • membrane_w_pos: The loss weight for cristae within membrane_band_nm of the membrane.
  • membrane_w_neg: The loss weight for the other voxels within the band. Pass 1.0 for both weights to train without the membrane weighting.
  • membrane_band_nm: The thickness of the membrane band in nanometer.
  • num_workers: The number of workers for the dataloaders.
  • checkpoint_path: A checkpoint to initialize the weights from.
  • resume: Whether to continue the previous run with this name, see supervised_training.
  • check: Whether to check the dataloaders instead of training.