synapse_net.training.supervised_training
1import json 2import os 3import random 4from glob import glob 5from typing import List, Mapping, Optional, Tuple, Union 6 7import torch 8import torch_em 9from sklearn.model_selection import train_test_split 10 11from synapse_net.inference.inference import get_model_path, get_available_models 12from synapse_net.inference.util import _restore_legacy_attributes 13from synapse_net.training.models import get_raw_transform, _check_backbone, _get_model 14from synapse_net.training.dataloaders import get_supervised_loader 15 16 17def _random_split(paths, val_fraction, seed): 18 if len(paths) == 0: 19 raise ValueError("Did not find any training data.") 20 # Shuffle with a separate random state, so that the split is deterministic for a given set of files. 21 paths = sorted(paths) 22 random.Random(seed).shuffle(paths) 23 # Validate on at least one file if there is more than one. 24 n_val = max(int(len(paths) * val_fraction), int(len(paths) > 1)) 25 return paths[:len(paths) - n_val], paths[len(paths) - n_val:] 26 27 28def _read_split(split_file: str, data_roots: Union[Mapping[str, str], str, None], key: str) -> List[str]: 29 """Read the entries of `key` from a split file. 30 31 The entries have the form '<root name>/<relative path>', and `data_roots` override the roots stored in the file. 32 If `data_roots` is a single folder, then the entries are paths relative to it. 33 """ 34 with open(split_file) as f: 35 split = json.load(f) 36 # The entries use '/', join their parts so that the paths match the ones found by glob on Windows. 37 if isinstance(data_roots, str): 38 return [os.path.join(data_roots, *entry.split("/")) for entry in split.get(key, [])] 39 roots = {**split.get("roots", {}), **(data_roots or {})} 40 paths = [] 41 for entry in split.get(key, []): 42 root, *parts = entry.split("/") 43 if root not in roots: 44 raise ValueError(f"{split_file} refers to the unknown data root '{root}'.") 45 paths.append(os.path.join(roots[root], *parts)) 46 return paths 47 48 49def _get_split_paths(data_roots, split_file, pattern, val_fraction, seed, exclude=()): 50 """Get the training and validation paths from a split file, or from a random split of the files in the roots.""" 51 if split_file is None: 52 roots = [data_roots] if isinstance(data_roots, str) else (data_roots or {}).values() 53 paths = [path for root in roots for path in glob(os.path.join(root, "**", pattern), recursive=True)] 54 return _random_split([path for path in paths if not any(ex in path for ex in exclude)], val_fraction, seed) 55 56 train_paths, val_paths = (_read_split(split_file, data_roots, key) for key in ("train", "val")) 57 missing = [path for path in train_paths + val_paths if not os.path.exists(path)] 58 if missing: 59 raise ValueError(f"{len(missing)} files from {split_file} do not exist, e.g. {missing[0]}.") 60 return train_paths, val_paths 61 62 63def supervised_training( 64 name: str, 65 train_paths: Tuple[str], 66 val_paths: Tuple[str], 67 label_key: str, 68 patch_shape: Tuple[int, int, int], 69 save_root: Optional[str] = None, 70 raw_key: str = "raw", 71 batch_size: int = 1, 72 lr: float = 1e-4, 73 n_iterations: int = int(1e5), 74 train_label_paths: Optional[Tuple[str]] = None, 75 val_label_paths: Optional[Tuple[str]] = None, 76 train_rois: Optional[Tuple[Tuple[slice]]] = None, 77 val_rois: Optional[Tuple[Tuple[slice]]] = None, 78 sampler: Optional[Union[callable, bool]] = None, 79 n_samples_train: Optional[int] = None, 80 n_samples_val: Optional[int] = None, 81 check: bool = False, 82 ignore_label: Optional[int] = None, 83 raw_transform: Optional[callable] = None, 84 label_transform: Optional[callable] = None, 85 loss_fn: Optional[torch.nn.Module] = None, 86 in_channels: int = 1, 87 out_channels: int = 2, 88 norm: Optional[str] = "InstanceNorm", 89 scale_factors: Optional[Tuple[Tuple[int, int, int]]] = None, 90 transform: Optional[callable] = None, 91 mask_channel: bool = False, 92 backbone: Optional[str] = None, 93 model_type: Optional[str] = None, 94 encoder_checkpoint: Optional[str] = None, 95 checkpoint_path: Optional[str] = None, 96 resume: bool = False, 97 save_every_kth_epoch: Optional[int] = None, 98 mixed_precision: bool = True, 99 early_stopping: Optional[int] = None, 100 log_image_interval: int = 100, 101 **loader_kwargs, 102): 103 """Run supervised segmentation training. 104 105 This function trains a UNet for predicting outputs for segmentation. 106 Expects instance labels and converts them to boundary targets. 107 This behaviour can be changed by passing custom arguments for `label_transform` 108 and/or `out_channels`. 109 110 Args: 111 name: The name for the checkpoint to be trained. 112 train_paths: Filepaths to the hdf5 files for the training data. 113 val_paths: Filepaths to the df5 files for the validation data. 114 label_key: The key that holds the labels inside of the hdf5. 115 patch_shape: The patch shape used for a training example. 116 In order to run 2d training pass a patch shape with a singleton in the z-axis, 117 e.g. 'patch_shape = [1, 512, 512]'. 118 save_root: Folder where the checkpoint will be saved. 119 raw_key: The key that holds the raw data inside of the hdf5. 120 batch_size: The batch size for training. 121 lr: The initial learning rate. 122 n_iterations: The number of iterations to train for. 123 train_label_paths: Optional paths containing the label data for training. 124 If not given, the labels are expected to be part of `train_paths`. 125 val_label_paths: Optional paths containing the label data for validation. 126 If not given, the labels are expected to be part of `val_paths`. 127 train_rois: Optional region of interests for training. 128 val_rois: Optional region of interests for validation. 129 sampler: Optional sampler for selecting patches for training. 130 By default a minimum instance sampler will be used. 131 n_samples_train: The number of train samples per epoch. By default this will be estimated 132 based on the patch_shape and size of the volumes used for training. 133 n_samples_val: The number of val samples per epoch. By default this will be estimated 134 based on the patch_shape and size of the volumes used for validation. 135 check: Whether to check the training and validation loaders instead of running training. 136 ignore_label: Ignore label in the ground-truth. The areas marked by this label will be 137 ignored in the loss computation. By default this option is not used. 138 raw_transform: Normalization applied to the raw data. By default the transform for `backbone` is used. 139 When `backbone` is None, torch_em standardization is used. 140 label_transform: Label transform that is applied to the segmentation to compute the targets. 141 If no label transform is passed (the default) a boundary transform is used. 142 loss_fn: Custom loss function. If None, will default to `torch_em.loss.DiceLoss`. 143 out_channels: The number of output channels of the UNet. 144 norm: The normalization layer of the 3D UNet, or None for no normalization. 145 This has no effect if a `backbone` is used. 146 scale_factors: The downscaling factors of the 3D UNet encoder, in ZYX. By default one anisotropic 147 level is used, pass more for data with a stronger anisotropy. Has no effect for 2D or a `backbone`. 148 transform: Joint transformation applied to the raw data and the labels. 149 By default padding and the standard augmentations are applied. 150 mask_channel: Whether the last channels in the labels should be used for masking the loss. 151 This can be used to implement more complex masking operations and is not compatible with `ignore_label`. 152 backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3" (ViT encoders of a UNETR), 153 or "cryosiam" (3D CNN encoder of a CryoZooUNet). 154 The ViT backbones must be set together with `model_type`. 155 model_type: Model type for the selected ViT `backbone` model family, for example "vit_b" or 156 "vit_b_em_organelles" for "sam". 157 encoder_checkpoint: Path to the pretrained encoder weights for `backbone`. 158 By default they are fetched for `backbone` and `model_type`. 159 checkpoint_path: Path to the directory with 'best.pt', to initialize the model from it. 160 resume: Whether to continue the previous run with this name in `save_root`, with its optimizer 161 and iteration count. `n_iterations` then includes the iterations of the previous run. 162 save_every_kth_epoch: Save checkpoints after every kth epoch in a separate file. 163 The corresponding checkpoints will be saved with the naming scheme 'epoch-{epoch}.pt'. 164 mixed_precision: Whether to train with mixed precision. 165 early_stopping: The number of epochs without improvement after which training is stopped. 166 log_image_interval: The interval (in iterations) at which images are written to the log. 167 loader_kwargs: Additional keyword arguments for the dataloader. 168 """ 169 _check_backbone(backbone, model_type, patch_shape) 170 171 if raw_transform is None: 172 raw_transform = get_raw_transform(backbone)[0] 173 174 train_loader = get_supervised_loader( 175 train_paths, raw_key, label_key, patch_shape, batch_size, 176 n_samples=n_samples_train, rois=train_rois, sampler=sampler, ignore_label=ignore_label, 177 label_transform=label_transform, label_paths=train_label_paths, raw_transform=raw_transform, 178 transform=transform, **loader_kwargs, 179 ) 180 val_loader = get_supervised_loader( 181 val_paths, raw_key, label_key, patch_shape, batch_size, 182 n_samples=n_samples_val, rois=val_rois, sampler=sampler, ignore_label=ignore_label, 183 label_transform=label_transform, label_paths=val_label_paths, raw_transform=raw_transform, 184 transform=transform, **loader_kwargs, 185 ) 186 187 if check: 188 from torch_em.util.debug import check_loader 189 check_loader(train_loader, n_samples=4) 190 check_loader(val_loader, n_samples=4) 191 return 192 193 if checkpoint_path is not None: 194 model = _restore_legacy_attributes(torch_em.util.load_model(checkpoint=checkpoint_path)) 195 else: 196 model = _get_model( 197 patch_shape, out_channels, in_channels=in_channels, backbone=backbone, 198 model_type=model_type, encoder_checkpoint=encoder_checkpoint, norm=norm, 199 scale_factors=scale_factors, 200 ) 201 202 base_loss = loss_fn if loss_fn is not None else torch_em.loss.DiceLoss() 203 metric = base_loss 204 205 # No ignore label -> we can use default loss. 206 if ignore_label is None and not mask_channel: 207 loss = base_loss 208 209 # If we have an ignore label the loss and metric have to be modified 210 # so that the ignore mask is not used in the gradient calculation. 211 elif ignore_label is not None: 212 loss = torch_em.loss.LossWrapper( 213 loss=base_loss, 214 transform=torch_em.loss.wrapper.MaskIgnoreLabel( 215 ignore_label=ignore_label, masking_method="multiply", 216 ) 217 ) 218 metric = loss 219 else: 220 loss = torch_em.loss.LossWrapper( 221 loss=base_loss, 222 transform=torch_em.loss.wrapper.ApplyAndRemoveMask( 223 masking_method="crop" if out_channels == 1 else "multiply") 224 ) 225 metric = loss 226 227 trainer = torch_em.default_segmentation_trainer( 228 name=name, 229 model=model, 230 train_loader=train_loader, 231 val_loader=val_loader, 232 learning_rate=lr, 233 mixed_precision=mixed_precision, 234 log_image_interval=log_image_interval, 235 early_stopping=early_stopping, 236 compile_model=False, 237 save_root=save_root, 238 loss=loss, 239 metric=metric, 240 ) 241 if resume: # Train only the remaining iterations; this fails if there is no previous run. 242 latest = os.path.join(trainer.checkpoint_folder, "latest.pt") 243 n_iterations -= torch.load(latest, map_location="cpu", weights_only=False)["iteration"] 244 trainer.fit(n_iterations, load_from_checkpoint="latest" if resume else None, 245 save_every_kth_epoch=save_every_kth_epoch) 246 247 248def _derive_key_from_files(files, key): 249 # Get all file extensions (general wild-cards may pick up files with multiple extensions). 250 extensions = list(set([os.path.splitext(ff)[1] for ff in files])) 251 252 # If we have more than 1 file extension we just use the key that was passed, 253 # as it is unclear how to derive a consistent key. 254 if len(extensions) > 1: 255 return files, key 256 257 ext = extensions[0] 258 extension_to_key = {".tif": None, ".mrc": "data", ".rec": "data"} 259 260 # Derive the key from the extension if the key is None. 261 if key is None and ext in extension_to_key: 262 key = extension_to_key[ext] 263 # If the key is None and can't be derived raise an error. 264 elif key is None and ext not in extension_to_key: 265 raise ValueError( 266 f"You have not passed a key for the data in {ext} format, for which the key cannot be derived." 267 ) 268 # If the key was passed and doesn't match the extension raise an error. 269 elif key is not None and ext in extension_to_key and key != extension_to_key[ext]: 270 raise ValueError( 271 f"The expected key {extension_to_key[ext]} for format {ext} did not match the passed key {key}." 272 ) 273 return files, key 274 275 276def _parse_input_folder(folder, pattern, key): 277 files = sorted(glob(os.path.join(folder, "**", pattern), recursive=True)) 278 return _derive_key_from_files(files, key) 279 280 281def _parse_input_files(args): 282 train_image_paths, raw_key = _parse_input_folder(args.train_folder, args.image_file_pattern, args.raw_key) 283 train_label_paths, label_key = _parse_input_folder(args.label_folder, args.label_file_pattern, args.label_key) 284 if len(train_image_paths) != len(train_label_paths): 285 raise ValueError( 286 f"The image and label paths parsed from {args.train_folder} and {args.label_folder} don't match." 287 f"The image folder contains {len(train_image_paths)}, the label folder contains {len(train_label_paths)}." 288 ) 289 290 if args.val_folder is None: 291 if args.val_label_folder is not None: 292 raise ValueError("You have passed a val_label_folder, but not a val_folder.") 293 train_image_paths, val_image_paths, train_label_paths, val_label_paths = train_test_split( 294 train_image_paths, train_label_paths, test_size=args.val_fraction, random_state=42 295 ) 296 else: 297 if args.val_label_folder is None: 298 raise ValueError("You have passed a val_folder, but not a val_label_folder.") 299 val_image_paths, _ = _parse_input_folder(args.val_folder, args.image_file_pattern, raw_key) 300 val_label_paths, _ = _parse_input_folder(args.val_label_folder, args.label_file_pattern, label_key) 301 302 return train_image_paths, train_label_paths, val_image_paths, val_label_paths, raw_key, label_key 303 304 305def _parse_checkpoint(initial_model): 306 if initial_model is None: 307 return None 308 if os.path.exists(initial_model): 309 return initial_model 310 model_path = get_model_path(initial_model) 311 return model_path 312 313 314def main(): 315 """@private 316 """ 317 import argparse 318 319 parser = argparse.ArgumentParser( 320 description="Train a model for foreground and boundary segmentation via supervised learning.\n\n" 321 "You can use this function to train a model for vesicle segmentation, or another segmentation task, like this:\n" # noqa 322 "synapse_net.run_supervised_training -n my_model -i /path/to/images -l /path/to/labels --patch_shape 32 192 192\n" # noqa 323 "The trained model will be saved in the folder 'checkpoints/my_model' (or whichever name you pass to the '-n' argument)." # noqa 324 "You can then use this model for segmentation with the SynapseNet GUI or CLI. " 325 "Check out the information below for details on the arguments of this function.", 326 formatter_class=argparse.RawTextHelpFormatter 327 ) 328 parser.add_argument("-n", "--name", required=True, help="The name of the model to be trained.") 329 parser.add_argument("-p", "--patch_shape", nargs=3, type=int, help="The patch shape for training.") 330 331 # Folders with training data, containing raw/image data and labels. 332 parser.add_argument("-i", "--train_folder", required=True, help="The input folder with the training image data.") 333 parser.add_argument("--image_file_pattern", default="*", 334 help="The pattern for selecting image files. For example, '*.mrc' to select all mrc files.") 335 parser.add_argument("--raw_key", 336 help="The internal path for the raw data. If not given, will be determined based on the file extension.") # noqa 337 parser.add_argument("-l", "--label_folder", required=True, help="The input folder with the training labels.") 338 parser.add_argument("--label_file_pattern", default="*", 339 help="The pattern for selecting label files. For example, '*.tif' to select all tif files.") 340 parser.add_argument("--label_key", 341 help="The internal path for the label data. If not given, will be determined based on the file extension.") # noqa 342 343 # Optional folders with validation data. If not given the training data is split into train/val. 344 parser.add_argument("--val_folder", 345 help="The input folder with the validation data. If not given the training data will be split for validation") # noqa 346 parser.add_argument("--val_label_folder", 347 help="The input folder with the validation labels. If not given the training data will be split for validation.") # noqa 348 349 # Optional: choose a model for initializing the weights. 350 available_models = get_available_models() 351 parser.add_argument( 352 "--initial_model", 353 help="Choose a model checkpoint for weight initialization.\n" 354 "This may either be the path to an existing model checkpoint or the name of a pretrained model.\n" 355 f"The following pretrained models are available: {available_models}.\n" 356 "If not given, the model will be randomly initialized." 357 ) 358 359 # More optional argument: 360 parser.add_argument("--batch_size", type=int, default=1, help="The batch size for training.") 361 parser.add_argument("--n_samples_train", type=int, help="The number of samples per epoch for training. If not given will be derived from the data size.") # noqa 362 parser.add_argument("--n_samples_val", type=int, help="The number of samples per epoch for validation. If not given will be derived from the data size.") # noqa 363 parser.add_argument("--val_fraction", type=float, default=0.15, help="The fraction of the data to use for validation. This has no effect if 'val_folder' and 'val_label_folder' were passed.") # noqa 364 parser.add_argument("--check", action="store_true", help="Visualize samples from the data loaders to ensure correct data instead of running training.") # noqa 365 parser.add_argument("--n_iterations", type=int, default=int(1e5), help="The maximal number of iterations to train for.") # noqa 366 parser.add_argument("--save_root", help="Root path for saving the checkpoint and log dir.") 367 args = parser.parse_args() 368 369 train_image_paths, train_label_paths, val_image_paths, val_label_paths, raw_key, label_key =\ 370 _parse_input_files(args) 371 checkpoint_path = _parse_checkpoint(args.initial_model) 372 373 supervised_training( 374 name=args.name, train_paths=train_image_paths, val_paths=val_image_paths, 375 train_label_paths=train_label_paths, val_label_paths=val_label_paths, 376 raw_key=raw_key, label_key=label_key, patch_shape=args.patch_shape, batch_size=args.batch_size, 377 n_samples_train=args.n_samples_train, n_samples_val=args.n_samples_val, 378 check=args.check, n_iterations=args.n_iterations, save_root=args.save_root, 379 checkpoint_path=checkpoint_path 380 )
def
supervised_training( name: str, train_paths: Tuple[str], val_paths: Tuple[str], label_key: str, patch_shape: Tuple[int, int, int], save_root: Optional[str] = None, raw_key: str = 'raw', batch_size: int = 1, lr: float = 0.0001, n_iterations: int = 100000, train_label_paths: Optional[Tuple[str]] = None, val_label_paths: Optional[Tuple[str]] = None, train_rois: Optional[Tuple[Tuple[slice]]] = None, val_rois: Optional[Tuple[Tuple[slice]]] = None, sampler: Union[<built-in function callable>, bool, NoneType] = None, n_samples_train: Optional[int] = None, n_samples_val: Optional[int] = None, check: bool = False, ignore_label: Optional[int] = None, raw_transform: Optional[<built-in function callable>] = None, label_transform: Optional[<built-in function callable>] = None, loss_fn: Optional[torch.nn.modules.module.Module] = None, in_channels: int = 1, out_channels: int = 2, norm: Optional[str] = 'InstanceNorm', scale_factors: Optional[Tuple[Tuple[int, int, int]]] = None, transform: Optional[<built-in function callable>] = None, mask_channel: bool = False, backbone: Optional[str] = None, model_type: Optional[str] = None, encoder_checkpoint: Optional[str] = None, checkpoint_path: Optional[str] = None, resume: bool = False, save_every_kth_epoch: Optional[int] = None, mixed_precision: bool = True, early_stopping: Optional[int] = None, log_image_interval: int = 100, **loader_kwargs):
64def supervised_training( 65 name: str, 66 train_paths: Tuple[str], 67 val_paths: Tuple[str], 68 label_key: str, 69 patch_shape: Tuple[int, int, int], 70 save_root: Optional[str] = None, 71 raw_key: str = "raw", 72 batch_size: int = 1, 73 lr: float = 1e-4, 74 n_iterations: int = int(1e5), 75 train_label_paths: Optional[Tuple[str]] = None, 76 val_label_paths: Optional[Tuple[str]] = None, 77 train_rois: Optional[Tuple[Tuple[slice]]] = None, 78 val_rois: Optional[Tuple[Tuple[slice]]] = None, 79 sampler: Optional[Union[callable, bool]] = None, 80 n_samples_train: Optional[int] = None, 81 n_samples_val: Optional[int] = None, 82 check: bool = False, 83 ignore_label: Optional[int] = None, 84 raw_transform: Optional[callable] = None, 85 label_transform: Optional[callable] = None, 86 loss_fn: Optional[torch.nn.Module] = None, 87 in_channels: int = 1, 88 out_channels: int = 2, 89 norm: Optional[str] = "InstanceNorm", 90 scale_factors: Optional[Tuple[Tuple[int, int, int]]] = None, 91 transform: Optional[callable] = None, 92 mask_channel: bool = False, 93 backbone: Optional[str] = None, 94 model_type: Optional[str] = None, 95 encoder_checkpoint: Optional[str] = None, 96 checkpoint_path: Optional[str] = None, 97 resume: bool = False, 98 save_every_kth_epoch: Optional[int] = None, 99 mixed_precision: bool = True, 100 early_stopping: Optional[int] = None, 101 log_image_interval: int = 100, 102 **loader_kwargs, 103): 104 """Run supervised segmentation training. 105 106 This function trains a UNet for predicting outputs for segmentation. 107 Expects instance labels and converts them to boundary targets. 108 This behaviour can be changed by passing custom arguments for `label_transform` 109 and/or `out_channels`. 110 111 Args: 112 name: The name for the checkpoint to be trained. 113 train_paths: Filepaths to the hdf5 files for the training data. 114 val_paths: Filepaths to the df5 files for the validation data. 115 label_key: The key that holds the labels inside of the hdf5. 116 patch_shape: The patch shape used for a training example. 117 In order to run 2d training pass a patch shape with a singleton in the z-axis, 118 e.g. 'patch_shape = [1, 512, 512]'. 119 save_root: Folder where the checkpoint will be saved. 120 raw_key: The key that holds the raw data inside of the hdf5. 121 batch_size: The batch size for training. 122 lr: The initial learning rate. 123 n_iterations: The number of iterations to train for. 124 train_label_paths: Optional paths containing the label data for training. 125 If not given, the labels are expected to be part of `train_paths`. 126 val_label_paths: Optional paths containing the label data for validation. 127 If not given, the labels are expected to be part of `val_paths`. 128 train_rois: Optional region of interests for training. 129 val_rois: Optional region of interests for validation. 130 sampler: Optional sampler for selecting patches for training. 131 By default a minimum instance sampler will be used. 132 n_samples_train: The number of train samples per epoch. By default this will be estimated 133 based on the patch_shape and size of the volumes used for training. 134 n_samples_val: The number of val samples per epoch. By default this will be estimated 135 based on the patch_shape and size of the volumes used for validation. 136 check: Whether to check the training and validation loaders instead of running training. 137 ignore_label: Ignore label in the ground-truth. The areas marked by this label will be 138 ignored in the loss computation. By default this option is not used. 139 raw_transform: Normalization applied to the raw data. By default the transform for `backbone` is used. 140 When `backbone` is None, torch_em standardization is used. 141 label_transform: Label transform that is applied to the segmentation to compute the targets. 142 If no label transform is passed (the default) a boundary transform is used. 143 loss_fn: Custom loss function. If None, will default to `torch_em.loss.DiceLoss`. 144 out_channels: The number of output channels of the UNet. 145 norm: The normalization layer of the 3D UNet, or None for no normalization. 146 This has no effect if a `backbone` is used. 147 scale_factors: The downscaling factors of the 3D UNet encoder, in ZYX. By default one anisotropic 148 level is used, pass more for data with a stronger anisotropy. Has no effect for 2D or a `backbone`. 149 transform: Joint transformation applied to the raw data and the labels. 150 By default padding and the standard augmentations are applied. 151 mask_channel: Whether the last channels in the labels should be used for masking the loss. 152 This can be used to implement more complex masking operations and is not compatible with `ignore_label`. 153 backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3" (ViT encoders of a UNETR), 154 or "cryosiam" (3D CNN encoder of a CryoZooUNet). 155 The ViT backbones must be set together with `model_type`. 156 model_type: Model type for the selected ViT `backbone` model family, for example "vit_b" or 157 "vit_b_em_organelles" for "sam". 158 encoder_checkpoint: Path to the pretrained encoder weights for `backbone`. 159 By default they are fetched for `backbone` and `model_type`. 160 checkpoint_path: Path to the directory with 'best.pt', to initialize the model from it. 161 resume: Whether to continue the previous run with this name in `save_root`, with its optimizer 162 and iteration count. `n_iterations` then includes the iterations of the previous run. 163 save_every_kth_epoch: Save checkpoints after every kth epoch in a separate file. 164 The corresponding checkpoints will be saved with the naming scheme 'epoch-{epoch}.pt'. 165 mixed_precision: Whether to train with mixed precision. 166 early_stopping: The number of epochs without improvement after which training is stopped. 167 log_image_interval: The interval (in iterations) at which images are written to the log. 168 loader_kwargs: Additional keyword arguments for the dataloader. 169 """ 170 _check_backbone(backbone, model_type, patch_shape) 171 172 if raw_transform is None: 173 raw_transform = get_raw_transform(backbone)[0] 174 175 train_loader = get_supervised_loader( 176 train_paths, raw_key, label_key, patch_shape, batch_size, 177 n_samples=n_samples_train, rois=train_rois, sampler=sampler, ignore_label=ignore_label, 178 label_transform=label_transform, label_paths=train_label_paths, raw_transform=raw_transform, 179 transform=transform, **loader_kwargs, 180 ) 181 val_loader = get_supervised_loader( 182 val_paths, raw_key, label_key, patch_shape, batch_size, 183 n_samples=n_samples_val, rois=val_rois, sampler=sampler, ignore_label=ignore_label, 184 label_transform=label_transform, label_paths=val_label_paths, raw_transform=raw_transform, 185 transform=transform, **loader_kwargs, 186 ) 187 188 if check: 189 from torch_em.util.debug import check_loader 190 check_loader(train_loader, n_samples=4) 191 check_loader(val_loader, n_samples=4) 192 return 193 194 if checkpoint_path is not None: 195 model = _restore_legacy_attributes(torch_em.util.load_model(checkpoint=checkpoint_path)) 196 else: 197 model = _get_model( 198 patch_shape, out_channels, in_channels=in_channels, backbone=backbone, 199 model_type=model_type, encoder_checkpoint=encoder_checkpoint, norm=norm, 200 scale_factors=scale_factors, 201 ) 202 203 base_loss = loss_fn if loss_fn is not None else torch_em.loss.DiceLoss() 204 metric = base_loss 205 206 # No ignore label -> we can use default loss. 207 if ignore_label is None and not mask_channel: 208 loss = base_loss 209 210 # If we have an ignore label the loss and metric have to be modified 211 # so that the ignore mask is not used in the gradient calculation. 212 elif ignore_label is not None: 213 loss = torch_em.loss.LossWrapper( 214 loss=base_loss, 215 transform=torch_em.loss.wrapper.MaskIgnoreLabel( 216 ignore_label=ignore_label, masking_method="multiply", 217 ) 218 ) 219 metric = loss 220 else: 221 loss = torch_em.loss.LossWrapper( 222 loss=base_loss, 223 transform=torch_em.loss.wrapper.ApplyAndRemoveMask( 224 masking_method="crop" if out_channels == 1 else "multiply") 225 ) 226 metric = loss 227 228 trainer = torch_em.default_segmentation_trainer( 229 name=name, 230 model=model, 231 train_loader=train_loader, 232 val_loader=val_loader, 233 learning_rate=lr, 234 mixed_precision=mixed_precision, 235 log_image_interval=log_image_interval, 236 early_stopping=early_stopping, 237 compile_model=False, 238 save_root=save_root, 239 loss=loss, 240 metric=metric, 241 ) 242 if resume: # Train only the remaining iterations; this fails if there is no previous run. 243 latest = os.path.join(trainer.checkpoint_folder, "latest.pt") 244 n_iterations -= torch.load(latest, map_location="cpu", weights_only=False)["iteration"] 245 trainer.fit(n_iterations, load_from_checkpoint="latest" if resume else None, 246 save_every_kth_epoch=save_every_kth_epoch)
Run supervised segmentation training.
This function trains a UNet for predicting outputs for segmentation.
Expects instance labels and converts them to boundary targets.
This behaviour can be changed by passing custom arguments for label_transform
and/or out_channels.
Arguments:
- name: The name for the checkpoint to be trained.
- train_paths: Filepaths to the hdf5 files for the training data.
- val_paths: Filepaths to the df5 files for the validation data.
- label_key: The key that holds the labels inside of the hdf5.
- patch_shape: The patch shape used for a training example. In order to run 2d training pass a patch shape with a singleton in the z-axis, e.g. 'patch_shape = [1, 512, 512]'.
- save_root: Folder where the checkpoint will be saved.
- raw_key: The key that holds the raw data inside of the hdf5.
- batch_size: The batch size for training.
- lr: The initial learning rate.
- n_iterations: The number of iterations to train for.
- train_label_paths: Optional paths containing the label data for training.
If not given, the labels are expected to be part of
train_paths. - val_label_paths: Optional paths containing the label data for validation.
If not given, the labels are expected to be part of
val_paths. - train_rois: Optional region of interests for training.
- val_rois: Optional region of interests for validation.
- sampler: Optional sampler for selecting patches for training. By default a minimum instance sampler will be used.
- n_samples_train: The number of train samples per epoch. By default this will be estimated based on the patch_shape and size of the volumes used for training.
- n_samples_val: The number of val samples per epoch. By default this will be estimated based on the patch_shape and size of the volumes used for validation.
- check: Whether to check the training and validation loaders instead of running training.
- ignore_label: Ignore label in the ground-truth. The areas marked by this label will be ignored in the loss computation. By default this option is not used.
- raw_transform: Normalization applied to the raw data. By default the transform for
backboneis used. Whenbackboneis None, torch_em standardization is used. - label_transform: Label transform that is applied to the segmentation to compute the targets. If no label transform is passed (the default) a boundary transform is used.
- loss_fn: Custom loss function. If None, will default to
torch_em.loss.DiceLoss. - out_channels: The number of output channels of the UNet.
- norm: The normalization layer of the 3D UNet, or None for no normalization.
This has no effect if a
backboneis used. - scale_factors: The downscaling factors of the 3D UNet encoder, in ZYX. By default one anisotropic
level is used, pass more for data with a stronger anisotropy. Has no effect for 2D or a
backbone. - transform: Joint transformation applied to the raw data and the labels. By default padding and the standard augmentations are applied.
- mask_channel: Whether the last channels in the labels should be used for masking the loss.
This can be used to implement more complex masking operations and is not compatible with
ignore_label. - backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3" (ViT encoders of a UNETR),
or "cryosiam" (3D CNN encoder of a CryoZooUNet).
The ViT backbones must be set together with
model_type. - model_type: Model type for the selected ViT
backbonemodel family, for example "vit_b" or "vit_b_em_organelles" for "sam". - encoder_checkpoint: Path to the pretrained encoder weights for
backbone. By default they are fetched forbackboneandmodel_type. - checkpoint_path: Path to the directory with 'best.pt', to initialize the model from it.
- resume: Whether to continue the previous run with this name in
save_root, with its optimizer and iteration count.n_iterationsthen includes the iterations of the previous run. - save_every_kth_epoch: Save checkpoints after every kth epoch in a separate file. The corresponding checkpoints will be saved with the naming scheme 'epoch-{epoch}.pt'.
- mixed_precision: Whether to train with mixed precision.
- early_stopping: The number of epochs without improvement after which training is stopped.
- log_image_interval: The interval (in iterations) at which images are written to the log.
- loader_kwargs: Additional keyword arguments for the dataloader.