[英]Q-learning model not improving
我正在嘗試解決 openAI 健身房中的推車問題。 通過Q學習。 我想我誤解了 Q-learning 的工作原理,因為我的模型沒有改進。
我使用字典作為我的 Q 表。 所以我“散列”(變成一個字符串)每個觀察。 並將其用作我表中的鍵。
我表中的每個鍵(觀察)都映射到另一個字典。 我在哪里存儲在此狀態下進行的每個移動及其相關的 Q 值。
話雖如此,我表中的條目可能如下所示:
'[''0.102'', ''1.021'', ''-0.133'', ''-1.574'']':
0: 0.1
所以在 state(observation): '[''0.102'', ''1.021'', ''-0.133'', ''-1.574'']'
一個動作: 0
已被記錄,q 值為: 0.01
.
我的邏輯在這里錯了嗎? 我真的不知道我的實現是否出錯了。
import gym
import random
import numpy as np
ENV = 'CartPole-v0'
env = gym.make(ENV)
class Qtable:
def __init__(self):
self.table = {}
def update_table(self, obs, action, value):
obs_hash = self.hash_obs(obs)
# Update table with new observation
if not obs_hash in self.table:
self.table[obs_hash] = {}
self.table[obs_hash][action] = value
else:
# Check if action has been recorded
# If such, check if this value was better
# If not, record new action for this obs
if action in self.table[obs_hash]:
if value > self.table[obs_hash][action]:
self.table[obs_hash][action] = value
else:
self.table[obs_hash][action] = value
def get_prev_value(self, obs, action):
obs_hash = self.hash_obs(obs)
if obs_hash in self.table:
if action in self.table[obs_hash]:
return self.table[obs_hash][action]
return 0
def get_max_value(self, obs):
obs_hash = self.hash_obs(obs)
if obs_hash in self.table:
key = max(self.table[obs_hash])
return self.table[obs_hash][key]
return 0
def has_action(self, obs):
obs_hash = self.hash_obs(obs)
if obs_hash in self.table:
if len(self.table[obs_hash]) > 0:
return True
return False
def get_best_action(self, obs):
obs_hash = self.hash_obs(obs)
if obs_hash in self.table:
return max(self.table[obs_hash])
# Makes a hashable entry of the observation
def hash_obs(self, obs):
return str(['{:.3f}'.format(i) for i in obs])
def play():
q_table = Qtable()
# Hyperparameters
alpha = 0.1
gamma = 0.6
epsilon = 0.1
episodes = 1000
total = 0
for i in range(episodes):
done = False
prev_obs = env.reset()
episode_reward = 0
while not done:
if random.uniform(0, 1) > epsilon and q_table.has_action(prev_obs):
# Exploit learned values
action = q_table.get_best_action(prev_obs)
else:
# Explore action space
action = env.action_space.sample()
# Render the environment
#env.render()
# Take a step
obs, reward, done, info = env.step(action)
if done:
reward = -200
episode_reward += reward
old_value = q_table.get_prev_value(prev_obs, action)
next_max = q_table.get_max_value(obs)
# Get the current sate value
new_value = (1-alpha)*old_value + alpha*(reward + gamma*next_max)
q_table.update_table(obs, action, new_value)
prev_obs = obs
total += episode_reward
print("average", total/episodes)
env.close()
play()
我想我想通了。 我誤解了這部分new_value = (1-alpha)*old_value + alpha*(reward + gamma*next_max)
這里next_max
是下一個狀態的最佳移動。 而不是(應該是)這個子樹的最大值。
因此,將 Q 表實現為哈希圖可能不是一個好主意..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.