Skip to content

ding.example.dqn_eval

ding.example.dqn_eval

Full Source Code

../ding/example/dqn_eval.py

1import gym 2import torch 3from ditk import logging 4from ding.model import DQN 5from ding.policy import DQNPolicy 6from ding.envs import DingEnvWrapper, BaseEnvManagerV2 7from ding.config import compile_config 8from ding.framework import task 9from ding.framework.context import OnlineRLContext 10from ding.framework.middleware import interaction_evaluator 11from ding.utils import set_pkg_seed 12from dizoo.classic_control.cartpole.config.cartpole_dqn_config import main_config, create_config 13 14 15def main(): 16 logging.getLogger().setLevel(logging.INFO) 17 main_config.exp_name = 'cartpole_dqn_eval' 18 cfg = compile_config(main_config, create_cfg=create_config, auto=True) 19 with task.start(async_mode=False, ctx=OnlineRLContext()): 20 evaluator_env = BaseEnvManagerV2( 21 env_fn=[lambda: DingEnvWrapper(gym.make("CartPole-v0")) for _ in range(cfg.env.evaluator_env_num)], 22 cfg=cfg.env.manager 23 ) 24 25 set_pkg_seed(cfg.seed, use_cuda=cfg.policy.cuda) 26 model = DQN(**cfg.policy.model) 27 28 # Load the pretrained weights. 29 # First, you should get a pretrained network weights. 30 # For example, you can run ``python3 -u ding/examples/dqn.py``. 31 pretrained_state_dict = torch.load('cartpole_dqn_seed0/ckpt/final.pth.tar', map_location='cpu')['model'] 32 model.load_state_dict(pretrained_state_dict) 33 34 policy = DQNPolicy(cfg.policy, model=model) 35 36 # Define the evaluator middleware. 37 task.use(interaction_evaluator(cfg, policy.eval_mode, evaluator_env)) 38 task.run(max_step=1) 39 40 41if __name__ == "__main__": 42 main()