Skip to content

Commit

Permalink
Add implementation for Q learning (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
m-naumann authored Nov 29, 2023
1 parent f80cced commit a849059
Show file tree
Hide file tree
Showing 7 changed files with 559 additions and 93 deletions.
4 changes: 3 additions & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ nav:
- Lateral Control (state-based): notebooks/lateral_control_state_based_notebook.ipynb
- Lateral Control (Riccati): notebooks/lateral_control_riccati_notebook.ipynb
- Graph Search: notebooks/a_star_notebook.ipynb
- Decision Making: notebooks/mdp.ipynb
- Decision Making:
- Value Iteration: notebooks/mdp_value_iteration.ipynb
- Q-Learning: notebooks/mdp_q_learning.ipynb
- API Documentation (partial): reference/

plugins:
Expand Down
238 changes: 238 additions & 0 deletions notebooks/mdp_q_learning.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from behavior_generation_lecture_python.mdp.mdp import (\n",
" MDP,\n",
" GridMDP,\n",
" expected_utility_of_action,\n",
" derive_policy,\n",
" q_learning,\n",
" GRID_MDP_DICT,\n",
" HIGHWAY_MDP_DICT,\n",
" LC_RIGHT_ACTION,\n",
" STAY_IN_LANE_ACTION,\n",
")\n",
"from behavior_generation_lecture_python.utils.grid_plotting import (\n",
" make_plot_grid_step_function,\n",
" make_plot_policy_step_function,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## TOY EXAMPLE"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"grid_mdp = GridMDP(**GRID_MDP_DICT)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"computed_utility_history = q_learning(\n",
" mdp=grid_mdp, alpha=0.1, epsilon=0.1, iterations=10000, return_history=True\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"plot_grid_step = make_plot_grid_step_function(\n",
" columns=4, rows=3, U_over_time=computed_utility_history\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"mkdocs_flag = False # set to true if you are running the notebook locally\n",
"if mkdocs_flag:\n",
" import ipywidgets\n",
" from IPython.display import display\n",
"\n",
" iteration_slider = ipywidgets.IntSlider(\n",
" min=0, max=len(computed_utility_history) - 1, step=1, value=0\n",
" )\n",
" w = ipywidgets.interactive(plot_grid_step, iteration=iteration_slider)\n",
" display(w)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_grid_step(1000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## HIGHWAY EXAMPLE"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if False:\n",
" # we will change this to true later on, to see the effect\n",
" HIGHWAY_MDP_DICT[\"transition_probabilities_per_action\"][LC_RIGHT_ACTION] = [\n",
" (0.4, LC_RIGHT_ACTION),\n",
" (0.6, STAY_IN_LANE_ACTION),\n",
" ]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"highway_mdp = GridMDP(**HIGHWAY_MDP_DICT)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"utility_history_highway = q_learning(\n",
" mdp=highway_mdp, alpha=0.1, epsilon=0.1, iterations=10000, return_history=True\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_grid_step_highway = make_plot_grid_step_function(\n",
" columns=10, rows=4, U_over_time=utility_history_highway\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"if mkdocs_flag:\n",
" iteration_slider = ipywidgets.IntSlider(\n",
" min=0, max=len(utility_history_highway) - 1, step=1, value=0\n",
" )\n",
" w = ipywidgets.interactive(plot_grid_step_highway, iteration=iteration_slider)\n",
" display(w)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_grid_step_highway(1000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"policy_array = [\n",
" derive_policy(highway_mdp, utility) for utility in utility_history_highway\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_policy_step_highway = make_plot_policy_step_function(\n",
" columns=10, rows=4, policy_over_time=policy_array\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if mkdocs_flag:\n",
" iteration_slider = ipywidgets.IntSlider(\n",
" min=0, max=len(utility_history_highway) - 1, step=1, value=0\n",
" )\n",
" w = ipywidgets.interactive(plot_policy_step_highway, iteration=iteration_slider)\n",
" display(w)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_policy_step_highway(1000)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"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.8.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
96 changes: 4 additions & 92 deletions notebooks/mdp.ipynb → notebooks/mdp_value_iteration.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -16,101 +16,13 @@
" HIGHWAY_MDP_DICT,\n",
" LC_RIGHT_ACTION,\n",
" STAY_IN_LANE_ACTION,\n",
")\n",
"from behavior_generation_lecture_python.utils.grid_plotting import (\n",
" make_plot_grid_step_function,\n",
" make_plot_policy_step_function,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# From https://github.com/aimacode/aima-python\n",
"\"\"\"\n",
"The MIT License (MIT)\n",
"\n",
"Copyright (c) 2016 aima-python contributors\n",
"\n",
"Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n",
"\n",
"The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n",
"\n",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
"\"\"\"\n",
"from collections import defaultdict\n",
"import matplotlib.pyplot as plt\n",
"\n",
"\n",
"def make_plot_grid_step_function(columns, rows, U_over_time, show=True):\n",
" \"\"\"ipywidgets interactive function supports single parameter as input.\n",
" This function creates and return such a function by taking as input\n",
" other parameters.\"\"\"\n",
"\n",
" def plot_grid_step(iteration):\n",
" data = U_over_time[iteration]\n",
" data = defaultdict(lambda: 0, data)\n",
" grid = []\n",
" for row in range(rows):\n",
" current_row = []\n",
" for column in range(columns):\n",
" current_row.append(data[(column, row)])\n",
" grid.append(current_row)\n",
" grid.reverse() # output like book\n",
" grid = [[-200 if y is None else y for y in x] for x in grid]\n",
" fig = plt.imshow(grid, cmap=plt.cm.bwr, interpolation=\"nearest\")\n",
"\n",
" plt.axis(\"off\")\n",
" fig.axes.get_xaxis().set_visible(False)\n",
" fig.axes.get_yaxis().set_visible(False)\n",
"\n",
" for col in range(len(grid)):\n",
" for row in range(len(grid[0])):\n",
" magic = grid[col][row]\n",
" fig.axes.text(\n",
" row, col, \"{0:.2f}\".format(magic), va=\"center\", ha=\"center\"\n",
" )\n",
" if show:\n",
" plt.show()\n",
"\n",
" return plot_grid_step"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"\n",
"def make_plot_policy_step_function(columns, rows, policy_over_time, show=True):\n",
" def plot_grid_step(iteration):\n",
" data = policy_over_time[iteration]\n",
" for row in range(rows):\n",
" for col in range(columns):\n",
" if not (col, row) in data:\n",
" continue\n",
" x = col + 0.5\n",
" y = row + 0.5\n",
" if data[(col, row)] is None:\n",
" plt.scatter([x], [y], color=\"black\")\n",
" continue\n",
" dx = data[(col, row)][0]\n",
" dy = data[(col, row)][1]\n",
" scaling = np.sqrt(dx**2.0 + dy**2.0) * 2.5\n",
" dx /= scaling\n",
" dy /= scaling\n",
" plt.arrow(x, y, dx, dy)\n",
" plt.axis(\"equal\")\n",
" plt.xlim([0, columns])\n",
" plt.ylim([0, rows])\n",
" if show:\n",
" plt.show()\n",
"\n",
" return plot_grid_step"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down
Loading

0 comments on commit a849059

Please sign in to comment.