Angad Sandhu
Search
Browse
On this page

CartPoleBalance

Using Deep Reinforcement Learning to create an RL intelligent agent that can Balance a Pole on a moving Cart

https://www.youtube.com/watch?v=cO5g5qLrLSo

Depencencies Needed

  • Tensorflow
  • Keras
  • Keras RL
  • OpenAI gym

Importing Libraries

# base libs
import gymnasium as gym
import numpy as np
import random
# tf libs
import keras as k
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Flatten
from tensorflow.keras.optimizers import Adam
# RL libs
from rl.agents import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory

Testing Random Env with OpenAI Gym

env = gym.make('CartPole-v1', render_mode="human")
states = env.observation_space.shape[0]
print(env.observation_space.shape)
actions = env.action_space.n
(4,)
: 
The Kernel crashed while executing code in the the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure. Click <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. View Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details.
print(f"States : {states} \nActions : {actions}")
States : 4 
Actions : 2
episodes = 50
for episode in range(episodes):
    state = env.reset()
    done = False
    score = 0

    while not done:
        env.render()
        action = random.choice([0,1])
        n_state, reward, done, truncated, info = env.step(action)
        score += reward
    print(f"Episode:{episode+1} Score:{score}")
Episode:1 Score:16.0
Episode:2 Score:19.0
Episode:3 Score:19.0
Episode:4 Score:15.0
Episode:5 Score:16.0
Episode:6 Score:37.0
Episode:7 Score:14.0
Episode:8 Score:89.0
Episode:9 Score:30.0
Episode:10 Score:10.0
Episode:11 Score:11.0
Episode:12 Score:18.0
Episode:13 Score:18.0
Episode:14 Score:18.0
Episode:15 Score:24.0
Episode:16 Score:25.0
Episode:17 Score:38.0
Episode:18 Score:21.0
Episode:19 Score:21.0
Episode:20 Score:29.0
Episode:21 Score:56.0
Episode:22 Score:13.0
Episode:23 Score:13.0
Episode:24 Score:30.0
Episode:25 Score:18.0
Episode:26 Score:21.0
Episode:27 Score:31.0
Episode:28 Score:13.0
Episode:29 Score:37.0
Episode:30 Score:68.0
Episode:31 Score:17.0
Episode:32 Score:23.0
Episode:33 Score:12.0
Episode:34 Score:18.0
Episode:35 Score:33.0
Episode:36 Score:10.0
Episode:37 Score:9.0
Episode:38 Score:9.0
Episode:39 Score:12.0
Episode:40 Score:25.0
Episode:41 Score:15.0
Episode:42 Score:16.0
Episode:43 Score:19.0
Episode:44 Score:54.0
Episode:45 Score:43.0
Episode:46 Score:26.0
Episode:47 Score:36.0
Episode:48 Score:14.0
Episode:49 Score:20.0
Episode:50 Score:16.0

Creating Deep Learning Model

def build_model(states, actions):
    model = Sequential()
    model.add(Flatten(input_shape=(1,) + env.observation_space.shape))
    model.add(Dense(16))
    model.add(Activation('relu'))
    model.add(Dense(16))
    model.add(Activation('relu'))
    model.add(Dense(16))
    model.add(Activation('relu'))
    model.add(Dense(actions))
    model.add(Activation('linear'))
    return model
model = build_model(states, actions)
model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 flatten (Flatten)           (None, 4)                 0         
                                                                 
 dense (Dense)               (None, 16)                80        
                                                                 
 activation (Activation)     (None, 16)                0         
                                                                 
 dense_1 (Dense)             (None, 16)                272       
                                                                 
 activation_1 (Activation)   (None, 16)                0         
                                                                 
 dense_2 (Dense)             (None, 16)                272       
                                                                 
 activation_2 (Activation)   (None, 16)                0         
                                                                 
 dense_3 (Dense)             (None, 2)                 34        
                                                                 
 activation_3 (Activation)   (None, 2)                 0         
                                                                 
=================================================================
Total params: 658
Trainable params: 658
Non-trainable params: 0
_________________________________________________________________

Building Keras-RL Agent

import numpy as np
import gym

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Flatten
from tensorflow.keras.optimizers import Adam

from rl.agents.dqn import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory


ENV_NAME = 'CartPole-v0'


# Get the environment and extract the number of actions.
env = gym.make(ENV_NAME)
np.random.seed(123)
nb_actions = env.action_space.n

# Next, we build a very simple model.
model = Sequential()
model.add(Flatten(input_shape=(1,) + env.observation_space.shape))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(nb_actions))
model.add(Activation('linear'))
print(model.summary())

# Finally, we configure and compile our agent. You can use every built-in tensorflow.keras optimizer and
# even the metrics!
memory = SequentialMemory(limit=50000, window_length=1)
policy = BoltzmannQPolicy()
dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=10,
               target_model_update=1e-2, policy=policy)
dqn.compile(Adam(learning_rate=1e-3), metrics=['mae'])

# Okay, now it's time to learn something! We visualize the training here for show, but this
# slows down training quite a lot. You can always safely abort the training prematurely using
# Ctrl + C.
dqn.fit(env, nb_steps=50000, visualize=True, verbose=2)

# After training is done, we save the final weights.
dqn.save_weights(f'dqn_{ENV_NAME}_weights.h5f', overwrite=True)

# Finally, evaluate our algorithm for 5 episodes.
dqn.test(env, nb_episodes=5, visualize=True)
Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 flatten_1 (Flatten)         (None, 4)                 0         
                                                                 
 dense_4 (Dense)             (None, 16)                80        
                                                                 
 activation_4 (Activation)   (None, 16)                0         
                                                                 
 dense_5 (Dense)             (None, 16)                272       
                                                                 
 activation_5 (Activation)   (None, 16)                0         
                                                                 
 dense_6 (Dense)             (None, 16)                272       
                                                                 
 activation_6 (Activation)   (None, 16)                0         
                                                                 
 dense_7 (Dense)             (None, 2)                 34        
                                                                 
 activation_7 (Activation)   (None, 2)                 0         
                                                                 
=================================================================
Total params: 658
Trainable params: 658
Non-trainable params: 0
_________________________________________________________________
None
Training for 50000 steps ...
ValueError: Error when checking input: expected flatten_1_input to have shape (1, 4) but got array with shape (1, 2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[19], line 45
     40 dqn.compile(Adam(learning_rate=1e-3), metrics=['mae'])
     42 # Okay, now it's time to learn something! We visualize the training here for show, but this
     43 # slows down training quite a lot. You can always safely abort the training prematurely using
     44 # Ctrl + C.
---> 45 dqn.fit(env, nb_steps=50000, visualize=True, verbose=2)
     47 # After training is done, we save the final weights.
     48 dqn.save_weights(f'dqn_{ENV_NAME}_weights.h5f', overwrite=True)

File c:\Python310\lib\site-packages\rl\core.py:168, in Agent.fit(self, env, nb_steps, action_repetition, callbacks, verbose, visualize, nb_max_start_steps, start_step_policy, log_interval, nb_max_episode_steps)
    165 callbacks.on_step_begin(episode_step)
    166 # This is were all of the work happens. We first perceive and compute the action
    167 # (forward step) and then use the reward to improve (backward step).
--> 168 action = self.forward(observation)
    169 if self.processor is not None:
    170     action = self.processor.process_action(action)

File c:\Python310\lib\site-packages\rl\agents\dqn.py:224, in DQNAgent.forward(self, observation)
    221 def forward(self, observation):
    222     # Select an action.
    223     state = self.memory.get_recent_state(observation)
--> 224     q_values = self.compute_q_values(state)
    225     if self.training:
    226         action = self.policy.select_action(q_values=q_values)

File c:\Python310\lib\site-packages\rl\agents\dqn.py:68, in AbstractDQNAgent.compute_q_values(self, state)
     67 def compute_q_values(self, state):
---> 68     q_values = self.compute_batch_q_values([state]).flatten()
     69     assert q_values.shape == (self.nb_actions,)
     70     return q_values

File c:\Python310\lib\site-packages\rl\agents\dqn.py:63, in AbstractDQNAgent.compute_batch_q_values(self, state_batch)
     61 def compute_batch_q_values(self, state_batch):
     62     batch = self.process_state_batch(state_batch)
---> 63     q_values = self.model.predict_on_batch(batch)
     64     assert q_values.shape == (len(state_batch), self.nb_actions)
     65     return q_values

File c:\Python310\lib\site-packages\keras\engine\training_v1.py:1303, in Model.predict_on_batch(self, x)
   1298     raise NotImplementedError(
   1299         "`predict_on_batch` is not supported for models distributed "
   1300         "with tf.distribute.Strategy."
   1301     )
   1302 # Validate and standardize user data.
-> 1303 inputs, _, _ = self._standardize_user_data(
   1304     x, extract_tensors_from_dataset=True
   1305 )
   1306 # If `self._distribution_strategy` is True, then we are in a replica
   1307 # context at this point.
   1308 if self.run_eagerly or self._distribution_strategy:

File c:\Python310\lib\site-packages\keras\engine\training_v1.py:2650, in Model._standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset)
   2641 if (
   2642     not run_eagerly
   2643     and is_build_called
   (...)
   2646     and any(_is_symbolic_tensor(v) for v in all_inputs)
   2647 ):
   2648     return [], [], None
-> 2650 return self._standardize_tensors(
   2651     x,
   2652     y,
   2653     sample_weight,
   2654     run_eagerly=run_eagerly,
   2655     dict_inputs=dict_inputs,
   2656     is_dataset=is_dataset,
   2657     class_weight=class_weight,
   2658     batch_size=batch_size,
   2659 )

File c:\Python310\lib\site-packages\keras\engine\training_v1.py:2691, in Model._standardize_tensors(self, x, y, sample_weight, run_eagerly, dict_inputs, is_dataset, class_weight, batch_size)
   2688 # Standardize the inputs.
   2689 if not isinstance(x, (tf.compat.v1.data.Dataset, tf.data.Dataset)):
   2690     # TODO(fchollet): run static checks with dataset output shape(s).
-> 2691     x = training_utils_v1.standardize_input_data(
   2692         x,
   2693         feed_input_names,
   2694         feed_input_shapes,
   2695         check_batch_axis=False,  # Don't enforce the batch size.
   2696         exception_prefix="input",
   2697     )
   2699 # Get typespecs for the input data and sanitize it if necessary.
   2700 # TODO(momernick): This should be capable of doing full input validation
   2701 # at all times - validate that this is so and refactor the
   2702 # standardization code.
   2703 if isinstance(x, tf.data.Dataset):

File c:\Python310\lib\site-packages\keras\engine\training_utils_v1.py:731, in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    725             for dim, ref_dim in zip(data_shape, shape):
    726                 if (
    727                     ref_dim != dim
    728                     and ref_dim is not None
    729                     and dim is not None
    730                 ):
--> 731                     raise ValueError(
    732                         "Error when checking "
    733                         + exception_prefix
    734                         + ": expected "
    735                         + names[i]
    736                         + " to have shape "
    737                         + str(shape)
    738                         + " but got array with shape "
    739                         + str(data_shape)
    740                     )
    741 return data

ValueError: Error when checking input: expected flatten_1_input to have shape (1, 4) but got array with shape (1, 2)
policy = BoltzmannQPolicy()
memory = SequentialMemory(limit=50000, window_length=1)
policy = BoltzmannQPolicy()
dqn = DQNAgent(model=model, nb_actions=actions, memory=memory, nb_steps_warmup=10,
               target_model_update=1e-2, policy=policy)
Adam._name = 'hey'
dqn.compile(Adam(learning_rate=1e-3), metrics=['mae'])
WARNING:tensorflow:From c:\Python310\lib\site-packages\tensorflow\python\autograph\pyct\static_analysis\liveness.py:83: Analyzer.lamba_check (from tensorflow.python.autograph.pyct.static_analysis.liveness) is deprecated and will be removed after 2023-09-23.
Instructions for updating:
Lambda fuctions will be no more assumed to be used in the statement where they are used, or at least in the same block. https://github.com/tensorflow/tensorflow/issues/56089
WARNING:tensorflow:From c:\Python310\lib\site-packages\tensorflow\python\autograph\pyct\static_analysis\liveness.py:83: Analyzer.lamba_check (from tensorflow.python.autograph.pyct.static_analysis.liveness) is deprecated and will be removed after 2023-09-23.
Instructions for updating:
Lambda fuctions will be no more assumed to be used in the statement where they are used, or at least in the same block. https://github.com/tensorflow/tensorflow/issues/56089
dqn.fit(env, nb_steps=50000, visualize=True, verbose=2)
Training for 50000 steps ...
ValueError: Error when checking input: expected flatten_input to have shape (1, 4) but got array with shape (1, 2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[17], line 1
----> 1 dqn.fit(env, nb_steps=50000, visualize=True, verbose=2)

File c:\Python310\lib\site-packages\rl\core.py:168, in Agent.fit(self, env, nb_steps, action_repetition, callbacks, verbose, visualize, nb_max_start_steps, start_step_policy, log_interval, nb_max_episode_steps)
    165 callbacks.on_step_begin(episode_step)
    166 # This is were all of the work happens. We first perceive and compute the action
    167 # (forward step) and then use the reward to improve (backward step).
--> 168 action = self.forward(observation)
    169 if self.processor is not None:
    170     action = self.processor.process_action(action)

File c:\Python310\lib\site-packages\rl\agents\dqn.py:224, in DQNAgent.forward(self, observation)
    221 def forward(self, observation):
    222     # Select an action.
    223     state = self.memory.get_recent_state(observation)
--> 224     q_values = self.compute_q_values(state)
    225     if self.training:
    226         action = self.policy.select_action(q_values=q_values)

File c:\Python310\lib\site-packages\rl\agents\dqn.py:68, in AbstractDQNAgent.compute_q_values(self, state)
     67 def compute_q_values(self, state):
---> 68     q_values = self.compute_batch_q_values([state]).flatten()
     69     assert q_values.shape == (self.nb_actions,)
     70     return q_values

File c:\Python310\lib\site-packages\rl\agents\dqn.py:63, in AbstractDQNAgent.compute_batch_q_values(self, state_batch)
     61 def compute_batch_q_values(self, state_batch):
     62     batch = self.process_state_batch(state_batch)
---> 63     q_values = self.model.predict_on_batch(batch)
     64     assert q_values.shape == (len(state_batch), self.nb_actions)
     65     return q_values

File c:\Python310\lib\site-packages\keras\engine\training_v1.py:1303, in Model.predict_on_batch(self, x)
   1298     raise NotImplementedError(
   1299         "`predict_on_batch` is not supported for models distributed "
   1300         "with tf.distribute.Strategy."
   1301     )
   1302 # Validate and standardize user data.
-> 1303 inputs, _, _ = self._standardize_user_data(
   1304     x, extract_tensors_from_dataset=True
   1305 )
   1306 # If `self._distribution_strategy` is True, then we are in a replica
   1307 # context at this point.
   1308 if self.run_eagerly or self._distribution_strategy:

File c:\Python310\lib\site-packages\keras\engine\training_v1.py:2650, in Model._standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset)
   2641 if (
   2642     not run_eagerly
   2643     and is_build_called
   (...)
   2646     and any(_is_symbolic_tensor(v) for v in all_inputs)
   2647 ):
   2648     return [], [], None
-> 2650 return self._standardize_tensors(
   2651     x,
   2652     y,
   2653     sample_weight,
   2654     run_eagerly=run_eagerly,
   2655     dict_inputs=dict_inputs,
   2656     is_dataset=is_dataset,
   2657     class_weight=class_weight,
   2658     batch_size=batch_size,
   2659 )

File c:\Python310\lib\site-packages\keras\engine\training_v1.py:2691, in Model._standardize_tensors(self, x, y, sample_weight, run_eagerly, dict_inputs, is_dataset, class_weight, batch_size)
   2688 # Standardize the inputs.
   2689 if not isinstance(x, (tf.compat.v1.data.Dataset, tf.data.Dataset)):
   2690     # TODO(fchollet): run static checks with dataset output shape(s).
-> 2691     x = training_utils_v1.standardize_input_data(
   2692         x,
   2693         feed_input_names,
   2694         feed_input_shapes,
   2695         check_batch_axis=False,  # Don't enforce the batch size.
   2696         exception_prefix="input",
   2697     )
   2699 # Get typespecs for the input data and sanitize it if necessary.
   2700 # TODO(momernick): This should be capable of doing full input validation
   2701 # at all times - validate that this is so and refactor the
   2702 # standardization code.
   2703 if isinstance(x, tf.data.Dataset):

File c:\Python310\lib\site-packages\keras\engine\training_utils_v1.py:731, in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    725             for dim, ref_dim in zip(data_shape, shape):
    726                 if (
    727                     ref_dim != dim
    728                     and ref_dim is not None
    729                     and dim is not None
    730                 ):
--> 731                     raise ValueError(
    732                         "Error when checking "
    733                         + exception_prefix
    734                         + ": expected "
    735                         + names[i]
    736                         + " to have shape "
    737                         + str(shape)
    738                         + " but got array with shape "
    739                         + str(data_shape)
    740                     )
    741 return data

ValueError: Error when checking input: expected flatten_input to have shape (1, 4) but got array with shape (1, 2)
def build_agent(model, actions):
    policy = BoltzmannQPolicy()
    memory = SequentialMemory(limit=50000, window_length=1)
    dqn = DQNAgent(model=model, memory=memory, policy=policy,
                    nb_actions=actions, nb_steps_warmup=10, target_model_update=1e-2)
    return dqn
dqn = build_agent(model, actions)
dqn.compile(Adam(lr=1e-3), metrics=['mse'])
dqn.fit(env, nb_steps=50000, visualize=True, verbose=2)
TypeError: Keras symbolic inputs/outputs do not implement `__len__`. You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. This error will also get raised if you try asserting a symbolic input/output directly.
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[30], line 1
----> 1 dqn = build_agent(model, actions)
      2 dqn.compile(Adam(lr=1e-3), metrics=['mse'])
      3 dqn.fit(env, nb_steps=50000, visualize=True, verbose=2)

Cell In[29], line 4, in build_agent(model, actions)
      2 policy = BoltzmannQPolicy()
      3 memory = SequentialMemory(limit=50000, window_length=1)
----> 4 dqn = DQNAgent(model=model, memory=memory, policy=policy,
      5                 nb_actions=actions, nb_steps_warmup=10, target_model_update=1e-2)
      6 return dqn

File c:\Python310\lib\site-packages\rl\agents\dqn.py:108, in DQNAgent.__init__(self, model, policy, test_policy, enable_double_dqn, enable_dueling_network, dueling_type, *args, **kwargs)
    105 super(DQNAgent, self).__init__(*args, **kwargs)
    107 # Validate (important) input.
--> 108 if hasattr(model.output, '__len__') and len(model.output) > 1:
    109     raise ValueError('Model "{}" has more than one output. DQN expects a model that has a single output.'.format(model))
    110 if model.output._keras_shape != (None, self.nb_actions):

File c:\Python310\lib\site-packages\keras\engine\keras_tensor.py:244, in KerasTensor.__len__(self)
    243 def __len__(self):
--> 244     raise TypeError(
    245         "Keras symbolic inputs/outputs do not "
    246         "implement `__len__`. You may be "
    247         "trying to pass Keras symbolic inputs/outputs "
    248         "to a TF API that does not register dispatching, "
    249         "preventing Keras from automatically "
    250         "converting the API call to a lambda layer "
    251         "in the Functional Model. This error will also get raised "
    252         "if you try asserting a symbolic input/output directly."
    253     )

TypeError: Keras symbolic inputs/outputs do not implement `__len__`. You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. This error will also get raised if you try asserting a symbolic input/output directly.

Saving Model

Reloading RL Model

Browse the library