본문 바로가기

머신러닝/강화학습

파이썬 강화학습 CartPole 코드 - Deep Q Learning

작동과정 >>

코랩에서 즉시 찍었더니 깜빡 깜빡 한다^^

 

훈련과정 >>

 

코드 >>

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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
################################################################################################
######################### 코랩에서 실시간으로 동작을 확인하기 위한 모듈 설치 #######################
###############################################################################################
!apt-get install -y xvfb x11-utils
!pip install gym[all]==0.17.* pyvirtualdisplay==0.2.* PyOpenGL==3.1.* PyOpenGL-accelerate==3.1.*
 
from pyvirtualdisplay import Display
display = Display(visible=False, size=(400300))
display.start()
 
################################################################################################
######################### 필요 모듈 임포트 하기 #################################################
################################################################################################
 
%matplotlib inline
import gym
import math
import random
import numpy
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as T
from typing import List, Set, Dict, Tuple, Union
 
 
is_ipython = 'inline' in matplotlib.get_backend()
if is_ipython: from IPython import display
 
 
############################################################################
########################## DQN 정의 ########################################
############################################################################
class DQN(nn.Module):
    def __init__(self, img_height: int, img_width: int):
        super().__init__()
 
        self.fc1 = nn.Linear(in_features = img_height * img_width * 3, out_features=24)
        self.fc2 = nn.Linear(in_features = 24, out_features=32)
        self.out = nn.Linear(in_features = 32, out_features=2)
 
    def forward(self, t: torch.Tensor) -> torch.Tensor:
        t = t.flatten(start_dim=1)
        t = F.relu(self.fc1(t))
        t = F.relu(self.fc2(t))
        t = self.out(t)
        return t
 
############################################################################
######## State, Action, Next_state, Reward를 담는 튜플 정의 #################
############################################################################
Experience = namedtuple(
    'Experience',
    ('state''action''next_state''reward')
)
 
############################################################################
########### 위에 정의한 Tuple을 담는 Memory Class 정의 #######################
############################################################################
class ReplayMemory():
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.memory = []
        self.push_count = 0
 
    def push(self, experience: Experience) -> None:
        if len(self.memory) < self.capacity:
            self.memory.append(experience)
        else:
            self.memory[self.push_count % self.capacity] = experience
        self.push_count += 1
 
    def sample(self, batch_size):
        return random.sample(self.memory, batch_size)
 
    def can_provide_sample(self, batch_size: int-> bool:
        return len(self.memory) >= batch_size
 
############################################################################
################# Exploit vs Explore 관계 정의 ##############################
############################################################################
class EpsilonGreedyStrategy():
    def __init__(self, start: float, end: float, decay: float):
        self.start = start
        self.end = end
        self.decay = decay
 
    def get_exploration_rate(self, current_step: int-> float:
        return self.end + (self.start - self.end) *\
            math.exp(-1 * current_step * self.decay)
 
############################################################################
############################ Agent 정의 ####################################
############################################################################
class Agent():
    def __init__(self, strategy: EpsilonGreedyStrategy, num_actions: int, device: str):
        self.current_step = 0
        self.strategy = strategy
        self.num_actions = num_actions
        self.device = device
 
    def select_action(self, state: torch.Tensor, policy_net: DQN) -> torch.Tensor:
        rate = self.strategy.get_exploration_rate(self.current_step)
        self.current_step += 1
 
        if rate > random.random():
            action = random.randrange(self.num_actions)
            return torch.tensor([action]).to(self.device)
        else:
            with torch.no_grad():
                return_action = policy_net(state).argmax(dim=1).to(self.device)
            return return_action
 
#############################################################################
############################ CartPole 환경 정의 #############################
############################################################################
class CartPoleEnvManager():
    def __init__(self, device: str):
        self.device = device
        # gym.make에 Unwrapped를 붙여 주어야 우리가 접근하지 못했던 배경 부분까지 접근할 수 있다.
        self.env = gym.make('CartPole-v0').unwrapped 
        self.env.reset()
        self.current_screen = None
        self.done = False
    
    def reset(self):
        self.env.reset()
        self.current_screen = None
 
    def close(self):
        self.env.close()
    
    def render(self, mode : str = "human"-> Union[None, numpy.ndarray]:
        return self.env.render(mode)
 
    def num_actions_available(self-> int:
        return self.env.action_space.n
    
    def take_action(self, action: Union[int, torch.Tensor]) -> torch.Tensor:
        if type(action) == int:
            _, reward, self.done, _ = self.env.step(action)
        elif type(action) == torch.Tensor:
            _, reward, self.done, _ = self.env.step(action.item())
        return torch.tensor([reward], device=self.device)
 
    def just_starting(self-> bool:
        return self.current_screen is None
 
    def get_state(self-> torch.Tensor:
        if self.just_starting() or self.done:
            self.current_screen = self.get_processed_screen()
            black_screen = torch.zeros_like(self.current_screen)
            return black_screen
        else:
            s1 = self.current_screen
            s2 = self.get_processed_screen()
            self.current_screen = s2
            return s2 - s1
 
    def get_current_state(self-> torch.Tensor:
        return self.render('rgb_array').transpose((2,0,1))
 
    def transform_screen_data(self, screen: torch.Tensor) -> torch.Tensor:
        screen = numpy.ascontiguousarray(screen, dtype=numpy.float32) / 255
        screen = torch.from_numpy(screen)
 
        resize = T.Compose([
                            T.ToPILImage(),
                            T.Resize((40,90)),
                            T.ToTensor()
        ])
 
        return resize(screen).unsqueeze(0).to(self.device)
    
    def crop_screen(self, screen: torch.Tensor) -> torch.Tensor:
        screen_height = screen.shape[1]
        top = int(screen_height * 0.4)
        bottom = int(screen_height * 0.8)
        screen = screen[:, top:bottom, :]
        return screen
 
    def get_processed_screen(self-> torch.Tensor:
        screen = self.render('rgb_array').transpose((2,0,1))
        screen = self.crop_screen(screen)
        return self.transform_screen_data(screen)
    
    def get_screen_height(self-> int:
        screen = self.get_processed_screen()
        return screen.shape[2]
    
    def get_screen_width(self-> int:
        screen = self.get_processed_screen()
        return screen.shape[3]
 
 
############################################################################
####################### 훈련 상태 동적 그래프 함수 정의 ######################
############################################################################
def plot(values: List[int], moving_avg_period):
    plt.figure(2)
    plt.clf()
    plt.title("Training...")
    plt.xlabel("Episode")
    plt.ylabel("Duration")
    plt.plot(values)
    plt.plot(get_moving_average(moving_avg_period, values))
    plt.pause(0.001)
    if is_ipython: display.clear_output(wait=True)
 
def get_moving_average(period: int, values: List[int]) -> numpy.ndarray:
    values = torch.tensor(values, dtype=torch.float)
    if len(values) >= period:
        moving_avg = values.unfold(dimension=0, size=period, step=1).mean(dim=1).flatten(start_dim=0)
        moving_avg = torch.cat((torch.zeros(period-1), moving_avg))
        return moving_avg.numpy()
    else:
        moving_avg = torch.zeros(len(values))
        return moving_avg.numpy()
 
def plot_cartpole_play(timestep: int-> None:
    if timestep < 195:
        plt.figure(2)
        plt.clf()
        plt.title("Cartpole_play....")
        plt.imshow(em.render('rgb_array'))
        plt.pause(0.001)
        if is_ipython: display.clear_output(wait=True)
 
    else:
        plt.figure(2)
        plt.clf()
        plt.title("Cartpole_Success")
        plt.imshow(em.render('rgb_array'))
        plt.pause(2)
        if is_ipython: display.clear_output(wait=True)
 
 
############################################################################
############# Experience의 개별 요소를 묶어주는 함수 정의 ####################
############################################################################
def extract_tensors(experiences: List[Experience]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    batch = Experience(*zip(*experiences))
    t1 = torch.cat(batch.state)
    t2 = torch.cat(batch.action)
    t3 = torch.cat(batch.reward)
    t4 = torch.cat(batch.next_state)
 
    return (t1, t2, t3, t4)
 
############################################################################
##################### Q-Value를 계산하는 함수 정의 #########################
############################################################################
class QValues():
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
    @staticmethod
    def get_current(policy_net: DQN, states: torch.Tensor, actions: torch.Tensor) -> torch.Tensor:
        return policy_net(states).gather(dim=1, index=actions.unsqueeze(-1))
 
    @staticmethod
    def get_next(target_net: DQN, next_states: torch.Tensor) -> torch.Tensor:
        final_state_locations = next_states.flatten(start_dim=1).max(dim=1)[0].eq(0).type(torch.bool)
        non_final_state_locations = (final_state_locations == False)
        non_final_states = next_states[non_final_state_locations]
        batch_size = next_states.shape[0]
        values = torch.zeros(batch_size).to(QValues.device)
        values[non_final_state_locations] = target_net(non_final_states).max(dim=1)[0].detach()
 
 
 
############################################################################
##################### DQN 훈련을 위한 HyperParameter 정의 ###################
############################################################################
batch_size: int = 512
gamma: float = 0.999
eps_start: float = 1
eps_end: float = 0.01
eps_decay: float = 0.001
target_update: int = 10
memory_size: int = 100000
lr: float = 0.001
num_episodes: int = 500
 
# 장치 정의
device: str = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
em: CartPoleEnvManager = CartPoleEnvManager(device)
strategy: EpsilonGreedyStrategy = EpsilonGreedyStrategy(eps_start, eps_end, eps_decay)
 
agent: Agent = Agent(strategy, em.num_actions_available(), device)
memory: ReplayMemory = ReplayMemory(memory_size)
 
# 네트워크 정의
policy_net: DQN = DQN(em.get_screen_height(), em.get_screen_width()).to(device)
target_net: DQN = DQN(em.get_screen_height(), em.get_screen_width()).to(device)
 
target_net.load_state_dict(policy_net.state_dict())
target_net.eval()
 
optimizer: torch.optim.Adam = torch.optim.Adam(params=policy_net.parameters(), lr=lr)
 
 
############################################################################
######################### DQN 훈련 시작 ####################################
############################################################################
episode_durations: List[int= []
 
for episode in range(num_episodes):
    em.reset()
    state: torch.Tensor = em.get_state()
 
    for timestep in count():
        action: torch.Tensor = agent.select_action(state, policy_net)
        reward: torch.Tensor = em.take_action(action)
        next_state: torch.Tensor = em.get_state()
        memory.push(Experience(state, action, next_state, reward))
        state = next_state
 
        if memory.can_provide_sample(batch_size):
            experiences: List[Experience] = memory.sample(batch_size)
            states, actions, rewards, next_states = extract_tensors(experiences)
 
            current_q_values: torch.Tensor = QValues.get_current(policy_net, states, actions)
            next_q_values: torch.Tensor = QValues.get_next(target_net, next_states)
            target_q_values: torch.Tensor = (next_q_values * gamma) + rewards
 
            loss = F.mse_loss(current_q_values, target_q_values.unsqueeze(1))
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
 
        if em.done:
            episode_durations.append(timestep)
            plot(episode_durations, 100)
            break
    if episode % target_update == 0:
        target_net.load_state_dict(policy_net.state_dict())
 
em.close()
 
 
#######################################################################
#################### CartPole 돌려보기 #################################
#######################################################################
 
success = []
with torch.no_grad():
 
    for episode in range(num_episodes):
        em.reset()
        state = em.get_state()
 
        for timestep in count():
            plot_cartpole_play(timestep)
 
            action: torch.Tensor = agent.select_action(state, policy_net)
            reward: torch.Tensor = em.take_action(action)
            next_state: torch.Tensor = em.get_state()
            state = next_state
            if em.done:
                if timestep >= 195:
                    success.append(True)
                else:
                    success.append(False)
 
                break
em.close()