• [PyTorch][chapter 63][强化学习-QLearning]


    前言:

           这里结合走迷宫的例子,重点学习一下QLearning迭代更新算法

          0,1,2,3,4 是房间,之间绿色的是代表可以走过去。

    5为出口

       可以用下图表示


    目录:

    1.      策略评估
    2.      策略改进
    3.      迭代算法
    4.      走迷宫实现Python

    一  策略评估

             

              强化学习最终是为了学习好的策略\pi,在不同的state 下面根据策略\pi做出最优的action.

    对于策略评估我们通过价值函数来度量.

          1.1 状态值函数  V

              T步累积奖赏:      V_{T}^{\pi}(s)=E_{\pi}[\frac{1}{T}\sum_{t=1}^{T}r_t|s_0=s],

              \gamma折扣累积奖赏:  V_{\gamma}^{\pi}(s)=E_{\pi}[\sum_{t=0}^{\infty }\gamma^tr_{t+1}|s_0=s]

         1.2 状态-动作值函数 Q

               T步累积奖赏:      Q_{T}^{\pi}(s,a)=E_{\pi}[\frac{1}{T}\sum_{t=1}^{T}r_t|s_0=s,a_0=a],

              \gamma折扣累积奖赏:  V_{\gamma}^{\pi}(s,a)=E_{\pi}[\sum_{t=0}^{\infty }\gamma^tr_{t+1}|s_0=s,a_0=a]

           1.3   Bellan 等式展开

                  状态值函数  V 

                   V_{T}^{\pi}(s)=\sum_{a \in A} \pi(s,a) \sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^a(\frac{1}{T}R_{s \rightarrow s^{'}}^{a}+\frac{T-1}{T}V_{T-1}^{\pi}(s^{'}))

                    V_{\gamma}^{\pi}(s)=\sum_{a \in A} \pi(s,a) \sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^a(R_{s \rightarrow s^{'}}^{a}+\gamma V_{\gamma}^{\pi}(s^{'}))

                   状态-动作函数Q

                  Q_{T}^{\pi}(s,a)=\sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^a(\frac{1}{T}R_{s \rightarrow s^{'}}^{a}+\frac{T-1}{T}V_{T-1}^{\pi}(s^{'}))

                  Q_{\gamma}^{\pi}(s,a)=\sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^a(R_{s \rightarrow s^{'}}^{a}+\gamma V_{\gamma}^{\pi}(s^{'}))


    二   策略改进

            强化学习的目的: 尝试各种策略\pi,找到值函数最大的策略(累积奖赏)

             \pi^{*}= argmax_{\pi} \sum_{s \in S} V^{\pi}(s)

           2.1 最优策略值函数

                 \forall s \in S :  v^{*}(s)=V^{\pi^{*}}(s)

             由于最优值函数的累积奖赏已经达到最大值,因此可以对Bellman 等式做个改动,即对动作求和改为最优

                V_{T}^{*}(s)=max_{a\in A} \sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^a(\frac{1}{T}R_{s \rightarrow s^{'}}^{a}+\frac{T-1}{T}V_{T-1}^{*}(s^{'})) ..1

                 V_{\gamma}^{*}(s)=max_{a\in A}\sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^a(R_{s \rightarrow s^{'}}^{a}+\gamma V_{\gamma}^{\pi}(s^{'}))...2

               则 

                      V^{*}(s)= max_{a \in A} Q^{\pi^{*}}(s,a)...3 

                 最优 状态-动作 Bellman 等式为:

              

                  Q_{T}^{*}(s,a)= \sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^a(\frac{1}{T}R_{s \rightarrow s^{'}}^{a}+\frac{T-1}{T} max_{a^{'} \in A}Q_{T-1}^{*}(s^{'},a^{'})) 

                  V_{\gamma}^{*}(s,a)=\sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^a(R_{s \rightarrow s^{'}}^{a}+\gamma max_{a^{'} \in A}Q_{\gamma}^{*}(s^{'},a^{'}))


    三    递推改进方式

                 原始策略为 \pi

                 改进后策略  \pi^{'}

                改变动作的条件为: V^{\pi}(s) \leq Q^{\pi}(s,\pi^{'}(s))

                 V^{\pi}(s) \leq Q^{\pi}(s,\pi^{'}(s))

                              

                           =\sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^{\pi^{'}(s)}(R_{s \rightarrow s^{'}}^{\pi^{'}(s)}+\gamma V^{\pi}(s^{'}))

                          \leq \sum_{s^{'} \in S}P_{s\rightarrow s^{'}}^{\pi^{'}(s)}(R_{s \rightarrow s^{'}}^{\pi^{'}(s)}+\gamma Q^{\pi}(s^{'},\pi^{'}(s^{'})))

                           ...

                          =V^{\pi^{'}}(s)


    四  值迭代算法

          

         4.1  环境变量

            Reward 和  QTable 都是矩阵

         

       4.2 迭代过程

        当state 为1,Q 函数更新过程

       

    5.3 收敛结果


    五    走迷宫实现Python
    reward 我们用一个矩阵表示:

     行代表: state

     列代表: action

     值代表: reward

    5.1 Environment.py 实现环境功能

    1. # -*- coding: utf-8 -*-
    2. """
    3. Created on Wed Nov 15 11:12:13 2023
    4. @author: chengxf2
    5. """
    6. import numpy as np
    7. from enum import Enum
    8. #print(Weekday.test.value) 房间
    9. class Room(Enum):
    10. room1 = 1
    11. room2 = 2
    12. room3 = 3
    13. room4 = 4
    14. room5 = 5
    15. class Environment():
    16. def action_name(self, action):
    17. if action ==0:
    18. name = "左"
    19. elif action ==1:
    20. name = "上"
    21. elif action ==2:
    22. name = "右"
    23. else:
    24. name = "上"
    25. return name
    26. def __init__(self):
    27. self.R =np.array([ [-1, -1, -1, -1, 0, -1],
    28. [-1, -1, -1, 0, -1, 100],
    29. [-1, -1, -1, 0, -1, -1],
    30. [-1, 0, 0, -1, 0, -1],
    31. [0, -1, -1, 0, -1, 100],
    32. [-1, 0, -1, -1, 0, 100]])
    33. def step(self, state, action):
    34. #即使奖励: 在state, 执行action, 转移新的 next_state,得到的即使奖励
    35. #print("\n step ",state, action)
    36. reward = self.R[state, action]
    37. next_state = action# action 网哪个房间走
    38. if action == Room.room5.value:
    39. done = True
    40. else:
    41. done = False
    42. return next_state, reward,done

    5.1 main.py 实现Agent 功能

    1. # -*- coding: utf-8 -*-
    2. """
    3. Created on Wed Nov 15 11:29:14 2023
    4. @author: chengxf2
    5. """
    6. # -*- coding: utf-8 -*-
    7. """
    8. Created on Mon Nov 13 09:39:37 2023
    9. @author: chengxf2
    10. """
    11. import numpy as np
    12. def init_state(WORLD_SIZE):
    13. S =[]
    14. for i in range(WORLD_SIZE):
    15. for j in range(WORLD_SIZE):
    16. state =[i,j]
    17. S.append(state)
    18. print(S)
    19. # -*- coding: utf-8 -*-
    20. """
    21. Created on Fri Nov 10 16:48:16 2023
    22. @author: chengxf2
    23. """
    24. import numpy as np
    25. from environment import Environment
    26. class Agent():
    27. def __init__(self,env):
    28. self.discount_factor = 0.8 #折扣率
    29. self.theta = 1e-3 #最大偏差
    30. self.nS = 6 #状态 个数
    31. self.nA= 6 #动作个数
    32. self.Q = np.zeros((6,6))
    33. self.env = env
    34. self.episode = 500
    35. #当前处于的位置,V 累积奖赏
    36. def one_step_lookahead(self,env, state, action):
    37. #print("\n state :",state, "\t action ",action)
    38. next_state, reward,done = env.step(state, action)
    39. maxQ_sa = max(self.Q[next_state,:])
    40. return next_state, reward, done,maxQ_sa
    41. def value_iteration(self, env, state, discount_factor =1.0):
    42. #随机选择一个action,但是不能为-1
    43. indices = np.where(env.R[state] >-1)[0]
    44. action = np.random.choice(indices,1)[0]
    45. #print("\n state :",state, "\t action ",action)
    46. next_state, reward, done,maxQ_sa = self.one_step_lookahead(env, state, action)
    47. #更新当前的Q值
    48. r = reward + self.discount_factor*maxQ_sa
    49. self.Q[state,action] = int(r)
    50. #未达到目标状态,走到房间5, 执行下一次迭代
    51. if done == False:
    52. self.value_iteration(env, next_state)
    53. def learn(self):
    54. for n in range(self.episode): #最大迭代次数
    55. #随机选择一个状态
    56. state = np.random.randint(0,self.nS)
    57. #必须达到目标状态,跳转到出口房间5
    58. self.value_iteration(env, state, discount_factor= self.discount_factor)
    59. #print("\n n ",n)
    60. print(self.Q)
    61. if __name__ == "__main__":
    62. env = Environment()
    63. agent =Agent(env)
    64. agent.learn()



    参考:

     8-QLearning基本原理_哔哩哔哩_bilibili

    9-QLearning迭代计算实例_哔哩哔哩_bilibili

    10-QLearning效果演示_哔哩哔哩_bilibili

  • 相关阅读:
    聊聊如何实现 LRU 缓存算法
    【异常】springboot集成@Cacheable缓存乱码的问题解决方案
    音频链接抓取技术在Lua中的实现
    Java 进程和线程 2
    Chrome插件开发入门
    【玩玩Vue】使用el-menu作为菜单时,通过一二级路由控制菜单高亮
    java集合类史上最细讲解 - Map篇
    Android11 热点设置永不关闭
    7-1 后序和中序构造二叉树
    设计模式之状态模式
  • 原文地址:https://blog.csdn.net/chengxf2/article/details/134393459