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
| import torch import gym
env = gym.make('CartPole-v1')
class RLInterface: def __init__(self): self.observation_space = env.observation_space.shape self.action_space = env.action_space def reset(self): obs = env.reset() return torch.tensor(obs, dtype=torch.float32) def step(self, action): action = int(action.item()) obs, reward, done, info = env.step(action=action) obs_tensor = torch.tensor(obs, dtype= torch.float32) reward_tensor = torch.tensor(reward, dtype=torch.float32) done_tensor = torch.tensor(done, dtype=torch.bool) return obs_tensor, reward_tensor, done_tensor, info
rl_env = RLInterface()
for episode in range(num_episodes): obs = rl_env.reset() while True: action = agent.choose_action(obs) next_obs, reward, done, _ = rl_env.step(action=action) agent.update(obs, action, reward, next_obs, done) obs = next_obs if done: break
env.close()
|