You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

eval.py 2.4 kB

4 years ago
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright 2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Evaluation for DQN"""
  16. import argparse
  17. import gym
  18. from mindspore import context
  19. from mindspore.common import set_seed
  20. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  21. from src.config import config_dqn as cfg
  22. from src.agent import Agent
  23. parser = argparse.ArgumentParser(description='MindSpore dqn Example')
  24. parser.add_argument('--device_target', type=str, default="Ascend", choices=['Ascend', 'GPU'],
  25. help='device where the code will be implemented (default: Ascend)')
  26. parser.add_argument('--ckpt_path', type=str, default=None, help='if is test, must provide\
  27. path where the trained ckpt file')
  28. args = parser.parse_args()
  29. set_seed(1)
  30. if __name__ == "__main__":
  31. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  32. env = gym.make('CartPole-v1')
  33. cfg.state_space_dim = env.observation_space.shape[0]
  34. cfg.action_space_dim = env.action_space.n
  35. agent = Agent(**cfg)
  36. # load checkpoint
  37. if args.ckpt_path:
  38. param_dict = load_checkpoint(args.ckpt_path)
  39. not_load_param = load_param_into_net(agent.policy_net, param_dict)
  40. if not_load_param:
  41. raise ValueError("Load param into net fail!")
  42. score = 0
  43. agent.load_dict()
  44. for episode in range(50):
  45. s0 = env.reset()
  46. total_reward = 1
  47. while True:
  48. a0 = agent.eval_act(s0)
  49. s1, r1, done, _ = env.step(a0)
  50. if done:
  51. r1 = -1
  52. if done:
  53. break
  54. total_reward += r1
  55. s0 = s1
  56. score += total_reward
  57. print("episode", episode, "total_reward", total_reward)
  58. print("mean_reward", score/50)