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 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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | import os import gym import time import threading import random import numpy as np import tensorflow as tf from skimage.color import rgb2gray from skimage.transform import resize from tensorflow.compat.v1.train import AdamOptimizer from tensorflow.keras.layers import Conv2D, Flatten, Dense # ¸ÖƼ¾²·¹µùÀ» À§ÇÑ ±Û·Î¹ú º¯¼ö global episode, score_avg, score_max episode, score_avg, score_max = 0, 0, 0 num_episode = 8000000 # ActorCritic Àΰø½Å°æ¸Á class ActorCritic(tf.keras.Model): def __init__(self, action_size, state_size): super(ActorCritic, self).__init__() self.conv1 = Conv2D(32, (8, 8), strides=(4, 4), activation='relu', input_shape=state_size) self.conv2 = Conv2D(64, (4, 4), strides=(2, 2), activation='relu') self.conv3 = Conv2D(64, (3, 3), strides=(1, 1), activation='relu') self.flatten = Flatten() self.shared_fc = Dense(512, activation='relu') self.policy = Dense(action_size, activation='linear') self.value = Dense(1, activation='linear') def call(self, x): x = self.conv1(x) x = self.conv2(x) x = self.flatten(x) x = self.shared_fc(x) policy = self.policy(x) value = self.value(x) return policy, value # ºê·¹ÀÌÅ©¾Æ¿ô¿¡¼ÀÇ A3CAgent Ŭ·¡½º (±Û·Î¹ú½Å°æ¸Á) class A3CAgent(): def __init__(self, action_size, env_name): self.env_name = env_name # »óÅÂ¿Í ÇൿÀÇ Å©±â Á¤ÀÇ self.state_size = (84, 84, 4) self.action_size = action_size # A3C ÇÏÀÌÆÛÆĶó¹ÌÅÍ self.discount_factor = 0.99 self.no_op_steps = 30 self.lr = 1e-4 # ¾²·¹µåÀÇ °¹¼ö self.threads = 16 # ±Û·Î¹ú Àΰø½Å°æ¸Á »ý¼º self.global_model = ActorCritic(self.action_size, self.state_size) # ±Û·Î¹ú Àΰø½Å°æ¸ÁÀÇ °¡ÁßÄ¡ ÃʱâÈ self.global_model.build(tf.TensorShape((None, *self.state_size))) # Àΰø½Å°æ¸Á ¾÷µ¥ÀÌÆ®ÇÏ´Â ¿ÉƼ¸¶ÀÌÀú ÇÔ¼ö »ý¼º self.optimizer = AdamOptimizer(self.lr, use_locking=True) # ÅÙ¼º¸µå ¼³Á¤ self.writer = tf.summary.create_file_writer('summary/breakout_a3c') # ÇнÀµÈ ±Û·Î¹ú½Å°æ¸Á ¸ðµ¨À» ÀúÀåÇÒ °æ·Î ¼³Á¤ self.model_path = os.path.join(os.getcwd(), 'save_model', 'model') # ¾²·¹µå¸¦ ¸¸µé¾î ÇнÀÀ» ÇÏ´Â ÇÔ¼ö def train(self): # ¾²·¹µå ¼ö ¸¸Å Runner Ŭ·¡½º »ý¼º runners = [Runner(self.action_size, self.state_size, self.global_model, self.optimizer, self.discount_factor, self.env_name, self.writer) for i in range(self.threads)] # °¢ ¾²·¹µå ½ÃÁ¤ for i, runner in enumerate(runners): print("Start worker #{:d}".format(i)) runner.start() # 10ºÐ (600ÃÊ)¿¡ ÇÑ ¹ø¾¿ ¸ðµ¨À» ÀúÀå while True: self.global_model.save_weights(self.model_path, save_format="tf") time.sleep(60 * 10) # ¾×ÅÍ·¯³Ê Ŭ·¡½º (¾²·¹µå) class Runner(threading.Thread): global_episode = 0 def __init__(self, action_size, state_size, global_model, optimizer, discount_factor, env_name, writer): threading.Thread.__init__(self) # A3CAgent Ŭ·¡½º¿¡¼ ³Ñ°ÜÁØ ÇÏÀÌÁØ ÆĶó¹ÌÅÍ ¼³Á¤ self.action_size = action_size self.state_size = state_size self.global_model = global_model self.optimizer = optimizer self.discount_factor = discount_factor self.states, self.actions, self.rewards = [], [], [] # ȯ°æ, ·ÎÄýŰæ¸Á, ÅÙ¼º¸µå »ý¼º self.local_model = ActorCritic(action_size, state_size) self.env = gym.make(env_name) self.writer = writer # ÇнÀ Á¤º¸¸¦ ±â·ÏÇÒ º¯¼ö self.avg_p_max = 0 self.avg_loss = 0 # k-ŸÀÓ½ºÅÜ °ª ¼³Á¤ self.t_max = 20 self.t = 0 # ºÒÇÊ¿äÇÑ ÇൿÀ» ÁÙ¿©ÁÖ±â À§ÇÑ dictionary self.action_dict = {0:1, 1:2, 2:3, 3:3} # ÅÙ¼º¸µå¿¡ ÇнÀ Á¤º¸¸¦ ±â·Ï def draw_tensorboard(self, score, step, e): avg_p_max = self.avg_p_max / float(step) with self.writer.as_default(): tf.summary.scalar('Total Reward/Episode', score, step=e) tf.summary.scalar('Average Max Prob/Episode', avg_p_max, step=e) tf.summary.scalar('Duration/Episode', step, step=e) # Á¤Ã¥½Å°æ¸ÁÀÇ Ãâ·ÂÀ» ¹Þ¾Æ È®·üÀûÀ¸·Î ÇൿÀ» ¼±Åà def get_action(self, history): history = np.float32(history / 255.) policy = self.local_model(history)[0][0] policy = tf.nn.softmax(policy) action_index = np.random.choice(self.action_size, 1, p=policy.numpy())[0] return action_index, policy # »ùÇÃÀ» ÀúÀå def append_sample(self, history, action, reward): self.states.append(history) act = np.zeros(self.action_size) act[action] = 1 self.actions.append(act) self.rewards.append(reward) # k-ŸÀÓ½ºÅÜÀÇ prediction °è»ê def discounted_prediction(self, rewards, done): discounted_prediction = np.zeros_like(rewards) running_add = 0 if not done: # value function last_state = np.float32(self.states[-1] / 255.) running_add = self.local_model(last_state)[-1][0].numpy() for t in reversed(range(0, len(rewards))): running_add = running_add * self.discount_factor + rewards[t] discounted_prediction[t] = running_add return discounted_prediction # ÀúÀåµÈ »ùÇõé·Î A3CÀÇ ¿À·ùÇÔ¼ö¸¦ °è»ê def compute_loss(self, done): discounted_prediction = self.discounted_prediction(self.rewards, done) discounted_prediction = tf.convert_to_tensor(discounted_prediction[:, None], dtype=tf.float32) states = np.zeros((len(self.states), 84, 84, 4)) for i in range(len(self.states)): states[i] = self.states[i] states = np.float32(states / 255.) policy, values = self.local_model(states) # °¡Ä¡ ½Å°æ¸Á ¾÷µ¥ÀÌÆ® advantages = discounted_prediction - values critic_loss = 0.5 * tf.reduce_sum(tf.square(advantages)) # Á¤Ã¥ ½Å°æ¸Á ¾÷µ¥ÀÌÆ® action = tf.convert_to_tensor(self.actions, dtype=tf.float32) policy_prob = tf.nn.softmax(policy) action_prob = tf.reduce_sum(action * policy_prob, axis=1, keepdims=True) cross_entropy = - tf.math.log(action_prob + 1e-10) actor_loss = tf.reduce_sum(cross_entropy * tf.stop_gradient(advantages)) entropy = tf.reduce_sum(policy_prob * tf.math.log(policy_prob + 1e-10), axis=1) entropy = tf.reduce_sum(entropy) actor_loss += 0.01 * entropy total_loss = 0.5 * critic_loss + actor_loss return total_loss # ·ÎÄýŰæ¸ÁÀ» ÅëÇØ ±×·¹À̵ð¾ðÆ®¸¦ °è»êÇÏ°í, ±Û·Î¹ú ½Å°æ¸ÁÀ» °è»êµÈ ±×·¹À̵ð¾ðÆ®·Î ¾÷µ¥ÀÌÆ® def train_model(self, done): global_params = self.global_model.trainable_variables local_params = self.local_model.trainable_variables with tf.GradientTape() as tape: total_loss = self.compute_loss(done) # ·ÎÄýŰæ¸ÁÀÇ ±×·¹À̵ð¾ðÆ® °è»ê grads = tape.gradient(total_loss, local_params) # ¾ÈÁ¤ÀûÀÎ ÇнÀÀ» À§ÇÑ ±×·¹À̵ð¾ðÆ® Ŭ¸®ÇÎ grads, _ = tf.clip_by_global_norm(grads, 40.0) # ·ÎÄýŰæ¸ÁÀÇ ¿À·ùÇÔ¼ö¸¦ ÁÙÀÌ´Â ¹æÇâÀ¸·Î ±Û·Î¹ú½Å°æ¸ÁÀ» ¾÷µ¥ÀÌÆ® self.optimizer.apply_gradients(zip(grads, global_params)) # ·ÎÄýŰæ¸ÁÀÇ °¡ÁßÄ¡¸¦ ±Û·Î¹ú½Å°æ¸ÁÀÇ °¡ÁßÄ¡·Î ¾÷µ¥ÀÌÆ® self.local_model.set_weights(self.global_model.get_weights()) # ¾÷µ¥ÀÌÆ® ÈÄ ÀúÀåµÈ »ùÇà ÃʱâÈ self.states, self.actions, self.rewards = [], [], [] def run(self): # ¾×ÅÍ·¯³Ê³¢¸® °øÀ¯ÇؾßÇÏ´Â ±Û·Î¹ú º¯¼ö global episode, score_avg, score_max step = 0 while episode < num_episode: done = False dead = False score, start_life = 0, 5 observe = self.env.reset() # ·£´ýÀ¸·Î »ÌÈù °ª ¸¸ÅÀÇ ÇÁ·¹ÀÓµ¿¾È ¿òÁ÷ÀÌÁö ¾ÊÀ½ for _ in range(random.randint(1, 30)): observe, _, _, _ = self.env.step(1) # ÇÁ·¹ÀÓÀ» Àüó¸® ÇÑ ÈÄ 4°³ÀÇ »óŸ¦ ½×¾Æ¼ ÀԷ°ªÀ¸·Î »ç¿ë. state = pre_processing(observe) history = np.stack([state, state, state, state], axis=2) history = np.reshape([history], (1, 84, 84, 4)) while not done: step += 1 self.t += 1 # Á¤Ã¥ È®·ü¿¡ µû¶ó ÇൿÀ» ¼±Åà action, policy = self.get_action(history) # 1: Á¤Áö, 2: ¿ÞÂÊ, 3: ¿À¸¥ÂÊ real_action = self.action_dict[action] # Á×¾úÀ» ¶§ ½ÃÀÛÇϱâ À§ÇØ ¹ß»ç ÇൿÀ» ÇÔ if dead: action, real_action, dead = 0, 1, False # ¼±ÅÃÇÑ ÇൿÀ¸·Î ȯ°æ¿¡¼ ÇÑ Å¸ÀÓ½ºÅÜ ÁøÇà observe, reward, done, info = self.env.step(real_action) # °¢ ŸÀÓ½ºÅܸ¶´Ù »óÅ Àüó¸® next_state = pre_processing(observe) next_state = np.reshape([next_state], (1, 84, 84, 1)) next_history = np.append(next_state, history[:, :, :, :3], axis=3) # Á¤Ã¥È®·üÀÇ ÃÖ´ë°ª self.avg_p_max += np.amax(policy.numpy()) if start_life > info['ale.lives']: dead = True start_life = info['ale.lives'] score += reward reward = np.clip(reward, -1., 1.) # »ùÇÃÀ» ÀúÀå self.append_sample(history, action, reward) if dead: history = np.stack((next_state, next_state, next_state, next_state), axis=2) history = np.reshape([history], (1, 84, 84, 4)) else: history = next_history # ¿¡ÇǼҵ尡 ³¡³ª°Å³ª ÃÖ´ë ŸÀÓ½ºÅÜ ¼ö¿¡ µµ´ÞÇϸé ÇнÀÀ» ÁøÇà if self.t >= self.t_max or done: self.train_model(done) self.t = 0 if done: # °¢ ¿¡ÇÇ¼Òµå ´ç ÇнÀ Á¤º¸¸¦ ±â·Ï episode += 1 score_max = score if score > score_max else score_max score_avg = 0.9 * score_avg + 0.1 * score if score_avg != 0 else score log = "episode: {:5d} | score : {:4.1f} | ".format(episode, score) log += "score max : {:4.1f} | ".format(score_max) log += "score avg : {:.3f}".format(score_avg) print(log) self.draw_tensorboard(score, step, episode) self.avg_p_max = 0 step = 0 # ÇнÀ¼Óµµ¸¦ ³ôÀ̱â À§ÇØ Èæ¹éȸéÀ¸·Î Àüó¸® def pre_processing(observe): processed_observe = np.uint8( resize(rgb2gray(observe), (84, 84), mode='constant') * 255) return processed_observe if __name__ == "__main__": global_agent = A3CAgent(action_size=3, env_name="BreakoutDeterministic-v4") global_agent.train() | cs |
test.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 | import gym import time import random import numpy as np import tensorflow as tf from skimage.color import rgb2gray from skimage.transform import resize from tensorflow.keras.layers import Conv2D, Flatten, Dense # ActorCritic Àΰø½Å°æ¸Á class ActorCritic(tf.keras.Model): def __init__(self, action_size, state_size): super(ActorCritic, self).__init__() self.conv1 = Conv2D(32, (8, 8), strides=(4, 4), activation='relu', input_shape=state_size) self.conv2 = Conv2D(64, (4, 4), strides=(2, 2), activation='relu') self.conv3 = Conv2D(64, (3, 3), strides=(1, 1), activation='relu') self.flatten = Flatten() self.shared_fc = Dense(512, activation='relu') self.policy = Dense(action_size, activation='linear') self.value = Dense(1, activation='linear') def call(self, x): x = self.conv1(x) x = self.conv2(x) x = self.flatten(x) x = self.shared_fc(x) policy = self.policy(x) value = self.value(x) return policy, value # ºê·¹ÀÌÅ©¾Æ¿ô¿¡¼ÀÇ Å×½ºÆ®¸¦ À§ÇÑ A3C ¿¡ÀÌÀüÆ® Ŭ·¡½º class A3CTestAgent: def __init__(self, action_size, state_size, model_path): self.action_size = action_size self.model = ActorCritic(action_size, state_size) self.model.load_weights(model_path) def get_action(self, history): history = np.float32(history / 255.) policy = self.model(history)[0][0] policy = tf.nn.softmax(policy) action_index = np.random.choice(self.action_size, 1, p=policy.numpy())[0] return action_index, policy def pre_processing(observe): processed_observe = np.uint8( resize(rgb2gray(observe), (84, 84), mode='constant') * 255) return processed_observe if __name__ == "__main__": # Å×½ºÆ®¸¦ À§ÇÑ È¯°æ, ¸ðµ¨ »ý¼º env = gym.make("BreakoutDeterministic-v4") state_size = (84, 84, 4) action_size = 3 model_path = './save_model/trained/model' render = True agent = A3CTestAgent(action_size, state_size, model_path) action_dict = {0:1, 1:2, 2:3, 3:3} num_episode = 10 for e in range(num_episode): done = False dead = False score, start_life = 0, 5 observe = env.reset() # ·£´ýÀ¸·Î »ÌÈù °ª ¸¸ÅÀÇ ÇÁ·¹ÀÓµ¿¾È ¿òÁ÷ÀÌÁö ¾ÊÀ½ for _ in range(random.randint(1, 30)): observe, _, _, _ = env.step(1) # ÇÁ·¹ÀÓÀ» Àüó¸® ÇÑ ÈÄ 4°³ÀÇ »óŸ¦ ½×¾Æ¼ ÀԷ°ªÀ¸·Î »ç¿ë. state = pre_processing(observe) history = np.stack([state, state, state, state], axis=2) history = np.reshape([history], (1, 84, 84, 4)) while not done: if render: env.render() time.sleep(0.05) # Á¤Ã¥ È®·ü¿¡ µû¶ó ÇൿÀ» ¼±Åà action, policy = agent.get_action(history) # 1: Á¤Áö, 2: ¿ÞÂÊ, 3: ¿À¸¥ÂÊ real_action = action_dict[action] # Á×¾úÀ» ¶§ ½ÃÀÛÇϱâ À§ÇØ ¹ß»ç ÇൿÀ» ÇÔ if dead: action, real_action, dead = 0, 1, False # ¼±ÅÃÇÑ ÇൿÀ¸·Î ȯ°æ¿¡¼ ÇÑ Å¸ÀÓ½ºÅÜ ÁøÇà observe, reward, done, info = env.step(real_action) # °¢ ŸÀÓ½ºÅܸ¶´Ù »óÅ Àüó¸® next_state = pre_processing(observe) next_state = np.reshape([next_state], (1, 84, 84, 1)) next_history = np.append(next_state, history[:, :, :, :3], axis=3) if start_life > info['ale.lives']: dead, start_life = True, info['ale.lives'] score += reward if dead: history = np.stack((next_state, next_state, next_state, next_state), axis=2) history = np.reshape([history], (1, 84, 84, 4)) else: history = next_history if done: # °¢ ¿¡ÇÇ¼Òµå ´ç ÇнÀ Á¤º¸¸¦ ±â·Ï print("episode: {:3d} | score : {:4.1f}".format(e, score)) | cs |