본문 바로가기
  • 인공지능 과 디지털 데이터 생성 실험실
  • 인공지능 과 자동화
  • 생성형 AI 실험실
4Z1 - Artificial Intelligence/강화학습 개론

MRL - 3

by Richrad Chung 2020. 9. 9.

dummy Q의 문제는 한쪽으로만 진행되어 Q가 갱신되지 않는 현상이 발생한다.

 

해결책으로 action을 랜덤하게 하게끔 처리해 주는것이다.

 

1. Exploit VS Exploration: decaying E-greedy 

2. Exploit VS Exploration: add random noise

 

랜덤처리를 하면 최적 경로가 아닌 긴 경로를 통해서도 목적에 도달 하게 된다.

 

이과정의 오류를 줄이고자 아래처럼 처리한다.

보상에 새로받을 감마를 곱해서 처리한다.

이렇게 하면짧은 쪽으로 유도되게 된다.

 

예제출처:jaynewho.com/post/10

 

# q_learning.py

import gym
import numpy as np
import matplotlib.pyplot as plt
from gym.envs.registration import register
import random as pr

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])

'''1. Q 값이 업데이트될 때 maxQ(s',a') 에 곱할 감마 값을 설정한다.'''
dis = .99

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

    '''2. E-Greedy 를 위한 확률값을 만들어준다. (step i이 지남에 따라 decay 되도록 설정)'''
    e = 1. / ((i // 100) + 1)  

    # The Q-Table learning algorithm : 한번 수행할 때 마다 Q 한칸 업데이트
    while not done:

        '''E-Greedy 를 따라 작은 확률로 랜덤하게 가고, 큰 확률로 높은 Q 를 따르는 쪽으로 간다.'''
        if np.random.rand(1) < e:
            action = env.action_space.sample()
        else:
            action = np.argmax(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 + dis * 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(Q)
plt.bar(range(len(rList)), rList, color="blue")
plt.show()

 

'4Z1 - Artificial Intelligence > 강화학습 개론' 카테고리의 다른 글

MRL - 5 : 마지막  (0) 2020.09.09
MRL - 4  (0) 2020.09.09
MRL - 2  (0) 2020.09.09
Recap - 강화 학습 정리 시작하기  (0) 2020.09.05
MRL - 1 : 시작하기  (0) 2020.08.31