Sitemap
Fawehdennis

Fawehdennis

Atari Games

3 min readMar 7, 2025

--

Use Deep Q-Learning with TensorFlow and Gymnasium

Reinforcement learning (RL) is a powerful machine learning paradigm for training agents to make decisions. One of the most widely used RL techniques is Deep Q-Learning (DQN), which uses deep neural networks to approximate Q-values. This blog post explores the implementation of DQN using TensorFlow and Gymnasium to train an agent for Atari games.

Understanding Deep Q-Learning

DQN is an extension of Q-learning that utilizes neural networks to approximate the action-value function, helping agents make decisions in high-dimensional environments. The core idea of DQN is to train a neural network to predict Q-values for each possible action in a given state and use these predictions to guide decision-making.

Key Components of DQN

  1. Convolutional Neural Network (CNN) — Extracts features from image-based environments.
  2. Experience Replay — Stores past experiences in a memory buffer to break correlations in training.
  3. Epsilon-Greedy Policy — Balances exploration and exploitation.
  4. Target Network — Stabilizes training by maintaining a separate network for computing target Q-values.
  5. Frame Stacking — Maintains temporal dependencies by stacking multiple frames as input.

Implementing DQN for Atari Games

I will use Gymnasium to create the Atari environment, TensorFlow to build neural networks, OpenCV for preprocessing images, and NumPy for numerical operations.

Get Fawehdennis’s stories in your inbox

Join Medium for free to get updates from this writer.

Step 1: Install Required Libraries

!pip install gymnasium[atari] tensorflow numpy opencv-python

Step 2: Import Dependencies

import gymnasium as gym
import numpy as np
import tensorflow as tf
import cv2
from collections import deque
import random

Step 3: Define Hyperparameters

EPISODES = 10
BATCH_SIZE = 32
GAMMA = 0.99
EPSILON = 1.0
EPSILON_MIN = 0.01
EPSILON_DECAY = 0.995
LEARNING_RATE = 0.00025
MEMORY_SIZE = 10000
FRAME_STACK = 4

Step 4: Preprocess Frames

def preprocess_frame(frame):
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
frame = cv2.resize(frame, (84, 84))
frame = frame / 255.0
return frame

Step 5: Stack Frames

def stack_frames(stack, frame, is_new_episode):
if is_new_episode:
stack = deque([frame] * FRAME_STACK, maxlen=FRAME_STACK)
else:
stack.append(frame)
return np.stack(stack, axis=-1), stack

Step 6: Build CNN Model

def build_model(state_shape, action_size):
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (8, 8), strides=(4, 4), activation='relu', input_shape=state_shape),
tf.keras.layers.Conv2D(64, (4, 4), strides=(2, 2), activation='relu'),
tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(action_size, activation='linear')
])
model.compile(loss='mse', optimizer=tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE))
return model

Step 7: Set Up Environment and Memory

env = gym.make('ALE/Breakout-v5', render_mode='rgb_array')
state_shape = (84, 84, FRAME_STACK)
action_size = env.action_space.n
model = build_model(state_shape, action_size)
target_model = build_model(state_shape, action_size)
memory = deque(maxlen=MEMORY_SIZE)

Step 8: Define Helper Functions

Updating the Target Model

def update_target_model():
target_model.set_weights(model.get_weights())

Choosing an Action with an Epsilon-Greedy Policy

def get_action(state, epsilon):
if np.random.rand() <= epsilon:
return random.randrange(action_size)
q_values = model.predict(np.expand_dims(state, axis=0), verbose=0)
return np.argmax(q_values[0])

Training the Model with Experience Replay

def train_model():
if len(memory) < BATCH_SIZE:
return
minibatch = random.sample(memory, BATCH_SIZE)
states = np.array([t[0] for t in minibatch])
actions = np.array([t[1] for t in minibatch])
rewards = np.array([t[2] for t in minibatch])
next_states = np.array([t[3] for t in minibatch])
dones = np.array([t[4] for t in minibatch])

targets = model.predict(states, verbose=0)
next_q_values = target_model.predict(next_states, verbose=0)
for i in range(BATCH_SIZE):
if dones[i]:
targets[i][actions[i]] = rewards[i]
else:
targets[i][actions[i]] = rewards[i] + GAMMA * np.max(next_q_values[i])

model.fit(states, targets, epochs=1, verbose=0)

Step 9: Train the Agent

epsilon = EPSILON
for episode in range(EPISODES):
frame = preprocess_frame(env.reset()[0])
state, frame_stack = stack_frames(None, frame, True)
total_reward = 0
done = False

while not done:
action = get_action(state, epsilon)
next_frame, reward, done, _, _ = env.step(action)
next_frame = preprocess_frame(next_frame)
next_state, frame_stack = stack_frames(frame_stack, next_frame, False)
memory.append((state, action, reward, next_state, done))
state = next_state
total_reward += reward
train_model()

update_target_model()
if epsilon > EPSILON_MIN:
epsilon *= EPSILON_DECAY

print(f"Episode: {episode + 1}, Total Reward: {total_reward}, Epsilon: {epsilon:.3f}")

env.close()

Conclusion

DQN enables agents to learn optimal policies for playing Atari games by leveraging deep learning techniques. By using frame preprocessing, frame stacking, and CNNs, the agent can efficiently extract meaningful features from high-dimensional visual input. Further improvements like Double DQN, Dueling Networks, and Prioritized Experience Replay can enhance training efficiency.

--

--