Raw File
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# CNTK 203: Reinforcement Learning Basics\n",
    "\n",
    "\n",
    "Reinforcement learning (RL) is an area of machine learning inspired by behaviorist psychology, concerned with how [software agents](https://en.wikipedia.org/wiki/Software_agent) ought to take [actions](https://en.wikipedia.org/wiki/Action_selection) in an environment so as to maximize some notion of cumulative reward. In machine learning, the environment is typically formulated as a [Markov decision process](https://en.wikipedia.org/wiki/Markov_decision_process) (MDP) as many reinforcement learning algorithms for this context utilize [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) techniques. \n",
    "\n",
    "In some machine learning settings, we do not have immediate access to labels, so we cannot rely on supervised learning techniques. If, however, there is something we can interact with and thereby get some feedback that tells us occasionally, whether our previous behavior was good or not, we can use RL to learn how to improve our behavior.\n",
    "\n",
    "Unlike in supervised learning, in RL, labeled correct input/output pairs are never presented and sub-optimal actions are never explicitly corrected. This mimics many of the online learning paradigms which involves finding a balance between exploration (of conditions or actions never learnt before) and exploitation (of already learnt conditions or actions from previous encounters). Multi-arm bandit problems is one of the category of RL algorithms where exploration vs. exploitation trade-off have been thoroughly studied. See figure below for [reference](http://www.simongrant.org/pubs/thesis/3/2.html).\n",
    "\n",
    "<img src=\"https://cntk.ai/jup/polecart.gif\", width=300, height=300>\n",
    "\n",
    "**Problem**\n",
    "\n",
    "We will use the [CartPole](https://gym.openai.com/envs/CartPole-v0) environment from OpenAI's [gym](https://github.com/openai/gym) simulator to teach a cart to balance a pole. As described in the link above, in the CartPole example, a pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The system is controlled by applying a force of +1 or -1 to the cart. A reward of +1 is provided for every timestep that the pole remains upright. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center. See figure below for reference.\n",
    "\n",
    "**Goal**\n",
    "Our goal is to prevent the pole from falling over as the cart moves with the pole in upright position (perpendicular to the cart) as the starting state. More specifically if the pole is less than 15 degrees from vertical while the cart is within 2.4 units of the center we will collect reward. In this tutorial, we will train till we learn a set of actions (policies) that lead to an average reward of 200 or more over last 50 batches. \n",
    "\n",
    "In, RL terminology, the goal is to find _policies_ $a$, that maximize the _reward_ $r$ (feedback) through interaction with some environment (in this case the pole being balanced on the cart). So given a series of experiences $$s \\xrightarrow{a} r, s'$$ we then can learn how to choose action $a$ in a given state $s$ to maximize the accumulated reward $r$ over time: \n",
    "\\begin{align}\n",
    "Q(s,a) &= r_0 + \\gamma r_1 + \\gamma^2 r_2 + \\ldots \\newline\n",
    "&= r_0 + \\gamma \\max_a Q^*(s',a)\n",
    "\\end{align}\n",
    "where $\\gamma \\in [0,1)$ is the discount factor that controls how much we should value reward that is further away. This is called the [*Bellmann*-equation](https://en.wikipedia.org/wiki/Bellman_equation). \n",
    "\n",
    "In this tutorial we will show how to model the state space, how to use the received reward to figure out which action yields the highest future reward. \n",
    "\n",
    "We present two different popular approaches here:\n",
    "\n",
    "**Deep Q-Networks**: DQNs have become famous in 2015 when they were successfully used to train how to play Atari just form raw pixels. We train neural network to learn the $Q(s,a)$ values (thus _Q-Network _). From these $Q$ functions values we choose the best action.\n",
    "\n",
    "**Policy gradient**: This method directly estimates the policy (set of actions) in the network. The outcome is a learning of an ordered set of actions which leads to maximize reward by probabilistically choosing a subset of actions. In this tutorial, we learn the actions using a gradient descent approach to learn the policies.\n",
    "\n",
    "In this tutorial, we focus how to implement RL in CNTK. We choose a straight forward shallow network. One can extend the approaches by replacing our shallow model with deeper networks that are introduced in other CNTK tutorials.  \n",
    "\n",
    "Additionally, this tutorial is in its early stages and will be evolving in future updates."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Before we start...\n",
    "Please run the following cell from the menu above or select the cell below and hit `Shift + Enter` to ensure the environment is ready. Verify that the following imports work in your notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from matplotlib import style\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "style.use('ggplot')\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We use the following construct to install the OpenAI gym package if it is not installed. For users new to Jupyter environment, this construct can be used to install any python package. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import gym\n",
    "except:\n",
    "    !pip install gym\n",
    "    import gym"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# CartPole: Data and Environment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will use the [CartPole](https://gym.openai.com/envs/CartPole-v0) environment from OpenAI's [gym](https://github.com/openai/gym) simulator to teach a cart to balance a pole. Please follow the links to get more details.\n",
    "\n",
    "In every time step, the agent\n",
    " * gets an observation $(x, \\dot{x}, \\theta, \\dot{\\theta})$, corresponding to *cart position*, *cart velocity*, *pole angle with the vertical*, *pole angular velocity*,\n",
    " * performs an action `LEFT` or `RIGHT`, and\n",
    " * receives \n",
    "  * a reward of +1 for having survived another time step, and\n",
    "  * a new state $(x', \\dot{x}', \\theta', \\dot{\\theta}')$\n",
    " \n",
    "The episode ends, if \n",
    " * the pole is more than 15 degrees from vertical and/or\n",
    " * the cart is moving more than 2.4 units from center.\n",
    " \n",
    "The task is considered done, if\n",
    " * the agent achieved and averaged reward of 200 over the last 50 episodes (if you manage to get a reward of 200 averaged over the last 100 episode you can consider submitting it to OpenAI)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Part 1: DQN\n",
    "\n",
    "After a transition $(s,a,r,s')$, we are trying to move our value function $Q(s,a)$ closer to our target $r+\\gamma \\max_{a'}Q(s',a')$, where $\\gamma$ is a discount factor for future rewards and ranges in value between 0 and 1.\n",
    "\n",
    "DQNs\n",
    " * learn the _Q-function_ that maps observation (state, action) to a `score`\n",
    " * use memory replay (previously recorded $Q$ values corresponding to different $(s,a)$ to decorrelate experiences (sequence state transitions)\n",
    " * use a second network to stabilize learning (*not* part of this tutorial)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setting up the model\n",
    "\\begin{equation}\n",
    "l_1 = relu( x W_1 + b_1) \\\\\n",
    "Q(s,a) = l_1 W_2 + b_2 \\\\\n",
    "\\end{equation}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will start with a slightly modified version for Keras, https://github.com/jaara/AI-blog/blob/master/CartPole-basic.py, published by Jaromír Janisch in his [AI blog](https://jaromiru.com/2016/09/27/lets-make-a-dqn-theory/), and will then incrementally convert it to use CNTK. \n",
    "\n",
    "We use a simple two-layer densely connected network, for simpler illustrations. More advance networks can be substituted.\n",
    "\n",
    "**CNTK** concepts: The commented out code is meant to be an illustration of the similarity of concepts between CNTK API/abstractions against Keras. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import random, numpy, math\n",
    "\n",
    "#from keras.models import Sequential\n",
    "#from keras.layers import *\n",
    "#from keras.optimizers import *\n",
    "from cntk import *\n",
    "from cntk.models import Sequential\n",
    "from cntk.layers import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "STATE_COUNT = 4 (corresponding to $(x, \\dot{x}, \\theta, \\dot{\\theta})$),\n",
    "\n",
    "ACTION_COUNT = 2 (corresponding to `LEFT` or `RIGHT`)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "env = gym.make('CartPole-v0')\n",
    "\n",
    "STATE_COUNT  = env.observation_space.shape[0]\n",
    "ACTION_COUNT = env.action_space.n\n",
    "\n",
    "STATE_COUNT, ACTION_COUNT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note: in the cell below we highlight how one would do it in Keras. And a marked similarity with CNTK. While CNTK allows for more compact representation, we present a slightly verbose illustration for ease of learning.\n",
    "\n",
    "Additionally, you will note that, CNTK model doesn't need to be compiled explicitly and is implicitly done when data is processed during training.\n",
    "\n",
    "CNTK effectively uses available memory on the system between minibatch execution. Thus the learning rates are stated as **rates per sample** instead of **rates per minibatch** (as with other toolkits)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "BATCH_SIZE_BASELINE = 50  # calculate average reward over these many episodes\n",
    "H = 64 # hidden layer size\n",
    "\n",
    "class Brain:\n",
    "    def __init__(self):\n",
    "        self.params = {}\n",
    "        self.model, self.trainer, self.loss = self._create()\n",
    "        # self.model.load_weights(\"cartpole-basic.h5\")\n",
    "        \n",
    "    def _create(self):\n",
    "        observation = input_variable(STATE_COUNT, np.float32, name=\"s\")\n",
    "        q_target = input_variable(ACTION_COUNT, np.float32, name=\"q\")\n",
    "\n",
    "        # model = Sequential()\n",
    "        # model.add(Dense(output_dim=64, activation='relu', input_dim=STATE_COUNT))\n",
    "        # model.add(Dense(output_dim=ACTION_COUNT, activation='linear'))\n",
    "\n",
    "        # Following a style similar to Keras \n",
    "        l1 = Dense(H, activation=relu)\n",
    "        l2 = Dense(ACTION_COUNT)\n",
    "        unbound_model = Sequential([l1, l2])\n",
    "        model = unbound_model(observation)\n",
    "\n",
    "        self.params = dict(W1=l1.W, b1=l1.b, W2=l2.W, b2=l2.b)            \n",
    "        \n",
    "        lr = 0.00025\n",
    "        # opt = RMSprop(lr=0.00025)\n",
    "        # model.compile(loss='mse', optimizer=opt)\n",
    "\n",
    "        # loss='mse'\n",
    "        loss = reduce_mean(square(model - q_target), axis=0)\n",
    "        meas = reduce_mean(square(model - q_target), axis=0)\n",
    "\n",
    "        # optimizer=opt\n",
    "        lr_schedule = learning_rate_schedule(lr, UnitType.minibatch)\n",
    "        learner = sgd(model.parameters, lr_schedule, gradient_clipping_threshold_per_sample=10)\n",
    "        trainer = Trainer(model, loss, meas, learner)\n",
    "\n",
    "        # CNTK: return trainer and loss as well\n",
    "        return model, trainer, loss\n",
    "\n",
    "    def train(self, x, y, epoch=1, verbose=0):\n",
    "        #self.model.fit(x, y, batch_size=64, nb_epoch=epoch, verbose=verbose)\n",
    "        arguments = dict(zip(self.loss.arguments, [y,x]))\n",
    "        updated, results =self.trainer.train_minibatch(arguments, outputs=[self.loss.output])\n",
    "\n",
    "    def predict(self, s):\n",
    "        return self.model.eval([s])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Memory` class stores the different states, actions and rewards."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Memory:   # stored as ( s, a, r, s_ )\n",
    "    samples = []\n",
    "\n",
    "    def __init__(self, capacity):\n",
    "        self.capacity = capacity\n",
    "\n",
    "    def add(self, sample):\n",
    "        self.samples.append(sample)        \n",
    "\n",
    "        if len(self.samples) > self.capacity:\n",
    "            self.samples.pop(0)\n",
    "\n",
    "    def sample(self, n):\n",
    "        n = min(n, len(self.samples))\n",
    "        return random.sample(self.samples, n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Agent` uses the `Brain` and `Memory` to replay the past actions to choose optimal set of actions that maximize the rewards."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "MEMORY_CAPACITY = 100000\n",
    "BATCH_SIZE = 64\n",
    "\n",
    "GAMMA = 0.99 # discount factor\n",
    "\n",
    "MAX_EPSILON = 1\n",
    "MIN_EPSILON = 0.01 # stay a bit curious even when getting old\n",
    "LAMBDA = 0.0001    # speed of decay\n",
    "\n",
    "class Agent:\n",
    "    steps = 0\n",
    "    epsilon = MAX_EPSILON\n",
    "\n",
    "    def __init__(self):\n",
    "        self.brain = Brain()\n",
    "        self.memory = Memory(MEMORY_CAPACITY)\n",
    "        \n",
    "    def act(self, s):\n",
    "        if random.random() < self.epsilon:\n",
    "            return random.randint(0, ACTION_COUNT-1)\n",
    "        else:\n",
    "            return numpy.argmax(self.brain.predict(s))\n",
    "\n",
    "    def observe(self, sample):  # in (s, a, r, s_) format\n",
    "        self.memory.add(sample)        \n",
    "\n",
    "        # slowly decrease Epsilon based on our eperience\n",
    "        self.steps += 1\n",
    "        self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps)\n",
    "\n",
    "    def replay(self):    \n",
    "        batch = self.memory.sample(BATCH_SIZE)\n",
    "        batchLen = len(batch)\n",
    "\n",
    "        no_state = numpy.zeros(STATE_COUNT)\n",
    "\n",
    "        \n",
    "        # CNTK: explicitly setting to float32\n",
    "        states = numpy.array([ o[0] for o in batch ], dtype=np.float32)\n",
    "        states_ = numpy.array([(no_state if o[3] is None else o[3]) for o in batch ], dtype=np.float32)\n",
    "\n",
    "        p = agent.brain.predict(states)\n",
    "        p_ = agent.brain.predict(states_)\n",
    "\n",
    "        # CNTK: explicitly setting to float32\n",
    "        x = numpy.zeros((batchLen, STATE_COUNT)).astype(np.float32)\n",
    "        y = numpy.zeros((batchLen, ACTION_COUNT)).astype(np.float32)\n",
    "        \n",
    "        for i in range(batchLen):\n",
    "            s, a, r, s_ = batch[i]\n",
    "            \n",
    "            # CNTK: [0] because of sequence dimension\n",
    "            t = p[0][i]\n",
    "            if s_ is None:\n",
    "                t[a] = r\n",
    "            else:\n",
    "                t[a] = r + GAMMA * numpy.amax(p_[0][i])\n",
    "\n",
    "            x[i] = s\n",
    "            y[i] = t\n",
    "\n",
    "        self.brain.train(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Brain surgery\n",
    "\n",
    "As any learning experiences, we expect to see the initial state of actions to be wild exploratory and over the iterations the system learns the range of actions that yield longer runs and collect more rewards. The tutorial below implements the [$\\epsilon$-greedy](https://en.wikipedia.org/wiki/Reinforcement_learning) approach. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "def plot_weights(weights, figsize=(7,5)):\n",
    "    '''Heat map of weights to see which neurons play which role'''\n",
    "    sns.set(style=\"white\")\n",
    "    f, ax = plt.subplots(len(weights), figsize=figsize)\n",
    "    cmap = sns.diverging_palette(220, 10, as_cmap=True)\n",
    "\n",
    "    for i, data in enumerate(weights):\n",
    "        axi = ax if len(weights)==1 else ax[i]\n",
    "        if isinstance(data, tuple): \n",
    "            w, title = data\n",
    "            axi.set_title(title)\n",
    "        else:\n",
    "            w = np.asarray(data)\n",
    "        sns.heatmap(w, cmap=cmap, square=True, center=True, #annot=True,\n",
    "                    linewidths=.5, cbar_kws={\"shrink\": .25}, ax=axi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exploration - exploitation trade-off\n",
    "\n",
    "Note that the initial $\\epsilon$ is set to 1 which implies we are entirely exploring but as steps increase we reduce exploration and start leveraging the learnt space to collect rewards (a.k.a. exploitation) as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def epsilon(steps):\n",
    "    return MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * np.exp(-LAMBDA * steps)\n",
    "plt.plot(range(10000), [epsilon(x) for x in range(10000)], 'r')\n",
    "plt.xlabel('step');plt.ylabel('$\\epsilon$')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are now ready to train our agent using **DQN**. Note this would take anywhere between 2-10 min and we stop whenever the learner hits the average reward of 200 over past 50 batches. One would get better results if they could train the learner until say one hits a reward of 200 or higher for say larger number of runs. This is left as an exercise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def run(agent):\n",
    "    s = env.reset()\n",
    "    R = 0 \n",
    "\n",
    "    while True:            \n",
    "        #env.render()\n",
    "\n",
    "        # CNTK: explicitly setting to float32\n",
    "        a = agent.act(s.astype(np.float32))\n",
    "\n",
    "        s_, r, done, info = env.step(a)\n",
    "\n",
    "        if done: # terminal state\n",
    "            s_ = None\n",
    "\n",
    "        agent.observe((s, a, r, s_))\n",
    "        agent.replay()            \n",
    "\n",
    "        s = s_\n",
    "        R += r\n",
    "\n",
    "        if done:\n",
    "            return R\n",
    "\n",
    "agent = Agent()\n",
    "\n",
    "episode_number = 0\n",
    "reward_sum = 0\n",
    "while episode_number<3000:\n",
    "    reward_sum += run(agent)\n",
    "    episode_number += 1\n",
    "    if episode_number % BATCH_SIZE_BASELINE == 0:\n",
    "        print('Episode: %d, Average reward for episode %f.' % (episode_number, \n",
    "                                                               reward_sum / BATCH_SIZE_BASELINE))\n",
    "        if episode_number%200==0:\n",
    "            plot_weights([(agent.brain.params['W1'], 'Episode %i $W_1$'%episode_number)], figsize=(14,5))\n",
    "        if reward_sum / BATCH_SIZE_BASELINE > 200:\n",
    "            print('Task solved in %d episodes' % episode_number)\n",
    "            plot_weights([(agent.brain.params['W1'], 'Episode %i $W_1$'%episode_number)], figsize=(14,5))            \n",
    "            break\n",
    "        reward_sum = 0\n",
    "agent.brain.model.save_model('dqn.mod', False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you run it, you should see something like\n",
    "\n",
    "```[2016-10-26 22:06:25,436] Making new env: CartPole-v0\n",
    "Episode: 50, Average reward for episode 23.700000.\n",
    "Episode: 100, Average reward for episode 18.720000.\n",
    "Episode: 150, Average reward for episode 17.960000.\n",
    "...\n",
    "Episode: 1750, Average reward for episode 100.180000.\n",
    "Episode: 1800, Average reward for episode 111.380000.\n",
    "Episode: 1850, Average reward for episode 207.240000.\n",
    "Task solved in 1850 episodes```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Task 1.1\n",
    "Rewrite the model without using the layer lib.\n",
    "#### Task 1.2\n",
    "Play with different [learners](https://cntk.ai/pythondocs/cntk.learner.html?highlight=learner#module-cntk.learner). Which one works better? Worse? Think about which parameters you would need to adapt when switching from one learner to the other."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Running the DQN model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import cntk as C\n",
    "env = gym.make('CartPole-v0')\n",
    "\n",
    "num_episodes = 10  # number of episodes to run\n",
    "\n",
    "modelPath = 'dqn.mod'\n",
    "root = C.load_model(modelPath)\n",
    "observation = env.reset()  # reset environment for new episode\n",
    "done = False\n",
    "for i_episode in range(num_episodes):\n",
    "    print(i_episode)\n",
    "    while not done:\n",
    "        env.render()\n",
    "        action = np.argmax(root.eval([observation.astype(np.float32)]))\n",
    "        observation, reward, done, info = env.step(action)\n",
    "    if done:\n",
    "        observation = env.reset()  # reset environment for new episode    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Part 2: Policy gradient\n",
    "**Goal:** \n",
    "\\begin{equation}\\text{maximize } E [R | \\pi_\\theta]\n",
    "\\end{equation}\n",
    "\n",
    "**Approach:**\n",
    "1. Collect experience (sample a bunch of trajectories through $(s,a)$ space)\n",
    "2. Update the policy so that _good_ experiences become more probable\n",
    "\n",
    "**Difference to DQN: **\n",
    " * we don't consider single $(s,a,r,s')$ transitions, but rather use whole episodes for the gradient updates\n",
    " * our parameters directly model the policy (output is an action probability), whereas in DQN they model the value function (output is raw score)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Rewards:\n",
    "Remember, we get +1 reward for every time step, in which we still were in the game. \n",
    "\n",
    "The problem: we normally do not know, which action led to a continuation of the game, and which was actually a bad one. Our simple heuristic: actions in the beginning of the episode are good, and those towards the end are likely bad (they led to losing the game after all)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def discount_rewards(r, gamma=0.999):\n",
    "    \"\"\"Take 1D float array of rewards and compute discounted reward \"\"\"\n",
    "    discounted_r = np.zeros_like(r)\n",
    "    running_add = 0\n",
    "    for t in reversed(range(0, r.size)):\n",
    "        running_add = running_add * gamma + r[t]\n",
    "        discounted_r[t] = running_add\n",
    "    return discounted_r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "discounted_epr = discount_rewards(np.ones(10))\n",
    "f, ax = plt.subplots(1, figsize=(5,2))\n",
    "sns.barplot(list(range(10)), discounted_epr, color=\"steelblue\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We normalize the rewards so that they tank below zero towards the end. gamma controls how late the rewards tank."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "discounted_epr_cent = discounted_epr - np.mean(discounted_epr)\n",
    "discounted_epr_norm = discounted_epr_cent/np.std(discounted_epr_cent)\n",
    "f, ax = plt.subplots(1, figsize=(5,2))\n",
    "sns.barplot(list(range(10)), discounted_epr_norm, color=\"steelblue\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "discounted_epr = discount_rewards(np.ones(10), gamma=0.5)\n",
    "discounted_epr_cent = discounted_epr - np.mean(discounted_epr)\n",
    "discounted_epr_norm = discounted_epr_cent/np.std(discounted_epr_cent)\n",
    "f, ax = plt.subplots(2, figsize=(5,3))\n",
    "sns.barplot(list(range(10)), discounted_epr, color=\"steelblue\", ax=ax[0])\n",
    "sns.barplot(list(range(10)), discounted_epr_norm, color=\"steelblue\", ax=ax[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setting up the model\n",
    "\\begin{equation}\n",
    "l_1 = relu( x W_1 + b_1) \\\\\n",
    "l_2 = l_1 W_2 + b_2 \\\\\n",
    "\\pi(a|s) = sigmoid(l_2)\n",
    "\\end{equation}\n",
    "\n",
    "Note: in policy gradient approach, the output of the dense layer is mapped into to a 0-1 range via the sigmoid function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import cntk as C \n",
    "\n",
    "TOTAL_EPISODES = 10000\n",
    "D = 4  # input dimensionality\n",
    "H = 10 # number of hidden layer neurons\n",
    "\n",
    "observations = C.input_variable(STATE_COUNT, np.float32, name=\"obs\")\n",
    "\n",
    "W1 = C.parameter(shape=(STATE_COUNT, H), init=C.glorot_uniform(), name=\"W1\")\n",
    "b1 = C.parameter(shape=H, name=\"b1\")\n",
    "layer1 = C.relu(C.times(observations, W1) + b1)\n",
    "\n",
    "W2 = C.parameter(shape=(H, ACTION_COUNT), init=C.glorot_uniform(), name=\"W2\")\n",
    "b2 = C.parameter(shape=ACTION_COUNT, name=\"b2\")\n",
    "score = C.times(layer1, W2) + b2\n",
    "# Until here it was similar to DQN\n",
    "\n",
    "probability = C.sigmoid(score, name=\"prob\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Policy Search**: The optimal policy search can be carried out with either gradient free approaches or by computing gradients over the policy space ($\\pi_\\theta$) which is parameterized by $\\theta$. In this tutorial, we use the classic forward (`loss.forward`) and back (`loss.backward`) propagation of errors over the parameterized space $\\theta$. In this case, $\\theta = \\{W_1, b_1, W_2, b_2\\}$, our model parameters.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "input_y = C.input_variable(1, np.float32, name=\"input_y\")\n",
    "advantages = C.input_variable(1, np.float32, name=\"advt\")\n",
    "\n",
    "loss = -C.reduce_mean(C.log(C.square(input_y - probability) + 1e-4) * advantages, axis=0, name='loss')\n",
    "\n",
    "lr = 0.001 \n",
    "lr_schedule = learning_rate_schedule(lr, UnitType.sample) \n",
    "sgd = C.sgd([W1, W2], lr_schedule)\n",
    "\n",
    "gradBuffer = dict((var.name, np.zeros(shape=var.shape)) for var in loss.parameters if var.name in ['W1', 'W2', 'b1', 'b2'])\n",
    "\n",
    "xs, hs, label, drs = [], [], [], []\n",
    "running_reward = None\n",
    "reward_sum = 0\n",
    "episode_number = 1\n",
    "\n",
    "observation = env.reset()\n",
    "\n",
    "while episode_number <= TOTAL_EPISODES:\n",
    "    x = np.reshape(observation, [1, STATE_COUNT]).astype(np.float32)\n",
    "\n",
    "    # Run the policy network and get an action to take.\n",
    "    prob = probability.eval(arguments={observations: x})[0][0][0]\n",
    "    action = 1 if np.random.uniform() < prob else 0\n",
    "\n",
    "    xs.append(x)  # observation\n",
    "    # grad that encourages the action that was taken to be taken\n",
    "\n",
    "    y = 1 if action == 0 else 0  # a \"fake label\"\n",
    "    label.append(y)\n",
    "\n",
    "    # step the environment and get new measurements\n",
    "    observation, reward, done, info = env.step(action)\n",
    "    reward_sum += float(reward)\n",
    "\n",
    "    # Record reward (has to be done after we call step() to get reward for previous action)\n",
    "    drs.append(float(reward))\n",
    "\n",
    "    if done:\n",
    "        # Stack together all inputs, hidden states, action gradients, and rewards for this episode\n",
    "        epx = np.vstack(xs)\n",
    "        epl = np.vstack(label).astype(np.float32)\n",
    "        epr = np.vstack(drs).astype(np.float32)\n",
    "        xs, label, drs = [], [], []  # reset array memory\n",
    "\n",
    "        # Compute the discounted reward backwards through time.\n",
    "        discounted_epr = discount_rewards(epr)\n",
    "        # Size the rewards to be unit normal (helps control the gradient estimator variance)\n",
    "        discounted_epr -= np.mean(discounted_epr)\n",
    "        discounted_epr /= np.std(discounted_epr)\n",
    "\n",
    "        # Forward pass\n",
    "        arguments = {observations: epx, input_y: epl, advantages: discounted_epr}\n",
    "        state, outputs_map = loss.forward(arguments, outputs=loss.outputs, \n",
    "                                          keep_for_backward=loss.outputs)\n",
    "        \n",
    "        # Backward psas\n",
    "        root_gradients = {v: np.ones_like(o) for v, o in outputs_map.items()}\n",
    "        vargrads_map = loss.backward(state, root_gradients, variables=set([W1, W2]))\n",
    "\n",
    "        for var, grad in vargrads_map.items():\n",
    "            gradBuffer[var.name] += grad\n",
    "\n",
    "        # Wait for some batches to finish to reduce noise\n",
    "        if episode_number % BATCH_SIZE_BASELINE == 0:\n",
    "            grads = {W1: gradBuffer['W1'].astype(np.float32), \n",
    "                     W2: gradBuffer['W2'].astype(np.float32)}\n",
    "            updated = sgd.update(grads, BATCH_SIZE_BASELINE)\n",
    "\n",
    "            # reset the gradBuffer\n",
    "            gradBuffer = dict((var.name, np.zeros(shape=var.shape)) \n",
    "                              for var in loss.parameters if var.name in ['W1', 'W2', 'b1', 'b2'])\n",
    "\n",
    "            print('Episode: %d. Average reward for episode %f.' % (episode_number, reward_sum / BATCH_SIZE_BASELINE))\n",
    "\n",
    "            if reward_sum / BATCH_SIZE_BASELINE > 200:\n",
    "                print('Task solved in: %d ' % episode_number)\n",
    "                break\n",
    "\n",
    "            reward_sum = 0\n",
    "\n",
    "        observation = env.reset()  # reset env\n",
    "        episode_number += 1\n",
    "probability.save_model('pg.mod', False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Solutions\n",
    "#### Solution 1.1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "observation = input_variable(STATE_COUNT, np.float32, name=\"s\")\n",
    "\n",
    "W1 = parameter(shape=(STATE_COUNT, H), init=glorot_uniform(), name=\"W1\")\n",
    "b1 = parameter(shape=H, name=\"b1\")\n",
    "layer1 = relu(times(observation, W1) + b1)\n",
    "W2 = parameter(shape=(H, ACTION_COUNT), init=glorot_uniform(), name=\"W2\")\n",
    "b2 = parameter(shape=ACTION_COUNT, name=\"b2\")\n",
    "model = times(layer1, W2) + b2\n",
    "W1.shape, b1.shape, W2.shape, b2.shape, model.shape"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "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.4.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
back to top