第17章強化学習
17.3.5. Implementation of Q-Learning17.3.5 Q学習の実装
We now show how to implement Q-Learning on FrozenLake from Open AI Gym. Note this is the same setup as we consider in Value Iteration experiment.
英語のヒント
では、Open AI GymのFrozenLakeでQ学習をどう実装するかを示す。これは価値反復の実験で考えたのと同じ設定であることに注意しよう。
%matplotlib inline
import random
import numpy as np
from d2l import torch as d2l
seed = 0 # Random number generator seed
gamma = 0.95 # Discount factor
num_iters = 256 # Number of iterations
alpha = 0.9 # Learing rate
epsilon = 0.9 # Epsilon in epsilion gready algorithm
random.seed(seed) # Set the random seed
np.random.seed(seed)
# Now set up the environment
env_info = d2l.make_env('FrozenLake-v1', seed=seed)In the FrozenLake environment, the robot moves on a grid (these are the states) with actions that are “up” (), “down” (), “left” (), and “right” (). The environment contains a number of holes (H) cells and frozen (F) cells as well as a goal cell (G), all of which are unknown to the robot. To keep the problem simple, we assume the robot has reliable actions, i.e. for all . If the robot reaches the goal, the trial ends and the robot receives a reward of irrespective of the action; the reward at any other state is for all actions. The objective of the robot is to learn a policy that reaches the goal location (G) from a given start location (S) (this is ) to maximize the return.
英語のヒント
FrozenLakeの環境では、ロボットはの格子(これが状態である)の上を、「上」()、「下」()、「左」()、「右」()の行動で動く。環境には、いくつかの穴(H)のマスと凍った(F)マス、そして目標のマス(G)があり、そのどれもロボットにはわからない。問題を簡単にするため、ロボットの行動は確実であると仮定する。つまり、すべてのについてである。ロボットが目標に到達すると試行は終わり、ロボットは行動にかかわらずの報酬を受け取る。それ以外の状態での報酬は、すべての行動についてである。ロボットの目的は、与えられた出発の場所(S)(これがである)から目標の場所(G)に到達する方策を学習して、収益を最大化することである。
We first implement -greedy method as follows:
英語のヒント
まず、グリーディ法を次のように実装する。
def e_greedy(env, Q, s, epsilon):
if random.random() < epsilon:
return env.action_space.sample()
else:
return np.argmax(Q[s,:])We are now ready to implement Q-learning:
英語のヒント
これで、Q学習を実装する準備ができた。
def q_learning(env_info, gamma, num_iters, alpha, epsilon):
env_desc = env_info['desc'] # 2D array specifying what each grid item means
env = env_info['env'] # 2D array specifying what each grid item means
num_states = env_info['num_states']
num_actions = env_info['num_actions']
Q = np.zeros((num_states, num_actions))
V = np.zeros((num_iters + 1, num_states))
pi = np.zeros((num_iters + 1, num_states))
for k in range(1, num_iters + 1):
# Reset environment
state, done = env.reset(), False
while not done:
# Select an action for a given state and acts in env based on selected action
action = e_greedy(env, Q, state, epsilon)
next_state, reward, done, _ = env.step(action)
# Q-update:
y = reward + gamma * np.max(Q[next_state,:])
Q[state, action] = Q[state, action] + alpha * (y - Q[state, action])
# Move to the next state
state = next_state
# Record max value and max action for visualization purpose only
for s in range(num_states):
V[k,s] = np.max(Q[s,:])
pi[k,s] = np.argmax(Q[s,:])
d2l.show_Q_function_progress(env_desc, V[:-1], pi[:-1])
q_learning(env_info=env_info, gamma=gamma, num_iters=num_iters, alpha=alpha, epsilon=epsilon)
This result shows that Q-learning can find the optimal solution for this problem roughly after 250 iterations. However, when we compare this result with the Value Iteration algorithm’s result (see Implementation of Value Iteration), we can see that the Value Iteration algorithm needs way fewer iterations to find the optimal solution for this problem. This happens because the Value Iteration algorithm has access to the full MDP whereas Q-learning does not.
英語のヒント
この結果は、Q学習がおよそ250回の反復の後にこの問題の最適解を見つけられることを示している。しかし、この結果を価値反復のアルゴリズムの結果(価値反復の実装を参照)と比べると、価値反復のアルゴリズムのほうが、この問題の最適解を見つけるのにはるかに少ない反復ですむことがわかる。これは、価値反復のアルゴリズムはMDP全体にアクセスできるのに対して、Q学習はそうではないからである。