3

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})
Jasha
  • 5,507
  • 2
  • 33
  • 44
pete2213
  • 69
  • 2
  • 7

2 Answers2

3

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.

Jasha
  • 5,507
  • 2
  • 33
  • 44
  • Note that the space after the comma is mandatory for hydra (i.e. use {key: value} and not {key:value}) . – CharlesG Jan 11 '22 at 12:58
  • 1
    I think you mean "colon" (`:`), not "comma" (`,`). This requirement is due to the [yaml spec](https://stackoverflow.com/questions/42124227/why-does-the-yaml-spec-mandate-a-space-after-the-colon). – Jasha Jan 13 '22 at 00:21
  • Indeed, thks for the correction. – CharlesG Jan 27 '22 at 15:58
1

On top of what Jasha said, if the constructor of the class you're targeting manually checks the type of its arguments (if isinstance(remapping, dict):) then you should instruct Hydra to convert the config data into dicts:

transform = hydra.utils.instantiate(config, _convert_="partial")
miccio
  • 133
  • 1
  • 10