強化學習之路一 QLearning 演算法

Please Call me 小強發表於2023-03-15

Q-Learning演演算法

理論

Q-Learning是一種強化學習演演算法,用於學習在給定狀態下采取不同行動的最佳策略。其公式如下:

\(Q(s,a) \leftarrow (1 - \alpha) \cdot Q(s,a) + \alpha \cdot (r + \gamma \cdot \max_{a'} Q(s',a'))\)

其中,\(Q(s,a)\)是在狀態\(s\)下采取行動\(a\)的預期回報,\(\alpha\)是學習率,\(r\)是在狀態\(s\)下采取行動\(a\)的即時回報,\(\gamma\)是折扣因子,\(s'\)是採取行動\(a\)後得到的新狀態。\(\max_{a'} Q(s',a')\)是在新狀態\(s'\)下采取不同行動所能獲得的最大預期回報。

Q-Learning公式的意義是,在當前狀態\(s\)下采取行動\(a\),更新當前狀態下采取行動\(a\)的預期回報\(Q(s,a)\)。更新公式中的第一項表示當前狀態下采取行動\(a\)的原始預期回報,第二項表示從當前狀態採取行動\(a\)後得到的新狀態\(s'\)的最大預期回報。透過不斷更新\(Q(s,a)\),我們可以學習到在不同狀態下采取不同行動的最佳策略。

將理論轉換為簡單易懂的python的程式碼:

alpha = 0.1
gamma = 0.5

# s 當前狀態 就是一個位置資訊
# a 執行動作 上下左右
# newS 當前狀態執行動作後的新狀態
# r 為執行動作a後,環境給的獎勵
def updateQ(s, a, r):
    newS = None
    if a == 0: # 上
        newS = (s[0]-1, s[1])
    elif a == 1: # 下
        newS = (s[0]+1, s[1])
    elif a == 2: # 左
        newS = (s[0], s[1]-1)
    elif a == 3: # 右
        newS = (s[0], s[1]+1)

    Q[s][a] += alpha * (r + gamma * max(Q[newS]) - Q[s][a])

中間小插曲

剛開始看到理論後,就開始擼程式碼了,沒有看其他人的寫的程式碼, 結果翻車了。
根據我的理解,我剛開始程式碼的Q表是每個狀態的價值表。動作的變化,引發環境改變,環境改變給出一個獎勵, 然後在更新Q表。
大家一定要注意是對Q表存的是每個狀態的每個動作的評價值
不過經過翻車,也算是加深了對Qlearning的理解

實際能執行demo

#coding:utf8
import random
import math
import gym
from gym import spaces
import numpy as np
S = "S" # 起始塊
G = "G" # 目標塊
F = "F" # 凍結塊
H = "H" # 危險塊
# 這個環境規則就是, 從S點走到G點,中間走到H點就GameOver
class MyEnv(gym.Env):
    metadata = {'render.modes': ['human']}

    def __init__(self):
        self.board = np.array([
            [S, F, F, F],
            [F, H, F, H],
            [F, F, F, H],
            [H, F, F, G],
        ])
        self.height, self.width = self.board.shape

        # 定義動作空間和觀察空間
        self.action_space = spaces.Discrete(4) # 上下左右
        self.observation_space = spaces.Tuple((
            spaces.Discrete(self.height),
            spaces.Discrete(self.width)
        ))
        self.reset()

    def step(self, action):
        if action == 0: # 上
            next_pos = (self.current_pos[0]-1, self.current_pos[1])
        elif action == 1: # 下
            next_pos = (self.current_pos[0]+1, self.current_pos[1])
        elif action == 2: # 左
            next_pos = (self.current_pos[0], self.current_pos[1]-1)
        elif action == 3: # 右
            next_pos = (self.current_pos[0], self.current_pos[1]+1)

        assert self._is_valid_pos(next_pos)

        # 步驟越多模型越差
        self.steps += 0.1
        if self.board[next_pos] == H:
            reward = -self.steps -self.width*self.height
            self.done = True
        elif self.board[next_pos] == G:
            reward = -self.steps
            self.done = True
        else:
            reward = -self.steps - abs(next_pos[0]-3) - abs(next_pos[1]-3)
            self.done = False

        self.current_pos = next_pos
        return self.current_pos, reward, self.done, self.board[next_pos] == H

    def reset(self):
        self.current_pos = (0, 0)
        self.done = False
        self.steps = 0
        return self.current_pos

    def render(self, mode='human'):
        for i in range(self.height):
            for j in range(self.width):
                if (i, j) == self.current_pos:
                    print("*", end="")
                else:
                    print(self.board[i][j], end="")
            print()
        print()

    def _is_valid_pos(self, pos):
        if pos[0] < 0 or pos[0] >= self.height or pos[1] < 0 or pos[1] >= self.width:
            return False
        return True
    
def softmax(x):
    exp_x = np.exp(x)
    return exp_x / np.sum(exp_x)
    
# 定義獲取當前位置動作的函式
def get_actions(row, col):
    actions = []
    if row < 3:  # 如果不在最後一行,則可以向下移動
        actions.append(1)
    if col < 3:  # 如果不在最後一列,則可以向右移動
        actions.append(3)
    if row > 0:  # 如果不在第一行,則可以向上移動
        actions.append(0)
    if col > 0:  # 如果不在第一列,則可以向左移動
        actions.append(2)
    return actions

env = MyEnv()
ACTIONS = np.arange(4)
ACTIONS_STR = '上|下|左|右'.split('|')

Q = np.random.rand(4, 4, 4)
for i in range(4):
    for j in range(4):
        actions = get_actions(i, j)
        for k in range(4):
            if k not in actions:
                # 經過soeftmax之後,執行這個動作的機率為0
                Q[(i, j, k)] = -float("inf")
            else:
                Q[(i, j, k)] = 0

def printQ():
    for i in range(4):
        for j in range(4):
            print("{}_{}: ".format(i,j), Q[(i,j)])

def getAction(s):
    action = np.argmax(softmax(Q[s]))
    return action

def train():
    alpha = 0.1
    gamma = 0.95
    # 90%機率
    useQ = 0.9
    for i in range(100):
        s = env.reset()
        while True:
            env.render()
            # 根據狀態獲取s, 選擇一個動作
            can_actions = get_actions(s[0], s[1])
            action = getAction(s) if np.random.uniform() < useQ else np.random.choice(can_actions)
            assert action in can_actions
            nextPos, reward, done, isH =  env.step(action)
            if done: # game over 沒有下一個狀態
                Q[s][action] +=  alpha * (reward - Q[s][action])
                break
            else:
                Q[s][action] +=  alpha * (reward + gamma * max(Q[nextPos]) - Q[s][action])
            s = nextPos
def play():
    s = env.reset()
    env.render()
    while True:
        # 根據狀態獲取s, 選擇一個動作
        action = getAction(s)
        print('執行了動作:', ACTIONS_STR[action])
        nextPos, reward, done, _ =  env.step(action)
        s = nextPos
        env.render()
        if done:
            print(reward)
            break

train()
printQ()
play()

展望

寫這個花費了很久,第一個原因是Q表建立錯誤, 第二個是中間非常容易死迴圈。
寫這個需要考慮到底需要迭代多少次合適,以及獎勵應該怎麼定合適,一定要有機率不按Q表選擇動作, 因為容易出現死迴圈。訓練步驟不能太少,Q表資訊不夠,也是容易出現死迴圈。
這個例子環境是固定的,環境變化,必須重新訓練
獎勵函式現在是 -step - 曼哈頓距離, 也就是說步驟越少以及距離越小,函式值越大
對無效動作給了-float("inf"), 充當動作的MASK, 使用softmax去對映,會得到0
image

相關文章