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

615 lines
453 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.4"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python3",
"display_name": "Python 3.7.4 64-bit ('base': conda)"
},
"interpreter": {
"hash": "c77bccf6af5544921fca6eddbefe5e7c44ddf71c61b63c74bd828ca1d0e389a0"
}
},
"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 [Segei 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 the wolf. We will train machine learning algorithms that will help Peter to explore the surroinding area and build an optimal navigation map.\n",
"\n",
"First, let's import a bunch of userful libraries:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 1,
"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 cat take some 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": {}
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from rlboard import *"
]
},
{
"source": [
"Let's now create a random board and see how it looks:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 3,
"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(#p13c0d516da)\">\r\n <image height=\"327\" id=\"imagef33cdae203\" transform=\"scale(1 -1)translate(0 -327)\" width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pvWRvX5zc1r+PtvlXr4hcJCL3ich9lUplL5ehlFL7r90N7o1jXSDh/aZw+1pg5hbHzQDWb+sNrLWLrbUnWGtPSKVSu1mGUkodeKK7+bqbgAuAL4b3N26x/RIRuQ44CRgd61LZniAIuOGGG3azlMk3ODjIE0880dQ1Ll++nKeeeoqNGzc2upQJbdiwgd/85jc081/U+Xy+qX/O5XKZzECGuTfMbXQpE2pf087y0vKm7ud+8skniUajLF++fMcHN0gQBBPu22Fwi8hPgJcAvSKyFvg09cD+mYi8A3gaeEN4+C3AWcAqoAy8fWcKdF3hve+dsjOHNkQ6bbjggjRTpjRvjU899RRXXZVlZKR5a5w3L8G55/aRyWQaXcqEotFoU/+ci8UiJyZO5ItTvtjoUib06PCjFJxCU5/HdDrNF7q/QHlKudGlTMgVd8J9Owxua+35E+w6bRvHWuDina5s/HUOGzYs2tW
},
"metadata": {
"needs_background": "light"
}
}
],
"source": [
"width, height = 8,8\n",
"m = Board(width,height)\n",
"m.randomize(seed=13)\n",
"m.plot()"
]
},
{
"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. To do this, he can essentially walk around until he finds and apple. Therefore, at any position he can chose between one of the following actions: up, down, left and right. We will define those actions as a dictionary, and map them to pairs of corresponding coordinate changes. For example, moving right (`R`) would correspond to a pair `(1,0)`."
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"actions = { \"U\" : (0,-1), \"D\" : (0,1), \"L\" : (-1,0), \"R\" : (1,0) }\n",
"action_idx = { a : i for i,a in enumerate(actions.keys()) }"
]
},
{
"source": [
"The strategy of our agent (Peter) is defined by so-called **policy**. A policy is a function that returns the action at any given state. In our case, the state of the problem is represented by the board, including the current position of the player. \n",
"\n",
"The goal of reinforcement learning is to eventually learn a good policy that will allow us to solve the problem efficiently. However, as a baseline, 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. With random walk, we will randomly chose the next action from allowed ones, until we reach the apple. "
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"tags": []
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"18"
]
},
"metadata": {},
"execution_count": 5
}
],
"source": [
"def random_policy(m):\n",
" return random.choice(list(actions))\n",
"\n",
"def walk(m,policy,start_position=None):\n",
" n = 0 # number of steps\n",
" # set initial position\n",
" if start_position:\n",
" m.human = start_position \n",
" else:\n",
" m.random_start()\n",
" while True:\n",
" if m.at() == Board.Cell.apple:\n",
" return n # success!\n",
" if m.at() in [Board.Cell.wolf, Board.Cell.water]:\n",
" return -1 # eaten by wolf or drowned\n",
" while True:\n",
" a = actions[policy(m)]\n",
" new_pos = m.move_pos(m.human,a)\n",
" if m.is_valid(new_pos) and m.at(new_pos)!=Board.Cell.water:\n",
" m.move(a) # do the actual move\n",
" break\n",
" n+=1\n",
"\n",
"walk(m,random_policy)"
]
},
{
"source": [
"Let's run random walk experiment several times and see the average number of steps taken:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Average path length = 32.87096774193548, eaten by wolf: 7 times\n"
]
}
],
"source": [
"def print_statistics(policy):\n",
" s,w,n = 0,0,0\n",
" for _ in range(100):\n",
" z = walk(m,policy)\n",
" if z<0:\n",
" w+=1\n",
" else:\n",
" s += z\n",
" n += 1\n",
" print(f\"Average path length = {s/n}, eaten by wolf: {w} times\")\n",
"\n",
"print_statistics(random_policy)"
]
},
{
"source": [
"## Reward Function\n",
"\n",
"To make out policy more intelligent, we need to understand which moves are \"better\" than others. To do this, we need to define our goal. The goal can be defined in terms of **reward function**, that will return some score value for each state. The higher the number - the better is the reward function\n",
"\n"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"move_reward = -0.1\n",
"goal_reward = 10\n",
"end_reward = -10\n",
"\n",
"def reward(m,pos=None):\n",
" pos = pos or m.human\n",
" if not m.is_valid(pos):\n",
" return end_reward\n",
" x = m.at(pos)\n",
" if x==Board.Cell.water or x == Board.Cell.wolf:\n",
" return end_reward\n",
" if x==Board.Cell.apple:\n",
" return goal_reward\n",
" return move_reward"
]
},
{
"source": [
"Interesting thing about reward function is that in most of the cases *we are only given substantial reward at the end of the game*. It means that out algorithm should somehow remember \"good\" steps that lead to positive reward at the end, and increase their importance. Similarly, all moves that lead to bad results should be discouraged.\n",
"\n",
"## Q-Learning\n",
"\n",
"An algorithm that we will discuss here is called **Q-Learning**. In this algorithm, the policy is defined by a function (or a data structure) called **Q-Table**. It records the \"goodness\" of each of the actions in a given state, i.e. $Q : {S\\times A}\\to\\mathbb{R}$, where $S$ is a set of states, $A$ is the set of actions.\n",
"\n",
"It is called Q-Table because it is often convenient to represent it as a 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": 55,
"metadata": {},
"outputs": [],
"source": [
"Q = np.ones((width,height,len(actions)),dtype=np.float)*1.0/len(actions)"
]
},
{
"source": [
"Notice that we initially initialize all values of Q-Table with equal value, in our case - 0.25. That corresponds to the \"random walk\" policy, because all moves in each state are equally good. We can 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": 9,
"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(#p37f08b6901)\">\r\n <image height=\"327\" id=\"image132510f9a4\" transform=\"scale(1 -1)translate(0 -327)\" width=\"327\" x=\"33.2875\" xlink:href=\"data:image/png;base64,\r\niVBORw0KGgoAAAANSUhEUgAAAUcAAAFHCAYAAAAySY5rAAAABHNCSVQICAgIfAhkiAAAIABJREFUeJzs3XmcFNW99/FPrV1dvc3KjuyCyqaCxpi4oAZxB0VjUNwAY9wFjXG5NxGJRuNOcokGjbhE44LRJBgVAUGIglEQZBAEVJBl1p7el6p6/ujpckYb86Dt7Z7reSfzGpzuqf5NMf3l1DmnzpEmTJjg9OzZk3KVSqWIRqNUV1eXupQ9CofDqKqKz+crdSl7tGvXLnbtqsFxlFKXskcVFdvp06d8fxcty6KxsZEuXbqUupQ9isViWJZFMBgsdSl71NjYiN/vx+PxlLqUPdq+fTtceeWVTjnbuHGj8+CDD5a6jK80f/58Z/ny5aUu4yvNnDnT8XiaHHDK9MN2zjzzslKfpq/U2NjozJo1q9RlfKVly5Y5L7zwQqnL+Epz5sxxNm7cWOoyvtIVV1z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Rz5kydm5trdYw6hXrxqJ3ZUEMl3wIdlFJnKKWigWHAhw20LiGEOKU0yFCJ1jqolBoPfALYgVe11t83xLqEEOJU01Bj3GitlwJLG+r1hRDiVCVnTgohRISR4hZCiAgjxS2EEBFGilsIISKMFLcQQkQYKW4hhIgwUtxCCBFhpLiFECLCSHELIUSEkeIWQogII8UthBARRopbCCEiTKMt7ry8vOprgYclwzDYvXu31THq5HK5OHDggNUx6nTgwAFcLpfVMeq0e/duDMOwOkattNbk5eVZHaNOfr+fvXv3Wh2jTmVlZZSVlZ2UdTXY1QGtsnXrVr7++ms2bdpEt27d6N69Oz179rQ61mG++OILtm7dytatW+ncuTOXX345LVu2tDrWYd5++20KCgqoqKigZcuWjBgxIqxmC/H5fMyfP589e/aQlJREVlYWw4YNszrWYQoKCli2bBk//PADHTt25Mwzz2TgwIFWxzrMunXrWL9+PRs3biQ7O5u+ffvSqVMnq2MdZsmSJeTn51NQUEC7du0YMmRIWM2uo7Vm7ty5FBYWAtCiRQtGjRqFUkefvKY+NLot7q+//po1a9bwl7/8hZ07d/LBBx9YHekIs2fPxu12c//997Ns2TI2b95sdaQjPProo3Tp0oXrrruOv//977jdbqsjHcbj8TBjxgyuvfZaunbtyqOPPmp1pCN8//33LF26lEmTJuH1ennllVesjnSERYsWsXPnTh555BHWrl3L119/bXWkIzz11FNkZGQwZswY5s+fz759+6yOdBjTNJk6dSr9+/enX79+TJ06FdM0G3Sdjaq48/Ly2LRpEzExMVx99dU8+OCDxMbGsnLlSquj1Vi4cCG9e/fm448/5uGHH+aFF15gwYIFlJeXWx2txuTJk/nb3/7Ggw8+yKpVq1i0aBG33Xab1bEOc9tttzF58mRGjx5NamoqL7zwAg899JDVsWpUVFQwb948unbtyhVXXMGIESPo27cv7733ntXRaqxatYro6Gh27tzJqFGjeOKJJ9i8eTM7d+60OlqN5557jjvvvJNnn32WefPmMX/+fCZPnhxWQ0/jxo3j6aefZvz48ZSWlvLee+8xbty4Bl1noxoqadOmDd26dWPHjh0sW7aMefPm4fV6ufDCC62OVuP6669n1KhR3HrrrVx66aXcf//93HzzzSQnJ1sdrcbUqVPp3r07c+fOJS0tjRtvvJGlS8NrToyXX36ZSy+9lPfff5+Kigpuu+02NmzYYHWsGklJSYwcOZK3336bzz77jBUrVrBy5Urmz59vdbQavXv3ZunSpVx44YX8/ve/58knn6Rr166cccYZVkercddddzFw4ECeeOIJOnbsyLhx43jyySex2cJnm/Oll14iOzub999/H6h6j2/cuLFB19moilspRffu3cnLy+PZZ5/F6/Vy0UUXNehY0y+llOKqq65iw4YNbN26lczMTNq1axdWGW02GyNHjuSDDz7AZrMxePBg4uPjrY51mNjYWC699FLmzp2LaZqMHDkyrN7MSinatm1L8+bNef755/H7/Vx99dVh9XNWSjFgwAC++OILnn32WQC6d+8edhlvueUWPvvsM7788kuys7Np2rRpWGW02WzccMMNvPnmmwDccMMNDf672KiKG6Bnz5707NmTlStXcuGFF4bVD7ja0KFDue666/juu+84//zzrY5zVPfddx8lJSWUlpbSoUMHq+McIS4ujpycHHJzc0lLS6NJkyZWRzpC+/btycnJYe3atZxzzjk4HA6rIx3hkksuYfDgwaxatYo+ffpYHeeoxo4di8vlYseOHWRnZ1sd5wg2m41HHnmEPXv2AJyUAw0aXXFXC9dfwmpRUVFhW9rVMjIyyMjIsDpGncLxfyo/16tXL6sj1EkpFfbvl4SEhLAs7UOdzCPDwudvSyGEEMdFilsIISKMFLcQQkQYKW4hhIgwUtxCCBFhpLiFECLCSHELIUSEkeIWQogII8UthBARRopbCCEizAmd8q6UygcqAQMIaq17KqXSgbeBNkA+cIPW+uCJxRRCCFGtPra4B2qtu2utq6eZeRBYrrXuACwP3RdCCFFPGmKo5BpgbujzucC1DbAOIYQ4ZZ1ocWvg30qp75RS1VM+NNNaFwKEPmae4DqEEEIc4kQv69pHa71XKZUJfKqU2nK8TwwV/TiAxMREcnNzTzBKw9mzZw9lZWVhnbG4uBjTNMM6o8vlIi8vj+LiYquj1Mrv94f197CiogKXyxXWGfft2xf275eysjJ++ukntNZWR6lVXfNWnlBxa633hj7uV0p9APQCipRSLbTWhUqpFsD+Wp47C5gFkJGRob/44osTidKgysrK2LNnD+GccceOHcTHx1NSUmJ1lFoVFxezatWqsJot/uecTmdY/5y9Xi+rD6xm8ReLrY5Sq/jCeAZ5BjX4hLknoqCggO+++47t27dbHaVWdX7/tNa/6gYkAEmHfL4KuBx4CngwtPxBYNqxXiszM1OHs9zcXD1r1iyrY9Tpgw8+0KtWrbI6Rp0ee+wxXVpaanWMWpmmqcePH291jDqVlJToHjk9NGH8X/NvmutFixZZ/a2q08yZM3Vubq7VMeoU6sWjduaJbHE3Az4ITQ0WBbyhtf5YKfUt8I5SagywGxh6AusQQgjxM7+6uLXWO4Gzj7K8BBh0IqGEEELUTs6cFEKICCPFLYQQEUaKWwghIowUtxBCRBgpbiGEiDBS3EIIEWGkuIUQIsJIcQshRISR4hZCiAgjxS2EEBFGilsIISKMFLcQQkQYKW4hhIgwUtxCCBFhGm1xL1y4MKynJfL7/SxZssTqGHUqKChg3bp1Vseo03fffUdBQYHVMeq0ZMkS/H6/1TEiWnl5eVjPTASwdetWtm7delLWdaJzToadL774gtmzZ9O7d29GjRrFVVddxdCh4TWXw8yZM1mzZg3du3dnxIgRTJo0iezsbKtjHeaee+7BMAzS0tJ47rnnePHFF0lISLA6Vg23280dd9xB27ZtKSsrQynFjBkzrI51mE2bNjFt2jR69uzJ7bffTq9evbjzzjutjhVxcnJy2L17N23btmX27Nk8+eSTnHbaaVbHqmGaJuPGjaNJkyZorSkpKWHWrFnYbA23XdyotrgNw2Dr1q107tyZG2+8kSuvvJINGzYQDAatjlbD7/ezZs0ahg4dyvDhw8nKyiI/Pz+s/jrweDx888033Hnnndxxxx01k7+Gk+rJXkePHs0999zDypUr8Xg8VseqobVm165dNGnShJtuuol
},
"metadata": {
"needs_background": "light"
}
}
],
"source": [
"m.plot(Q)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"source": [
"In the center of each cell there is an \"arrow\" that indicates the preferred direction of movement. Since all directions are equal, a dot is displayed.\n",
"\n",
"Now we need to run the simulation, explore our environment, and learn better distribution of Q-Table values, which will allow us to find the path to the apple much faster.\n",
"\n",
"## Essence of Q-Learning: Bellman Equation\n",
"\n",
"Once we start moving, each action will have a corresponding reward, i.e. we can theoretically select the next action based on the highest immediate reward. However, in most of the states the move will not achieve our goal or reaching the apple, and thus we cannot immediately decide which direction is better.\n",
"\n",
"> It is not the immediate result that matters, but rather the final result, which we will obtain at the end of the simulation.\n",
"\n",
"In order to account for this delayed reward, we need to use the principles of **[dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming)**, which allows us to think about out problem recursively.\n",
"\n",
"Suppose we are now at the state $s$, and we want to move to the next state $s'$. By doing so, we will receive the immediate reward $r(s,a)$, defined by reward function, plus some future reward. If we suppose that our Q-Table correctly reflects the \"attractiveness\" of each action, then at state $s'$ we will chose an action $a'$ that corresponds to maximum value of $Q(s',a')$. Thus, the best possible future reward we could get at state $s'$ will be defined as $\\max_{a'}Q(s',a')$ (maximum here is computed over all possible actions $a'$ at state $s'$). \n",
"\n",
"This gives the **Bellman formula** for calculating the value of Q-Table at state $s$, given action $a$:\n",
"\n",
"$$Q(s,a) = r(s,a) + \\gamma \\max_{a'} Q(s',a')$$\n",
"\n",
"Here $\\gamma$ is so-called **discount factor** that determines to which extent you should prefer current reward over the future reward and vice versa.\n",
"\n",
"## Learning Algorithm\n",
"\n",
"Given the equation above, we can now 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",
"In the algorithm above, we did not specify how exactly we should chose an action at step 2.1. If we are choosing the action randomly, we will randomly **explore** the environment, and we are quite likely to die often, and also explore such areas where we would not normally go. An alternative approach would be to **exploit** the Q-Table values that we already know, and thus to chose the best action (with highers Q-Table value) at state $s$. This, however, will prevent us from exploring other states, and quite likely we might not find the optimal solution.\n",
"\n",
"Thus, the best approach is to balance between exploration and exploitation. This can be easily done by choosing the action at state $s$ with probabilities proportional to values in Q-Table. In the beginning, when Q-Table values are all the same, it would correspond to random selection, but 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": [
"def probs(v,eps=1e-4):\n",
" v = v-v.min()+eps\n",
" v = v/v.sum()\n",
" return v"
]
},
{
"source": [
"We add small amount `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",
"for epoch in range(10000):\n",
" clear_output(wait=True)\n",
" print(f\"Epoch = {epoch}\",end='')\n",
"\n",
" # Pick initial point\n",
" m.random_start()\n",
" \n",
" # Start travelling\n",
" n=0\n",
" cum_reward = 0\n",
" while True:\n",
" x,y = m.human\n",
" v = probs(Q[x,y])\n",
" a = random.choices(list(actions),weights=v)[0]\n",
" dpos = actions[a]\n",
" m.move(dpos)\n",
" r = reward(m)\n",
" cum_reward += r\n",
" if r==end_reward or cum_reward < -1000:\n",
" print(f\" {n} steps\",end='\\r')\n",
" lpath.append(n)\n",
" break\n",
" alpha = np.exp(-n / 3000)\n",
" gamma = 0.5\n",
" ai = action_idx[a]\n",
" Q[x,y,ai] = (1 - alpha) * Q[x,y,ai] + alpha * (r + gamma * Q[x+dpos[0], y+dpos[1]].max())\n",
" n+=1"
]
},
{
"source": [
"After executing this algorithm, Q-Table should be updated with values that define the attractiveness of different actions at each step. We can try to visualize Q-Table by plotting a vector at each cell that will point in the desired direction of movement. For simplicity, we draw small circle instead of arrow head."
],
"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+BHTso3b0bwxQYAo46bS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FGUyIqNjSUYDBq+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": [
"def qpolicy_strict(m):\n",
" x,y = m.human\n",
" v = probs(Q[x,y])\n",
" a = list(actions)[np.argmax(v)]\n",
" return a\n",
"\n",
"walk(m,qpolicy_strict)"
]
},
{
"source": [
"If you try the code above several times, you may notice that sometimes it just \"hangs\", and you need to press STOP button in the notebook to interrupt it. This happens because there could be situations when two states \"point\" to each other in terms of optimal Q-Value, in which case the agents ends up moving between those states indefinitely.\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.\n",
"\n",
"Better navigation policy would be the one that we have used during training, which combines exploitation and exploration. In this policy, we will select each action with a certain probability, proportional to the values in Q-Table. This strategy may still result in the agent returning back to the position it has already explored, but, as you can see from the code below, it results in very short average path to the desired location (remember that `print_statistics` runs the simulation 100 times): "
],
"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",
"def qpolicy(m):\n",
" x,y = m.human\n",
" v = probs(Q[x,y])\n",
" a = random.choices(list(actions),weights=v)[0]\n",
" return a\n",
"\n",
"print_statistics(qpolicy)"
]
},
{
"source": [
"## Investigating Learning Process\n",
"\n",
"As we have mentioned, the learning process is a balance between exploration and exploration of gained knowledge about the structure of problem space. We have seen that the result of learning (the ability to help an agent to find short path to the goal) has improved, but it is also interesting to observe how the average path length behaves during 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+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAgAElEQVR4nO3de5wU5Z3v8c8vEk1islETkuPtlcFdT3LMvjbRsF5iTnajibdkQ5KjOeRKjKsnWT3rms1mwVw8q/EWL6gJXlAwxBsqQSWCIgJeuDPc5TrDfQBhhoFhYBiYgef80U8PPT19qe7p7qrp+r5fL5jup6qrnuqq/tVTTz31POacQ0RE4uE9YWdAREQqR0FfRCRGFPRFRGJEQV9EJEYU9EVEYqRf2BnI5aMf/airqakJOxsiIn3KggULmpxz/TNNi3TQr6mpoba2NuxsiIj0KWa2Mds0Ve+IiMSIgr6ISIwo6IuIxIiCvohIjCjoi4jEiIK+iEiMKOiLiMSIgr5IlXr1nW007T0QdjYkYhT0RapQy/4OfvLkQn78x/lhZ0UiRkFfpAp1HjoMQMOu/SHnRKJGQV9EJEYU9EVEYkRBX0QkRhT0RURiREFfRCRGFPRFRGJEQV9EJEYU9EVEYkRBX0QkRhT0RURiREFfRCRGFPRFRGJEQV9EJEYU9EVEYkRBX0QkRhT0RURiREFfRCRGFPRFRGJEQV9EJEYU9EVE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JXwdl336r0FG3dVdP398s9yhHPuDeAN/3odGVrfOOfagSuyfP5W4NZCM9lbyRK+Wu+E6/fT6vn9tHo
},
"metadata": {
"needs_background": "light"
}
}
],
"source": [
"plt.plot(lpath)"
]
},
{
"source": [
"What we see here is that at first the average path length increased. This is probably due to the fact that when we know nothing about the environment - we are likely to get trapped into bad states, water or wolf. As we learn more and start using this knowledge, we can explore the environment for longer, but we still do not know well where apples are.\n",
"\n",
"Once we learn enough, it becomes easier for the agent to achieve the goal, and the path length starts to decrease. However, we are still open to exploration, so we often diverge away from the best path, and explore new options, making the path longer than optimal.\n",
"\n",
"What we also observe on this graph, is that at some point the length increased abruptly. This indicates stochastic nature of the process, and that we can at some point \"sploil\" the Q-Table coefficients, by overwriting them with new values. This ideally should be minimized by decreasing learning rate (i.e. towards the end of training we only adjust Q-Table values by a small value).\n",
"\n",
"Overall, it is important to remember that the success and quality of the learning process significantly depends on parameters, such as leaning rate, learning rate decay and discount factor. Those are often called **hyperparameters**, to distinguish them from **parameters** which we optimize during training (eg. Q-Table coefficients). The process of finding best hyperparameter values is called **hyperparameter optimization**, and it deserves a separate topic."
],
"cell_type": "markdown",
"metadata": {}
},
{
"source": [
"## Exercise\n",
"#### More Realistic Peter and the Wolf World\n",
"\n",
"In our situation, Peter was able to move around almost without getting tired or hungry. In more realistic world, we has to sit down and rest from time to time, and also to feed himself. Let's make our world more realistic, by implementing the following rules:\n",
"\n",
"1. By moving from one place to another, Peter loses **energy** and gains some **fatigue**.\n",
"2. Peter can gain more energy by eating apples.\n",
"3. Peter can get rid of fatigue by resting under the tree or on the grass (i.e. walking into a board location with a tree or grass - green field)\n",
"4. Peter needs to find and kill the wolf\n",
"5. In order to kill the wolf, Peter needs to have certain levels of energy and fatigue, otherwise he loses the battle.\n",
"\n",
"Modify the reward function above according to the rules of the game, run the reinforcement learning algorithm to learn the best strategy for winning the game, and compare the results of random walk with your algorithm in terms of number of games won and lost.\n",
"\n",
"\n",
"> **Note**: You may need to adjust hyperparameters to make it work, especially the number of epochs. Because the success of the game (fighting the wolf) is a rare event, you can expect much longer training time.\n",
"\n"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
]
}