This repository has been archived by the owner on Dec 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
train.py
78 lines (61 loc) · 2.13 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'''
Author: jianzhnie
Date: 2022-09-02 12:23:30
LastEditors: jianzhnie
LastEditTime: 2022-09-02 12:29:55
Description:
Copyright (c) 2022 by jianzhnie@126.com, All Rights Reserved.
'''
import sys
import gym
import numpy as np
import torch
sys.path.append('../../')
from cartpole_agent import CartpoleAgent
from cartpole_model import CartpoleModel
from rltoolkit.policy.modelfree.policy_gradient import PolicyGradient
from rltoolkit.utils import logger
OBS_DIM = 4
ACT_DIM = 2
LEARNING_RATE = 1e-3
def run_episode(env, agent, train_or_test='train'):
obs_list, action_list, reward_list = [], [], []
obs = env.reset()
while True:
obs_list.append(obs)
if train_or_test == 'train':
action = agent.sample(obs)
else:
action = agent.predict(obs)
action_list.append(action)
obs, reward, done, _ = env.step(action)
reward_list.append(reward)
if done:
break
return obs_list, action_list, reward_list
def calc_reward_to_go(reward_list):
for i in range(len(reward_list) - 2, -1, -1):
reward_list[i] += reward_list[i + 1]
return np.array(reward_list)
def main():
env = gym.make('CartPole-v0')
device = torch.device(
'cuda') if torch.cuda.is_available() else torch.device('cpu')
model = CartpoleModel(obs_dim=OBS_DIM, act_dim=ACT_DIM)
alg = PolicyGradient(model, LEARNING_RATE, device=device)
agent = CartpoleAgent(alg, device=device)
for i in range(1000): # 1000 episodes
obs_list, action_list, reward_list = run_episode(env, agent)
if i % 10 == 0:
logger.info('Episode {}, Reward Sum {}.'.format(
i, sum(reward_list)))
batch_obs = np.array(obs_list)
batch_action = np.array(action_list)
batch_reward = calc_reward_to_go(reward_list)
agent.learn(batch_obs, batch_action, batch_reward)
if (i + 1) % 100 == 0:
_, _, reward_list = run_episode(env, agent, train_or_test='test')
total_reward = np.sum(reward_list)
logger.info('Test reward: {}'.format(total_reward))
if __name__ == '__main__':
main()