Book Image

Hands-On Q-Learning with Python

By : Nazia Habib
Book Image

Hands-On Q-Learning with Python

By: Nazia Habib

Overview of this book

Q-learning is a machine learning algorithm used to solve optimization problems in artificial intelligence (AI). It is one of the most popular fields of study among AI researchers. This book starts off by introducing you to reinforcement learning and Q-learning, in addition to helping you become familiar with OpenAI Gym as well as libraries such as Keras and TensorFlow. A few chapters into the book, you will gain insights into model-free Q-learning and use deep Q-networks and double deep Q-networks to solve complex problems. This book will guide you in exploring use cases such as self-driving vehicles and OpenAI Gym’s CartPole problem. You will also learn how to tune and optimize Q-networks and their hyperparameters. As you progress, you will understand the reinforcement learning approach to solving real-world problems. You will also explore how to use Q-learning and related algorithms in scientific research. Toward the end, you’ll gain insight into what’s in store for reinforcement learning. By the end of this book, you will be equipped with the skills you need to solve reinforcement learning problems using Q-learning algorithms with OpenAI Gym, Keras, and TensorFlow.
Table of Contents (14 chapters)
Free Chapter
1
Section 1: Q-Learning: A Roadmap
6
Section 2: Building and Optimizing Q-Learning Agents
9
Section 3: Advanced Q-Learning Challenges with Keras, TensorFlow, and OpenAI Gym

Getting started with the CartPole task

Let's get an instance of CartPole-v1 running.

We import the necessary package and build the environment with the call to gym.make(), as shown in the following code snippet:

import gym

env = gym.make('CartPole-v1')
env.reset()

done = False

while not done:
env.render()
# Take a random action
observation, reward, done, info = env.step(env.action_space.sample())

We run a loop that renders the environment for a maximum of 1,000 steps. It takes random actions at each timestep using env.step().

Here's the output displaying the CartPole-v1 environment:

You should see a small window pop up with the CartPole environment displayed.

Because we're taking random actions in our current simulation, we're not taking any of the information about the pole's direction or velocity into account. The pole will quickly...