开始使用免费开始使用

实现 Q-learning 更新规则

Q-learning 是强化学习(RL)中的一种离策略算法,目标是在给定当前状态下找到应采取的最佳动作。与会考虑实际下一步所采取动作的 SARSA 不同,Q-learning 不论实际采取了哪个动作,都会用可获得的最大未来回报来更新其 Q 值。正是这种区别,使得 Q-learning 即使在遵循探索性甚至随机策略时,也能学习到最优策略。下面的任务是实现一个函数,按照 Q-learning 规则来更新 Q 表。Q-learning 的更新规则见下图,您的任务是基于该规则实现一个用于更新 Q 表的函数。

NumPy 库已作为 np 导入供您使用。

Image showing the mathematical formula of the Q-learning update rule.

本练习是课程的一部分

Python 中的 Gymnasium 强化学习

查看课程

练习说明

  • 读取给定状态-动作对的当前 Q 值。
  • actions 中对所有可能动作进行比较,确定下一状态的最大 Q 值。
  • 使用 Q-learning 公式更新当前状态-动作对的 Q 值。
  • 在智能体于状态 0 采取动作 0、获得回报 5、并转移到状态 1 的前提下,更新 Q 表 Q

交互式实操练习

通过完成这段示例代码来试试这个练习。

actions = ['action1', 'action2'] 
def update_q_table(state, action, reward, next_state):
  	# Get the old value of the current state-action pair
    old_value = ____
    # Determine the maximum Q-value for the next state
    next_max = ____
    # Compute the new value of the current state-action pair
    Q[state, action] = ____

alpha = 0.1
gamma = 0.95
Q = np.array([[10, 8], [20, 15]], dtype='float32')
# Update the Q-table
____
print(Q)
编辑并运行代码