Skip to content

deeplabcut.generate_training_dataset.multiple_individuals_trainingsetmanipulation

Functions:

Name Description
create_multianimaltraining_dataset

Creates a training dataset for multi-animal datasets. Labels from all the

create_multianimaltraining_dataset

create_multianimaltraining_dataset(
    config,
    num_shuffles=1,
    Shuffles=None,
    windows2linux=False,
    net_type=None,
    detector_type=None,
    numdigits=2,
    crop_size=(400, 400),
    crop_sampling="hybrid",
    paf_graph=None,
    trainIndices=None,
    testIndices=None,
    n_edges_threshold=105,
    paf_graph_degree=6,
    userfeedback: bool = True,
    weight_init: WeightInitialization | None = None,
    engine: Engine | None = None,
    ctd_conditions: int | str | Path | tuple[int, str] | tuple[int, int] | None = None,
)

Creates a training dataset for multi-animal datasets. Labels from all the extracted frames are merged into a single .h5 file. Only the videos included in the config file are used to create this dataset. [OPTIONAL] Use the function 'add_new_videos' at any stage of the project to add more videos to the project.

Important differences to standard: - stores coordinates with numdigits as many digits

Parameter


config : string Full path of the config.yaml file as a string.

num_shuffles : int, optional Number of shuffles of training dataset to create, i.e. [1,2,3] for num_shuffles=3. Default is set to 1.

Shuffles: list of shuffles. Alternatively the user can also give a list of shuffles (integers!).

net_type: string Type of networks. The options available depend on which engine is used. See Lauer et al. 2021 https://www.biorxiv.org/content/10.1101/2021.04.30.442096v1 Currently supported options are: TensorFlow * resnet_50 * resnet_101 * resnet_152 * efficientnet-b0 * efficientnet-b1 * efficientnet-b2 * efficientnet-b3 * efficientnet-b4 * efficientnet-b5 * efficientnet-b6 PyTorch (call deeplabcut.pose_estimation_pytorch.available_models() for a complete list) * animaltokenpose_base * cspnext_m * cspnext_s * cspnext_x * ctd_coam_w32 * ctd_coam_w48 * ctd_prenet_hrnet_w32 * ctd_prenet_hrnet_w48 * ctd_prenet_rtmpose_m * ctd_prenet_rtmpose_x * ctd_prenet_rtmpose_x_human * dekr_w18 * dekr_w32 * dekr_w48 * dlcrnet_stride16_ms5 * dlcrnet_stride32_ms5 * hrnet_w18 * hrnet_w32 * hrnet_w48 * resnet_101 * resnet_50 * rtmpose_m * rtmpose_s * rtmpose_x * top_down_cspnext_m * top_down_cspnext_s * top_down_cspnext_x * top_down_hrnet_w18 * top_down_hrnet_w32 * top_down_hrnet_w48 * top_down_resnet_101 * top_down_resnet_50

detector_type: string, optional, default=None Only for the PyTorch engine. When passing creating shuffles for top-down models, you can specify which detector you want. If the detector_type is None, the ssdlite will be used. The list of all available detectors can be obtained by calling deeplabcut.pose_estimation_pytorch.available_detectors(). Supported options: * ssdlite * fasterrcnn_mobilenet_v3_large_fpn * fasterrcnn_resnet50_fpn_v2

numdigits: int, optional

crop_size: tuple of int, optional Only for the TensorFlow engine. Dimensions (width, height) of the crops for data augmentation. Default is 400x400.

crop_sampling: str, optional Only for the TensorFlow engine. Crop centers sampling method. Must be either: "uniform" (randomly over the image), "keypoints" (randomly over the annotated keypoints), "density" (weighing preferentially dense regions of keypoints), or "hybrid" (alternating randomly between "uniform" and "density"). Default is "hybrid".

paf_graph: list of lists, or "config" optional (default=None) Only for the TensorFlow engine. If not None, overwrite the default complete graph. This is useful for advanced users who already know a good graph, or simply want to use a specific one. Note that, in that case, the data-driven selection procedure upon model evaluation will be skipped.

   "config" will use the skeleton defined in the config file.

trainIndices: list of lists, optional (default=None) List of one or multiple lists containing train indexes. A list containing two lists of training indexes will produce two splits.

testIndices: list of lists, optional (default=None) List of one or multiple lists containing test indexes.

n_edges_threshold: int, optional (default=105) Only for the TensorFlow engine. Number of edges above which the graph is automatically pruned.

paf_graph_degree: int, optional (default=6) Only for the TensorFlow engine. Degree of paf_graph when automatically pruning it (before training).

userfeedback: bool, optional, default=True If False, all requested train/test splits are created (no matter if they already exist). If you want to assure that previous splits etc. are not overwritten, set this to True and you will be asked for each split.

weight_init: WeightInitialisation, optional, default=None PyTorch engine only. Specify how model weights should be initialized. The default mode uses transfer learning from ImageNet weights.

engine: Engine, optional Whether to create a pose config for a Tensorflow or PyTorch model. Defaults to the value specified in the project configuration file. If no engine is specified for the project, defaults to deeplabcut.compat.DEFAULT_ENGINE.

ctd_conditions: int | str | Path | tuple[int, str] | tuple[int, int] , optional, default = None, If using a conditional-top-down (CTD) net_type, this argument needs to be specified. It defines the conditions that will be used with the CTD model. It can be either: * A shuffle number (ctd_conditions: int), which must correspond to a bottom-up (BU) network type. * A predictions file path (ctd_conditions: string | Path), which must correspond to a .json or .h5 predictions file. * A shuffle number and a particular snapshot (ctd_conditions: tuple[int, str] | tuple[int, int]), which respectively correspond to a bottom-up (BU) network type and a particular snapshot name or index.

Example


deeplabcut.create_multianimaltraining_dataset('/analysis/project/reaching-task/config.yaml',num_shuffles=1)

deeplabcut.create_multianimaltraining_dataset('/analysis/project/reaching-task/config.yaml', Shuffles=[0,1,2], trainIndices=[trainInd1, trainInd2, trainInd3], testIndices=[testInd1, testInd2, testInd3])

Windows:

deeplabcut.create_multianimaltraining_dataset(r'C:\Users\Ulf\looming-task\config.yaml',Shuffles=[3,17,5])


Source code in deeplabcut/generate_training_dataset/multiple_individuals_trainingsetmanipulation.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
def create_multianimaltraining_dataset(
    config,
    num_shuffles=1,
    Shuffles=None,
    windows2linux=False,
    net_type=None,
    detector_type=None,
    numdigits=2,
    crop_size=(400, 400),
    crop_sampling="hybrid",
    paf_graph=None,
    trainIndices=None,
    testIndices=None,
    n_edges_threshold=105,
    paf_graph_degree=6,
    userfeedback: bool = True,
    weight_init: WeightInitialization | None = None,
    engine: Engine | None = None,
    ctd_conditions: int | str | Path | tuple[int, str] | tuple[int, int] | None = None,
):
    """Creates a training dataset for multi-animal datasets. Labels from all the
    extracted frames are merged into a single .h5 file.\n Only the videos included in
    the config file are used to create this dataset.\n [OPTIONAL] Use the function
    'add_new_videos' at any stage of the project to add more videos to the project.

    Important differences to standard:
     - stores coordinates with numdigits as many digits

    Parameter
    ----------
    config : string
        Full path of the config.yaml file as a string.

    num_shuffles : int, optional
        Number of shuffles of training dataset to create, i.e. [1,2,3] for num_shuffles=3. Default is set to 1.

    Shuffles: list of shuffles.
        Alternatively the user can also give a list of shuffles (integers!).

    net_type: string
        Type of networks. The options available depend on which engine is used. See
        Lauer et al. 2021 https://www.biorxiv.org/content/10.1101/2021.04.30.442096v1
        Currently supported options are:
            TensorFlow
                * ``resnet_50``
                * ``resnet_101``
                * ``resnet_152``
                * ``efficientnet-b0``
                * ``efficientnet-b1``
                * ``efficientnet-b2``
                * ``efficientnet-b3``
                * ``efficientnet-b4``
                * ``efficientnet-b5``
                * ``efficientnet-b6``
            PyTorch (call ``deeplabcut.pose_estimation_pytorch.available_models()`` for
            a complete list)
                * ``animaltokenpose_base``
                * ``cspnext_m``
                * ``cspnext_s``
                * ``cspnext_x``
                * ``ctd_coam_w32``
                * ``ctd_coam_w48``
                * ``ctd_prenet_hrnet_w32``
                * ``ctd_prenet_hrnet_w48``
                * ``ctd_prenet_rtmpose_m``
                * ``ctd_prenet_rtmpose_x``
                * ``ctd_prenet_rtmpose_x_human``
                * ``dekr_w18``
                * ``dekr_w32``
                * ``dekr_w48``
                * ``dlcrnet_stride16_ms5``
                * ``dlcrnet_stride32_ms5``
                * ``hrnet_w18``
                * ``hrnet_w32``
                * ``hrnet_w48``
                * ``resnet_101``
                * ``resnet_50``
                * ``rtmpose_m``
                * ``rtmpose_s``
                * ``rtmpose_x``
                * ``top_down_cspnext_m``
                * ``top_down_cspnext_s``
                * ``top_down_cspnext_x``
                * ``top_down_hrnet_w18``
                * ``top_down_hrnet_w32``
                * ``top_down_hrnet_w48``
                * ``top_down_resnet_101``
                * ``top_down_resnet_50``

    detector_type: string, optional, default=None
        Only for the PyTorch engine.
        When passing creating shuffles for top-down models, you can specify which
        detector you want. If the detector_type is None, the ```ssdlite``` will be used.
        The list of all available detectors can be obtained by calling
        ``deeplabcut.pose_estimation_pytorch.available_detectors()``. Supported options:
            * ``ssdlite``
            * ``fasterrcnn_mobilenet_v3_large_fpn``
            * ``fasterrcnn_resnet50_fpn_v2``

    numdigits: int, optional

    crop_size: tuple of int, optional
        Only for the TensorFlow engine.
        Dimensions (width, height) of the crops for data augmentation.
        Default is 400x400.

    crop_sampling: str, optional
        Only for the TensorFlow engine.
        Crop centers sampling method. Must be either:
        "uniform" (randomly over the image),
        "keypoints" (randomly over the annotated keypoints),
        "density" (weighing preferentially dense regions of keypoints),
        or "hybrid" (alternating randomly between "uniform" and "density").
        Default is "hybrid".

    paf_graph: list of lists, or "config" optional (default=None)
        Only for the TensorFlow engine.
        If not None, overwrite the default complete graph. This is useful for advanced users who
        already know a good graph, or simply want to use a specific one. Note that, in that case,
        the data-driven selection procedure upon model evaluation will be skipped.

        "config" will use the skeleton defined in the config file.

    trainIndices: list of lists, optional (default=None)
        List of one or multiple lists containing train indexes.
        A list containing two lists of training indexes will produce two splits.

    testIndices: list of lists, optional (default=None)
        List of one or multiple lists containing test indexes.

    n_edges_threshold: int, optional (default=105)
        Only for the TensorFlow engine.
        Number of edges above which the graph is automatically pruned.

    paf_graph_degree: int, optional (default=6)
        Only for the TensorFlow engine.
        Degree of paf_graph when automatically pruning it (before training).

    userfeedback: bool, optional, default=True
        If ``False``, all requested train/test splits are created (no matter if they
        already exist). If you want to assure that previous splits etc. are not
        overwritten, set this to ``True`` and you will be asked for each split.

    weight_init: WeightInitialisation, optional, default=None
        PyTorch engine only. Specify how model weights should be initialized. The
        default mode uses transfer learning from ImageNet weights.

    engine: Engine, optional
        Whether to create a pose config for a Tensorflow or PyTorch model. Defaults to
        the value specified in the project configuration file. If no engine is specified
        for the project, defaults to ``deeplabcut.compat.DEFAULT_ENGINE``.

    ctd_conditions: int | str | Path | tuple[int, str] | tuple[int, int] , optional, default = None,
        If using a conditional-top-down (CTD) net_type, this argument needs to be specified.
        It defines the conditions that will be used with the CTD model.
        It can be either:
            * A shuffle number (ctd_conditions: int), which must correspond to a bottom-up (BU) network type.
            * A predictions file path (ctd_conditions: string | Path), which must correspond to a .json or .h5
            predictions file.
            * A shuffle number and a particular snapshot (ctd_conditions: tuple[int, str] | tuple[int, int]), which
            respectively correspond to a bottom-up (BU) network type and a particular snapshot name or index.

    Example
    --------
    >>> deeplabcut.create_multianimaltraining_dataset('/analysis/project/reaching-task/config.yaml',num_shuffles=1)

    >>> deeplabcut.create_multianimaltraining_dataset('/analysis/project/reaching-task/config.yaml', Shuffles=[0,1,2],
    trainIndices=[trainInd1, trainInd2, trainInd3], testIndices=[testInd1, testInd2, testInd3])

    Windows:
    >>> deeplabcut.create_multianimaltraining_dataset(r'C:\\Users\\Ulf\\looming-task\\config.yaml',Shuffles=[3,17,5])
    --------
    """
    if windows2linux:
        warnings.warn(
            "`windows2linux` has no effect since 2.2.0.4 and will be removed in 2.2.1.",
            FutureWarning,
            stacklevel=2,
        )

    if len(crop_size) != 2 or not all(isinstance(v, int) for v in crop_size):
        raise ValueError("Crop size must be a tuple of two integers (width, height).")

    if crop_sampling not in ("uniform", "keypoints", "density", "hybrid"):
        raise ValueError(
            f"Invalid sampling {crop_sampling}. Must be either 'uniform', 'keypoints', 'density', or 'hybrid."
        )

    # Loading metadata from config file:
    cfg = auxiliaryfunctions.read_config(config)
    scorer = cfg["scorer"]
    project_path = cfg["project_path"]
    # Create path for training sets & store data there
    trainingsetfolder = auxiliaryfunctions.get_training_set_folder(cfg)
    full_training_path = Path(project_path, trainingsetfolder)
    auxiliaryfunctions.attempt_to_make_folder(full_training_path, recursive=True)

    # Create the trainset metadata file, if it doesn't yet exist
    if not metadata.TrainingDatasetMetadata.path(cfg).exists():
        trainset_metadata = metadata.TrainingDatasetMetadata.create(cfg)
        trainset_metadata.save()

    Data = merge_annotateddatasets(cfg, full_training_path)
    if Data is None:
        return
    Data = Data[scorer]

    if net_type is None:  # loading & linking pretrained models
        net_type = cfg.get("default_net_type", "dlcrnet_ms5")

    # load the engine to use to create the shuffle
    if engine is None:
        engine = compat.get_project_engine(cfg)

    if not (any(net in net_type for net in ("resnet", "eff", "dlc", "mob")) or engine == Engine.PYTORCH):
        raise ValueError(f"Unsupported network {net_type} for engine {engine}.")

    multi_stage = False
    ### dlcnet_ms5: backbone resnet50 + multi-fusion & multi-stage module
    ### dlcr101_ms5/dlcr152_ms5: backbone resnet101/152 + multi-fusion & multi-stage module
    if all(net in net_type for net in ("dlcr", "_ms5")) and engine != Engine.PYTORCH:
        num_layers = re.findall("dlcr([0-9]*)", net_type)[0]
        if num_layers == "":
            num_layers = 50
        net_type = f"resnet_{num_layers}"
        multi_stage = True

    dataset_type = "multi-animal-imgaug"
    (
        individuals,
        uniquebodyparts,
        multianimalbodyparts,
    ) = auxfun_multianimal.extractindividualsandbodyparts(cfg)

    if paf_graph is None:  # Automatically form a complete PAF graph
        n_bpts = len(multianimalbodyparts)
        partaffinityfield_graph = [list(edge) for edge in combinations(range(n_bpts), 2)]
        n_edges_orig = len(partaffinityfield_graph)
        # If the graph is unnecessarily large (with 15+ keypoints by default),
        # we randomly prune it to a size guaranteeing an average node degree of 6;
        # see Suppl. Fig S9c in Lauer et al., 2022.
        if n_edges_orig >= n_edges_threshold:
            partaffinityfield_graph = auxfun_multianimal.prune_paf_graph(
                partaffinityfield_graph,
                average_degree=paf_graph_degree,
            )
    else:
        if paf_graph == "config":
            # Use the skeleton defined in the config file
            skeleton = cfg["skeleton"]
            paf_graph = [
                sorted((multianimalbodyparts.index(bpt1), multianimalbodyparts.index(bpt2))) for bpt1, bpt2 in skeleton
            ]
            print("Using `skeleton` from the config file as a paf_graph. Data-driven skeleton will not be computed.")

        # Ignore possible connections between 'multi' and 'unique' body parts;
        # one can never be too careful...
        to_ignore = auxfun_multianimal.filter_unwanted_paf_connections(cfg, paf_graph)
        partaffinityfield_graph = [edge for i, edge in enumerate(paf_graph) if i not in to_ignore]
        auxfun_multianimal.validate_paf_graph(cfg, partaffinityfield_graph)

    print("Utilizing the following graph:", partaffinityfield_graph)
    # Disable the prediction of PAFs if the graph is empty
    partaffinityfield_predict = bool(partaffinityfield_graph)

    # Loading the encoder (if necessary downloading from TF)
    dlcparent_path = auxiliaryfunctions.get_deeplabcut_path()
    defaultconfigfile = os.path.join(dlcparent_path, "pose_cfg.yaml")

    if engine == Engine.PYTORCH:
        model_path = dlcparent_path
    else:
        model_path = auxfun_models.check_for_weights(net_type, Path(dlcparent_path))

    Shuffles = validate_shuffles(cfg, Shuffles, num_shuffles, userfeedback)

    # print(trainIndices,testIndices, Shuffles, augmenter_type,net_type)
    if trainIndices is None and testIndices is None:
        splits = []
        for shuffle in Shuffles:  # Creating shuffles starting from 1
            for train_frac in cfg["TrainingFraction"]:
                train_inds, test_inds = SplitTrials(range(len(Data)), train_frac)
                splits.append((train_frac, shuffle, (train_inds, test_inds)))
    else:
        if len(trainIndices) != len(testIndices) != len(Shuffles):
            raise ValueError("Number of Shuffles and train and test indexes should be equal.")
        splits = []
        for shuffle, (train_inds, test_inds) in enumerate(zip(trainIndices, testIndices, strict=False)):
            trainFraction = round(len(train_inds) * 1.0 / (len(train_inds) + len(test_inds)), 2)
            print(f"You passed a split with the following fraction: {int(100 * trainFraction)}%")
            # Now that the training fraction is guaranteed to be correct,
            # the values added to pad the indices are removed.
            train_inds = np.asarray(train_inds)
            train_inds = train_inds[train_inds != -1]
            test_inds = np.asarray(test_inds)
            test_inds = test_inds[test_inds != -1]
            splits.append((trainFraction, Shuffles[shuffle], (train_inds, test_inds)))

    top_down = False
    if engine == Engine.PYTORCH and net_type.startswith("top_down_"):
        top_down = True
        net_type = net_type[len("top_down_") :]

    for trainFraction, shuffle, (trainIndices, testIndices) in splits:
        ####################################################
        # Generating data structure with labeled information & frame metadata (for deep cut)
        ####################################################
        print(
            "Creating training data for: Shuffle:",
            shuffle,
            "TrainFraction: ",
            trainFraction,
        )

        # Make training file!
        data = format_multianimal_training_data(
            Data,
            trainIndices,
            cfg["project_path"],
            numdigits,
        )

        if len(trainIndices) > 0:
            (
                datafilename,
                metadatafilename,
            ) = auxiliaryfunctions.get_data_and_metadata_filenames(trainingsetfolder, trainFraction, shuffle, cfg)
            ################################################################################
            # Saving metadata and data file (Pickle file)
            ################################################################################
            auxiliaryfunctions.save_metadata(
                os.path.join(project_path, metadatafilename),
                data,
                trainIndices,
                testIndices,
                trainFraction,
            )
            metadata.update_metadata(
                cfg=cfg,
                train_fraction=trainFraction,
                shuffle=shuffle,
                engine=engine,
                train_indices=trainIndices,
                test_indices=testIndices,
                overwrite=not userfeedback,
            )

            datafilename = datafilename.split(".mat")[0] + ".pickle"
            import pickle

            with open(os.path.join(project_path, datafilename), "wb") as f:
                # Pickle the 'labeled-data' dictionary using the highest protocol available.
                pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

            ################################################################################
            # Creating file structure for training &
            # Test files as well as pose_yaml files (containing training and testing information)
            #################################################################################

            modelfoldername = auxiliaryfunctions.get_model_folder(
                trainFraction,
                shuffle,
                cfg,
                engine=engine,
            )
            auxiliaryfunctions.attempt_to_make_folder(Path(config).parents[0] / modelfoldername, recursive=True)
            auxiliaryfunctions.attempt_to_make_folder(str(Path(config).parents[0] / modelfoldername / "train"))
            auxiliaryfunctions.attempt_to_make_folder(str(Path(config).parents[0] / modelfoldername / "test"))

            path_train_config = str(
                os.path.join(
                    cfg["project_path"],
                    Path(modelfoldername),
                    "train",
                    "pose_cfg.yaml",
                )
            )
            path_test_config = str(
                os.path.join(
                    cfg["project_path"],
                    Path(modelfoldername),
                    "test",
                    "pose_cfg.yaml",
                )
            )
            path_inference_config = str(
                os.path.join(
                    cfg["project_path"],
                    Path(modelfoldername),
                    "test",
                    "inference_cfg.yaml",
                )
            )

            if engine == Engine.TF:
                jointnames = [str(bpt) for bpt in multianimalbodyparts]
                jointnames.extend([str(bpt) for bpt in uniquebodyparts])
                items2change = {
                    "dataset": datafilename,
                    "engine": engine.aliases[0],
                    "metadataset": metadatafilename,
                    "num_joints": len(multianimalbodyparts) + len(uniquebodyparts),  # cfg["uniquebodyparts"]),
                    "all_joints": [
                        [i] for i in range(len(multianimalbodyparts) + len(uniquebodyparts))
                    ],  # cfg["uniquebodyparts"]))],
                    "all_joints_names": jointnames,
                    "init_weights": str(model_path),
                    "project_path": str(cfg["project_path"]),
                    "net_type": net_type,
                    "multi_stage": multi_stage,
                    "pairwise_loss_weight": 0.1,
                    "pafwidth": 20,
                    "partaffinityfield_graph": partaffinityfield_graph,
                    "partaffinityfield_predict": partaffinityfield_predict,
                    "weigh_only_present_joints": False,
                    "num_limbs": len(partaffinityfield_graph),
                    "dataset_type": dataset_type,
                    "optimizer": "adam",
                    "batch_size": 8,
                    "multi_step": [[1e-4, 7500], [5 * 1e-5, 12000], [1e-5, 200000]],
                    "save_iters": 10000,
                    "display_iters": 500,
                    "num_idchannel": (len(cfg["individuals"]) if cfg.get("identity", False) else 0),
                    "crop_size": list(crop_size),
                    "crop_sampling": crop_sampling,
                }

                trainingdata = MakeTrain_pose_yaml(
                    items2change,
                    path_train_config,
                    defaultconfigfile,
                    save=(engine == Engine.TF),
                )
                keys2save = [
                    "dataset",
                    "num_joints",
                    "all_joints",
                    "all_joints_names",
                    "net_type",
                    "multi_stage",
                    "init_weights",
                    "global_scale",
                    "location_refinement",
                    "locref_stdev",
                    "dataset_type",
                    "partaffinityfield_predict",
                    "pairwise_predict",
                    "partaffinityfield_graph",
                    "num_limbs",
                    "dataset_type",
                    "num_idchannel",
                ]

                MakeTest_pose_yaml(
                    trainingdata,
                    keys2save,
                    path_test_config,
                    nmsradius=5.0,
                    minconfidence=0.01,
                    sigma=1,
                    locref_smooth=False,
                )  # setting important def. values for inference
            elif engine == Engine.PYTORCH:
                from deeplabcut.pose_estimation_pytorch.config.make_pose_config import (
                    make_pytorch_pose_config,
                    make_pytorch_test_config,
                )
                from deeplabcut.pose_estimation_pytorch.modelzoo.config import (
                    make_super_animal_finetune_config,
                )

                # backwards compatibility with version 2.X
                if net_type == "dlcrnet_ms5":
                    net_type = "dlcrnet_stride16_ms5"

                config_path = Path(path_train_config).with_name(engine.pose_cfg_name)
                if weight_init is not None and weight_init.with_decoder:
                    pytorch_cfg = make_super_animal_finetune_config(
                        project_config=cfg,
                        pose_config_path=config_path,
                        model_name=net_type,
                        detector_name=detector_type,
                        weight_init=weight_init,
                        save=True,
                    )
                else:
                    pytorch_cfg = make_pytorch_pose_config(
                        project_config=cfg,
                        pose_config_path=config_path,
                        net_type=net_type,
                        top_down=top_down,
                        detector_type=detector_type,
                        weight_init=weight_init,
                        save=True,
                        ctd_conditions=ctd_conditions,
                    )

                make_pytorch_test_config(pytorch_cfg, path_test_config, save=True)

            # Setting inference cfg file:
            default_inf_path = Path(dlcparent_path) / "inference_cfg.yaml"
            inf_updates = dict(
                minimalnumberofconnections=int(len(cfg["multianimalbodyparts"]) / 2),
                topktoretain=len(cfg["individuals"]),
                withid=cfg.get("identity", False),
            )
            MakeInference_yaml(inf_updates, path_inference_config, default_inf_path)

            print(
                "The training dataset is successfully created. Use the function "
                "'train_network' to start training. Happy training!"
            )
        else:
            pass