QLearning
QLearning並沒有直接將這個Q值(q_target是估計值)直接賦予新的Q,而是採用漸進的方式類似梯度下降,朝target邁近一小步,取決於α,這就能夠減少估計誤差造成的影響。類似隨機梯度下降,最後可以收斂到最優的Q值。
一、QLearning算法思維
二、QLearning算法更新思維
1.導入模塊
from maze_env import Maze #環境模塊
from RL_brain import QLearningTable #思考模塊
2.更新迭代
def update():
#---------------------------------------------------------------------------------
#Reapeat(episode):學習100次
for episode in range(100):
#----------------------------------------------------------------------------------
# 初始化 state 的觀測值;並開始內循環
observation = env.reset()
while True:
# 更新可視化環境
env.render()
#----------------------------------------------------------------------------------
# 1°Action
action = RL.choose_action(str(observation))
# 2°獲得反饋S'(下一步觀測值)和R(當前步獎勵)和done (是否是掉下地獄或者升上天堂)
observation_, reward, done = env.step(action)
# 3°更新Q表:RL 從這個序列 (state, action, reward, state_) 中學習
RL.learn(str(observation), action, reward, str(observation_))
# 4°S'→state的觀測值
observation = observation_
#------------------------------------------------------------------------------------
# 如果掉下地獄或者升上天堂, 這回合就結束了
if done:
break
# 結束遊戲並關閉窗口
print('game over')
env.destroy()
if __name__ == "__main__":
# 定義環境 env 和 RL 方式
env = Maze()
RL = QLearningTable(actions=list(range(env.n_actions)))
# 開始可視化環境 env
env.after(100, update)
env.mainloop()
三、思維決策
1.思維構架
import numpy as np
import pandas as pd
class QLearningTable:
# 初始化
def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9):
# 選行爲
def choose_action(self, observation):
# 學習更新參數
def learn(self, s, a, r, s_):
# 檢測 state 是否存在
def check_state_exist(self, state):
2、函數實現
2.1.初始化
- actions: 所有行爲
- epsilon: 貪婪率e_greesy
- lr: 學習率α
- gamma: 獎勵衰減γ
- q_table: Q表
def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9):
self.actions = actions # a list
self.lr = learning_rate # 學習率
self.gamma = reward_decay # 獎勵衰減
self.epsilon = e_greedy # 貪婪度
self.q_table = pd.DataFrame(columns=self.actions, dtype=np.float64) # 初始 q_table
2.選行爲choose_action
- if:在貪婪率內則選擇最大(防止數值相同 choice亂序)
- else:隨機選擇
def choose_action(self, observation):
self.check_state_exist(observation) # 檢測本 state 是否在 q_table 中存在
# 選擇 action
if np.random.uniform() < self.epsilon: # 選擇 Q value 最高的 action
state_action = self.q_table.loc[observation, :]
# 同一個 state, 可能會有多個相同的 Q action value, 所以我們亂序一下
action = np.random.choice(state_action[state_action == np.max(state_action)].index)
else: # 隨機選擇 action
action = np.random.choice(self.actions)
return action
3.學習更新參數(更新Q表)
def learn(self, s, a, r, s_):
self.check_state_exist(s_) # 檢測 q_table 中是否存在 s_
q_predict = self.q_table.loc[s, a] # 獲取Q預測值
if s_ != 'terminal': # 獲取真實值
q_target = r + self.gamma * self.q_table.loc[s_, :].max() # 下個state不是終止符
else:
q_target = r # 下個 state 是終止符
# 更新Q表:更新對應的state-action 值
self.q_table.loc[s, a] += self.lr * (q_target - q_predict)
4.檢測Q表中有無當前state—action值
如果還沒有當前 state, 那我我們就插入一組全 0 數據, 當做這個 state 的所有 action 初始 values.
def check_state_exist(self, state):
if state not in self.q_table.index:
# append new state to q table
self.q_table = self.q_table.append(
pd.Series(
[0]*len(self.actions),
index=self.q_table.columns,
name=state,
)
)