-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathAC_sparse.py
163 lines (118 loc) · 4.59 KB
/
AC_sparse.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
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
# -*- coding: utf-8 -*-
import os
import numpy as np
from keras.layers import Input, Dense
from keras.models import Model
from keras.optimizers import Adam
import keras.backend as K
from DRL import DRL
class AC(DRL):
"""Actor Critic Algorithms with sparse action.
"""
def __init__(self):
super(AC, self).__init__()
self.actor = self._build_actor()
self.critic = self._build_critic()
self.gamma = 0.9
def load(self):
if os.path.exists('model/actor_acs.h5') and os.path.exists('model/critic_acs.h5'):
self.actor.load_weights('model/actor_acs.h5')
self.critic.load_weights('model/critic_acs.h5')
def _build_actor(self):
"""actor model.
"""
inputs = Input(shape=(4,))
x = Dense(20, activation='relu')(inputs)
x = Dense(20, activation='relu')(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(inputs=inputs, outputs=x)
return model
def _build_critic(self):
"""critic model.
"""
inputs = Input(shape=(4,))
x = Dense(20, activation='relu')(inputs)
x = Dense(20, activation='relu')(x)
x = Dense(1, activation='linear')(x)
model = Model(inputs=inputs, outputs=x)
return model
def _actor_loss(self, y_true, y_pred):
"""actor loss function.
Arguments:
y_true: (action, reward)
y_pred: action_prob
Returns:
loss: reward loss
"""
action_pred = y_pred
action_true, td_error = y_true[:, 0], y_true[:, 1]
action_true = K.reshape(action_true, (-1, 1))
loss = K.binary_crossentropy(action_true, action_pred)
loss = loss * K.flatten(td_error)
return loss
def discount_reward(self, next_states, reward, done):
"""Discount reward for Critic
Arguments:
next_states: next_states
rewards: reward of last action.
done: if game done.
"""
q = self.critic.predict(next_states)[0][0]
target = reward
if not done:
target = reward + self.gamma * q
return target
def train(self, episode):
"""training model.
Arguments:
episode: ganme episode
Returns:
history: training history
"""
self.actor.compile(loss=self._actor_loss, optimizer=Adam(lr=0.001))
self.critic.compile(loss='mse', optimizer=Adam(lr=0.01))
history = {'episode': [], 'Episode_reward': [],
'actor_loss': [], 'critic_loss': []}
for i in range(episode):
observation = self.env.reset()
rewards = []
alosses = []
closses = []
while True:
x = observation.reshape(-1, 4)
# choice action with prob.
prob = self.actor.predict(x)[0][0]
action = np.random.choice(np.array(range(2)), p=[1 - prob, prob])
next_observation, reward, done, _ = self.env.step(action)
next_observation = next_observation.reshape(-1, 4)
rewards.append(reward)
target = self.discount_reward(next_observation, reward, done)
y = np.array([target])
# TD_error = (r + gamma * next_q) - current_q
td_error = target - self.critic.predict(x)[0][0]
# loss1 = mse((r + gamma * next_q), current_q)
loss1 = self.critic.train_on_batch(x, y)
y = np.array([[action, td_error]])
loss2 = self.actor.train_on_batch(x, y)
observation = next_observation[0]
alosses.append(loss2)
closses.append(loss1)
if done:
episode_reward = sum(rewards)
aloss = np.mean(alosses)
closs = np.mean(closses)
history['episode'].append(i)
history['Episode_reward'].append(episode_reward)
history['actor_loss'].append(aloss)
history['critic_loss'].append(closs)
print('Episode: {} | Episode reward: {} | actor_loss: {:.3f} | critic_loss: {:.3f}'.format(i, episode_reward, aloss, closs))
break
self.actor.save_weights('model/actor_acs.h5')
self.critic.save_weights('model/critic_acs.h5')
return history
if __name__ == '__main__':
model = AC()
history = model.train(300)
model.save_history(history, 'ac_sparse.csv')
model.load()
model.play('acs')