Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Deep Reinforcement Learning Hands-On
Deep Reinforcement Learning Hands-On

Deep Reinforcement Learning Hands-On: Apply modern RL methods, with deep Q-networks, value iteration, policy gradients, TRPO, AlphaGo Zero and more

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Deep Reinforcement Learning Hands-On

Chapter 2. OpenAI Gym

After talking so much about the theoretical concepts of RL, let's start doing something practical. In this chapter, we'll learn the basics of the OpenAI Gym API and write our first randomly behaving agent to make ourselves familiar with all the concepts.

The anatomy of the agent

As we saw in the previous chapter, there are several entities in RL's view of the world:

  • Agent: A person or a thing that takes an active role. In practice, it's some piece of code, which implements some policy. Basically, this policy must decide what action is needed at every time step, given our observations.
  • Environment: Some model of the world, which is external to the agent and has the responsibility of providing us with observations and giving us rewards. It changes its state based on our actions.

Let's show how both of them can be implemented in Python for a simplistic situation. We will define an environment that gives the agent random rewards for a limited number of steps, regardless of the agent's actions. This scenario is not very useful, but will allow us to focus on specific methods in both the environment and the agent classes. Let's start with the environment:

class Environment:
    def __init__(self):
        self.steps_left...

Hardware and software requirements

The examples in this book were implemented and tested using Python version 3.6. I assume that you're already familiar with the language and common concepts such as virtual environments, so I won't cover in detail how to install the package and how to do this in an isolated way. The external libraries we'll use in this book are open source software, including the following:

  • NumPy: This is a library for scientific computing and implementing matrix operations and common functions.
  • OpenCV Python bindings: This is a computer vision library, which provides many functions for image processing.
  • Gym: This is a RL framework developed and maintained by OpenAI with various environments that can be communicated with, in a unified way.
  • PyTorch: This is a flexible and expressive Deep Learning (DL) library. A short essential crash course on it will be given in the next chapter.
  • Ptanhttps://github.com/Shmuma/ptan): This is an open source extension to...

OpenAI Gym API

The Python library called Gym was developed and has been maintained by OpenAI (www.openai.com). The main goal of Gym is to provide a rich collection of environments for RL experiments using a unified interface. So, it's not surprising that the central class in the library is an environment, which is called Env. It exposes several methods and fields that provide the required information about an environment's capabilities. From high level, every environment provides you with these pieces of information and functionality:

  • A set of actions that are allowed to be executed in an environment. Gym supports both discrete and continuous actions, as well as their combination.
  • The shape and boundaries of the observations that an environment provides the agent with.
  • A method called step to execute an action, which returns the current observation, reward, and indication that the episode is over.
  • A method called reset to return the environment to its initial state and to obtain...

The random CartPole agent

Although the environment is much more complex than our first example in The anatomy of the agent section, the code of the agent is much shorter. This is the power of reusability, abstractions, and third-party libraries!

So, here is the code (you can find it in Chapter02/02_cartpole_random.py):

import gym

if __name__ == "__main__":
    env = gym.make("CartPole-v0")
    total_reward = 0.0
    total_steps = 0
    obs = env.reset()

Here, we create the environment and initialize the counter of steps and the reward accumulator. On the last line, we reset the environment to obtain the first observation (which we'll not use, as our agent is stochastic):

   while True:
        action = env.action_space.sample()
        obs, reward, done, _ = env.step(action)
        total_reward += reward
        total_steps += 1
        if done:
            break

   print("Episode done in %d steps, total reward %.2f" % (total_steps, total_reward...

The extra Gym functionality – wrappers and monitors

What we discussed so far covers two-thirds of the Gym core API and the essential functions required to start writing agents. The rest of the API you can live without, but it will make your life easier and your code cleaner. So, let's look at a quick overview of the rest of the API.

Wrappers

Very frequently, you will want to extend the environment's functionality in some generic way. For example, an environment gives you some observations, but you want to accumulate them in some buffer and provide to the agent the N last observations, which is a common scenario for dynamic computer games, when one single frame is just not enough to get the full information about the game state. Another example is when you want to be able to crop or preprocess an image's pixels to make it more convenient for the agent to digest or if you want to normalize reward scores somehow. There are many such situations that have the same structure...

Summary

My congratulations! You have started to learn the practical side of RL! In this chapter, we installed OpenAI Gym with tons of environments to play with, studied its basic API and created a randomly behaving agent. You also learned how to extend the functionality of existing environments in a modular way and got familiar with a way to record our agent's activity using the Monitor wrapper.

In the next chapter, we will do a quick DL recap using PyTorch, which is a favorite library among DL researchers. Stay tuned.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore deep reinforcement learning (RL), from the first principles to the latest algorithms
  • Evaluate high-profile RL methods, including value iteration, deep Q-networks, policy gradients, TRPO, PPO, DDPG, D4PG, evolution strategies and genetic algorithms
  • Keep up with the very latest industry developments, including AI-driven chatbots

Description

Deep Reinforcement Learning Hands-On is a comprehensive guide to the very latest DL tools and their limitations. You will evaluate methods including Cross-entropy and policy gradients, before applying them to real-world environments. Take on both the Atari set of virtual games and family favorites such as Connect4. The book provides an introduction to the basics of RL, giving you the know-how to code intelligent learning agents to take on a formidable array of practical tasks. Discover how to implement Q-learning on 'grid world' environments, teach your agent to buy and trade stocks, and find out how natural language models are driving the boom in chatbots.

Who is this book for?

Some fluency in Python is assumed. Basic deep learning (DL) approaches should be familiar to readers and some practical experience in DL will be helpful. This book is an introduction to deep reinforcement learning (RL) and requires no background in RL.

What you will learn

  • Understand the DL context of RL and implement complex DL models
  • Learn the foundation of RL: Markov decision processes
  • Evaluate RL methods including Cross-entropy, DQN, Actor-Critic, TRPO, PPO, DDPG, D4PG and others
  • Discover how to deal with discrete and continuous action spaces in various environments
  • Defeat Atari arcade games using the value iteration method
  • Create your own OpenAI Gym environment to train a stock trading agent
  • Teach your agent to play Connect4 using AlphaGo Zero
  • Explore the very latest deep RL research on topics including AI-driven chatbots

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 21, 2018
Length: 546 pages
Edition : 1st
Language : English
ISBN-13 : 9781788834247
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 21, 2018
Length: 546 pages
Edition : 1st
Language : English
ISBN-13 : 9781788834247
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 103.97
Mastering Machine Learning Algorithms
€36.99
Hands-On Reinforcement Learning with Python
€29.99
Deep Reinforcement Learning Hands-On
€36.99
Total 103.97 Stars icon
Banner background image

Table of Contents

20 Chapters
1. What is Reinforcement Learning? Chevron down icon Chevron up icon
2. OpenAI Gym Chevron down icon Chevron up icon
3. Deep Learning with PyTorch Chevron down icon Chevron up icon
4. The Cross-Entropy Method Chevron down icon Chevron up icon
5. Tabular Learning and the Bellman Equation Chevron down icon Chevron up icon
6. Deep Q-Networks Chevron down icon Chevron up icon
7. DQN Extensions Chevron down icon Chevron up icon
8. Stocks Trading Using RL Chevron down icon Chevron up icon
9. Policy Gradients – An Alternative Chevron down icon Chevron up icon
10. The Actor-Critic Method Chevron down icon Chevron up icon
11. Asynchronous Advantage Actor-Critic Chevron down icon Chevron up icon
12. Chatbots Training with RL Chevron down icon Chevron up icon
13. Web Navigation Chevron down icon Chevron up icon
14. Continuous Action Space Chevron down icon Chevron up icon
15. Trust Regions – TRPO, PPO, and ACKTR Chevron down icon Chevron up icon
16. Black-Box Optimization in RL Chevron down icon Chevron up icon
17. Beyond Model-Free – Imagination Chevron down icon Chevron up icon
18. AlphaGo Zero Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(34 Ratings)
5 star 67.6%
4 star 14.7%
3 star 5.9%
2 star 5.9%
1 star 5.9%
Filter icon Filter
Top Reviews

Filter reviews by




Daniel Bain Oct 22, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really wonderful book on Reinforcement Learning. Most of the best sources in the field are more theoretical than practical (which is great too) but don't help in walking through how to actually implement many of the recent breakthroughs that make this an exciting field. This book is great because the author actually explains sometimes confusing techniques in clear language. Moreover, the book walks through actual code examples and explains many of the nuances.
Amazon Verified review Amazon
Dr. Heiko Bauer Aug 06, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Der Autor hat tiefes Verständnis und bringt passende Beispiele.Ich habe selbst 2 Patente auf dem Gebiet und dachte, ich kenne mich aus, aber erst das Buch bringt tieferes Verständnis, welche Verfahren gut funktionieren und warum.
Amazon Verified review Amazon
Cliente Amazon Jul 10, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Claridad en la explicacion de los conceptos. Muchos ejemplos y prácticas útiles.
Amazon Verified review Amazon
eldil Nov 21, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
/Awesome/ book - so detailed and clear, all differences between methods are motivated. Performance graphs for everything, his own free library and plenty of examples and experiments. Too, this is the only Packt book that covers D4PG, which came out just before it was published. I'd pay the price of this book /monthly/, for a newsletter or something where he keeps you up to date on the latest. Worth twice the price, second edition when? :) Doesn't cover RNNs or LSTMs as much as I'd like but no points off for that.
Amazon Verified review Amazon
RustorGo Jul 13, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Almost finished Chapter 3, very well written, apparently that the author really know what he is talking about, and able to write clearly. Previous one or two books from Packt disappointed me (lack of depth, cook book style), but this one is a pleasant surprise!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.