Á¤¼ºÈÆ
    7Àå) ¾ÆŸ¸® ºê·¹ÀÌÅ© ¾Æ¿ô (DQN)
°­È­ÇнÀ ½Ç½À (¾ÆŸ¸® ºê·¹ÀÌÅ©¾Æ¿ô).pdf [2220 KB]   ºê·¹ÀÌÅ© ¾Æ¿ô ½ÇÇà°á°ú.mp4 [6194 KB]  



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
import os
import gym
import random
import numpy as np
import tensorflow as tf
from collections import deque
 
from skimage.color import rgb2gray
from skimage.transform import resize
 
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Conv2D, Dense, Flatten
 
 
# »óÅ°¡ ÀÔ·Â, Å¥ÇÔ¼ö°¡ Ãâ·ÂÀΠÀΰø½Å°æ¸Á »ý¼º
class DQN(tf.keras.Model):
    def __init__(self, action_size, state_size):
        super(DQN, self).__init__()
        self.conv1 = Conv2D(32, (88), strides=(44), activation='relu',
                            input_shape=state_size)
        self.conv2 = Conv2D(64, (44), strides=(22), activation='relu')
        self.conv3 = Conv2D(64, (33), strides=(11), activation='relu')
        self.flatten = Flatten()
        self.fc = Dense(512, activation='relu')
        self.fc_out = Dense(action_size)
 
    def call(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = self.conv3(x)
        x = self.flatten(x)
        x = self.fc(x)
        q = self.fc_out(x)
        return q
 
 
# ºê·¹ÀÌÅ©¾Æ¿ô ¿¹Á¦¿¡¼­ÀÇ DQN ¿¡ÀÌÀüÆ®
class DQNAgent:
    def __init__(self, action_size, state_size=(84844)):
        self.render = False
 
        # »óÅ¿͠ÇൿÀÇ Å©±â Á¤ÀÇ
        self.state_size = state_size
        self.action_size = action_size
 
        # DQN ÇÏÀÌÆÛÆĶó¹ÌÅÍ
        self.discount_factor = 0.99
        self.learning_rate = 1e-4
        self.epsilon = 1.
        self.epsilon_start, self.epsilon_end = 1.00.02
        self.exploration_steps = 1000000.
        self.epsilon_decay_step = self.epsilon_start - self.epsilon_end
        self.epsilon_decay_step /= self.exploration_steps
        self.batch_size = 32
        self.train_start = 50000
        self.update_target_rate = 10000
 
        # ¸®Ç÷¹ÀÌ ¸Þ¸ð¸®, ÃÖ´ë Å©±â 100,000
        self.memory = deque(maxlen=100000)
        # °ÔÀÓ ½ÃÀÛ ÈÄ ·£´ýÇÏ°Ô ¿òÁ÷ÀÌÁö ¾Ê´Â °Í¿¡ ´ëÇÑ ¿É¼Ç
        self.no_op_steps = 30
 
        # ¸ðµ¨°ú Å¸±ê ¸ðµ¨ »ý¼º
        self.model = DQN(action_size, state_size)
        self.target_model = DQN(action_size, state_size)
        self.optimizer = Adam(self.learning_rate, clipnorm=10.)
        # Å¸±ê ¸ðµ¨ ÃʱâÈ­
        self.update_target_model()
 
        self.avg_q_max, self.avg_loss = 00
 
        self.writer = tf.summary.create_file_writer('summary/breakout_dqn')
        self.model_path = os.path.join(os.getcwd(), 'save_model''model')
 
    # Å¸±ê ¸ðµ¨À» ¸ðµ¨ÀÇ °¡ÁßÄ¡·Î ¾÷µ¥ÀÌÆ®
    def update_target_model(self):
        self.target_model.set_weights(self.model.get_weights())
 
    # ÀԽǷРŽ¿å Á¤Ã¥À¸·Î Çൿ ¼±ÅÃ
    def get_action(self, history):
        history = np.float32(history / 255.0)
        if np.random.rand() <= self.epsilon:
            return random.randrange(self.action_size)
        else:
            q_value = self.model(history)
            return np.argmax(q_value[0])
 
    # »ùÇà<s, a, r, s'>À» ¸®Ç÷¹ÀÌ ¸Þ¸ð¸®¿¡ ÀúÀå
    def append_sample(self, history, action, reward, next_history, dead):
        self.memory.append((history, action, reward, next_history, dead))
 
    # ÅÙ¼­º¸µå¿¡ ÇнÀ Á¤º¸¸¦ ±â·Ï
    def draw_tensorboard(self, score, step, episode):
        with self.writer.as_default():
            tf.summary.scalar('Total Reward/Episode', score, step=episode)
            tf.summary.scalar('Average Max Q/Episode',
                              self.avg_q_max / float(step), step=episode)
            tf.summary.scalar('Duration/Episode', step, step=episode)
            tf.summary.scalar('Average Loss/Episode',
                              self.avg_loss / float(step), step=episode)
 
    # ¸®Ç÷¹ÀÌ ¸Þ¸ð¸®¿¡¼­ ¹«ÀÛÀ§·Î ÃßÃâÇÑ ¹èÄ¡·Î ¸ðµ¨ ÇнÀ
    def train_model(self):
        if self.epsilon > self.epsilon_end:
            self.epsilon -= self.epsilon_decay_step
 
        # ¸Þ¸ð¸®¿¡¼­ ¹èÄ¡ Å©±â¸¸Å­ ¹«ÀÛÀ§·Î »ùÇàÃßÃâ
        batch = random.sample(self.memory, self.batch_size)
 
        history = np.array([sample[0][0/ 255. for sample in batch],
                           dtype=np.float32)
        actions = np.array([sample[1for sample in batch])
        rewards = np.array([sample[2for sample in batch])
        next_history = np.array([sample[3][0/ 255. for sample in batch],
                                dtype=np.float32)
        dones = np.array([sample[4for sample in batch])
 
        # ÇнÀ ÆĶó¸ÞÅÍ
        model_params = self.model.trainable_variables
        with tf.GradientTape() as tape:
            # ÇöÀç »óÅ¿¡ ´ëÇÑ ¸ðµ¨ÀǠťÇÔ¼ö
            predicts = self.model(history)
            one_hot_action = tf.one_hot(actions, self.action_size)
            predicts = tf.reduce_sum(one_hot_action * predicts, axis=1)
 
            # ´ÙÀ½ »óÅ¿¡ ´ëÇѠŸ±ê ¸ðµ¨ÀǠťÇÔ¼ö
            target_predicts = self.target_model(next_history)
 
            # º§¸¸ ÃÖÀû ¹æÁ¤½ÄÀ» ±¸¼ºÇϱâ À§ÇѠŸ±ê°ú Å¥ÇÔ¼öÀÇ ÃÖ´ë °ª °è»ê
            max_q = np.amax(target_predicts, axis=1)
            targets = rewards + (1 - dones) * self.discount_factor * max_q
 
            # ÈĹö·Î½º °è»ê
            error = tf.abs(targets - predicts)
            quadratic_part = tf.clip_by_value(error, 0.01.0)
            linear_part = error - quadratic_part
            loss = tf.reduce_mean(0.5 * tf.square(quadratic_part) + linear_part)
 
            self.avg_loss += loss.numpy()
 
        # ¿À·ùÇÔ¼ö¸¦ ÁÙÀ̴ ¹æÇâÀ¸·Î ¸ðµ¨ ¾÷µ¥ÀÌÆ®
        grads = tape.gradient(loss, model_params)
        self.optimizer.apply_gradients(zip(grads, model_params))
 
 
# ÇнÀ¼Óµµ¸¦ ³ôÀ̱â À§ÇØ Èæ¹éÈ­¸éÀ¸·Î Àüó¸®
def pre_processing(observe):
    processed_observe = np.uint8(
        resize(rgb2gray(observe), (8484), mode='constant'* 255)
    return processed_observe
 
 
if __name__ == "__main__":
    # È¯°æ°ú DQN ¿¡ÀÌÀüÆ® »ý¼º
    env = gym.make('BreakoutDeterministic-v4')
    agent = DQNAgent(action_size=3)
 
    global_step = 0
    score_avg = 0
    score_max = 0
 
    # ºÒÇÊ¿äÇÑ ÇൿÀ» ¾ø¾ÖÁÖ±â À§ÇÑ µñ¼Å³Ê¸® ¼±¾ð
    action_dict = {0:11:22:33:3}
 
    num_episode = 50000
    for e in range(num_episode):
        done = False
        dead = False
 
        step, score, start_life = 005
        # env ÃʱâÈ­
        observe = env.reset()
 
        # ·£´ýÀ¸·Î »ÌÈù °ª ¸¸Å­ÀÇ ÇÁ·¹ÀÓµ¿¾È ¿òÁ÷ÀÌÁö ¾ÊÀ½
        for _ in range(random.randint(1, agent.no_op_steps)):
            observe, _, _, _ = env.step(1)
 
        # ÇÁ·¹ÀÓÀ» Àü󸮠ÇÑ ÈÄ 4°³ÀÇ »óŸ¦ ½×¾Æ¼­ ÀԷ°ªÀ¸·Î »ç¿ë.
        state = pre_processing(observe)
        history = np.stack((state, state, state, state), axis=2)
        history = np.reshape([history], (184844))
 
        while not done:
            if agent.render:
                env.render()
            global_step += 1
            step += 1
 
            # ¹Ù·Î Àü history¸¦ ÀÔ·ÂÀ¸·Î ¹Þ¾Æ ÇൿÀ» ¼±ÅÃ
            action = agent.get_action(history)
            # 1: Á¤Áö, 2: ¿ÞÂÊ, 3: ¿À¸¥ÂÊ
            real_action = action_dict[action]
 
            # Á×¾úÀ» ¶§ ½ÃÀÛÇϱâ À§ÇØ ¹ß»ç ÇൿÀ» ÇÔ
            if dead:
                action, real_action, dead = 01False
 
            # ¼±ÅÃÇÑ ÇൿÀ¸·Î È¯°æ¿¡¼­ ÇѠŸÀÓ½ºÅÜ ÁøÇà
            observe, reward, done, info = env.step(real_action)
            # °¢ Å¸ÀÓ½ºÅܸ¶´Ù »óÅ Àüó¸®
            next_state = pre_processing(observe)
            next_state = np.reshape([next_state], (184841))
            next_history = np.append(next_state, history[:, :, :, :3], axis=3)
 
            agent.avg_q_max += np.amax(agent.model(np.float32(history / 255.))[0])
 
            if start_life > info['ale.lives']:
                dead = True
                start_life = info['ale.lives']
 
            score += reward
            reward = np.clip(reward, -1.1.)
            # »ùÇà<s, a, r, s'>À» ¸®Ç÷¹ÀÌ ¸Þ¸ð¸®¿¡ ÀúÀå ÈÄ ÇнÀ
            agent.append_sample(history, action, reward, next_history, dead)
 
            # ¸®Ç÷¹ÀÌ ¸Þ¸ð¸® Å©±â°¡ Á¤ÇسõÀº ¼öÄ¡¿¡ µµ´ÞÇÑ ½ÃÁ¡ºÎÅÍ ¸ðµ¨ ÇнÀ ½ÃÀÛ
            if len(agent.memory) >= agent.train_start:
                agent.train_model()
                # ÀÏÁ¤ ½Ã°£¸¶´Ù Å¸°Ù¸ðµ¨À» ¸ðµ¨ÀÇ °¡ÁßÄ¡·Î ¾÷µ¥ÀÌÆ®
                if global_step % agent.update_target_rate == 0:
                    agent.update_target_model()
 
            if dead:
                history = np.stack((next_state, next_state,
                                    next_state, next_state), axis=2)
                history = np.reshape([history], (184844))
            else:
                history = next_history
 
            if done:
                # °¢ ¿¡ÇǼҵ場ç ÇнÀ Á¤º¸¸¦ ±â·Ï
                if global_step > agent.train_start:
                    agent.draw_tensorboard(score, step, e)
 
                score_avg = 0.9 * score_avg + 0.1 * score if score_avg != 0 else score
                score_max = score if score > score_max else score_max
 
                log = "episode: {:5d} | ".format(e)
                log += "score: {:4.1f} | ".format(score)
                log += "score max : {:4.1f} | ".format(score_max)
                log += "score avg: {:4.1f} | ".format(score_avg)
                log += "memory length: {:5d} | ".format(len(agent.memory))
                log += "epsilon: {:.3f} | ".format(agent.epsilon)
                log += "q avg : {:3.2f} | ".format(agent.avg_q_max / float(step))
                log += "avg loss : {:3.2f}".format(agent.avg_loss / float(step))
                print(log)
 
                agent.avg_q_max, agent.avg_loss = 00
 
        # 1000 ¿¡ÇǼҵ帶´Ù ¸ðµ¨ ÀúÀå
        if e % 1000 == 0:
            agent.model.save_weights("./save_model/model", save_format="tf")
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
126
127
128
129
130
131
132
133
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, Dense, Flatten
 
 
# »óÅ°¡ ÀÔ·Â, Å¥ÇÔ¼ö°¡ Ãâ·ÂÀΠÀΰø½Å°æ¸Á »ý¼º
class DQN(tf.keras.Model):
    def __init__(self, action_size, state_size):
        super(DQN, self).__init__()
        self.conv1 = Conv2D(32, (88), strides=(44), activation='relu',
                            input_shape=state_size)
        self.conv2 = Conv2D(64, (44), strides=(22), activation='relu')
        self.conv3 = Conv2D(64, (33), strides=(11), activation='relu')
        self.flatten = Flatten()
        self.fc = Dense(512, activation='relu')
        self.fc_out = Dense(action_size)
 
    def call(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = self.conv3(x)
        x = self.flatten(x)
        x = self.fc(x)
        q = self.fc_out(x)
        return q
 
 
# ºê·¹ÀÌÅ©¾Æ¿ô ¿¹Á¦¿¡¼­ÀÇ DQN ¿¡ÀÌÀüÆ®
class DQNAgent:
    def __init__(self, action_size, state_size, model_path):
        self.render = False
 
        # »óÅ¿͠ÇൿÀÇ Å©±â Á¤ÀÇ
        self.state_size = state_size
        self.action_size = action_size
 
        self.epsilon = 0.02
 
        # ¸ðµ¨°ú Å¸±ê ¸ðµ¨ »ý¼º
        self.model = DQN(action_size, state_size)
        self.model.load_weights(model_path)
 
    # ÀԽǷРŽ¿å Á¤Ã¥À¸·Î Çൿ ¼±ÅÃ
    def get_action(self, history):
        history = np.float32(history / 255.0)
        if np.random.rand() <= self.epsilon:
            return random.randrange(self.action_size)
        else:
            q_value = self.model(history)
            return np.argmax(q_value[0])
 
 
def pre_processing(observe):
    processed_observe = np.uint8(
        resize(rgb2gray(observe), (8484), mode='constant'* 255)
    return processed_observe
 
 
if __name__ == "__main__":
    # È¯°æ ¼¼ÆÃ
    env = gym.make("BreakoutDeterministic-v4")
    render = True
 
    # Å×½ºÆ®¸¦ À§ÇÑ ¿¡ÀÌÀüÆ® »ý¼º
    state_size = (84844)
    action_size = 3
    model_path = './save_model/trained/model'
    agent = DQNAgent(action_size, state_size, model_path)
 
    # ºÒÇÊ¿äÇÑ ÇൿÀ» ¾ø¾ÖÁÖ±â À§ÇÑ µñ¼Å³Ê¸® ¼±¾ð
    action_dict = {0:11:22:33:3}
 
    num_episode = 10
    for e in range(num_episode):
        done = False
        dead = False
 
        score, start_life = 05
        # env ÃʱâÈ­
        observe = env.reset()
 
        # ·£´ýÀ¸·Î »ÌÈù °ª ¸¸Å­ÀÇ ÇÁ·¹ÀÓµ¿¾È ¿òÁ÷ÀÌÁö ¾ÊÀ½
        for _ in range(random.randint(130)):
            observe, _, _, _ = env.step(1)
 
        # ÇÁ·¹ÀÓÀ» Àü󸮠ÇÑ ÈÄ 4°³ÀÇ »óŸ¦ ½×¾Æ¼­ ÀԷ°ªÀ¸·Î »ç¿ë.
        state = pre_processing(observe)
        history = np.stack([state, state, state, state], axis=2)
        history = np.reshape([history], (184844))
 
        while not done:
            if render:
                env.render()
                time.sleep(0.05)
 
            # ¹Ù·Î Àü history¸¦ ÀÔ·ÂÀ¸·Î ¹Þ¾Æ ÇൿÀ» ¼±ÅÃ
            action = agent.get_action(history)
            # 1: Á¤Áö, 2: ¿ÞÂÊ, 3: ¿À¸¥ÂÊ
            real_action = action_dict[action]
            
            # Á×¾úÀ» ¶§ ½ÃÀÛÇϱâ À§ÇØ ¹ß»ç ÇൿÀ» ÇÔ
            if dead:
                action, real_action, dead = 01False
 
            # ¼±ÅÃÇÑ ÇൿÀ¸·Î È¯°æ¿¡¼­ ÇѠŸÀÓ½ºÅÜ ÁøÇà
            observe, reward, done, info = env.step(real_action)
            # °¢ Å¸ÀÓ½ºÅܸ¶´Ù »óÅ Àüó¸®
            next_state = pre_processing(observe)
            next_state = np.reshape([next_state], (184841))
            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], (184844))
            else:
                history = next_history
 
            if done:
                # °¢ ¿¡ÇǼҵ場ç Å×½ºÆ® Á¤º¸¸¦ ±â·Ï
                print("episode: {:3d} | score : {:4.1f}".format(e, score))
cs

 

  µî·ÏÀÏ : 2021-11-01 [03:08] Á¶È¸ : 690 ´Ù¿î : 505   
 
¡â ÀÌÀü±Û7Àå) ¾ÆŸ¸® ºê·¹ÀÌÅ© ¾Æ¿ô (A3C)
¡ä ´ÙÀ½±Û°­È­ÇнÀ/½ÉÃþ°­È­ÇнÀ Ư°­ (github)
°­È­ÇнÀ ÀÌ·Ð ¹× ½Ç½À(MD) ½Ç½À
¹øÈ£ ¨Ï Á¦ ¸ñ À̸§
¹Ù´ÚºÎÅÍ ¹è¿ì´Â °­È­ ÇнÀ ÄÚµå (github)
°­È­ÇнÀ/½ÉÃþ°­È­ÇнÀ Ư°­ (github)
ÆÄÀ̽ã°ú Äɶ󽺷Π¹è¿ì´Â °­È­ÇнÀ (github)
25 lÆÄÀ̽ã°ú Äɶ󽺷Π¹è¿ì´Â °­È­ÇнÀ (github) Á¤¼ºÈÆ
24 ¦¦❶ 7Àå) ¾ÆŸ¸® ºê·¹ÀÌÅ© ¾Æ¿ô (A3C) Á¤¼ºÈÆ
23 ¦¦❶ 7Àå) ¾ÆŸ¸® ºê·¹ÀÌÅ© ¾Æ¿ô (DQN) Á¤¼ºÈÆ
22 l°­È­ÇнÀ/½ÉÃþ°­È­ÇнÀ Ư°­ (github) Á¤¼ºÈÆ
21 ¦¦❶ 13Àå) ½º³×ÀÌÅ© °ÔÀÓ ¸¶½ºÅÍ µÇ±â Á¤¼ºÈÆ
20 ¦¦❶ 10Àå) ÀÚÀ²ÁÖÇàÂ÷¸¦ À§ÇÑ AI Á¤¼ºÈÆ
19 l¹Ù´ÚºÎÅÍ ¹è¿ì´Â °­È­ ÇнÀ ÄÚµå (github) Á¤¼ºÈÆ
18 ¦¦❶ ÆÄÀ̽ã°ú Äɶ󽺷Π¹è¿ì´Â °­È­ÇнÀÀÌ 5Àå) ÅÙ¼­Ç÷Π2.0°ú ÄÉ¶ó½º Á¤¼ºÈÆ
17    ¦¦❷ ÆÄÀ̽ã°ú Äɶ󽺷Π¹è¿ì´Â °­È­ÇнÀÀÌ 5Àå) ÅÙ¼­Ç÷Π2.0°ú ÄÉ¶ó½º Á¤¼ºÈÆ
16 ¦¦❶ l9Àå) ActorCritic (ch9_ActorCritic.py) Á¤¼ºÈÆ
15    ¦¦❷ 9Àå) Advantage ActorCritic ½Ç½À (ÆÄÀ̽ã°ú Äɶ󽺷Π¹è¿ì´Â °­È­ÇнÀ 6Àå A2C) Á¤¼ºÈÆ
14       ¦¦❸ 9Àå) ¿¬¼ÓÀû ¾×ÅÍ-Å©¸®Æ½ ½Ç½À (ÆÄÀ̽ã°ú Äɶ󽺷Π¹è¿ì´Â °­È­ÇнÀ 6Àå) Á¤¼ºÈÆ
13          ¦¦❹ ¿¬¼ÓÀû ¾×ÅÍ-Å©¸®Æ½ ½ÇÇà ȯ°æ ¹× °á°ú Á¤¼ºÈÆ
12 ¦¦❶ l9Àå) REINFORCE (ch9_REINFORCE.py) Á¤¼ºÈÆ
11 ¦¦❶ l8Àå) DQN (ch8_DQN.py) Á¤¼ºÈÆ

[1][2]