-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
164 lines (146 loc) * 6.6 KB
/
agent.py
File metadata and controls
164 lines (146 loc) * 6.6 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from torch.nn import functional as F
from torch.distributions import Categorical
from torch.utils.data import BatchSampler, SubsetRandomSampler
from utils import *
class PPOAgent(object):
def __init__(self, args: dict):
self.batch_size = args["batch_size"] # batch size
self.lr_a = args["lr_a"] # Ce Lue Wang Luo Xue Xi Lu
self.lr_c = args["lr_c"] # Jie Zhi Wang Luo Xue Xi Lu
self.gamma = args["gamma"] # Zhe Kou Yin Zi
self.lamda = args["lambda"] # GAE l
self.epsilon = args["epsilon"] # PPO e
self.k_epochs = args["k_epochs"] # PPO Xun Lian Lun Shu
self.entropy_coef = args["entropy_coef"]
# Shen Jing Wang Luo
self.pai_set = {
20: get_model("actor", "./model/non_maze.pth", 20).to(device),
19: get_model("actor", "./model/maze.pth", 19).to(device),
10: get_model("actor", "./model/non_maze1v1.pth", 10).to(device),
9: get_model("actor", "./model/maze1v1.pth", 9).to(device)
}
self.v_set = {
20: get_model("critic", "./model/non_maze_critic.pth", 20).to(device),
19: get_model("critic", "./model/maze_critic.pth", 19).to(device),
10: get_model("critic", "./model/non_maze1v1_critic.pth", 10).to(device),
9: get_model("critic", "./model/maze1v1_critic.pth", 9).to(device)
}
self.pai = self.pai_set[20]
self.v = self.v_set[20]
self.optimizer_actor = torch.optim.Adam(self.pai.parameters(), lr=self.lr_a, eps=1e-5)
self.optimizer_critic = torch.optim.Adam(self.v.parameters(), lr=self.lr_c, eps=1e-5)
# others
self.mse_loss_fn = nn.MSELoss()
def learn(self, rep, step_t):
"""
learn from experience
:param rep:
:param step_t:
:return:
"""
s, a, a_log_prob, r, s_, done = rep.get_data()
# Quan Bu Song Jin NQia
s = s.to(device)
a = a.to(device)
a_log_prob = a_log_prob.to(device)
r = r.to(device)
s_ = s_.to(device)
done = done.to(device)
# Li Yong GAEJi Suan You Shi Han Shu
adv = []
gae = 0
with torch.no_grad(): # Bu Xu Yao Ti Du
vs = self.v(s)
vs_ = self.v(s_)
deltas = r + self.gamma * (1.0 - done) * vs_ - vs
for delta, d in zip(reversed(deltas.flatten()), reversed(done.flatten())):
gae = delta + self.gamma * self.lamda * gae * (1.0 - d)
adv.insert(0, gae)
adv = torch.tensor(adv, dtype=torch.float).view(-1, 1).to(device)
v_target = adv + vs
# You Shi Gui Yi Hua
adv = ((adv - adv.mean()) / (adv.std() + 1e-5))
# Can Shu Geng Xin kLun
for _ in range(self.k_epochs):
for index in BatchSampler(SubsetRandomSampler(range(self.batch_size)), self.batch_size, False):
mask = at.mask(s[index], s[index].shape[2])
dist_now = Categorical(mask * self.pai.softmax(self.pai(s[index])))
dist_entropy = dist_now.entropy().view(-1, 1) # shape(batch_size x 1)
a_log_prob_now = dist_now.log_prob(a[index].squeeze()).view(-1, 1) # shape(batch_size x 1)
# https://www.luogu.com.cn/paste/9vwi6ls0
# Ji Suan Ce Lue Ti Du
ratios = torch.exp(a_log_prob_now - a_log_prob[index]) # shape(batch_size x 1)
surr1 = ratios * adv[index]
surr2 = torch.clamp(ratios, 1 - self.epsilon, 1 + self.epsilon) * adv[index]
actor_loss = -torch.min(surr1,
surr2) - self.entropy_coef * dist_entropy # shape(batch_size x 1)
# Geng Xin Ce Lue Wang Luo
self.optimizer_actor.zero_grad()
actor_loss.mean().backward()
# Ti Du Cai Jian
torch.nn.utils.clip_grad_norm_(self.pai.parameters(), 0.5)
self.optimizer_actor.step()
# Jie Zhi Wang Luo Ti Du
v_s = self.v(s[index])
critic_loss = self.mse_loss_fn(v_target[index], v_s)
# Geng Xin Jie Zhi Wang Luo
self.optimizer_critic.zero_grad()
critic_loss.backward()
# Ti Du Cai Jian
torch.nn.utils.clip_grad_norm_(self.v.parameters(), 0.5)
self.optimizer_critic.step()
self.lr_decay(step_t)
def lr_decay(self, total_steps):
"""
Xue Xi Lu Shuai Jian
:param total_steps: Yi Xun Lian Bu Shu
:return:
"""
decay_rate = 0.1
upt = 1 / (1 + decay_rate * total_steps)
lr_a_now = self.lr_a * upt
lr_c_now = self.lr_c * upt
for p in self.optimizer_actor.param_groups:
p['lr'] = lr_a_now
for p in self.optimizer_critic.param_groups:
p['lr'] = lr_c_now
def predict(self, observation):
"""
Cong Ce Lue Wang Luo Cai Yang Dong Zuo
:param observation: s_t
:return: 2 tensors: action, ln(p(a_t|s_t))
"""
with torch.no_grad():
mask = at.mask(observation, observation.shape[2])
act_ = self.pai(observation) * mask
action_p = Categorical(self.pai.softmax(act_))
action = action_p.sample()
a_log_prob = action_p.log_prob(action)
return action, a_log_prob
def change_network(self, map_size):
"""
Dang Mo Shi Geng Huan Shi Geng Huan Shen Jing Wang Luo
:param map_size:
:return:
"""
self.pai = self.pai_set[map_size]
self.v = self.v_set[map_size]
def warm_up(self):
"""
Yu Re Yin Wei Shen Jing Wang Luo Di Yi Ci Pao Hui Bi Jiao Man
:return:
"""
t = torch.zeros([1, 12, 20, 20]).to(device)
self.pai(t)
self.v(t)
def save(self):
# Bao Cun Ce Lue Wang Luo
torch.save(self.pai_set[20], "./model/non_maze.pth")
torch.save(self.pai_set[10], "./model/non_maze1v1.pth")
torch.save(self.pai_set[19], "./model/maze.pth")
torch.save(self.pai_set[9], "./model/maze1v1.pth")
# Bao Cun Jie Zhi Wang Luo
torch.save(self.v_set[20], "./model/non_maze_critic.pth")
torch.save(self.v_set[10], "./model/non_maze1v1_critic.pth")
torch.save(self.v_set[19], "./model/maze_critic.pth")
torch.save(self.v_set[9], "./model/maze1v1_critic.pth")