@@ -104,3 +104,40 @@ configuration file and use it the script like so:
104104 # Set the seed for numpy
105105 np.random.seed(config.seed)
106106 # application-specific seed setting
107+
108+ Instantiating objects
109+ ---------------------
110+
111+ Another cool feature of Hydra is object instantiating. Imagine you want to try different
112+ Optimizers for your Deep Neural Network (DNN) or you want to try different DNNs in the same pipeline.
113+ Instead of doing ``if-else `` statements, you write one line of code and let Hydra choose the
114+ appropriate object class based on your configuration. See the script
115+ `examples/hydra_instantiate.py <https://github.com/ebezzam/python-dev-tips/blob/main/examples/hydra_instantiate.py >`_
116+ for the example.
117+
118+ .. code-block :: python
119+ @hydra.main (version_base = None , config_path = " configs" , config_name = " instantiate" )
120+ def run (config ):
121+ # instantiate object from config
122+ example_array = instantiate(config.array)
123+ # application specific choice of object class
124+
125+ ``instantiate `` function from ``hydra.utils `` allows you to define an object in a YAML file
126+ without being tied to a particular class. To do this, you need to define ``_target_ `` in
127+ your config (see configs in ``configs/array ``) and object initialization arguments. Object class
128+ can be either defined in your project (``configs/array/ExampleZeros ``, ``configs/array/ExampleArange ``)
129+ or taken from a package (``configs/array/ExampleNumpy ``).
130+
131+ Note that here we use another Hydra feature: config grouping and splitting. Instead of writing
132+ configurations for all objects in the main config and copying configuration files, we create a sub-directory ``array ``,
133+ where all ``array `` configs are defined. Now we can run the main config with the ``array `` of
134+ our choice simply by specifying it in the command line. For example, ``python3 hydra_instantiate.py array=ExampleNumpy ``
135+ or ``python3 hydra_instantiate.py array=ExampleZeros ``.
136+
137+ Object instantiating is recursive, i.e. some of the arguments of the class can also be
138+ defined using ``_target_ `` and they will be created automatically. For example,
139+ ``python3 hydra_instantiate.py array=ExampleArange +array/transform=power `` defines the ``transform `` argument of
140+ the ``ExampleArange `` class as the ``PowerTransform `` class. The ``+array/transform=power `` in the command line
141+ means adding the ``transform `` argument to the current ``array `` configuration from the ``power.yaml `` config defined
142+ in ``configs/array/transform ``. That is, you can have sub-sub-directories. The default values from sub-sub-directories
143+ can also be changed in the command-line: ``python3 hydra_instantiate.py array=ExampleArange +array/transform=power array.transform.pow=3 ``
0 commit comments