-
Notifications
You must be signed in to change notification settings - Fork 1
/
reinforce.py
83 lines (60 loc) · 1.86 KB
/
reinforce.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
79
80
81
82
83
# %% - Andriy Drozdyuk
import torch
import gym
max_steps = 50_000
step = 0
lr = 0.005
γ = 0.9999
env = gym.make('CartPole-v0')
nn = torch.nn.Sequential(
torch.nn.Linear(4, 64),
torch.nn.ReLU(),
torch.nn.Linear(64, env.action_space.n),
torch.nn.Softmax(dim=-1)
)
optim = torch.optim.Adam(nn.parameters(), lr=lr)
while step <= max_steps:
obs = torch.tensor(env.reset(), dtype=torch.float)
done = False
Actions, States, Rewards = [], [], []
while not done:
probs = nn(obs)
dist = torch.distributions.Categorical(probs=probs)
action = dist.sample().item()
obs_, rew, done, _ = env.step(action)
Actions.append(torch.tensor(action, dtype=torch.int))
States.append(obs)
Rewards.append(rew)
obs = torch.tensor(obs_, dtype=torch.float)
step += 1
DiscountedReturns = []
for t in range(len(Rewards)):
G = 0.0
for k, r in enumerate(Rewards[t:]):
G += (γ**k)*r
DiscountedReturns.append(G)
for State, Action, G in zip(States, Actions, DiscountedReturns):
probs = nn(State)
dist = torch.distributions.Categorical(probs=probs)
log_prob = dist.log_prob(Action)
loss = - log_prob*G
optim.zero_grad()
loss.backward()
optim.step()
# %% Play
for _ in range(5):
Rewards = []
obs = torch.tensor(env.reset(), dtype=torch.float)
done = False
env.render()
while not done:
probs = nn(obs)
c = torch.distributions.Categorical(probs=probs)
action = c.sample().item()
obs_, rew, done, _info = env.step(action)
env.render()
obs = torch.tensor(obs_, dtype=torch.float)
Rewards.append(rew)
print(f'Reward: {sum(Rewards)}')
env.close()
# %%