由于目前已有针对这些参考资料的详细解释,这里作为快速的学习方法,这个系列只重点记忆一下每个方法的特征和代码实现,后期有其他感悟再不断完善。
这里视频,和代码资源参考的是张沫凡RL系列,书籍参考的是Sutton的经典教材,翻译版:)
- 视频地址:https://morvanzhou.github.io/tutorials/machine-learning/reinforcement-learning/
- GitHub源:https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow
- 参考教材:《强化学习》第二版,Richard S. Sutton,andrew G. Barto著,俞凯等译。对应的英文教材是《Reinforcement Learning: An Introduction》。
Part 1. Q-learning
Part 2. 示例代码
Part 3. 演示效果
Part 1. Q-learning
(1)建立Q表,表中条目指的是在当前状态下,动作价值的长期回报。
(2)设计动作选择策略:ε-greedy (S, A)
(3)设计状态生成和立即回报策略:(S_, R)
(4)设计Q表更新策略:通过缩小目标动作价值q-target和预估价值q-predict间的差距来进行值的更新。
Part 2. 示例代码
"""
场景:在一维的模拟世界里,Zoe 从起始点到达终点的路径探索。
"""
"""
任务特征:
(1)建立Q 表
(2)生成(S, A,S_, R)序列
(3)EPISODES 游戏回合
"""
import numpy as np
import pandas as pd
import time
np.random.seed(2)
N_STATES = 6
ACTIONS = ['left', 'right']
EPSILON = 0.9
ALPHA = 0.1
GAMMA = 0.9
MAX_EPISODES = 13
FRESH_TIME = 0.3
# -----------------------------------------------
# 建立Q表 Q-table
def build_q_table(n_states, actions):
table = pd.DataFrame(
np.zeros((n_states, len(actions))),
columns=actions,
)
#print(table)
return table
# -----------------------------------------------
# 选择动作 A 策略:EPSILON-greedy
def choose_action(state, q_table):
state_actions = q_table.iloc[state, :]
if(np.random.uniform() > EPSILON) or ((state_actions == 0).all()):
action_name = np.random.choice(ACTIONS)
else:
action_name = state_actions.idxmax()
return action_name
# -----------------------------------------------
# 与环境交互生成下一状态 S_ 和奖励 R
def get_env_feedback(S, A):
if A == 'right':
if S == N_STATES - 2:
S_ = 'terminal'
R = 1
else:
S_ = S + 1
R = 0
else:
R = 0
if S == 0:
S_ = S
else:
S_ = S - 1
return S_, R
# -----------------------------------------------
# 环境交互更新 (从打印角度)
def update_env(S, episode, step_counter):
env_list = ['-']*(N_STATES-1) + ['T']
if S == 'terminal':
interaction = 'Episode %s: total_steps = %s' % (episode+1, step_counter)
print('\r{}'.format(interaction), end='')
time.sleep(2)
print('\r ', end='')
else:
env_list[S] = 'o'
interaction = ''.join(env_list)
print('\r{}'.format(interaction), end='')
time.sleep(FRESH_TIME)
# -----------------------------------------------
"""
增强学习函数主体
q-predict 预估得分
q-targrt 学习得分
通过缩小动作价值的目标得分和预估得分间的差距来进行动作价值更新,即Q-表的更新
"""
def rl():
q_table = build_q_table(N_STATES, ACTIONS)
for episode in range(MAX_EPISODES):
step_counter = 0
S = 0
is_terminated = False
update_env(S, episode, step_counter)
while not is_terminated:
A = choose_action(S, q_table)
S_, R = get_env_feedback(S, A)
q_predict = q_table.loc[S, A]
if S_ != 'terminal':
q_target = R + GAMMA * q_table.iloc[S_, :].max()
else:
q_target = R
is_terminated = True
q_table.loc[S, A] += ALPHA * (q_target - q_predict)
S = S_
update_env(S, episode, step_counter+1)
step_counter += 1
return q_table
# -----------------------------------------------
# main函数:程序入口
if __name__ == "__main__":
#table = build_q_table(N_STATES, ACTIONS)
#print(table)
q_table = rl()
print('\r\nQ-table:\n')
print(q_table)