{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"execution": {},
"id": "view-in-github"
},
"source": [
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"# Tutorial 2: Learning to Act: Multi-Armed Bandits\n",
"\n",
"**Week 3, Day 4: Basic Reinforcement Learning (RL)**\n",
"\n",
"**By Neuromatch Academy**\n",
"\n",
"__Content creators:__ Marcelo G Mattar, Eric DeWitt, Matt Krause, Matthew Sargent, Anoop Kulkarni, Sowmya Parthiban, Feryal Behbahani, Jane Wang\n",
"\n",
"__Content reviewers:__ Ella Batty, Byron Galbraith, Michael Waskom, Ezekiel Williams, Mehul Rastogi, Lily Cheng, Roberto Guidotti, Arush Tagade, Kelson Shilling-Scrivo\n",
"\n",
"__Production editors:__ Gagana B, Spiros Chavlis\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
""
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"---\n",
"\n",
"# Tutorial Objectives\n",
" \n",
"*Estimated timing of tutorial: 45 min*\n",
"\n",
"In this tutorial we will model the simplest types of acting agents. An acting agent can affect how much reward it receives, so it must learn how to identify the actions that lead to the most reward. You will use 'bandits' to understand the fundamentals of how a policy interacts with the learning algorithm in reinforcement learning.\n",
" \n",
"* You will understand the fundamental tradeoff between exploration and exploitation in a policy.\n",
"* You will understand how the learning rate interacts with exploration to find the best available action."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Tutorial slides\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" These are the slides for all videos in this tutorial.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"remove-input"
]
},
"outputs": [],
"source": [
"# @title Tutorial slides\n",
"\n",
"# @markdown These are the slides for all videos in this tutorial.\n",
"from IPython.display import IFrame\n",
"IFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/n9v4c/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"These are the slides for all videos in this tutorial. If you want to locally download the slides, click [here](https://osf.io/download/n9v4c/)."
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"---\n",
"# Setup"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Install dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"# @title Install dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "both",
"execution": {}
},
"outputs": [],
"source": [
"# Imports\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Figure Settings\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"#@title Figure Settings\n",
"import ipywidgets as widgets # interactive display\n",
"%config InlineBackend.figure_format = 'retina'\n",
"plt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plotting Functions\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"#@title Plotting Functions\n",
"np.set_printoptions(precision=3)\n",
"\n",
"def plot_choices(q, epsilon, choice_fn, n_steps=1000, rng_seed=1):\n",
" np.random.seed(rng_seed)\n",
" counts = np.zeros_like(q)\n",
" for t in range(n_steps):\n",
" action = choice_fn(q, epsilon)\n",
" counts[action] += 1\n",
"\n",
" fig, ax = plt.subplots()\n",
" ax.bar(range(len(q)), counts/n_steps)\n",
" ax.set(ylabel='% chosen', xlabel='action', ylim=(0,1), xticks=range(len(q)))\n",
"\n",
"\n",
"def plot_multi_armed_bandit_results(results):\n",
" fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(20, 4))\n",
" ax1.plot(results['rewards'])\n",
" ax1.set(title=f\"Total Reward: {np.sum(results['rewards']):.2f}\",\n",
" xlabel='step', ylabel='reward')\n",
" ax2.plot(results['qs'])\n",
" ax2.set(xlabel='step', ylabel='value')\n",
" ax2.legend(range(len(results['mu'])))\n",
" ax3.plot(results['mu'], label='latent')\n",
" ax3.plot(results['qs'][-1], label='learned')\n",
" ax3.set(xlabel='action', ylabel='value')\n",
" ax3.legend()\n",
"\n",
"\n",
"def plot_parameter_performance(labels, fixed, trial_rewards, trial_optimal):\n",
" fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(16, 6))\n",
"\n",
" ax1.plot(np.mean(trial_rewards, axis=1).T)\n",
" ax1.set(title=f'Average Reward ({fixed})', xlabel='step', ylabel='reward')\n",
" ax1.legend(labels)\n",
"\n",
" ax2.plot(np.mean(trial_optimal, axis=1).T)\n",
" ax2.set(title=f'Performance ({fixed})', xlabel='step', ylabel='% optimal')\n",
" ax2.legend(labels)"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"---\n",
"# Section 1: Multi-Armed Bandits"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Video 1: Multi-Armed Bandits\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"remove-input"
]
},
"outputs": [],
"source": [
"# @title Video 1: Multi-Armed Bandits\n",
"from ipywidgets import widgets\n",
"from IPython.display import YouTubeVideo\n",
"from IPython.display import IFrame\n",
"from IPython.display import display\n",
"\n",
"\n",
"class PlayVideo(IFrame):\n",
" def __init__(self, id, source, page=1, width=400, height=300, **kwargs):\n",
" self.id = id\n",
" if source == 'Bilibili':\n",
" src = f'https://player.bilibili.com/player.html?bvid={id}&page={page}'\n",
" elif source == 'Osf':\n",
" src = f'https://mfr.ca-1.osf.io/render?url=https://osf.io/download/{id}/?direct%26mode=render'\n",
" super(PlayVideo, self).__init__(src, width, height, **kwargs)\n",
"\n",
"\n",
"def display_videos(video_ids, W=400, H=300, fs=1):\n",
" tab_contents = []\n",
" for i, video_id in enumerate(video_ids):\n",
" out = widgets.Output()\n",
" with out:\n",
" if video_ids[i][0] == 'Youtube':\n",
" video = YouTubeVideo(id=video_ids[i][1], width=W,\n",
" height=H, fs=fs, rel=0)\n",
" print(f'Video available at https://youtube.com/watch?v={video.id}')\n",
" else:\n",
" video = PlayVideo(id=video_ids[i][1], source=video_ids[i][0], width=W,\n",
" height=H, fs=fs, autoplay=False)\n",
" if video_ids[i][0] == 'Bilibili':\n",
" print(f'Video available at https://www.bilibili.com/video/{video.id}')\n",
" elif video_ids[i][0] == 'Osf':\n",
" print(f'Video available at https://osf.io/{video.id}') \n",
" display(video)\n",
" tab_contents.append(out)\n",
" return tab_contents\n",
"\n",
"\n",
"video_ids = [('Youtube', 'kdiXr1zsfo0'), ('Bilibili', 'BV1M54y1B7S3')]\n",
"tab_contents = display_videos(video_ids, W=730, H=410)\n",
"tabs = widgets.Tab()\n",
"tabs.children = tab_contents\n",
"for i in range(len(tab_contents)):\n",
" tabs.set_title(i, video_ids[i][0])\n",
"display(tabs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"Consider the following learning problem. You are faced repeatedly with a choice among $k$ different options, or actions. After each choice you receive a reward signal in the form of a numerical value, where the larger value is the better. Your objective is to maximize the expected total reward over some time period, for example, over 1000 action selections, or time steps.\n",
"\n",
"This is the original form of the k-armed bandit problem. This name derives from the colloquial name for a slot machine, the \"one-armed bandit\", because it has the one lever to pull, and it is often rigged to take more money than it pays out over time. The multi-armed bandit extension is to imagine, for instance, that you are faced with multiple slot machines that you can play, but only one at a time. Which machine should you play, i.e., which arm should you pull, which action should you take, at any given time to maximize your total payout.\n",
"\n",
"\n",
"\n",
"\n",
"While there are many different levels of sophistication and assumptions in how the rewards are determined, we will consider here the simple scenario where each action results in a reward drawn from a different Gaussian distribution with unknown mean and unit variance. Since each action is associated with a different mean reward, the goal of the agent is to find the action with highest mean. But since the rewards are noisy (the corresponding Gaussians have unit variance), those means cannot be determined from a single observed reward. \n",
"\n",
"This problem setting is referred to as the *environment*. We will solve this *optimization problem* with an *agent*, in this case an algorithm that takes in rewards and returns actions."
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"---\n",
"# Section 2: Choosing an Action\n",
" \n",
"*Estimated timing to here from start of tutorial: 10 min*\n",
"\n",
"The first thing our agent needs to be able to do is choose which arm to pull. The strategy for choosing actions based on our expectations is called a *policy* (often denoted $\\pi$). We could have a random policy -- just pick an arm at random each time -- though this doesn't seem likely to be capable of optimizing our reward. We want some intentionality, and to do that we need a way of describing our beliefs about the arms' reward potential. We do this with an action-value function\n",
"\n",
"\\begin{equation}\n",
"q(a) = \\mathbb{E} [r_{t} | a_{t} = a]\n",
"\\end{equation}\n",
"\n",
"where the value $q$ for taking action $a \\in A$ at time $t$ is equal to the expected value of the reward $r_t$ given that we took action $a$ at that time. In practice, this is often represented as an array of values, where each action's value is a different element in the array.\n",
"\n",
"Great, now that we have a way to describe our beliefs about the values each action should return, let's come up with a policy.\n",
"\n",
"An obvious choice would be to take the action with the highest expected value. This is referred to as the *greedy* policy\n",
"\n",
"\\begin{equation}\n",
"a_{t} = \\text{argmax}_{a} \\; q_{t} (a)\n",
"\\end{equation}\n",
"\n",
"where our choice action is the one that maximizes the current value function.\n",
"\n",
"So far so good, but it can't be this easy. And, in fact, the greedy policy does have a fatal flaw: it easily gets trapped in local maxima. It never explores to see what it hasn't seen before if one option is already better than the others. This leads us to a fundamental challenge in coming up with effective policies."
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"**The Exploitation-Exploration Dilemma**\n",
"\n",
"If we never try anything new, if we always stick to the safe bet, we don't know what we are missing. Sometimes we aren't missing much of anything, and regret not sticking with our preferred choice, yet other times we stumble upon something new that was way better than we thought.\n",
"\n",
"This is the exploitation-exploration dilemma: do you go with your best choice now, or risk the less certain option with the hope of finding something better. Too much exploration, however, means you may end up with a sub-optimal reward once it's time to stop.\n",
"\n",
"In order to avoid getting stuck in local minima while also maximizing reward, effective policies need some way to balance between these two aims.\n",
"\n",
"A simple extension to our greedy policy is to add some randomness. For instance, a coin flip -- heads we take the best choice now, tails we pick one at random. This is referred to as the $\\epsilon$-greedy policy:\n",
"\n",
"\\begin{equation}\n",
"P (a_{t} = a) = \n",
" \\begin{cases}\n",
" 1 - \\epsilon + \\epsilon/N & \\quad \\text{if } a_{t} = \\text{argmax}_{a} \\; q_{t} (a) \\\\\n",
" \\epsilon/N & \\quad \\text{else} \n",
" \\end{cases} \n",
"\\end{equation}\n",
"\n",
"which is to say that with probability 1 - $\\epsilon$ for $\\epsilon \\in [0,1]$ we select the greedy choice, and otherwise we select an action at random (including the greedy option).\n",
"\n",
"Despite its relative simplicity, the epsilon-greedy policy is quite effective, which leads to its general popularity."
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"### Coding Exercise 2: Implement Epsilon-Greedy\n",
"\n",
"*Referred to in video as Exercise 1*\n",
"\n",
"In this exercise you will implement the epsilon-greedy algorithm for deciding which action to take from a set of possible actions given their value function and a probability $\\epsilon$ of simply choosing one at random. \n",
"\n",
"TIP: You may find [`np.random.random`](https://numpy.org/doc/stable/reference/random/generated/numpy.random.random.html), [`np.random.choice`](https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html), and [`np.argmax`](https://numpy.org/doc/stable/reference/generated/numpy.argmax.html) useful here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {}
},
"outputs": [],
"source": [
"def epsilon_greedy(q, epsilon):\n",
" \"\"\"Epsilon-greedy policy: selects the maximum value action with probability\n",
" (1-epsilon) and selects randomly with epsilon probability.\n",
"\n",
" Args:\n",
" q (ndarray): an array of action values\n",
" epsilon (float): probability of selecting an action randomly\n",
"\n",
" Returns:\n",
" int: the chosen action\n",
" \"\"\"\n",
" #####################################################################\n",
" ## TODO for students: implement the epsilon greedy decision algorithm\n",
" # Fill out function and remove\n",
" raise NotImplementedError(\"Student exercise: implement the epsilon greedy decision algorithm\")\n",
" #####################################################################\n",
" # write a boolean expression that determines if we should take the best action\n",
" be_greedy = ...\n",
"\n",
" if be_greedy:\n",
"\n",
" # write an expression for selecting the best action from the action values\n",
" action = ...\n",
"\n",
" else:\n",
"\n",
" # write an expression for selecting a random action\n",
" action = ...\n",
"\n",
" return action\n",
"\n",
"\n",
"\n",
"# Set parameters\n",
"q = [-2, 5, 0, 1]\n",
"epsilon = 0.1\n",
"\n",
"# Visualize\n",
"# plot_choices(q, epsilon, epsilon_greedy)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"execution": {}
},
"source": [
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W3D4_BasicReinforcementLearning/solutions/W3D4_Tutorial2_Solution_94bf6b77.py)\n",
"\n",
"*Example output:*\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"This is what we should expect, that the action with the largest value (action 1) is selected about (1-$\\epsilon$) of the time, or 90% for $\\epsilon = 0.1$, and the remaining 10% is split evenly amongst the other options. Use the demo below to explore how changing $\\epsilon$ affects the distribution of selected actions."
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"### Interactive Demo 2: Changing Epsilon\n",
"\n",
"Epsilon is our one parameter for balancing exploitation and exploration. Given a set of values $q = [-2, 5, 0, 1]$, use the widget below to see how changing $\\epsilon$ influences our selection of the max value 5 (action = 1) vs the others."
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"#### Think! 2: Changing Epsilon\n",
"\n",
"At the extremes of its range (0 and 1), the $\\epsilon$-greedy policy reproduces two other policies. What are they?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Make sure you execute this cell to enable the widget!\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"#@title\n",
"\n",
"#@markdown Make sure you execute this cell to enable the widget!\n",
"\n",
"@widgets.interact(epsilon=widgets.FloatSlider(0.1, min=0.0, max=1.0))\n",
"def explore_epilson_values(epsilon=0.1):\n",
" q = [-2, 5, 0, 1]\n",
" plot_choices(q, epsilon, epsilon_greedy, rng_seed=None)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"execution": {}
},
"source": [
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W3D4_BasicReinforcementLearning/solutions/W3D4_Tutorial2_Solution_35c251e1.py)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"---\n",
"# Section 3: Learning from Rewards\n",
"\n",
"*Estimated timing to here from start of tutorial: 25 min*\n",
"\n",
"Now that we have a policy for deciding what to do, how do we learn from our actions?\n",
"\n",
"One way to do this is just keep a record of every result we ever got and use the averages for each action. If we have a potentially very long running episode, the computational cost of keeping all these values and recomputing the mean over and over again isn't ideal. Instead we can use a streaming mean calculation, which looks like this:\n",
"\n",
"\\begin{equation}\n",
"q_{t+1}(a) \\leftarrow q_{t}(a) + \\frac{1}{n_t} (r_{t} - q_{t}(a))\n",
"\\end{equation}\n",
"\n",
"where our action-value function $q_t(a)$ is the mean of the rewards seen so far, $n_t$ is the number of actions taken by time $t$, and $r_t$ is the reward just received for taking action $a$.\n",
"\n",
"This still requires us to remember how many actions we've taken, so let's generalize this a bit further and replace the action total with a general parameter $\\alpha$, which we will call the learning rate\n",
"\n",
"\\begin{equation}\n",
"q_{t+1}(a) \\leftarrow q_{t}(a) + \\alpha (r_{t} - q_{t}(a)).\n",
"\\end{equation}"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"## Coding Exercise 3: Updating Action Values\n",
"\n",
"*Referred to in video as Exercise 2*\n",
"\n",
"In this exercise you will implement the action-value update rule above. The function will take in the action-value function represented as an array `q`, the action taken, the reward received, and the learning rate, `alpha`. The function will return the updated value for the selection action."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {}
},
"outputs": [],
"source": [
"def update_action_value(q, action, reward, alpha):\n",
" \"\"\" Compute the updated action value given the learning rate and observed\n",
" reward.\n",
"\n",
" Args:\n",
" q (ndarray): an array of action values\n",
" action (int): the action taken\n",
" reward (float): the reward received for taking the action\n",
" alpha (float): the learning rate\n",
"\n",
" Returns:\n",
" float: the updated value for the selected action\n",
" \"\"\"\n",
" #####################################################\n",
" ## TODO for students: compute the action value update\n",
" # Fill out function and remove\n",
" raise NotImplementedError(\"Student exercise: compute the action value update\")\n",
" #####################################################\n",
"\n",
" # Write an expression for the updated action value\n",
" value = ...\n",
"\n",
" return value\n",
"\n",
"\n",
"\n",
"# Set parameters\n",
"q = [-2, 5, 0, 1]\n",
"action = 2\n",
"print(f\"Original q({action}) value = {q[action]}\")\n",
"\n",
"## Update action - uncomment to check your solution!\n",
"# q[action] = update_action_value(q, 2, 10, 0.01)\n",
"# print(f\"Updated q({action}) value = {q[action]}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"execution": {}
},
"source": [
"[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W3D4_BasicReinforcementLearning/solutions/W3D4_Tutorial2_Solution_f6bc3345.py)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"You should see\n",
"\n",
"\n",
"\n",
"```\n",
"Original q(2) value = 0\n",
"Updated q(2) value = 0.1\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"---\n",
"# Section 4: Solving Multi-Armed Bandits\n",
"\n",
"*Estimated timing to here from start of tutorial: 31 min*\n",
"\n",
"Now that we have both a policy and a learning rule, we can combine these to solve our original multi-armed bandit task. Recall that we have some number of arms that give rewards drawn from Gaussian distributions with unknown mean and unit variance, and our goal is to find the arm with the highest mean.\n",
"\n",
"First, let's see how we will simulate this environment by reading through the annotated code below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {}
},
"outputs": [],
"source": [
"def multi_armed_bandit(n_arms, epsilon, alpha, n_steps):\n",
" \"\"\" A Gaussian multi-armed bandit using an epsilon-greedy policy. For each\n",
" action, rewards are randomly sampled from normal distribution, with a mean\n",
" associated with that arm and unit variance.\n",
"\n",
" Args:\n",
" n_arms (int): number of arms or actions\n",
" epsilon (float): probability of selecting an action randomly\n",
" alpha (float): the learning rate\n",
" n_steps (int): number of steps to evaluate\n",
"\n",
" Returns:\n",
" dict: a dictionary containing the action values, actions, and rewards from\n",
" the evaluation along with the true arm parameters mu and the optimality of\n",
" the chosen actions.\n",
" \"\"\"\n",
" # Gaussian bandit parameters\n",
" mu = np.random.normal(size=n_arms)\n",
"\n",
" # Evaluation and reporting state\n",
" q = np.zeros(n_arms)\n",
" qs = np.zeros((n_steps, n_arms))\n",
" rewards = np.zeros(n_steps)\n",
" actions = np.zeros(n_steps)\n",
" optimal = np.zeros(n_steps)\n",
"\n",
" # Run the bandit\n",
" for t in range(n_steps):\n",
"\n",
" # Choose an action\n",
" action = epsilon_greedy(q, epsilon)\n",
" actions[t] = action\n",
"\n",
" # Compute rewards for all actions\n",
" all_rewards = np.random.normal(mu)\n",
"\n",
" # Observe the reward for the chosen action\n",
" reward = all_rewards[action]\n",
" rewards[t] = reward\n",
"\n",
" # Was it the best possible choice?\n",
" optimal_action = np.argmax(all_rewards)\n",
" optimal[t] = action == optimal_action\n",
"\n",
" # Update the action value\n",
" q[action] = update_action_value(q, action, reward, alpha)\n",
" qs[t] = q\n",
"\n",
" results = {\n",
" 'qs': qs,\n",
" 'actions': actions,\n",
" 'rewards': rewards,\n",
" 'mu': mu,\n",
" 'optimal': optimal\n",
" }\n",
"\n",
" return results"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"We can use our multi-armed bandit method to evaluate how our epsilon-greedy policy and learning rule perform at solving the task. First we will set our environment to have 10 arms and our agent parameters to $\\epsilon=0.1$ and $\\alpha=0.01$. In order to get a good sense of the agent's performance, we will run the episode for 1000 steps."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Execute to see visualization\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"# @markdown Execute to see visualization\n",
"\n",
"# set for reproducibility, comment out / change seed value for different results\n",
"np.random.seed(1)\n",
"\n",
"n_arms = 10\n",
"epsilon = 0.1\n",
"alpha = 0.01\n",
"n_steps = 1000\n",
"\n",
"results = multi_armed_bandit(n_arms, epsilon, alpha, n_steps)\n",
"\n",
"fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(16, 6))\n",
"ax1.plot(results['rewards'])\n",
"ax1.set(title=f'Observed Reward ($\\epsilon$={epsilon}, $\\\\alpha$={alpha})',\n",
" xlabel='step', ylabel='reward')\n",
"ax2.plot(results['qs'])\n",
"ax2.set(title=f'Action Values ($\\epsilon$={epsilon}, $\\\\alpha$={alpha})',\n",
" xlabel='step', ylabel='value')\n",
"ax2.legend(range(n_arms));"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"Alright, we got some rewards that are kind of all over the place, but the agent seemed to settle in on the first arm as the preferred choice of action relatively quickly. Let's see how well we did at recovering the true means of the Gaussian random variables behind the arms."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Execute to see visualization\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"# @markdown Execute to see visualization\n",
"\n",
"fig, ax = plt.subplots()\n",
"ax.plot(results['mu'], label='latent')\n",
"ax.plot(results['qs'][-1], label='learned')\n",
"ax.set(title=f'$\\epsilon$={epsilon}, $\\\\alpha$={alpha}',\n",
" xlabel='action', ylabel='value')\n",
"ax.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"Well, we seem to have found a very good estimate for action 0, but most of the others are not great. In fact, we can see the effect of the local maxima trap at work -- the greedy part of our algorithm locked onto action 0, which is actually the 2nd best choice to action 6. Since these are the means of Gaussian random variables, we can see that the overlap between the two would be quite high, so even if we did explore action 6, we may draw a sample that is still lower than our estimate for action 0.\n",
"\n",
"However, this was just one choice of parameters. Perhaps there is a better combination?\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"## Interactive Demo 4: Changing Epsilon and Alpha\n",
"\n",
"*Referred to in video as Exercise 3*\n",
"\n",
"Use the widget below to explore how varying the values of $\\epsilon$ (exploitation-exploration tradeoff), $\\alpha$ (learning rate), and even the number of actions $k$, changes the behavior of our agent."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Make sure you execute this cell to enable the widget!\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"#@title\n",
"\n",
"#@markdown Make sure you execute this cell to enable the widget!\n",
"\n",
"@widgets.interact_manual(k=widgets.IntSlider(10, min=2, max=15),\n",
" epsilon=widgets.FloatSlider(0.1, min=0.0, max=1.0),\n",
" alpha=widgets.FloatLogSlider(0.01, min=-3, max=0))\n",
"def explore_bandit_parameters(k=10, epsilon=0.1, alpha=0.001):\n",
" results = multi_armed_bandit(k, epsilon, alpha, 1000)\n",
" plot_multi_armed_bandit_results(results)"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"While we can see how changing the epsilon and alpha values impact the agent's behavior, this doesn't give us a great sense of which combination is optimal. Due to the stochastic nature of both our rewards and our policy, a single trial run isn't sufficient to give us this information. Let's run multiple trials and compare the average performance.\n",
"\n",
"First we will look at different values for $\\epsilon \\in [0.0, 0.1, 0.2]$ to a fixed $\\alpha=0.1$. We will run 200 trials as a nice balance between speed and accuracy."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Execute this cell to see visualization\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"# @markdown Execute this cell to see visualization\n",
"\n",
"# set for reproducibility, comment out / change seed value for different results\n",
"np.random.seed(1)\n",
"\n",
"epsilons = [0.0, 0.1, 0.2]\n",
"alpha = 0.1\n",
"n_trials = 200\n",
"trial_rewards = np.zeros((len(epsilons), n_trials, n_steps))\n",
"trial_optimal = np.zeros((len(epsilons), n_trials, n_steps))\n",
"for i, epsilon in enumerate(epsilons):\n",
" for n in range(n_trials):\n",
" results = multi_armed_bandit(n_arms, epsilon, alpha, n_steps)\n",
" trial_rewards[i, n] = results['rewards']\n",
" trial_optimal[i, n] = results['optimal']\n",
"\n",
"labels = [f'$\\epsilon$={e}' for e in epsilons]\n",
"fixed = f'$\\\\alpha$={alpha}'\n",
"plot_parameter_performance(labels, fixed, trial_rewards, trial_optimal)"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"On the left we have plotted the average reward over time, and we see that while $\\epsilon=0$ (the greedy policy) does well initially, $\\epsilon=0.1$ starts to do slightly better in the long run, while $\\epsilon=0.2$ does the worst. Looking on the right, we see the percentage of times the optimal action (the best possible choice at time $t$) was taken, and here again we see a similar pattern of $\\epsilon=0.1$ starting out a bit slower but eventually having a slight edge in the longer run.\n",
"\n",
"We can also do the same for the learning rates. We will evaluate $\\alpha \\in [0.01, 0.1, 1.0]$ to a fixed $\\epsilon=0.1$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Execute this cell to see visualization\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"execution": {},
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"# @markdown Execute this cell to see visualization\n",
"\n",
"# set for reproducibility, comment out / change seed value for different results\n",
"np.random.seed(1)\n",
"\n",
"epsilon = 0.1\n",
"alphas = [0.01, 0.1, 1.0]\n",
"n_trials = 200\n",
"trial_rewards = np.zeros((len(epsilons), n_trials, n_steps))\n",
"trial_optimal = np.zeros((len(epsilons), n_trials, n_steps))\n",
"for i, alpha in enumerate(alphas):\n",
" for n in range(n_trials):\n",
" results = multi_armed_bandit(n_arms, epsilon, alpha, n_steps)\n",
" trial_rewards[i, n] = results['rewards']\n",
" trial_optimal[i, n] = results['optimal']\n",
"\n",
"labels = [f'$\\\\alpha$={a}' for a in alphas]\n",
"fixed = f'$\\epsilon$={epsilon}'\n",
"plot_parameter_performance(labels, fixed, trial_rewards, trial_optimal)"
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"Again we see a balance between an effective learning rate. $\\alpha=0.01$ is too weak to quickly incorporate good values, while $\\alpha=1$ is too strong likely resulting in high variance in values due to the Gaussian nature of the rewards."
]
},
{
"cell_type": "markdown",
"metadata": {
"execution": {}
},
"source": [
"---\n",
"# Summary\n",
"\n",
"*Estimated timing of tutorial: 45 min*\n",
"\n",
"In this tutorial you implemented both the epsilon-greedy decision algorithm and a learning rule for solving a multi-armed bandit scenario. You saw how balancing exploitation and exploration in action selection is critical in finding optimal solutions. You also saw how choosing an appropriate learning rate determines how well an agent can generalize the information they receive from rewards.\n"
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [],
"include_colab_link": true,
"name": "W3D4_Tutorial2",
"provenance": [],
"toc_visible": true
},
"kernel": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"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.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 0
}