공부 기록/모두를 위한 딥러닝 (RL)
3-2. Dummy Q-learning 구현
건조젤리
2019. 11. 18. 17:09
김성훈 교수님의 강의내용을 정리한 내용입니다.
출처 : http://hunkim.github.io/ml/
모두를 위한 머신러닝/딥러닝 강의
hunkim.github.io
Q-learning 알고리즘의 구현
* 0으로 채워진 Q 배열을 선언한다. 이때 env.observation_space.n = 16, env.action_space.n = 4 이므로 이를 이용한다.
* rargmax(): 값이 모두 동일하다면 랜덤하게 하나를 선택한다.
* Q 업데이트 코드 확인.
rargmax의 구현 코드 확인!
보상값(0 or 1)을 저장하는 rList를 추가하였다.
H (구덩이) 에 빠질경우는 0,
G (목표지점) 에 도착할 경우는 1이다.
95%의 성공 확률을 보인다.
앞부분은 거의 0이지만 약 100회 반복부터는 모두 1의 확률을 갖고있다.
실행 결과 Q의 값을 확인해 보자.
Agent가 목적지를 잘 찾아감을 알 수 있다.
구현 코드 (환경: ubuntu:16.04 python 3.6)
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
|
import gym
import numpy as np
import matplotlib.pyplot as plt
from gym.envs.registration import register
import random as pr
# https://gist.github.com/stober/1943451
def rargmax(vector):
""" Argmax that chooses randomly among eligible maximum indices. """
m = np.amax(vector)
indices = np.nonzero(vector == m)[0]
return pr.choice(indices)
register(
id='FrozenLake-v3',
entry_point='gym.envs.toy_text:FrozenLakeEnv',
kwargs={'map_name': '4x4',
'is_slippery': False}
)
env = gym.make('FrozenLake-v3')
# Initialize table with all zeros
Q = np.zeros([env.observation_space.n, env.action_space.n])
# Set learning parameters
num_episodes = 2000
# create lists to contain total rewards and steps per episode
rList = []
for i in range(num_episodes):
# Reset environment and get first new observation
state = env.reset()
rAll = 0
done = False
# The Q-Table learning algorithm
while not done:
action = rargmax(Q[state, :])
# Get new state and reward from environment
new_state, reward, done, _ = env.step(action)
# Update Q-Table with new knowledge using learning rate
Q[state, action] = reward + np.max(Q[new_state, :])
rAll += reward
state = new_state
rList.append(rAll)
print("Success rate: " + str(sum(rList) / num_episodes))
print("Final Q-Table Values")
print("LEFT DOWN RIGHT UP")
print(Q)
plt.bar(range(len(rList)), rList, color="blue")
plt.show()
|
cs |