handson-ml/18_reinforcement_learning.i...

2335 lines
78 KiB
Plaintext
Raw Normal View History

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"**Chapter 18 Reinforcement Learning**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"_This notebook contains all the sample code and solutions to the exercises in chapter 18._"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<table align=\"left\">\n",
" <td>\n",
2022-02-19 10:09:28 +01:00
" <a href=\"https://colab.research.google.com/github/ageron/handson-ml3/blob/main/18_reinforcement_learning.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
" </td>\n",
" <td>\n",
2022-02-19 10:09:28 +01:00
" <a target=\"_blank\" href=\"https://kaggle.com/kernels/welcome?src=https://github.com/ageron/handson-ml3/blob/main/18_reinforcement_learning.ipynb\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" /></a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
2022-02-19 10:09:28 +01:00
"metadata": {
"tags": []
},
"source": [
"# WORK IN PROGRESS\n",
"<img src=\"https://freesvg.org/img/Lavori-in-corso.png\" width=\"200\" />\n",
"\n",
"**I'm still working on updating this chapter to the 3rd edition. Please come back in a few weeks.**"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dFXIv9qNpKzt",
"tags": []
},
"source": [
"# Setup"
]
},
{
"cell_type": "markdown",
2022-02-19 10:09:28 +01:00
"metadata": {
"id": "8IPbJEmZpKzu"
},
"source": [
2022-02-19 11:03:20 +01:00
"This project requires Python 3.7 or above:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {
"id": "TFSU3FCOpKzu"
},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"import sys\n",
"\n",
2022-02-19 11:03:20 +01:00
"assert sys.version_info >= (3, 7)"
2022-02-19 10:09:28 +01:00
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TAlKky09pKzv"
},
"source": [
"It also requires Scikit-Learn ≥ 1.0.1:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YqCwW7cMpKzw"
},
"outputs": [],
"source": [
2021-05-25 02:07:29 +02:00
"import sklearn\n",
"\n",
2022-02-19 10:09:28 +01:00
"assert sklearn.__version__ >= \"1.0.1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GJtVEqxfpKzw"
},
"source": [
"And TensorFlow ≥ 2.6:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0Piq5se2pKzx"
},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"import tensorflow as tf\n",
"\n",
2022-02-19 10:09:28 +01:00
"assert tf.__version__ >= \"2.6.0\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DDaDoLQTpKzx"
},
"source": [
"As we did in earlier chapters, let's define the default font sizes to make the figures prettier:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8d4TH3NbpKzx"
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
2019-05-26 17:30:39 +02:00
"\n",
2022-02-19 10:09:28 +01:00
"plt.rc('font', size=14)\n",
"plt.rc('axes', labelsize=14, titlesize=14)\n",
"plt.rc('legend', fontsize=14)\n",
"plt.rc('xtick', labelsize=10)\n",
"plt.rc('ytick', labelsize=10)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RcoUIRsvpKzy"
},
"source": [
"And let's create the `images/rl` folder (if it doesn't already exist), and define the `save_fig()` function which is used through this notebook to save the figures in high-res for the book:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PQFH5Y9PpKzy"
},
"outputs": [],
"source": [
"from pathlib import Path\n",
"\n",
"IMAGES_PATH = Path() / \"images\" / \"rl\"\n",
"IMAGES_PATH.mkdir(parents=True, exist_ok=True)\n",
"\n",
2019-05-26 17:30:39 +02:00
"def save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n",
" path = IMAGES_PATH / f\"{fig_id}.{fig_extension}\"\n",
" if tight_layout:\n",
" plt.tight_layout()\n",
2019-05-26 17:30:39 +02:00
" plt.savefig(path, format=fig_extension, dpi=resolution)"
]
},
2022-02-19 10:09:28 +01:00
{
"cell_type": "markdown",
"metadata": {
"id": "YTsawKlapKzy"
},
"source": [
"This chapter can be very slow without a GPU, so let's make sure there's one, or else issue a warning:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ekxzo6pOpKzy"
},
"outputs": [],
"source": [
"if not tf.config.list_physical_devices('GPU'):\n",
" print(\"No GPU was detected. Neural nets can be very slow without a GPU.\")\n",
" if \"google.colab\" in sys.modules:\n",
" print(\"Go to Runtime > Change runtime and select a GPU hardware \"\n",
" \"accelerator.\")\n",
" if \"kaggle_secrets\" in sys.modules:\n",
" print(\"Go to Settings > Accelerator and select GPU.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's install the gym library, which provides many environments for Reinforcement Learning. Some of these environments require an X server to plot graphics, so we need to install xvfb on Colab or Kaggle (that's an in-memory X server, since the runtimes are not hooked to a screen). We also need to install pyvirtualdisplay, which provides a Python interface to xvfb. And let's also install the Box2D and Atari environments. By running the following cell, you also accept the Atari ROM license."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if \"google.colab\" in sys.modules or \"kaggle_secrets\" in sys.modules:\n",
" !apt update &> /dev/null && apt install -y xvfb &> /dev/null\n",
" %pip install -q -U gym pyglet pyvirtualdisplay\n",
" %pip install -q -U gym[box2d,atari,accept-rom-license]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction to OpenAI gym"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this notebook we will be using [OpenAI gym](https://gym.openai.com/), a great toolkit for developing and comparing Reinforcement Learning algorithms. It provides many environments for your learning *agents* to interact with. Let's start by importing `gym`:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import gym"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Let's list all the available environments:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"gym.envs.registry.all()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"The Cart-Pole is a very simple environment composed of a cart that can move left or right, and pole placed vertically on top of it. The agent must move the cart left or right to keep the pole upright."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"env = gym.make('CartPole-v1')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Let's initialize the environment by calling is `reset()` method. This returns an observation:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"env.seed(42)\n",
"obs = env.reset()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Observations vary depending on the environment. In this case it is a 1D NumPy array composed of 4 floats: they represent the cart's horizontal position, its velocity, the angle of the pole (0 = vertical), and the angular velocity."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"obs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"An environment can be visualized by calling its `render()` method, and you can pick the rendering mode (the rendering options depend on the environment)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"**Warning**: some environments (including the Cart-Pole) require access to your display, which opens up a separate window, even if you specify `mode=\"rgb_array\"`. In general you can safely ignore that window. However, if Jupyter is running on a headless server (ie. without a screen) it will raise an exception. One way to avoid this is to install a fake X server like [Xvfb](http://en.wikipedia.org/wiki/Xvfb). On Debian or Ubuntu:\n",
"\n",
"```bash\n",
"$ apt update\n",
"$ apt install -y xvfb\n",
"```\n",
"\n",
"You can then start Jupyter using the `xvfb-run` command:\n",
"\n",
"```bash\n",
"$ xvfb-run -s \"-screen 0 1400x900x24\" jupyter notebook\n",
"```\n",
"\n",
"Alternatively, you can install the [pyvirtualdisplay](https://github.com/ponty/pyvirtualdisplay) Python library which wraps Xvfb:\n",
2019-05-26 17:30:39 +02:00
"\n",
"```bash\n",
"%pip install -U pyvirtualdisplay\n",
2019-05-26 17:30:39 +02:00
"```\n",
"\n",
"And run the following code:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"try:\n",
" import pyvirtualdisplay\n",
" display = pyvirtualdisplay.Display(visible=0, size=(1400, 900)).start()\n",
"except ImportError:\n",
" pass"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"env.render()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this example we will set `mode=\"rgb_array\"` to get an image of the environment as a NumPy array:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"img = env.render(mode=\"rgb_array\")\n",
"img.shape"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def plot_environment(env, figsize=(5,4)):\n",
" plt.figure(figsize=figsize)\n",
" img = env.render(mode=\"rgb_array\")\n",
" plt.imshow(img)\n",
" plt.axis(\"off\")\n",
" return img"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"plot_environment(env)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Let's see how to interact with an environment. Your agent will need to select an action from an \"action space\" (the set of possible actions). Let's see what this environment's action space looks like:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"env.action_space"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Yep, just two possible actions: accelerate towards the left or towards the right."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Since the pole is leaning toward the right (`obs[2] > 0`), let's accelerate the cart toward the right:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"action = 1 # accelerate right\n",
"obs, reward, done, info = env.step(action)\n",
"obs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Notice that the cart is now moving toward the right (`obs[1] > 0`). The pole is still tilted toward the right (`obs[2] > 0`), but its angular velocity is now negative (`obs[3] < 0`), so it will likely be tilted toward the left after the next step."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"plot_environment(env)\n",
"save_fig(\"cart_pole_plot\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Looks like it's doing what we're telling it to do!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The environment also tells the agent how much reward it got during the last step:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"reward"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When the game is over, the environment returns `done=True`:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"done"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Finally, `info` is an environment-specific dictionary that can provide some extra information that you may find useful for debugging or for training. For example, in some games it may indicate how many lives the agent has."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"info"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"The sequence of steps between the moment the environment is reset until it is done is called an \"episode\". At the end of an episode (i.e., when `step()` returns `done=True`), you should reset the environment before you continue to use it."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"if done:\n",
" obs = env.reset()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Now how can we make the poll remain upright? We will need to define a _policy_ for that. This is the strategy that the agent will use to select an action at each step. It can use all the past actions and observations to decide what to do."
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"# A simple hard-coded policy"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Let's hard code a simple strategy: if the pole is tilting to the left, then push the cart to the left, and _vice versa_. Let's see if that works:"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"env.seed(42)\n",
"\n",
"def basic_policy(obs):\n",
" angle = obs[2]\n",
" return 0 if angle < 0 else 1\n",
"\n",
"totals = []\n",
"for episode in range(500):\n",
" episode_rewards = 0\n",
" obs = env.reset()\n",
" for step in range(200):\n",
" action = basic_policy(obs)\n",
" obs, reward, done, info = env.step(action)\n",
" episode_rewards += reward\n",
" if done:\n",
" break\n",
" totals.append(episode_rewards)"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"np.mean(totals), np.std(totals), min(totals), max(totals)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Well, as expected, this strategy is a bit too basic: the best it did was to keep the poll up for only 68 steps. This environment is considered solved when the agent keeps the poll up for 200 steps."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Let's visualize one episode:"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"env.seed(42)\n",
"\n",
"frames = []\n",
"\n",
"obs = env.reset()\n",
"for step in range(200):\n",
" img = env.render(mode=\"rgb_array\")\n",
" frames.append(img)\n",
" action = basic_policy(obs)\n",
"\n",
" obs, reward, done, info = env.step(action)\n",
" if done:\n",
" break"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Now show the animation:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"def update_scene(num, frames, patch):\n",
" patch.set_data(frames[num])\n",
" return patch,\n",
"\n",
"def plot_animation(frames, repeat=False, interval=40):\n",
" fig = plt.figure()\n",
" patch = plt.imshow(frames[0])\n",
" plt.axis('off')\n",
" anim = animation.FuncAnimation(\n",
" fig, update_scene, fargs=(frames, patch),\n",
" frames=len(frames), repeat=repeat, interval=interval)\n",
" plt.close()\n",
" return anim"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"plot_animation(frames)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Clearly the system is unstable and after just a few wobbles, the pole ends up too tilted: game over. We will need to be smarter than that!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"# Neural Network Policies"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's create a neural network that will take observations as inputs, and output the probabilities of actions to take for each observation. To choose an action, the network will estimate a probability for each action, then we will select an action randomly according to the estimated probabilities. In the case of the Cart-Pole environment, there are just two possible actions (left or right), so we only need one output neuron: it will output the probability `p` of the action 0 (left), and of course the probability of action 1 (right) will be `1 - p`."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2021-10-17 04:04:08 +02:00
"tf.keras.backend.clear_session()\n",
2019-05-26 17:30:39 +02:00
"tf.random.set_seed(42)\n",
"np.random.seed(42)\n",
"\n",
2019-05-26 17:30:39 +02:00
"n_inputs = 4 # == env.observation_space.shape[0]\n",
"\n",
2021-10-17 04:04:08 +02:00
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Dense(5, activation=\"elu\", input_shape=[n_inputs]),\n",
" tf.keras.layers.Dense(1, activation=\"sigmoid\"),\n",
2019-05-26 17:30:39 +02:00
"])"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"In this particular environment, the past actions and observations can safely be ignored, since each observation contains the environment's full state. If there were some hidden state then you may need to consider past actions and observations in order to try to infer the hidden state of the environment. For example, if the environment only revealed the position of the cart but not its velocity, you would have to consider not only the current observation but also the previous observation in order to estimate the current velocity. Another example is if the observations are noisy: you may want to use the past few observations to estimate the most likely current state. Our problem is thus as simple as can be: the current observation is noise-free and contains the environment's full state."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"You may wonder why we plan to pick a random action based on the probability given by the policy network, rather than just picking the action with the highest probability. This approach lets the agent find the right balance between _exploring_ new actions and _exploiting_ the actions that are known to work well. Here's an analogy: suppose you go to a restaurant for the first time, and all the dishes look equally appealing so you randomly pick one. If it turns out to be good, you can increase the probability to order it next time, but you shouldn't increase that probability to 100%, or else you will never try out the other dishes, some of which may be even better than the one you tried."
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Let's write a small function that will run the model to play one episode, and return the frames so we can display an animation:"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"def render_policy_net(model, n_max_steps=200, seed=42):\n",
" frames = []\n",
" env = gym.make(\"CartPole-v1\")\n",
" env.seed(seed)\n",
" np.random.seed(seed)\n",
" obs = env.reset()\n",
" for step in range(n_max_steps):\n",
" frames.append(env.render(mode=\"rgb_array\"))\n",
" left_proba = model.predict(obs.reshape(1, -1))\n",
" action = int(np.random.rand() > left_proba)\n",
" obs, reward, done, info = env.step(action)\n",
" if done:\n",
" break\n",
" env.close()\n",
" return frames"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Now let's look at how well this randomly initialized policy network performs:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"frames = render_policy_net(model)\n",
"plot_animation(frames)"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Yeah... pretty bad. The neural network will have to learn to do better. First let's see if it is capable of learning the basic policy we used earlier: go left if the pole is tilting left, and go right if it is tilting right."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"We can make the same net play in 50 different environments in parallel (this will give us a diverse training batch at each step), and train for 5000 iterations. We also reset environments when they are done. We train the model using a custom training loop so we can easily use the predictions at each training step to advance the environments."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"n_environments = 50\n",
"n_iterations = 5000\n",
"\n",
"envs = [gym.make(\"CartPole-v1\") for _ in range(n_environments)]\n",
"for index, env in enumerate(envs):\n",
" env.seed(index)\n",
"np.random.seed(42)\n",
"observations = [env.reset() for env in envs]\n",
2021-10-17 04:04:08 +02:00
"optimizer = tf.keras.optimizers.RMSprop()\n",
"loss_fn = tf.keras.losses.binary_crossentropy\n",
2019-05-26 17:30:39 +02:00
"\n",
"for iteration in range(n_iterations):\n",
" # if angle < 0, we want proba(left) = 1., or else proba(left) = 0.\n",
" target_probas = np.array([([1.] if obs[2] < 0 else [0.])\n",
" for obs in observations])\n",
" with tf.GradientTape() as tape:\n",
" left_probas = model(np.array(observations))\n",
" loss = tf.reduce_mean(loss_fn(target_probas, left_probas))\n",
" print(\"\\rIteration: {}, Loss: {:.3f}\".format(iteration, loss.numpy()), end=\"\")\n",
" grads = tape.gradient(loss, model.trainable_variables)\n",
" optimizer.apply_gradients(zip(grads, model.trainable_variables))\n",
" actions = (np.random.rand(n_environments, 1) > left_probas.numpy()).astype(np.int32)\n",
" for env_index, env in enumerate(envs):\n",
" obs, reward, done, info = env.step(actions[env_index][0])\n",
" observations[env_index] = obs if not done else env.reset()\n",
"\n",
"for env in envs:\n",
" env.close()"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"frames = render_policy_net(model)\n",
"plot_animation(frames)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Looks like it learned the policy correctly. Now let's see if it can learn a better policy on its own. One that does not wobble as much."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"# Policy Gradients"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"To train this neural network we will need to define the target probabilities `y`. If an action is good we should increase its probability, and conversely if it is bad we should reduce it. But how do we know whether an action is good or bad? The problem is that most actions have delayed effects, so when you win or lose points in an episode, it is not clear which actions contributed to this result: was it just the last action? Or the last 10? Or just one action 50 steps earlier? This is called the _credit assignment problem_.\n",
"\n",
"The _Policy Gradients_ algorithm tackles this problem by first playing multiple episodes, then making the actions in good episodes slightly more likely, while actions in bad episodes are made slightly less likely. First we play, then we go back and think about what we did."
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Let's start by creating a function to play a single step using the model. We will also pretend for now that whatever action it takes is the right one, so we can compute the loss and its gradients (we will just save these gradients for now, and modify them later depending on how good or bad the action turned out to be):"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"def play_one_step(env, obs, model, loss_fn):\n",
" with tf.GradientTape() as tape:\n",
" left_proba = model(obs[np.newaxis])\n",
" action = (tf.random.uniform([1, 1]) > left_proba)\n",
" y_target = tf.constant([[1.]]) - tf.cast(action, tf.float32)\n",
" loss = tf.reduce_mean(loss_fn(y_target, left_proba))\n",
" grads = tape.gradient(loss, model.trainable_variables)\n",
" obs, reward, done, info = env.step(int(action[0, 0].numpy()))\n",
" return obs, reward, done, grads"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"If `left_proba` is high, then `action` will most likely be `False` (since a random number uniformally sampled between 0 and 1 will probably not be greater than `left_proba`). And `False` means 0 when you cast it to a number, so `y_target` would be equal to 1 - 0 = 1. In other words, we set the target to 1, meaning we pretend that the probability of going left should have been 100% (so we took the right action)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Now let's create another function that will rely on the `play_one_step()` function to play multiple episodes, returning all the rewards and gradients, for each episode and each step:"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"def play_multiple_episodes(env, n_episodes, n_max_steps, model, loss_fn):\n",
" all_rewards = []\n",
" all_grads = []\n",
" for episode in range(n_episodes):\n",
" current_rewards = []\n",
" current_grads = []\n",
" obs = env.reset()\n",
" for step in range(n_max_steps):\n",
" obs, reward, done, grads = play_one_step(env, obs, model, loss_fn)\n",
" current_rewards.append(reward)\n",
" current_grads.append(grads)\n",
" if done:\n",
" break\n",
" all_rewards.append(current_rewards)\n",
" all_grads.append(current_grads)\n",
" return all_rewards, all_grads"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"The Policy Gradients algorithm uses the model to play the episode several times (e.g., 10 times), then it goes back and looks at all the rewards, discounts them and normalizes them. So let's create couple functions for that: the first will compute discounted rewards; the second will normalize the discounted rewards across many episodes."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"def discount_rewards(rewards, discount_rate):\n",
" discounted = np.array(rewards)\n",
" for step in range(len(rewards) - 2, -1, -1):\n",
" discounted[step] += discounted[step + 1] * discount_rate\n",
" return discounted\n",
"\n",
2019-05-26 17:30:39 +02:00
"def discount_and_normalize_rewards(all_rewards, discount_rate):\n",
" all_discounted_rewards = [discount_rewards(rewards, discount_rate)\n",
" for rewards in all_rewards]\n",
" flat_rewards = np.concatenate(all_discounted_rewards)\n",
" reward_mean = flat_rewards.mean()\n",
" reward_std = flat_rewards.std()\n",
" return [(discounted_rewards - reward_mean) / reward_std\n",
" for discounted_rewards in all_discounted_rewards]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Say there were 3 actions, and after each action there was a reward: first 10, then 0, then -50. If we use a discount factor of 80%, then the 3rd action will get -50 (full credit for the last reward), but the 2nd action will only get -40 (80% credit for the last reward), and the 1st action will get 80% of -40 (-32) plus full credit for the first reward (+10), which leads to a discounted reward of -22:"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"discount_rewards([10, 0, -50], discount_rate=0.8)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"To normalize all discounted rewards across all episodes, we compute the mean and standard deviation of all the discounted rewards, and we subtract the mean from each discounted reward, and divide by the standard deviation:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"discount_and_normalize_rewards([[10, 0, -50], [10, 20]], discount_rate=0.8)"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"n_iterations = 150\n",
"n_episodes_per_update = 10\n",
"n_max_steps = 200\n",
"discount_rate = 0.95"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2021-10-17 04:04:08 +02:00
"optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n",
"loss_fn = tf.keras.losses.binary_crossentropy"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2021-10-17 04:04:08 +02:00
"tf.keras.backend.clear_session()\n",
2019-05-26 17:30:39 +02:00
"np.random.seed(42)\n",
"tf.random.set_seed(42)\n",
"\n",
2021-10-17 04:04:08 +02:00
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Dense(5, activation=\"elu\", input_shape=[4]),\n",
" tf.keras.layers.Dense(1, activation=\"sigmoid\"),\n",
2019-05-26 17:30:39 +02:00
"])"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"env = gym.make(\"CartPole-v1\")\n",
"env.seed(42);\n",
"\n",
2019-05-26 17:30:39 +02:00
"for iteration in range(n_iterations):\n",
" all_rewards, all_grads = play_multiple_episodes(\n",
" env, n_episodes_per_update, n_max_steps, model, loss_fn)\n",
" total_rewards = sum(map(sum, all_rewards)) # Not shown in the book\n",
" print(\"\\rIteration: {}, mean rewards: {:.1f}\".format( # Not shown\n",
" iteration, total_rewards / n_episodes_per_update), end=\"\") # Not shown\n",
" all_final_rewards = discount_and_normalize_rewards(all_rewards,\n",
" discount_rate)\n",
" all_mean_grads = []\n",
" for var_index in range(len(model.trainable_variables)):\n",
" mean_grads = tf.reduce_mean(\n",
" [final_reward * all_grads[episode_index][step][var_index]\n",
" for episode_index, final_rewards in enumerate(all_final_rewards)\n",
" for step, final_reward in enumerate(final_rewards)], axis=0)\n",
" all_mean_grads.append(mean_grads)\n",
" optimizer.apply_gradients(zip(all_mean_grads, model.trainable_variables))\n",
"\n",
2019-05-26 17:30:39 +02:00
"env.close()"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"frames = render_policy_net(model)\n",
"plot_animation(frames)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"# Markov Chains"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"np.random.seed(42)\n",
"\n",
2019-05-26 17:30:39 +02:00
"transition_probabilities = [ # shape=[s, s']\n",
" [0.7, 0.2, 0.0, 0.1], # from s0 to s0, s1, s2, s3\n",
" [0.0, 0.0, 0.9, 0.1], # from s1 to ...\n",
" [0.0, 1.0, 0.0, 0.0], # from s2 to ...\n",
" [0.0, 0.0, 0.0, 1.0]] # from s3 to ...\n",
"\n",
2019-05-26 17:30:39 +02:00
"n_max_steps = 50\n",
"\n",
2019-05-26 17:30:39 +02:00
"def print_sequence():\n",
" current_state = 0\n",
" print(\"States:\", end=\" \")\n",
" for step in range(n_max_steps):\n",
" print(current_state, end=\" \")\n",
" if current_state == 3:\n",
" break\n",
" current_state = np.random.choice(range(4), p=transition_probabilities[current_state])\n",
" else:\n",
" print(\"...\", end=\"\")\n",
" print()\n",
"\n",
"for _ in range(10):\n",
" print_sequence()"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"# Markov Decision Process"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Let's define some transition probabilities, rewards and possible actions. For example, in state s0, if action a0 is chosen then with proba 0.7 we will go to state s0 with reward +10, with probability 0.3 we will go to state s1 with no reward, and with never go to state s2 (so the transition probabilities are `[0.7, 0.3, 0.0]`, and the rewards are `[+10, 0, 0]`):"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"transition_probabilities = [ # shape=[s, a, s']\n",
" [[0.7, 0.3, 0.0], [1.0, 0.0, 0.0], [0.8, 0.2, 0.0]],\n",
" [[0.0, 1.0, 0.0], None, [0.0, 0.0, 1.0]],\n",
" [None, [0.8, 0.1, 0.1], None]]\n",
"rewards = [ # shape=[s, a, s']\n",
" [[+10, 0, 0], [0, 0, 0], [0, 0, 0]],\n",
" [[0, 0, 0], [0, 0, 0], [0, 0, -50]],\n",
" [[0, 0, 0], [+40, 0, 0], [0, 0, 0]]]\n",
"possible_actions = [[0, 1, 2], [0, 2], [1]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"# Q-Value Iteration"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"Q_values = np.full((3, 3), -np.inf) # -np.inf for impossible actions\n",
"for state, actions in enumerate(possible_actions):\n",
" Q_values[state, actions] = 0.0 # for all possible actions"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"gamma = 0.90 # the discount factor\n",
"\n",
2019-05-26 17:30:39 +02:00
"history1 = [] # Not shown in the book (for the figure below)\n",
"for iteration in range(50):\n",
" Q_prev = Q_values.copy()\n",
" history1.append(Q_prev) # Not shown\n",
" for s in range(3):\n",
" for a in possible_actions[s]:\n",
" Q_values[s, a] = np.sum([\n",
" transition_probabilities[s][a][sp]\n",
2022-02-19 10:09:28 +01:00
" * (rewards[s][a][sp] + gamma * Q_prev[sp].max())\n",
2019-05-26 17:30:39 +02:00
" for sp in range(3)])\n",
"\n",
2019-05-26 17:30:39 +02:00
"history1 = np.array(history1) # Not shown"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"Q_values"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"Q_values.argmax(axis=1)"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The optimal policy for this MDP, when using a discount factor of 0.90, is to choose action a0 when in state s0, and choose action a0 when in state s1, and finally choose action a1 (the only possible action) when in state s2."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's try again with a discount factor of 0.95:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"Q_values = np.full((3, 3), -np.inf) # -np.inf for impossible actions\n",
"for state, actions in enumerate(possible_actions):\n",
" Q_values[state, actions] = 0.0 # for all possible actions"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"gamma = 0.95 # the discount factor\n",
"\n",
2019-05-26 17:30:39 +02:00
"for iteration in range(50):\n",
" Q_prev = Q_values.copy()\n",
" for s in range(3):\n",
" for a in possible_actions[s]:\n",
" Q_values[s, a] = np.sum([\n",
" transition_probabilities[s][a][sp]\n",
2022-02-19 10:09:28 +01:00
" * (rewards[s][a][sp] + gamma * Q_prev[sp].max())\n",
2019-05-26 17:30:39 +02:00
" for sp in range(3)])"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"Q_values"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"Q_values.argmax(axis=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"Now the policy has changed! In state s1, we now prefer to go through the fire (choose action a2). This is because the discount factor is larger so the agent values the future more, and it is therefore ready to pay an immediate penalty in order to get more future rewards."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Q-Learning"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Q-Learning works by watching an agent play (e.g., randomly) and gradually improving its estimates of the Q-Values. Once it has accurate Q-Value estimates (or close enough), then the optimal policy consists in choosing the action that has the highest Q-Value (i.e., the greedy policy)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will need to simulate an agent moving around in the environment, so let's define a function to perform some action and get the new state and a reward:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"def step(state, action):\n",
" probas = transition_probabilities[state][action]\n",
" next_state = np.random.choice([0, 1, 2], p=probas)\n",
" reward = rewards[state][action][next_state]\n",
" return next_state, reward"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We also need an exploration policy, which can be any policy, as long as it visits every possible state many times. We will just use a random policy, since the state space is very small:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"def exploration_policy(state):\n",
" return np.random.choice(possible_actions[state])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's initialize the Q-Values like earlier, and run the Q-Learning algorithm:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"np.random.seed(42)\n",
"\n",
2019-05-26 17:30:39 +02:00
"Q_values = np.full((3, 3), -np.inf)\n",
"for state, actions in enumerate(possible_actions):\n",
" Q_values[state][actions] = 0\n",
"\n",
2019-05-26 17:30:39 +02:00
"alpha0 = 0.05 # initial learning rate\n",
"decay = 0.005 # learning rate decay\n",
"gamma = 0.90 # discount factor\n",
"state = 0 # initial state\n",
"history2 = [] # Not shown in the book\n",
"\n",
2019-05-26 17:30:39 +02:00
"for iteration in range(10000):\n",
" history2.append(Q_values.copy()) # Not shown\n",
" action = exploration_policy(state)\n",
" next_state, reward = step(state, action)\n",
2022-02-19 10:09:28 +01:00
" next_value = Q_values[next_state].max() # greedy policy at the next step\n",
2019-05-26 17:30:39 +02:00
" alpha = alpha0 / (1 + iteration * decay)\n",
" Q_values[state, action] *= 1 - alpha\n",
" Q_values[state, action] += alpha * (reward + gamma * next_value)\n",
" state = next_state\n",
"\n",
"history2 = np.array(history2) # Not shown"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2019-05-26 17:30:39 +02:00
"Q_values"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"Q_values.argmax(axis=1) # optimal action for each state"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"true_Q_value = history1[-1, 0, 0]\n",
"\n",
2019-05-26 17:30:39 +02:00
"fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)\n",
"axes[0].set_ylabel(\"Q-Value$(s_0, a_0)$\", fontsize=14)\n",
"axes[0].set_title(\"Q-Value Iteration\", fontsize=14)\n",
"axes[1].set_title(\"Q-Learning\", fontsize=14)\n",
"for ax, width, history in zip(axes, (50, 10000), (history1, history2)):\n",
" ax.plot([0, width], [true_Q_value, true_Q_value], \"k--\")\n",
" ax.plot(np.arange(width), history[:, 0, 0], \"b-\", linewidth=2)\n",
" ax.set_xlabel(\"Iterations\", fontsize=14)\n",
" ax.axis([0, width, 0, 24])\n",
"\n",
"save_fig(\"q_value_plot\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"# Deep Q-Network"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's build the DQN. Given a state, it will estimate, for each possible action, the sum of discounted future rewards it can expect after it plays that action (but before it sees its outcome):"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-17 04:04:08 +02:00
"tf.keras.backend.clear_session()\n",
2019-05-26 17:30:39 +02:00
"tf.random.set_seed(42)\n",
"np.random.seed(42)\n",
"\n",
"env = gym.make(\"CartPole-v1\")\n",
"input_shape = [4] # == env.observation_space.shape\n",
"n_outputs = 2 # == env.action_space.n\n",
"\n",
2021-10-17 04:04:08 +02:00
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Dense(32, activation=\"elu\", input_shape=input_shape),\n",
" tf.keras.layers.Dense(32, activation=\"elu\"),\n",
" tf.keras.layers.Dense(n_outputs)\n",
2019-05-26 17:30:39 +02:00
"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2019-05-26 17:30:39 +02:00
"To select an action using this DQN, we just pick the action with the largest predicted Q-value. However, to ensure that the agent explores the environment, we choose a random action with probability `epsilon`."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"def epsilon_greedy_policy(state, epsilon=0):\n",
" if np.random.rand() < epsilon:\n",
" return np.random.randint(n_outputs)\n",
2019-05-26 17:30:39 +02:00
" else:\n",
" Q_values = model.predict(state[np.newaxis])\n",
2022-02-19 10:09:28 +01:00
" return Q_values[0].argmax()"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will also need a replay memory. It will contain the agent's experiences, in the form of tuples: `(obs, action, reward, next_obs, done)`. We can use the `deque` class for that (but make sure to check out DeepMind's excellent [Reverb library](https://github.com/deepmind/reverb) for a much more robust implementation of experience replay):"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"from collections import deque\n",
"\n",
"replay_memory = deque(maxlen=2000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And let's create a function to sample experiences from the replay memory. It will return 5 NumPy arrays: `[obs, actions, rewards, next_obs, dones]`."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"def sample_experiences(batch_size):\n",
" indices = np.random.randint(len(replay_memory), size=batch_size)\n",
" batch = [replay_memory[index] for index in indices]\n",
" states, actions, rewards, next_states, dones = [\n",
" np.array([experience[field_index] for experience in batch])\n",
" for field_index in range(5)]\n",
2019-05-26 17:30:39 +02:00
" return states, actions, rewards, next_states, dones"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can create a function that will use the DQN to play one step, and record its experience in the replay memory:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"def play_one_step(env, state, epsilon):\n",
" action = epsilon_greedy_policy(state, epsilon)\n",
" next_state, reward, done, info = env.step(action)\n",
" replay_memory.append((state, action, reward, next_state, done))\n",
" return next_state, reward, done, info"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lastly, let's create a function that will sample some experiences from the replay memory and perform a training step:\n",
"\n",
"**Notes**:\n",
"* The first 3 releases of the 2nd edition were missing the `reshape()` operation which converts `target_Q_values` to a column vector (this is required by the `loss_fn()`).\n",
"* The book uses a learning rate of 1e-3, but in the code below I use 1e-2, as it significantly improves training. I also tuned the learning rates of the DQN variants below."
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"batch_size = 32\n",
"discount_rate = 0.95\n",
2021-10-17 04:04:08 +02:00
"optimizer = tf.keras.optimizers.Adam(learning_rate=1e-2)\n",
"loss_fn = tf.keras.losses.mean_squared_error\n",
2019-05-26 17:30:39 +02:00
"\n",
"def training_step(batch_size):\n",
" experiences = sample_experiences(batch_size)\n",
" states, actions, rewards, next_states, dones = experiences\n",
" next_Q_values = model.predict(next_states)\n",
2022-02-19 10:09:28 +01:00
" max_next_Q_values = next_Q_values.max(axis=1)\n",
" target_Q_values = (rewards +\n",
" (1 - dones) * discount_rate * max_next_Q_values)\n",
" target_Q_values = target_Q_values.reshape(-1, 1)\n",
2019-05-26 17:30:39 +02:00
" mask = tf.one_hot(actions, n_outputs)\n",
" with tf.GradientTape() as tape:\n",
" all_Q_values = model(states)\n",
" Q_values = tf.reduce_sum(all_Q_values * mask, axis=1, keepdims=True)\n",
" loss = tf.reduce_mean(loss_fn(target_Q_values, Q_values))\n",
" grads = tape.gradient(loss, model.trainable_variables)\n",
" optimizer.apply_gradients(zip(grads, model.trainable_variables))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And now, let's train the model!"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"env.seed(42)\n",
"np.random.seed(42)\n",
"tf.random.set_seed(42)\n",
"\n",
"rewards = [] \n",
"best_score = 0"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"for episode in range(600):\n",
" obs = env.reset() \n",
" for step in range(200):\n",
" epsilon = max(1 - episode / 500, 0.01)\n",
" obs, reward, done, info = play_one_step(env, obs, epsilon)\n",
" if done:\n",
" break\n",
" rewards.append(step) # Not shown in the book\n",
" if step >= best_score: # Not shown\n",
2019-05-26 17:30:39 +02:00
" best_weights = model.get_weights() # Not shown\n",
" best_score = step # Not shown\n",
" print(\"\\rEpisode: {}, Steps: {}, eps: {:.3f}\".format(episode, step + 1, epsilon), end=\"\") # Not shown\n",
" if episode > 50:\n",
" training_step(batch_size)\n",
"\n",
"model.set_weights(best_weights)"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(8, 4))\n",
"plt.plot(rewards)\n",
"plt.xlabel(\"Episode\", fontsize=14)\n",
"plt.ylabel(\"Sum of rewards\", fontsize=14)\n",
"save_fig(\"dqn_rewards_plot\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"env.seed(42)\n",
"state = env.reset()\n",
"\n",
"frames = []\n",
"\n",
"for step in range(200):\n",
" action = epsilon_greedy_policy(state)\n",
" state, reward, done, info = env.step(action)\n",
" if done:\n",
" break\n",
" img = env.render(mode=\"rgb_array\")\n",
" frames.append(img)\n",
" \n",
"plot_animation(frames)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Not bad at all! 😀"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Double DQN"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-17 04:04:08 +02:00
"tf.keras.backend.clear_session()\n",
2019-05-26 17:30:39 +02:00
"tf.random.set_seed(42)\n",
"np.random.seed(42)\n",
"\n",
2021-10-17 04:04:08 +02:00
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Dense(32, activation=\"elu\", input_shape=[4]),\n",
" tf.keras.layers.Dense(32, activation=\"elu\"),\n",
" tf.keras.layers.Dense(n_outputs)\n",
2019-05-26 17:30:39 +02:00
"])\n",
"\n",
2021-10-17 04:04:08 +02:00
"target = tf.keras.models.clone_model(model)\n",
2019-05-26 17:30:39 +02:00
"target.set_weights(model.get_weights())"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"batch_size = 32\n",
"discount_rate = 0.95\n",
2021-10-17 04:04:08 +02:00
"optimizer = tf.keras.optimizers.Adam(learning_rate=6e-3)\n",
"loss_fn = tf.keras.losses.Huber()\n",
2019-05-26 17:30:39 +02:00
"\n",
"def training_step(batch_size):\n",
" experiences = sample_experiences(batch_size)\n",
" states, actions, rewards, next_states, dones = experiences\n",
" next_Q_values = model.predict(next_states)\n",
2022-02-19 10:09:28 +01:00
" best_next_actions = next_Q_values.argmax(axis=1)\n",
2019-05-26 17:30:39 +02:00
" next_mask = tf.one_hot(best_next_actions, n_outputs).numpy()\n",
" next_best_Q_values = (target.predict(next_states) * next_mask).sum(axis=1)\n",
" target_Q_values = (rewards + \n",
" (1 - dones) * discount_rate * next_best_Q_values)\n",
" target_Q_values = target_Q_values.reshape(-1, 1)\n",
2019-05-26 17:30:39 +02:00
" mask = tf.one_hot(actions, n_outputs)\n",
" with tf.GradientTape() as tape:\n",
" all_Q_values = model(states)\n",
" Q_values = tf.reduce_sum(all_Q_values * mask, axis=1, keepdims=True)\n",
" loss = tf.reduce_mean(loss_fn(target_Q_values, Q_values))\n",
" grads = tape.gradient(loss, model.trainable_variables)\n",
" optimizer.apply_gradients(zip(grads, model.trainable_variables))"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"replay_memory = deque(maxlen=2000)"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"env.seed(42)\n",
"np.random.seed(42)\n",
"tf.random.set_seed(42)\n",
"\n",
"rewards = []\n",
"best_score = 0\n",
"\n",
"for episode in range(600):\n",
" obs = env.reset() \n",
" for step in range(200):\n",
" epsilon = max(1 - episode / 500, 0.01)\n",
" obs, reward, done, info = play_one_step(env, obs, epsilon)\n",
" if done:\n",
" break\n",
" rewards.append(step)\n",
" if step >= best_score:\n",
2019-05-26 17:30:39 +02:00
" best_weights = model.get_weights()\n",
" best_score = step\n",
" print(\"\\rEpisode: {}, Steps: {}, eps: {:.3f}\".format(episode, step + 1, epsilon), end=\"\")\n",
" if episode >= 50:\n",
2019-05-26 17:30:39 +02:00
" training_step(batch_size)\n",
" if episode % 50 == 0:\n",
" target.set_weights(model.get_weights())\n",
2019-05-26 17:30:39 +02:00
" # Alternatively, you can do soft updates at each step:\n",
" #if episode >= 50:\n",
2019-05-26 17:30:39 +02:00
" #target_weights = target.get_weights()\n",
" #online_weights = model.get_weights()\n",
" #for index in range(len(target_weights)):\n",
" # target_weights[index] = 0.99 * target_weights[index] + 0.01 * online_weights[index]\n",
2019-05-26 17:30:39 +02:00
" #target.set_weights(target_weights)\n",
"\n",
"model.set_weights(best_weights)"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(8, 4))\n",
"plt.plot(rewards)\n",
"plt.xlabel(\"Episode\", fontsize=14)\n",
"plt.ylabel(\"Sum of rewards\", fontsize=14)\n",
"save_fig(\"double_dqn_rewards_plot\")\n",
2019-05-26 17:30:39 +02:00
"plt.show()"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"env.seed(43)\n",
2019-05-26 17:30:39 +02:00
"state = env.reset()\n",
"\n",
"frames = []\n",
"\n",
"for step in range(200):\n",
" action = epsilon_greedy_policy(state)\n",
" state, reward, done, info = env.step(action)\n",
" if done:\n",
" break\n",
" img = env.render(mode=\"rgb_array\")\n",
" frames.append(img)\n",
" \n",
2019-05-26 17:30:39 +02:00
"plot_animation(frames)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Dueling Double DQN"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-17 04:04:08 +02:00
"tf.keras.backend.clear_session()\n",
2019-05-26 17:30:39 +02:00
"tf.random.set_seed(42)\n",
"np.random.seed(42)\n",
"\n",
2021-10-17 04:04:08 +02:00
"K = tf.keras.backend\n",
"input_states = tf.keras.layers.Input(shape=[4])\n",
"hidden1 = tf.keras.layers.Dense(32, activation=\"elu\")(input_states)\n",
"hidden2 = tf.keras.layers.Dense(32, activation=\"elu\")(hidden1)\n",
"state_values = tf.keras.layers.Dense(1)(hidden2)\n",
"raw_advantages = tf.keras.layers.Dense(n_outputs)(hidden2)\n",
2019-05-26 17:30:39 +02:00
"advantages = raw_advantages - K.max(raw_advantages, axis=1, keepdims=True)\n",
"Q_values = state_values + advantages\n",
2021-10-17 04:04:08 +02:00
"model = tf.keras.Model(inputs=[input_states], outputs=[Q_values])\n",
2019-05-26 17:30:39 +02:00
"\n",
2021-10-17 04:04:08 +02:00
"target = tf.keras.models.clone_model(model)\n",
2019-05-26 17:30:39 +02:00
"target.set_weights(model.get_weights())"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"batch_size = 32\n",
"discount_rate = 0.95\n",
2021-10-17 04:04:08 +02:00
"optimizer = tf.keras.optimizers.Adam(learning_rate=7.5e-3)\n",
"loss_fn = tf.keras.losses.Huber()\n",
2019-05-26 17:30:39 +02:00
"\n",
"def training_step(batch_size):\n",
" experiences = sample_experiences(batch_size)\n",
" states, actions, rewards, next_states, dones = experiences\n",
" next_Q_values = model.predict(next_states)\n",
2022-02-19 10:09:28 +01:00
" best_next_actions = next_Q_values.argmax(axis=1)\n",
2019-05-26 17:30:39 +02:00
" next_mask = tf.one_hot(best_next_actions, n_outputs).numpy()\n",
" next_best_Q_values = (target.predict(next_states) * next_mask).sum(axis=1)\n",
" target_Q_values = (rewards + \n",
" (1 - dones) * discount_rate * next_best_Q_values)\n",
" target_Q_values = target_Q_values.reshape(-1, 1)\n",
2019-05-26 17:30:39 +02:00
" mask = tf.one_hot(actions, n_outputs)\n",
" with tf.GradientTape() as tape:\n",
" all_Q_values = model(states)\n",
" Q_values = tf.reduce_sum(all_Q_values * mask, axis=1, keepdims=True)\n",
" loss = tf.reduce_mean(loss_fn(target_Q_values, Q_values))\n",
" grads = tape.gradient(loss, model.trainable_variables)\n",
" optimizer.apply_gradients(zip(grads, model.trainable_variables))"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"replay_memory = deque(maxlen=2000)"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"env.seed(42)\n",
"np.random.seed(42)\n",
"tf.random.set_seed(42)\n",
"\n",
"rewards = []\n",
"best_score = 0\n",
"\n",
"for episode in range(600):\n",
" obs = env.reset() \n",
" for step in range(200):\n",
" epsilon = max(1 - episode / 500, 0.01)\n",
" obs, reward, done, info = play_one_step(env, obs, epsilon)\n",
" if done:\n",
" break\n",
" rewards.append(step)\n",
" if step >= best_score:\n",
2019-05-26 17:30:39 +02:00
" best_weights = model.get_weights()\n",
" best_score = step\n",
" print(\"\\rEpisode: {}, Steps: {}, eps: {:.3f}\".format(episode, step + 1, epsilon), end=\"\")\n",
" if episode >= 50:\n",
2019-05-26 17:30:39 +02:00
" training_step(batch_size)\n",
" if episode % 50 == 0:\n",
" target.set_weights(model.get_weights())\n",
2019-05-26 17:30:39 +02:00
"\n",
"model.set_weights(best_weights)"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"plt.plot(rewards)\n",
"plt.xlabel(\"Episode\")\n",
"plt.ylabel(\"Sum of rewards\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"env.seed(42)\n",
"state = env.reset()\n",
"\n",
"frames = []\n",
"\n",
"for step in range(200):\n",
" action = epsilon_greedy_policy(state)\n",
" state, reward, done, info = env.step(action)\n",
" if done:\n",
" break\n",
" img = env.render(mode=\"rgb_array\")\n",
" frames.append(img)\n",
" \n",
"plot_animation(frames)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This looks like a pretty robust agent!"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"env.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"# Exercise Solutions"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"## 1. to 7."
2019-05-26 17:30:39 +02:00
]
},
2021-10-18 01:54:17 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"1. Reinforcement Learning is an area of Machine Learning aimed at creating agents capable of taking actions in an environment in a way that maximizes rewards over time. There are many differences between RL and regular supervised and unsupervised learning. Here are a few:\n",
" * In supervised and unsupervised learning, the goal is generally to find patterns in the data and use them to make predictions. In Reinforcement Learning, the goal is to find a good policy.\n",
" * Unlike in supervised learning, the agent is not explicitly given the \"right\" answer. It must learn by trial and error.\n",
" * Unlike in unsupervised learning, there is a form of supervision, through rewards. We do not tell the agent how to perform the task, but we do tell it when it is making progress or when it is failing.\n",
" * A Reinforcement Learning agent needs to find the right balance between exploring the environment, looking for new ways of getting rewards, and exploiting sources of rewards that it already knows. In contrast, supervised and unsupervised learning systems generally don't need to worry about exploration; they just feed on the training data they are given.\n",
" * In supervised and unsupervised learning, training instances are typically independent (in fact, they are generally shuffled). In Reinforcement Learning, consecutive observations are generally _not_ independent. An agent may remain in the same region of the environment for a while before it moves on, so consecutive observations will be very correlated. In some cases a replay memory (buffer) is used to ensure that the training algorithm gets fairly independent observations.\n",
"2. Here are a few possible applications of Reinforcement Learning, other than those mentioned in Chapter 18:\n",
" * Music personalization: The environment is a user's personalized web radio. The agent is the software deciding what song to play next for that user. Its possible actions are to play any song in the catalog (it must try to choose a song the user will enjoy) or to play an advertisement (it must try to choose an ad that the user will be interested in). It gets a small reward every time the user listens to a song, a larger reward every time the user listens to an ad, a negative reward when the user skips a song or an ad, and a very negative reward if the user leaves.\n",
" * Marketing: The environment is your company's marketing department. The agent is the software that defines which customers a mailing campaign should be sent to, given their profile and purchase history (for each customer it has two possible actions: send or don't send). It gets a negative reward for the cost of the mailing campaign, and a positive reward for estimated revenue generated from this campaign.\n",
" * Product delivery: Let the agent control a fleet of delivery trucks, deciding what they should pick up at the depots, where they should go, what they should drop off, and so on. It will get positive rewards for each product delivered on time, and negative rewards for late deliveries.\n",
"3. When estimating the value of an action, Reinforcement Learning algorithms typically sum all the rewards that this action led to, giving more weight to immediate rewards and less weight to later rewards (considering that an action has more influence on the near future than on the distant future). To model this, a discount factor is typically applied at each time step. For example, with a discount factor of 0.9, a reward of 100 that is received two time steps later is counted as only 0.9<sup>2</sup> × 100 = 81 when you are estimating the value of the action. You can think of the discount factor as a measure of how much the future is valued relative to the present: if it is very close to 1, then the future is valued almost as much as the present; if it is close to 0, then only immediate rewards matter. Of course, this impacts the optimal policy tremendously: if you value the future, you may be willing to put up with a lot of immediate pain for the prospect of eventual rewards, while if you don't value the future, you will just grab any immediate reward you can find, never investing in the future.\n",
"4. To measure the performance of a Reinforcement Learning agent, you can simply sum up the rewards it gets. In a simulated environment, you can run many episodes and look at the total rewards it gets on average (and possibly look at the min, max, standard deviation, and so on).\n",
"5. The credit assignment problem is the fact that when a Reinforcement Learning agent receives a reward, it has no direct way of knowing which of its previous actions contributed to this reward. It typically occurs when there is a large delay between an action and the resulting reward (e.g., during a game of Atari's _Pong_, there may be a few dozen time steps between the moment the agent hits the ball and the moment it wins the point). One way to alleviate it is to provide the agent with shorter-term rewards, when possible. This usually requires prior knowledge about the task. For example, if we want to build an agent that will learn to play chess, instead of giving it a reward only when it wins the game, we could give it a reward every time it captures one of the opponent's pieces.\n",
"6. An agent can often remain in the same region of its environment for a while, so all of its experiences will be very similar for that period of time. This can introduce some bias in the learning algorithm. It may tune its policy for this region of the environment, but it will not perform well as soon as it moves out of this region. To solve this problem, you can use a replay memory; instead of using only the most immediate experiences for learning, the agent will learn based on a buffer of its past experiences, recent and not so recent (perhaps this is why we dream at night: to replay our experiences of the day and better learn from them?).\n",
"7. An off-policy RL algorithm learns the value of the optimal policy (i.e., the sum of discounted rewards that can be expected for each state if the agent acts optimally) while the agent follows a different policy. Q-Learning is a good example of such an algorithm. In contrast, an on-policy algorithm learns the value of the policy that the agent actually executes, including both exploration and exploitation."
2021-10-18 01:54:17 +02:00
]
},
{
2022-02-19 10:09:28 +01:00
"cell_type": "markdown",
2021-10-18 01:54:17 +02:00
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"## 8.\n",
"_Exercise: Use policy gradients to solve OpenAI Gym's LunarLander-v2 environment. You will need to install the Box2D dependencies (`%pip install -U gym[box2d]`)._"
2021-10-18 01:54:17 +02:00
]
},
2019-05-26 17:30:39 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"Let's start by creating a LunarLander-v2 environment:"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"env = gym.make(\"LunarLander-v2\")"
2019-05-26 17:30:39 +02:00
]
},
{
2022-02-19 10:09:28 +01:00
"cell_type": "markdown",
2019-05-26 17:30:39 +02:00
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"The inputs are 8-dimensional:"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"env.observation_space"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
"env.seed(42)\n",
2022-02-19 10:09:28 +01:00
"obs = env.reset()\n",
"obs"
2019-05-26 17:30:39 +02:00
]
},
{
2022-02-19 10:09:28 +01:00
"cell_type": "markdown",
2019-05-26 17:30:39 +02:00
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"From the [source code](https://github.com/openai/gym/blob/master/gym/envs/box2d/lunar_lander.py), we can see that these each 8D observation (x, y, h, v, a, w, l, r) correspond to:\n",
"* x,y: the coordinates of the spaceship. It starts at a random location near (0, 1.4) and must land near the target at (0, 0).\n",
"* h,v: the horizontal and vertical speed of the spaceship. It starts with a small random speed.\n",
"* a,w: the spaceship's angle and angular velocity.\n",
"* l,r: whether the left or right leg touches the ground (1.0) or not (0.0)."
2019-05-26 17:30:39 +02:00
]
},
{
2022-02-19 10:09:28 +01:00
"cell_type": "markdown",
2019-05-26 17:30:39 +02:00
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"The action space is discrete, with 4 possible actions:"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"env.action_space"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"Looking at the [LunarLander-v2's description](https://gym.openai.com/envs/LunarLander-v2/), these actions are:\n",
"* do nothing\n",
"* fire left orientation engine\n",
"* fire main engine\n",
"* fire right orientation engine"
2019-05-26 17:30:39 +02:00
]
},
{
2022-02-19 10:09:28 +01:00
"cell_type": "markdown",
2019-05-26 17:30:39 +02:00
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"Let's create a simple policy network with 4 output neurons (one per possible action):"
2019-05-26 17:30:39 +02:00
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
2019-05-26 17:30:39 +02:00
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"tf.keras.backend.clear_session()\n",
"np.random.seed(42)\n",
"tf.random.set_seed(42)\n",
"\n",
"n_inputs = env.observation_space.shape[0]\n",
"n_outputs = env.action_space.n\n",
"\n",
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Dense(32, activation=\"relu\", input_shape=[n_inputs]),\n",
" tf.keras.layers.Dense(32, activation=\"relu\"),\n",
" tf.keras.layers.Dense(n_outputs, activation=\"softmax\"),\n",
"])"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"Note that we're using the softmax activation function in the output layer, instead of the sigmoid activation function \n",
"like we did for the CartPole-v1 environment. This is because we only had two possible actions for the CartPole-v1 environment, so a binary classification model worked fine. However, since we now how more than two possible actions, we need a multiclass classification model."
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"Next, let's reuse the `play_one_step()` and `play_multiple_episodes()` functions we defined for the CartPole-v1 Policy Gradient code above, but we'll just tweak the `play_one_step()` function to account for the fact that the model is now a multiclass classification model rather than a binary classification model. We'll also tweak the `play_multiple_episodes()` function to call our tweaked `play_one_step()` function rather than the original one, and we add a big penalty if the spaceship does not land (or crash) before a maximum number of steps."
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"def lander_play_one_step(env, obs, model, loss_fn):\n",
" with tf.GradientTape() as tape:\n",
" probas = model(obs[np.newaxis])\n",
" logits = tf.math.log(probas + tf.keras.backend.epsilon())\n",
" action = tf.random.categorical(logits, num_samples=1)\n",
" loss = tf.reduce_mean(loss_fn(action, probas))\n",
" grads = tape.gradient(loss, model.trainable_variables)\n",
" obs, reward, done, info = env.step(action[0, 0].numpy())\n",
" return obs, reward, done, grads\n",
2019-05-26 17:30:39 +02:00
"\n",
2022-02-19 10:09:28 +01:00
"def lander_play_multiple_episodes(env, n_episodes, n_max_steps, model, loss_fn):\n",
" all_rewards = []\n",
" all_grads = []\n",
" for episode in range(n_episodes):\n",
" current_rewards = []\n",
" current_grads = []\n",
" obs = env.reset()\n",
" for step in range(n_max_steps):\n",
" obs, reward, done, grads = lander_play_one_step(env, obs, model, loss_fn)\n",
" current_rewards.append(reward)\n",
" current_grads.append(grads)\n",
" if done:\n",
" break\n",
" all_rewards.append(current_rewards)\n",
" all_grads.append(current_grads)\n",
" return all_rewards, all_grads"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"We'll keep exactly the same `discount_rewards()` and `discount_and_normalize_rewards()` functions as earlier:"
]
},
{
2019-05-26 17:30:39 +02:00
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
2019-05-26 17:30:39 +02:00
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"def discount_rewards(rewards, discount_rate):\n",
" discounted = np.array(rewards)\n",
" for step in range(len(rewards) - 2, -1, -1):\n",
" discounted[step] += discounted[step + 1] * discount_rate\n",
" return discounted\n",
"\n",
2022-02-19 10:09:28 +01:00
"def discount_and_normalize_rewards(all_rewards, discount_rate):\n",
" all_discounted_rewards = [discount_rewards(rewards, discount_rate)\n",
" for rewards in all_rewards]\n",
" flat_rewards = np.concatenate(all_discounted_rewards)\n",
" reward_mean = flat_rewards.mean()\n",
" reward_std = flat_rewards.std()\n",
" return [(discounted_rewards - reward_mean) / reward_std\n",
" for discounted_rewards in all_discounted_rewards]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"Now let's define some hyperparameters:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"n_iterations = 200\n",
"n_episodes_per_update = 16\n",
"n_max_steps = 1000\n",
"discount_rate = 0.99"
]
},
{
2022-02-19 10:09:28 +01:00
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"Again, since the model is a multiclass classification model, we must use the categorical cross-entropy rather than the binary cross-entropy. Moreover, since the `lander_play_one_step()` function sets the targets as class indices rather than class probabilities, we must use the `sparse_categorical_crossentropy()` loss function:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"optimizer = tf.keras.optimizers.Nadam(learning_rate=0.005)\n",
"loss_fn = tf.keras.losses.sparse_categorical_crossentropy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"We're ready to train the model. Let's go!"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
2022-02-19 10:09:28 +01:00
"env.seed(42)\n",
"\n",
2022-02-19 10:09:28 +01:00
"mean_rewards = []\n",
"\n",
"for iteration in range(n_iterations):\n",
" all_rewards, all_grads = lander_play_multiple_episodes(\n",
" env, n_episodes_per_update, n_max_steps, model, loss_fn)\n",
" mean_reward = sum(map(sum, all_rewards)) / n_episodes_per_update\n",
" print(\"\\rIteration: {}/{}, mean reward: {:.1f} \".format(\n",
" iteration + 1, n_iterations, mean_reward), end=\"\")\n",
" mean_rewards.append(mean_reward)\n",
" all_final_rewards = discount_and_normalize_rewards(all_rewards,\n",
" discount_rate)\n",
" all_mean_grads = []\n",
" for var_index in range(len(model.trainable_variables)):\n",
" mean_grads = tf.reduce_mean(\n",
" [final_reward * all_grads[episode_index][step][var_index]\n",
" for episode_index, final_rewards in enumerate(all_final_rewards)\n",
" for step, final_reward in enumerate(final_rewards)], axis=0)\n",
" all_mean_grads.append(mean_grads)\n",
" optimizer.apply_gradients(zip(all_mean_grads, model.trainable_variables))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's look at the learning curve:"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"plt.plot(mean_rewards)\n",
"plt.xlabel(\"Episode\")\n",
"plt.ylabel(\"Mean reward\")\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's look at the result!"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def lander_render_policy_net(model, n_max_steps=500, seed=42):\n",
" frames = []\n",
" env = gym.make(\"LunarLander-v2\")\n",
" env.seed(seed)\n",
" tf.random.set_seed(seed)\n",
" np.random.seed(seed)\n",
" obs = env.reset()\n",
" for step in range(n_max_steps):\n",
" frames.append(env.render(mode=\"rgb_array\"))\n",
" probas = model(obs[np.newaxis])\n",
2021-10-17 04:04:08 +02:00
" logits = tf.math.log(probas + tf.keras.backend.epsilon())\n",
" action = tf.random.categorical(logits, num_samples=1)\n",
" obs, reward, done, info = env.step(action[0, 0].numpy())\n",
" if done:\n",
" break\n",
" env.close()\n",
" return frames"
]
},
{
"cell_type": "code",
2022-02-19 10:09:28 +01:00
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"frames = lander_render_policy_net(model, seed=42)\n",
"plot_animation(frames)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That's pretty good. You can try training it for longer and/or tweaking the hyperparameters to see if you can get it to go over 200."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Moreover, you should always ensure that the preprocessed images contain enough information to play the game. For example, the blasts from the laser cannon and from the aliens should still be visible despite the limited resolution. In this particular case, the preprocessing we did for Breakout still works fine for Space Invaders, but that's something you should always check if you want try other games. To do this, you can let the agent play randomly for a while, and record the preprocessed frames, then play the animation and ensure the game still looks playable.\n",
"\n",
"You will also need to let the agent train for quite a long time to get good performance. Sadly, the DQN algorithm is not able to reach superhuman level on Space Invaders, likely because humans are able to learn efficient long term strategies in this game, whereas DQN can only master fairly short strategies. But there has been a lot of progress over the past few years, and now many other RL algorithms are able to surpass human experts at this game. Check out the [State-of-the-Art for Space Invaders on paperswithcode.com](https://paperswithcode.com/sota/atari-games-on-atari-2600-space-invaders)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2022-02-19 10:09:28 +01:00
"## 9.\n",
"_Exercise: If you have about $100 to spare, you can purchase a Raspberry Pi 3 plus some cheap robotics components, install TensorFlow on the Pi, and go wild! For an example, check out this [fun post](https://homl.info/2) by Lukas Biewald, or take a look at GoPiGo or BrickPi. Start with simple goals, like making the robot turn around to find the brightest angle (if it has a light sensor) or the closest object (if it has a sonar sensor), and move in that direction. Then you can start using Deep Learning: for example, if the robot has a camera, you can try to implement an object detection algorithm so it detects people and moves toward them. You can also try to use RL to make the agent learn on its own how to use the motors to achieve that goal. Have fun!_"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It's your turn now: go crazy, be creative, but most of all, be patient and move forward step by step, you can do it!"
]
}
],
"metadata": {
2022-02-19 10:09:28 +01:00
"interpreter": {
"hash": "95c485e91159f3a8b550e08492cb4ed2557284663e79130c96242e7ff9e65ae1"
},
"kernelspec": {
2022-02-19 10:09:28 +01:00
"display_name": "Python 3",
"language": "python",
2022-02-19 10:09:28 +01:00
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
2016-11-25 09:34:55 +01:00
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
2016-11-25 09:34:55 +01:00
"pygments_lexer": "ipython3",
2021-10-17 03:27:34 +02:00
"version": "3.8.12"
}
},
"nbformat": 4,
2021-10-17 08:21:13 +02:00
"nbformat_minor": 4
}