Search code examples
pythonyamlfb-hydra

How to pass dictionary elements from hydra config file


I am trying to instantiate objects with hydra, I have a class torchio.transforms.RemapLabels that I am using in my config file:

_target_: torchio.transforms.RemapLabels

The problem is that torchio.transforms.RemapLabels takes dictionary elements as input, how do I pass those from my hydra config file? (config.yaml)?

I am getting error when instantiating:

TypeError: Error instantiating 'torchio.transforms.preprocessing.label.remap_labels.RemapLabels' : __init__() missing 1 required positional argument: 'remapping'

example usage of remap label:

transform = torchio.RemapLabels({2:1, 4:3, 6:5, 8:7})

Solution

  • There are two options: you can pass the inputs as positional arguments or as named arguments.

    Using named arguments (a.k.a. keyword arguments) in your yaml file:

    _target_: torchio.transforms.RemapLabels
    remapping:
      2: 1
      4: 3
      6: 5
      8: 7
    masking_method: "Anterior"
    

    or, using json-style maps:

    _target_: torchio.transforms.RemapLabels
    remapping: {2: 1, 4: 3, 6: 5, 8: 7}
    masking_method: "Anterior"
    

    Using positional arguments in your yaml file:

    _target_: torchio.transforms.RemapLabels
    _args_:
      - 2: 1
        4: 3
        6: 5
        8: 7
      - "Anterior"
    

    Or, equivalently:

    _target_: torchio.transforms.RemapLabels
    _args_:
      - {2: 1, 4: 3, 6: 5, 8: 7}
      - "Anterior"
    

    For more information, please refer to the docs on Instantiating objects with Hydra.