You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ML-For-Beginners/8-Reinforcement/1-QLearning/notebook.ipynb

404 lines
291 KiB

{
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.0"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python3",
"display_name": "Python 3.7.0 64-bit ('3.7')"
},
"interpreter": {
"hash": "70b38d7a306a849643e446cd70466270a13445e5987dfa1344ef2b127438fa4d"
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"source": [
"# Peter and the Wolf: Reinforcement Learning Primer\n",
"\n",
"In this tutorial, we will learn how to apply Reinforcement learning to a problem of path finding. The setting is inspired by [Peter and the Wolf](https://en.wikipedia.org/wiki/Peter_and_the_Wolf) musical fairy tale by Russian composer [Sergei Prokofiev](https://en.wikipedia.org/wiki/Sergei_Prokofiev). It is a story about young pioneer Peter, who bravely goes out of his house to the forest clearing to chase a wolf. We will train machine learning algorithms that will help Peter to explore the surrounding area and build an optimal navigation map.\n",
"\n",
"First, let's import a bunch of useful libraries:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import random\n",
"import math"
]
},
{
"source": [
"## Overview of Reinforcement Learning\n",
"\n",
"**Reinforcement Learning** (RL) is a learning technique that allows us to learn an optimal behaviour of an **agent** in some **environment** by running many experiments. An agent in this environment should have some **goal**, defined by a **reward function**.\n",
"\n",
"## The Environment\n",
"\n",
"For simplicity, let's consider Peter's world to be a square board of size `width` x `height`. Each cell in this board can either be:\n",
"* **ground**, on which Peter and other creatures can walk\n",
"* **water**, on which you obviously cannot walk\n",
"* **a tree** or **grass** - a place where you can rest\n",
"* **an apple**, which represents something Peter would be glad to find in order to feed himself\n",
"* **a wolf**, which is dangerous and should be avoided\n",
"\n",
"To work with the environment, we will define a class called `Board`. In order not to clutter this notebook too much, we have moved all code to work with the board into separate `rlboard` module, which we will now import. You may look inside this module to get more details about the internals of the implementation."
],
"cell_type": "markdown",
"metadata": {}
},
{
"source": [
"Let's now create a random board and see how it looks:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# code block 1"
]
},
{
"source": [
"## Actions and Policy\n",
"\n",
"In our example, Peter's goal would be to find an apple, while avoiding the wolf and other obstacles. Define those actions as a dictionary, and map them to pairs of corresponding coordinate changes."
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"# code block 2"
]
},
{
"source": [
"The strategy of our agent (Peter) is defined by a so-called **policy**. Let's consider the simplest policy called **random walk**.\n",
"\n",
"## Random walk\n",
"\n",
"Let's first solve our problem by implementing a random walk strategy."
],
"cell_type": "markdown",
"metadata": {}
},
{
"source": [
"# Let's run a random walk experiment several times and see the average number of steps taken: code block 3"
],
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"# code block 4"
]
},
{
"source": [
"## Reward Function\n",
"\n",
"To make our policy more intelligent, we need to understand which moves are \"better\" than others.\n",
"\n"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"#code block 5"
]
},
{
"source": [
"## Q-Learning\n",
"\n",
"Build a Q-Table, or multi-dimensional array. Since our board has dimentions `width` x `height`, we can represent Q-Table by a numpy array with shape `width` x `height` x `len(actions)`:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"# code block 6"
]
},
{
"source": [
"Pass the Q-Table to the `plot` function in order to visualize the table on the board:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"output_type": "error",
"ename": "NameError",
"evalue": "name 'm' is not defined",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-10-8b8a9e4cb2b8>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mm\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mplot\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mQ\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'm' is not defined"
]
}
],
"source": [
"m.plot(Q)"
]
},
{
"source": [
"\n",
"## Essence of Q-Learning: Bellman Equation and Learning Algorithm\n",
"\n",
"Write a pseudo-code for our leaning algorithm:\n",
"\n",
"* Initialize Q-Table Q with equal numbers for all states and actions\n",
"* Set learning rate $\\alpha\\leftarrow 1$\n",
"* Repeat simulation many times\n",
" 1. Start at random position\n",
" 1. Repeat\n",
" 1. Select an action $a$ at state $s$\n",
" 2. Exectute action by moving to a new state $s'$\n",
" 3. If we encounter end-of-game condition, or total reward is too small - exit simulation \n",
" 4. Compute reward $r$ at the new state\n",
" 5. Update Q-Function according to Bellman equation: $Q(s,a)\\leftarrow (1-\\alpha)Q(s,a)+\\alpha(r+\\gamma\\max_{a'}Q(s',a'))$\n",
" 6. $s\\leftarrow s'$\n",
" 7. Update total reward and decrease $\\alpha$.\n",
"\n",
"## Exploit vs. Explore\n",
"\n",
"The best approach is to balance between exploration and exploitation. As we learn more about our environment, we would be more likely to follow the optimal route, however, choosing the unexplored path once in a while.\n",
"\n",
"## Python Implementation\n",
"\n",
"Now we are ready to implement the learning algorithm. Before that, we also need some function that will convert arbitrary numbers in the Q-Table into a vector of probabilities for corresponding actions:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"# code block 7"
]
},
{
"source": [
"We add a small amount of `eps` to the original vector in order to avoid division by 0 in the initial case, when all components of the vector are identical.\n",
"\n",
"The actual learning algorithm we will run for 5000 experiments, also called **epochs**: "
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
""
]
}
],
"source": [
"\n",
"from IPython.display import clear_output\n",
"\n",
"lpath = []\n",
"\n",
"# code block 8"
]
},
{
"source": [
"After executing this algorithm, the Q-Table should be updated with values that define the attractiveness of different actions at each step. Visualize the table here:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": "<Figure size 792x432 with 1 Axes>",
"image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\r\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\r\n \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\r\n<!-- Created with matplotlib (https://matplotlib.org/) -->\r\n<svg height=\"360.646265pt\" version=\"1.1\" viewBox=\"0 0 366.6475 360.646265\" width=\"366.6475pt\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\r\n <defs>\r\n <style type=\"text/css\">\r\n*{stroke-linecap:butt;stroke-linejoin:round;white-space:pre;}\r\n </style>\r\n </defs>\r\n <g id=\"figure_1\">\r\n <g id=\"patch_1\">\r\n <path d=\"M 0 360.646265 \r\nL 366.6475 360.646265 \r\nL 366.6475 0 \r\nL 0 0 \r\nz\r\n\" style=\"fill:none;\"/>\r\n </g>\r\n <g id=\"axes_1\">\r\n <g id=\"patch_2\">\r\n <path d=\"M 33.2875 336.76814 \r\nL 359.4475 336.76814 \r\nL 359.4475 10.60814 \r\nL 33.2875 10.60814 \r\nz\r\n\" style=\"fill:#ffffff;\"/>\r\n </g>\r\n <g clip-path=\"url(#p03670b802c)\">\r\n <image height=\"327\" id=\"imagefd2c98b8a1\" transform=\"scale(1 -1)translate(0 -327)\" width=\"327\" x=\"33.2875\" xlink:href=\"data:image/png;base64,\r\niVBORw0KGgoAAAANSUhEUgAAAUcAAAFHCAYAAAAySY5rAAAABHNCSVQICAgIfAhkiAAAIABJREFUeJzsnXecU1X6/9+3JTd1KgwgvQwoqFQVCwrq2gvfdeG3q+KKqIAFBLGsrgosrGCBXbGsK/ZVXBsqWHARBAELoiJN6b1Mn0x67j2/PzK5MjrYyExmnPvWvMLk3pzz5Cb55JzzPOd5pP/7v/8TRxxxBA2VaDRKVVUVeXl5mTblkFRUVKCqKh6PJy3tGYbBtm3b6NSpU1raA9i/fz/79+cjhJK2NtNNdvZu2rU7/M+iYRhs376djh07snnzZtq3b09lZSWmaR7W58gwDEpKSmjevPlh21hXBINBDMPA7/enrc1vv/2WwsLCtLVXUlKC1+vF6XSmrc10s3v3bhgzZoxoyGzcuFE8/vjjmTbjR3n99dfF8uXL09ZeeXm5GDRoUNraE0KIyZMnC6ezVIBooDdTDBlyfVpeazAYFLfccov49NNPxaBBg8SOHTvElClTxNKlSw+r3ZKSEjFlypS02FhXfPTRR2Lu3Llpa88wDNGzZ8+0tSeEEI899pjYuHFjWttMNzfeeKOQM63QNjbpxu12c/rppzN8+HDWrFnD1Vdfzdq1azn55JMzbZpNI0LNtAE2NnXBKaecwvz58/njH//IAw88QEFBQVrbN00TAEmSEEL85L0Qgng4jBGPW20omoZpGpiGaT2mOhzEY7EafTl0HYeuH7L9lB2NjdR1+f5rqe2xg59zqGPp4OA2bXG0+U3icrlo27Ytuq7TunVrsrKy0tp+aWkphmHg9XoJBALk5eVRUVFBXl4eZWVl+Hw+Dhw4QE5ODlVVAVa/PZ8Vzz3DppWfAsmFhI7HH8+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NZHjzzTd5+umnIzZVUFGUyIqNjSUYDBq+CO7nn39mxowZvPbaa8TFxRmSoVYUbgiNkY0cOZJ58+axd+9eo+MoinISBg4cyNy5c6t94dbzzz+PpmksWbKEJUuW8Nxzzxk6XFNrCjeEZknccccdjB8/PipXFSqKcmy9e/fmm2++qbbtCL7++mvOPfdcTjvtNLp168a3337LiBEjqnWI6GhqVeGG0N013njjDYYOHcr+/fuNjqMoyt/UsmXLahnn9vl8ZGZmMnbsWFq2bEkwGERKWa2zRypifAIDxMXF8cILL7BixQqjoyiK8je9/fbb3H777RFvx+l0sm/fPjp06MDXX3/Nl19+icPhiIp9U2pl4QZo2LAhAwcONDqGoih/k81mY9CgQbz33nsRbSctLY0zzjiDf/7zn9xwww0MGzaMoqKiqJhHfkrP41YU5dRjsVjo2LEjn332GTfddFNE2+rbty8XXHAB9913Hy+//LIhU/+ORhVuRVFqnKSkJKxWK3l5eaSnp0esnfj4eOLj48v3iDF64U+ZWjtUoihKzXXGGWeQkJBQbbc1q67tBE6U6nErilIjDRgwwPBpeUapVOEWQmQCTkADglLKc4QQdYAPgWZAJnCjlPJ
},
"metadata": {
"needs_background": "light"
}
}
],
"source": [
"m.plot(Q)"
]
},
{
"source": [
"## Checking the Policy\n",
"\n",
"Since Q-Table lists the \"attractiveness\" of each action at each state, it is quite easy to use it to define the efficient navigation in our world. In the simplest case, we can just select the action corresponding to the highest Q-Table value:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"2"
]
},
"metadata": {},
"execution_count": 13
}
],
"source": [
"# code block 9"
]
},
{
"source": [
"If you try the code above several times, you may notice that sometimes it just \"hangs\", and you need to press the STOP button in the notebook to interrupt it. \n",
"\n",
"> **Task 1:** Modify the `walk` function to limit the maximum length of path by a certain number of steps (say, 100), and watch the code above return this value from time to time.\n",
"\n",
"> **Task 2:** Modify the `walk` function so that it does not go back to the places where is has already been previously. This will prevent `walk` from looping, however, the agent can still end up being \"trapped\" in a location from which it is unable to escape."
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Average path length = 5.31, eaten by wolf: 0 times\n"
]
}
],
"source": [
"\n",
"# code block 10"
]
},
{
"source": [
"## Investigating the Learning Process"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[<matplotlib.lines.Line2D at 0x26dab295a48>]"
]
},
"metadata": {},
"execution_count": 57
},
{
"output_type": "display_data",
"data": {
"text/plain": "<Figure size 432x288 with 1 Axes>",
"image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\r\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\r\n \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\r\n<!-- Created with matplotlib (https://matplotlib.org/) -->\r\n<svg height=\"248.518125pt\" version=\"1.1\" viewBox=\"0 0 382.368508 248.518125\" width=\"382.368508pt\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\r\n <defs>\r\n <style type=\"text/css\">\r\n*{stroke-linecap:butt;stroke-linejoin:round;white-space:pre;}\r\n </style>\r\n </defs>\r\n <g id=\"figure_1\">\r\n <g id=\"patch_1\">\r\n <path d=\"M -0 248.518125 \r\nL 382.368508 248.518125 \r\nL 382.368508 0 \r\nL -0 0 \r\nz\r\n\" style=\"fill:none;\"/>\r\n </g>\r\n <g id=\"axes_1\">\r\n <g id=\"patch_2\">\r\n <path d=\"M 39.65 224.64 \r\nL 374.45 224.64 \r\nL 374.45 7.2 \r\nL 39.65 7.2 \r\nz\r\n\" style=\"fill:#ffffff;\"/>\r\n </g>\r\n <g id=\"matplotlib.axis_1\">\r\n <g id=\"xtick_1\">\r\n <g id=\"line2d_1\">\r\n <defs>\r\n <path d=\"M 0 0 \r\nL 0 3.5 \r\n\" id=\"m9289ace8dd\" style=\"stroke:#000000;stroke-width:0.8;\"/>\r\n </defs>\r\n <g>\r\n <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"54.868182\" xlink:href=\"#m9289ace8dd\" y=\"224.64\"/>\r\n </g>\r\n </g>\r\n <g id=\"text_1\">\r\n <!-- 0 -->\r\n <defs>\r\n <path d=\"M 31.78125 66.40625 \r\nQ 24.171875 66.40625 20.328125 58.90625 \r\nQ 16.5 51.421875 16.5 36.375 \r\nQ 16.5 21.390625 20.328125 13.890625 \r\nQ 24.171875 6.390625 31.78125 6.390625 \r\nQ 39.453125 6.390625 43.28125 13.890625 \r\nQ 47.125 21.390625 47.125 36.375 \r\nQ 47.125 51.421875 43.28125 58.90625 \r\nQ 39.453125 66.40625 31.78125 66.40625 \r\nz\r\nM 31.78125 74.21875 \r\nQ 44.046875 74.21875 50.515625 64.515625 \r\nQ 56.984375 54.828125 56.984375 36.375 \r\nQ 56.984375 17.96875 50.515625 8.265625 \r\nQ 44.046875 -1.421875 31.78125 -1.421875 \r\nQ 19.53125 -1.421875 13.0625 8.265625 \r\nQ 6.59375 17.96875 6.59375 36.375 \r\nQ 6.59375 54.828125 13.0625 64.515625 \r\nQ 19.53125 74.21875 31.78125 74.21875 \r\nz\r\n\" id=\"DejaVuSans-48\"/>\r\n </defs>\r\n <g transform=\"translate(51.686932 239.238438)scale(0.1 -0.1)\">\r\n <use xlink:href=\"#DejaVuSans-48\"/>\r\n </g>\r\n </g>\r\n </g>\r\n <g id=\"xtick_2\">\r\n <g id=\"line2d_2\">\r\n <g>\r\n <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"115.746997\" xlink:href=\"#m9289ace8dd\" y=\"224.64\"/>\r\n </g>\r\n </g>\r\n <g id=\"text_2\">\r\n <!-- 2000 -->\r\n <defs>\r\n <path d=\"M 19.1875 8.296875 \r\nL 53.609375 8.296875 \r\nL 53.609375 0 \r\nL 7.328125 0 \r\nL 7.328125 8.296875 \r\nQ 12.9375 14.109375 22.625 23.890625 \r\nQ 32.328125 33.6875 34.8125 36.53125 \r\nQ 39.546875 41.84375 41.421875 45.53125 \r\nQ 43.3125 49.21875 43.3125 52.78125 \r\nQ 43.3125 58.59375 39.234375 62.25 \r\nQ 35.15625 65.921875 28.609375 65.921875 \r\nQ 23.96875 65.921875 18.8125 64.3125 \r\nQ 13.671875 62.703125 7.8125 59.421875 \r\nL 7.8125 69.390625 \r\nQ 13.765625 71.78125 18.9375 73 \r\nQ 24.125 74.21875 28.421875 74.21875 \r\nQ 39.75 74.21875 46.484375 68.546875 \r\nQ 53.21875 62.890625 53.21875 53.421875 \r\nQ 53.21875 48.921875 51.53125 44.890625 \r\nQ 49.859375 40.875 45.40625 35.40625 \r\nQ 44.1875 33.984375 37.640625 27.21875 \r\nQ 31.109375 20.453125 19.1875 8.296875 \r\nz\r\n\" id=\"DejaVuSans-50\"/>\r\n </defs>\r\n <g transform=\"translate(103.021997 239.238438)scale(0.1 -0.1)\">\r\n <use xlink:href=\"#DejaVuSans-50\"/>\r\n <use x=\"63.623047\" xlink:href=\"#DejaVuSans-48\"/>\r\n <use x=\"127.246094\" xlink:href=\"#DejaVuSans-48\"/>\r\n <use x=\"190.869141\" xlink:href=\"#DejaVuSans-48\"/>\r\n </g>\r\n </g>\r\n </g>\r\n <g id=\"xtick_3\">\r\n <g id=\"line2d_3\">\r\n <g>\r\n <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"176.625812\" xlink:href=\"#m9289ace8dd\" y=\"224.64\"/>\r\n </g>\r\n </g>\r\n <g id=\"text_3\">\r\n <!-- 400
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAX0AAAD4CAYAAAAAczaOAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xL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C7jKp18F7HLO/Q0w3M+HmZ0BDAY+DVwCPGhmR/Uu+yIR5n+zql6UXCLZtbKZnQJ8FXjMvzfgAmCcn2UM8A3/epB/j59+oZ9/EDDWOXfAObceqAfOLsVGBKWSv4RCx50UI+Q6/fuAXwDJuwwfAXY75zr9+wbgZP/6ZGAzgJ/e4ufvSs/wmS5mdo2Z1ZpZbWNjYwGbIiIi+eQN+mb2NWCHc25BanKGWdMHCkqfluszRxKcG+mcG+icG9i/f/982SuIWjVI2DoOHWZWfVPY2ZAIyRqWynSFGKSkfz7wdTPbAIwlUa1zH3CcmfXz85wCbPWvG4BTAfz0DwPNqekZPiNSvVJ+1fdOWcN3H5vbNU5qqbR3HCrp8qT88sb0sKp3nHPDnHOnOOdqSNyIneac+x4wHbjczzYEeMm/nuDf46dPc4nnzCcAg33rngHA6cC8km1JACrpS5gMWLtjLwBNew+WdNnN+0q7PCmf1vbOrNMqcfunN+30/xP4mZnVk6izH+XTRwEf8ek/A4YCOOeWA88BK4BXgWudcyqexMg9r61mWUNL2NkI7K7Jq3hhUUPJlucobeHtF+OWUDN0YgmXKJXwdl336r0FG3dVdP398s9yhHPuDeAN/3odGVrfOOfagSuyfP5W4NZCM9lbyRK+Wu+E6/fT6vn9tHo
},
"metadata": {
"needs_background": "light"
}
}
],
"source": [
"plt.plot(lpath)"
]
},
{
"source": [
"## Exercise\n",
"## A more realistic Peter and the Wolf world\n",
"\n",
"\n"
],
"cell_type": "markdown",
"metadata": {}
}
]
}