简体   繁体   中英

Q-learning model not improving

Im trying to solve the cartpole problem in openAI's gym. By Q learning. I think I have misunderstood how Q-learning works, since my model is not improving.

Im using a dictionary as my Q table. So I "hash" (turning into a string) every observation. And using this as a key in my table.

Each key (observation) in my table is mapped to another dictionary. Where I store each move that has been taken in this state and its associated Q value.

With that said, an entry in my table could look like this:

'[''0.102'', ''1.021'', ''-0.133'', ''-1.574'']':
  0: 0.1

So in state(observation): '[''0.102'', ''1.021'', ''-0.133'', ''-1.574'']' an action: 0 has been recorded with an q value of: 0.01 .

Is my logic wrong here? I cant really figure out if where I went wrong with my implementation.

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()

I think I figured it out. I have misunderstood this part new_value = (1-alpha)*old_value + alpha*(reward + gamma*next_max)

Here next_max is the best move of the next state. And not (as it should be) the max value of this subtree.

So implementing a Q table as a hashmap is probably not a good idea..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM