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
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 eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781788839303
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.