Skip to content

ding.model.common.utils

ding.model.common.utils

create_model(cfg)

Overview

Create a neural network model according to the given EasyDict-type cfg.

Arguments: - cfg: (:obj:EasyDict): User's model config. The key import_name is used to import modules, and they key type is used to indicate the model. Returns: - (:obj:torch.nn.Module): The created neural network model. Examples: >>> cfg = EasyDict({ >>> 'import_names': ['ding.model.template.q_learning'], >>> 'type': 'dqn', >>> 'obs_shape': 4, >>> 'action_shape': 2, >>> }) >>> model = create_model(cfg)

.. tip:: This method will not modify the cfg , it will deepcopy the cfg and then modify it.

Full Source Code

../ding/model/common/utils.py

1import copy 2import torch 3from easydict import EasyDict 4from ding.utils import import_module, MODEL_REGISTRY 5 6 7def create_model(cfg: EasyDict) -> torch.nn.Module: 8 """ 9 Overview: 10 Create a neural network model according to the given EasyDict-type ``cfg``. 11 Arguments: 12 - cfg: (:obj:`EasyDict`): User's model config. The key ``import_name`` is \ 13 used to import modules, and they key ``type`` is used to indicate the model. 14 Returns: 15 - (:obj:`torch.nn.Module`): The created neural network model. 16 Examples: 17 >>> cfg = EasyDict({ 18 >>> 'import_names': ['ding.model.template.q_learning'], 19 >>> 'type': 'dqn', 20 >>> 'obs_shape': 4, 21 >>> 'action_shape': 2, 22 >>> }) 23 >>> model = create_model(cfg) 24 25 .. tip:: 26 This method will not modify the ``cfg`` , it will deepcopy the ``cfg`` and then modify it. 27 """ 28 cfg = copy.deepcopy(cfg) 29 import_module(cfg.pop('import_names', [])) 30 # here we must use the pop opeartion to ensure compatibility 31 return MODEL_REGISTRY.build(cfg.pop("type"), **cfg)