A complete implementation of Deep Q-Network (DQN) reinforcement learning agent to solve the OpenAI Gym CartPole environment.
This project demonstrates how to train a neural network agent using Deep Q-Learning to balance a pole on a moving cart. The agent learns to take optimal actions (move left or right) to keep the pole upright for as long as possible.
- Deep Q-Network (DQN) implementation using Keras and Keras-RL
- Experience Replay for stable learning
- Target Network for consistent training targets
- Model Persistence - save and reload trained agents
- Performance Visualization - watch the trained agent in action
- Python 3.7+
- TensorFlow 2.3.0
- OpenAI Gym
- Keras-RL2
- Clone or download this repository
- Install dependencies:
pip install tensorflow==2.3.0 pip install gym pip install keras pip install keras-rl2
Simply execute the Python script:
python deep_reinforcement_learning.py- Random Performance: ~10-30 points per episode (baseline)
- Trained DQN: ~200 points per episode (perfect performance)
- Training Time: ~4-5 minutes (50,000 steps)
- Environment Setup - CartPole environment initialization
- Model Architecture - Neural network summary
- Training Progress - Real-time training metrics
- Performance Testing - 100 episodes of evaluation
- Visualization - Watch the trained agent balance the pole
- Model Persistence - Save/load demonstration
- Experience Collection: Agent interacts with environment, storing (state, action, reward, next_state) tuples
- Q-Learning: Updates Q-values using Bellman equation: Q(s,a) = r + γ * max Q(s',a')
- Neural Network: Approximates Q-values for all state-action pairs
- Experience Replay: Randomly samples past experiences to break correlations
- Target Network: Uses separate network for stable learning targets
Input (4) → Flatten → Dense(24, ReLU) → Dense(24, ReLU) → Output(2, Linear)
- State Space: 4 dimensions (cart position, cart velocity, pole angle, pole angular velocity)
- Action Space: 2 actions (move left: 0, move right: 1)
- Goal: Keep pole upright for maximum time (200 steps = perfect score)
RL-GYM/
├── deep_reinforcement_learning.py # Main implementation
├── dqn_weights.h5f # Saved model weights (created after training)
└── README.md # This file
- Training Steps: Change
nb_steps=50000for longer/shorter training - Memory Size: Adjust
limit=50000in SequentialMemory - Learning Rate: Modify
lr=1e-3in Adam optimizer - Network Size: Change Dense layer neurons (currently 24)
- Test Episodes: Adjust
nb_episodes=100for testing
# Longer training
dqn.fit(game, nb_steps=100000, visualize=False, verbose=1)
# Larger network
model.add(Dense(64, activation='relu')) # Instead of 24
# Different learning rate
dqn.compile(Adam(lr=1e-4), metrics=['mae']) # Slower learning- CartPole-v0: Classic balancing problem (this project)
- LunarLander-v2: Landing a spacecraft
- Acrobot-v1: Swinging up a double pendulum
- MountainCar-v0: Climbing a hill with limited power
Import Errors:
# Make sure you have the correct versions
pip install tensorflow==2.3.0
pip install keras-rl2Training Not Converging:
- Increase training steps:
nb_steps=100000 - Adjust learning rate:
lr=1e-4orlr=1e-2 - Check if environment is working properly
Memory Issues:
- Reduce memory size:
limit=25000 - Use smaller network: Dense(16) instead of Dense(24)
- GPU Acceleration: Install TensorFlow-GPU for faster training
- Hyperparameter Tuning: Experiment with learning rates and network sizes
- Environment Variations: Try different Gym environments
- Advanced Algorithms: Implement Dueling DQN, Double DQN, or A3C