{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "10b81170-9c77-44e0-d2f1-37c8d50e9d46"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "6026b7a6-7d1c-4459-88ee-3bdf038dedb3"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "expected_utility = r\"\"\" $EU(a) = \\sum_s P(RESULT(a) = s')U(s')$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" \n",
        "**Combining Beliefs and Desires under Uncertainty**\n",
        "- The agent's preferences are captured by a **utility function**, \\\n",
        "which assigns a single number to express the desirability of a state.\n",
        "- **Expected utility** of an action given the evidence is the average utility value fo the outcomes, \\\n",
        "weighted by the probability that the outcome occurs:\n",
        "\n",
        "**Maximum expected utility (MEU)** principle\n",
        "- a rational agent should choose the action that maximizes the agent's expected utility. \n",
        "- If an agent acts so as to maximize a utility function that correctly reflects the performance measure,\\\n",
        " then the agent will achieve the highest possible performance score.\"\"\"\n",
        "\n",
        "chapter16_2 =  \"\"\" **The Basis of Utility Theory**\n",
        "- ***6 Constraints that we require any reasonable preference relation to obey***\n",
        "  - *Orderability*: The agent has to decide its preference\n",
        "  - *Transitivity*: A>B, B>C, then A>C\n",
        "  - *Continuity*\n",
        "  - *Substitutability* : If the agent is indifferent about A and B, then B can substitute A\n",
        "  - *Monotonicity* : If A>B then prefer lotter with higher probability for A\n",
        "  - *Decomposability*\n",
        "\n",
        "- *value function* or *utility function* : preference ranking on states in a deterministic environment.\n",
        "\"\"\"\n",
        "chapter16_3 =  \"\"\" **Utility function**\n",
        "- Must obey the 6 constraints\n",
        "- \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\"\n",
        "**Markov Decision Processes**\n",
        "- A **sequential** decision problem\n",
        "- **Fully observable** environment\n",
        "- with a **stochastic** transition model\n",
        "- Has **additive rewards**\n",
        "- **Non-deterministic search problem**\n",
        "- Solve through **expectimax** search\n",
        "\n",
        "To find MDP solution(policy),\n",
        "- We need:\n",
        "  - A set of states *S*\n",
        "  - A set of actions *A*\n",
        "  - A transition function (probability = the model) P(s’|s,a) (or T(s,a,s’))\n",
        "  - A reward function (utility function) R(s,a,s’) (and discount gamma) \n",
        "  - An initial state *S0*\n",
        "  - One or more terminal states\n",
        "\n",
        "- Policy === solution\n",
        "  - Maps from a state onto the action to take if the agent is in that state\n",
        "  - $\\pi$(s) = a\n",
        "  - $\\pi$*(s) is the *optimal policy*: maximizes the expected utility of the actions taken by the agent.\n",
        "  - Even though the policy told me to go to a certain direction, there is no guarantee that it will go there. It is **stochastic**\n",
        "  \n",
        "- We need to compute the **expected utility** of all the possible paths generated by a policy\n",
        "-\tEven if the same policy is executed multiple times by the agent, this may lead to different sequence of states and actions (environment history) and thus a different score under the reward function\n",
        "- the *performance* of an agent is the sum of the rewards for the transitions it takes.\n",
        "\n",
        "**Discounting**\n",
        "- Each time we descend a level, we multiply in the discount factor once\n",
        "- Make values of rewards decay exponentially\n",
        "- *Why?* \n",
        "  - Sooner rewards probably have higher utility than later rewards\n",
        "  - This helps our algorithms converge\n",
        "  - We want more rewards sooner because the world is uncertain.\n",
        "\n",
        "**Stationary Preferences**\n",
        "- Theorem: If we assume stationary preferences, then there are only two ways to define utilities \\\n",
        "*additive and discounted utility*\n",
        "\n",
        "**Infinite Utilities**\n",
        "- Solutions to infinite utilities\n",
        "  - Finite horizon: terminate episodes after a fixed T steps -- try to avoid this\n",
        "  - Discounting\n",
        "    - smaller gamma means smaller \"horizon\" - shorter term focus\n",
        "  - Absorbing state\n",
        "    - Guarantee that for every policy, a terminal state will eventually be reached\n",
        "    \n",
        "**Reward function** (utility function)\n",
        "  - “rewards” can be positive or negative but are bounded by some maximum value\n",
        "  - We must specify the utility function on a sequence of states and actions because the decision process is sequential\n",
        "  - The agent can receive a reward at each time step based on its transition from s to s’ via action a.\n",
        "  - R(s, a, s’)\n",
        "  - Rewards are additive\n",
        "\n",
        "**Stochastic transition function**\n",
        "  - P(s’ | s, a) or T(s,a,s’)\n",
        "  - The probability of arriving in state s’ given that we are in state s and we selected action a\n",
        "  - Transitions are Markovian: the probability of arriving in s’ only depends on \\\n",
        "  s and not the history of earlier states\n",
        "\n",
        "\n",
        "**Optimal Quantities**\n",
        "- The value (utility) of a state s:\n",
        "  - V*(s) = expected utility starting in s and acting optimally \n",
        "-\tThe value (utility) of a q-state (s,a):\n",
        "  - Q*(s,a) = expected utility starting out having taken action a from state s and acting optimally\n",
        "-\tThe optimal policy:\n",
        "  - $\\pi$*(s) = optimal action from state s\n",
        "\n",
        "**Values of States**\n",
        "-\tFundamental operation: compute the expectimax value of a state\n",
        "  - Expected utility under optimal action\n",
        "  - Average sum of discounted rewards\n",
        "  - Recursive definition of value:\n",
        "    $V*(s) = max Q*(s,a)\n",
        "- We want to find the optimal quantity\n",
        "\n",
        "**Hyperdrive Search Tree**\n",
        "- each level of tree, you get a reward\n",
        "\n",
        "**Racing Search Tree**\n",
        "\n",
        "**Bellman Equation** - characterize optimal value\n",
        "- A rule of how to be optimal/maximize utility in an uncertain world\n",
        "- Use expectimax recurrence to see a simple one-step lookahead relationship amongst optimal utility values\n",
        "- $V^*(s) = max \\sum_s' T(s,a,s')[R(s,a,s')+\\gamma V*(s')])$\n",
        "\n",
        "**Value Iteration**\n",
        "- Start with V_0(s) = 0: no time steps left means an expected reward sum of zero\n",
        "- Given vector of V_k(s) values, do one ply of expectimax from each state\n",
        "- Repeat until convergence\n",
        "- Complexity of each iteration: $O(S^2A)$\n",
        "- *Theorem*: will converge to unique optimal values\n",
        "  - basic idea: approximations get refined towards optimal values\n",
        "  - Policy may converge long before values do\n",
        "\n",
        "**Convergence**\n",
        "- *How do we know then the Vk vectors are going to converge*\n",
        "  1. If the tree has maximum depth M, then Vm holds the actual untruncated values\n",
        "  2. If the discount is less than 1\n",
        "- How fast it converges depends on *$\\gamma$ or effective depth*\n",
        "  - closer to 1, deeper the depth gets\n",
        "\n",
        "**Fixed Policies**\n",
        "- If we fix some policy $\\pi$(s) then the tree would be simpler - only one action per state\n",
        "- *Finding utilities* does not include $max$\n",
        "\n",
        "**Policy Evaluation**\n",
        "- How do we calculate the V's for a fixed policy $\\pi$\n",
        "- Idea 1: Turn recursive Bellman equations into updates (like value iteration)\n",
        "  - Efficiency: O(S^2) per iteration\n",
        "- Idea 2: Without the maxes the Bellman equations are linear system\n",
        "\n",
        "**Policy Extraction**\n",
        "  **Computing actions from values**\n",
        "  - $\\pi^*(s) = arg max \\sum_s' T(s,a,s')[R(s,a,s')+\\gamma V*(s')])$\n",
        "  - Performing one expectimax(one step)\n",
        "  - *policy extraction* = Gets the policy implied by the values\n",
        "\n",
        "  **Computing actions from Q-values**\n",
        "  - Just choose the best value\n",
        "  - $\\pi^*(s) = arg max Q^*(s,a)$\n",
        "\n",
        "**Policy Iteration**\n",
        "- *Problems with value iteration*\n",
        "  - It's slow - O(S^2A) per iteration\n",
        "  - The \"max\" at each state rarely changes\n",
        "  - The policy often converges long before the values\n",
        "- Approach\n",
        "  - Step 1: Policy evaluation: calculate utilities for some fixed policy (not optimal utilities ) until convergence\n",
        "  - Step 2: Policy improvement: update policy using one-step look-ahead with resulting converged (but not optimal) utilities as future values\n",
        "  - Repeat steps until policy converges\n",
        "- Converges faster than value iteration\n",
        "\n",
        "**Value vs. Policy Iteration**\n",
        "- Both value iteration and policy iteration compute the same thing (all optimal values)\n",
        "- In *value iteration*:\n",
        "  • Every iteration updates both the values and (implicitly) the policy\n",
        "  • We don’t track the policy, but taking the max over actions implicitly recomputes it\n",
        "- In *policy iteration*:\n",
        "  • We do several passes that update utilities with fixed policy (each pass is fast because we consider only one action, not all of them)\n",
        "  • After the policy is evaluated, a new policy is chosen (slow like a value iteration pass)\n",
        "  • The new policy will be better (or we’re done) \n",
        "- Both are dynamic programs for solving MDPs\n",
        "\n",
        "**MDP Algorithms**\n",
        "- to Compute *optimal values* : use Value iteration or policy iteration\n",
        "- to Compute values for a *particular policy*: use policy evaluation\n",
        "- to Turn your values into a policy: use policy extraction (one-step lookahead)\n",
        "\n",
        "These all look the same!\n",
        "• They basically are – they are all variations of Bellman updates\n",
        "• They all use one-step lookahead expectimax fragments\n",
        "• They differ only in whether we plug in a fixed policy or max over actions\n",
        "\n",
        "**Maximum Expected Utility**\n",
        "- Why use average utilities not minimax? Because we are in an uncertain world\n",
        "- *Principle of maximum expected utility*\n",
        "  - A rational agent should choose the action that *maximizes its expected utility, given its knowledge*\n",
        "\n",
        "*Our goal is to **maximize expected utility***\n",
        "\n",
        "**Utilities**\n",
        "- They are functions from outcomes (states of the world) to real numbers that describe an agent's preferences\n",
        "- Any \"rational\" preferences can be summarized as a utility function\n",
        "- They have uncertain outcomes\n",
        "\n",
        "**Preferences**\n",
        "- An agent must have preference among:\n",
        "  - Prizes: A, B , etc.\n",
        "  - Lotteries: situations with uncertain prizes $L = [p,A; (1-p),B]$\n",
        "  - Notation:\n",
        "    - Preference: A>B\n",
        "    - Indifferencce: A~B\n",
        "\n",
        "**Rational Preferences**\n",
        "- *Axioms of Rationality*\n",
        "  - Orderability\n",
        "  - Transitivity\n",
        "  - Continuity \n",
        "  - Substitutability\n",
        "  - Monotonicity\n",
        "\n",
        "**Utility Scales**\n",
        "- *Normalized utilities*: u_+ = 1.0, u=0.0\n",
        "- *Micromorts*: one-millionth chance of death, useful for paying to reduce product risks, etc.\n",
        "- *QALYs*: quality-adjusted life years, useful for medical decisions involving substantial risk \n",
        "\n",
        "**Money**\n",
        "- is not a good utility function\n",
        "- is not in linear fashion\"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"Single number to express the desirability of a state\",\n",
        "\"expected utility\" : \"average utility value of the outcomes, weighted by the probabiliyt that the outcome occurs\" + r\"\"\" $EU(a) = \\sum_s P(RESULT(a) = s')U(s')$ \"\"\",\n",
        "\"Decision-theoretic agent\" : \"Assigns a continuous range of values to states. Can more easiliy choose a better state even when no best state is available\",\n",
        "\"Preference elicitation\" : \"Presenting choices and using the observed preference to pin down the underlying utility function.\",\n",
        "\"Sequential decision problems\" : \"Problems in which agent's utility depends on a sequence of decisions.\",\n",
        "\"Policy\" : \"Choice of action for each state\",\n",
        "\"Utility\" : \"Sum of (discounted) rewards\",\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "ffb345da-13a1-4554-f83d-b6e39b863de6"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n \n**Combining Beliefs and Desires under Uncertainty**\n- The agent's preferences are captured by a **utility function**, which assigns a single number to express the desirability of a state.\n- **Expected utility** of an action given the evidence is the average utility value fo the outcomes, weighted by the probability that the outcome occurs:\n\n**Maximum expected utility (MEU)** principle\n- a rational agent should choose the action that maximizes the agent's expected utility. \n- If an agent acts so as to maximize a utility function that correctly reflects the performance measure, then the agent will achieve the highest possible performance score.\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n **The Basis of Utility Theory**\n- ***6 Constraints that we require any reasonable preference relation to obey***\n  - *Orderability*: The agent has to decide its preference\n  - *Transitivity*: A>B, B>C, then A>C\n  - *Continuity*\n  - *Substitutability* : If the agent is indifferent about A and B, then B can substitute A\n  - *Monotonicity* : If A>B then prefer lotter with higher probability for A\n  - *Decomposability*\n\n- *value function* or *utility function* : preference ranking on states in a deterministic environment.\n\n\n## AIMA Chapter 16.3 Utility Functions\n **Utility function**\n- Must obey the 6 constraints\n- \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n\n**Markov Decision Processes**\n- A **sequential** decision problem\n- **Fully observable** environment\n- with a **stochastic** transition model\n- Has **additive rewards**\n- **Non-deterministic search problem**\n- Solve through **expectimax** search\n\nTo find MDP solution(policy),\n- We need:\n  - A set of states *S*\n  - A set of actions *A*\n  - A transition function (probability = the model) P(s’|s,a) (or T(s,a,s’))\n  - A reward function (utility function) R(s,a,s’) (and discount gamma) \n  - An initial state *S0*\n  - One or more terminal states\n\n- Policy === solution\n  - Maps from a state onto the action to take if the agent is in that state\n  - $\\pi$(s) = a\n  - $\\pi$*(s) is the *optimal policy*: maximizes the expected utility of the actions taken by the agent.\n  - Even though the policy told me to go to a certain direction, there is no guarantee that it will go there. It is **stochastic**\n  \n- We need to compute the **expected utility** of all the possible paths generated by a policy\n-\tEven if the same policy is executed multiple times by the agent, this may lead to different sequence of states and actions (environment history) and thus a different score under the reward function\n- the *performance* of an agent is the sum of the rewards for the transitions it takes.\n\n**Discounting**\n- Each time we descend a level, we multiply in the discount factor once\n- Make values of rewards decay exponentially\n- *Why?* \n  - Sooner rewards probably have higher utility than later rewards\n  - This helps our algorithms converge\n  - We want more rewards sooner because the world is uncertain.\n\n**Stationary Preferences**\n- Theorem: If we assume stationary preferences, then there are only two ways to define utilities *additive and discounted utility*\n\n**Infinite Utilities**\n- Solutions to infinite utilities\n  - Finite horizon: terminate episodes after a fixed T steps -- try to avoid this\n  - Discounting\n    - smaller gamma means smaller \"horizon\" - shorter term focus\n  - Absorbing state\n    - Guarantee that for every policy, a terminal state will eventually be reached\n    \n**Reward function** (utility function)\n  - “rewards” can be positive or negative but are bounded by some maximum value\n  - We must specify the utility function on a sequence of states and actions because the decision process is sequential\n  - The agent can receive a reward at each time step based on its transition from s to s’ via action a.\n  - R(s, a, s’)\n  - Rewards are additive\n\n**Stochastic transition function**\n  - P(s’ | s, a) or T(s,a,s’)\n  - The probability of arriving in state s’ given that we are in state s and we selected action a\n  - Transitions are Markovian: the probability of arriving in s’ only depends on   s and not the history of earlier states\n\n\n**Optimal Quantities**\n- The value (utility) of a state s:\n  - V*(s) = expected utility starting in s and acting optimally \n-\tThe value (utility) of a q-state (s,a):\n  - Q*(s,a) = expected utility starting out having taken action a from state s and acting optimally\n-\tThe optimal policy:\n  - $\\pi$*(s) = optimal action from state s\n\n**Values of States**\n-\tFundamental operation: compute the expectimax value of a state\n  - Expected utility under optimal action\n  - Average sum of discounted rewards\n  - Recursive definition of value:\n    $V*(s) = max Q*(s,a)\n- We want to find the optimal quantity\n\n**Hyperdrive Search Tree**\n- each level of tree, you get a reward\n\n**Racing Search Tree**\n\n**Bellman Equation** - characterize optimal value\n- A rule of how to be optimal/maximize utility in an uncertain world\n- Use expectimax recurrence to see a simple one-step lookahead relationship amongst optimal utility values\n- $V^*(s) = max \\sum_s' T(s,a,s')[R(s,a,s')+\\gamma V*(s')])$\n\n**Value Iteration**\n- Start with V_0(s) = 0: no time steps left means an expected reward sum of zero\n- Given vector of V_k(s) values, do one ply of expectimax from each state\n- Repeat until convergence\n- Complexity of each iteration: $O(S^2A)$\n- *Theorem*: will converge to unique optimal values\n  - basic idea: approximations get refined towards optimal values\n  - Policy may converge long before values do\n\n**Convergence**\n- *How do we know then the Vk vectors are going to converge*\n  1. If the tree has maximum depth M, then Vm holds the actual untruncated values\n  2. If the discount is less than 1\n- How fast it converges depends on *$\\gamma$ or effective depth*\n  - closer to 1, deeper the depth gets\n\n**Fixed Policies**\n- If we fix some policy $\\pi$(s) then the tree would be simpler - only one action per state\n- *Finding utilities* does not include $max$\n\n**Policy Evaluation**\n- How do we calculate the V's for a fixed policy $\\pi$\n- Idea 1: Turn recursive Bellman equations into updates (like value iteration)\n  - Efficiency: O(S^2) per iteration\n- Idea 2: Without the maxes the Bellman equations are linear system\n\n**Policy Extraction**\n  **Computing actions from values**\n  - $\\pi^*(s) = arg max \\sum_s' T(s,a,s')[R(s,a,s')+\\gamma V*(s')])$\n  - Performing one expectimax(one step)\n  - *policy extraction* = Gets the policy implied by the values\n\n  **Computing actions from Q-values**\n  - Just choose the best value\n  - $\\pi^*(s) = arg max Q^*(s,a)$\n\n**Policy Iteration**\n- *Problems with value iteration*\n  - It's slow - O(S^2A) per iteration\n  - The \"max\" at each state rarely changes\n  - The policy often converges long before the values\n- Approach\n  - Step 1: Policy evaluation: calculate utilities for some fixed policy (not optimal utilities ) until convergence\n  - Step 2: Policy improvement: update policy using one-step look-ahead with resulting converged (but not optimal) utilities as future values\n  - Repeat steps until policy converges\n- Converges faster than value iteration\n\n**Value vs. Policy Iteration**\n- Both value iteration and policy iteration compute the same thing (all optimal values)\n- In *value iteration*:\n  • Every iteration updates both the values and (implicitly) the policy\n  • We don’t track the policy, but taking the max over actions implicitly recomputes it\n- In *policy iteration*:\n  • We do several passes that update utilities with fixed policy (each pass is fast because we consider only one action, not all of them)\n  • After the policy is evaluated, a new policy is chosen (slow like a value iteration pass)\n  • The new policy will be better (or we’re done) \n- Both are dynamic programs for solving MDPs\n\n**MDP Algorithms**\n- to Compute *optimal values* : use Value iteration or policy iteration\n- to Compute values for a *particular policy*: use policy evaluation\n- to Turn your values into a policy: use policy extraction (one-step lookahead)\n\nThese all look the same!\n• They basically are – they are all variations of Bellman updates\n• They all use one-step lookahead expectimax fragments\n• They differ only in whether we plug in a fixed policy or max over actions\n\n**Maximum Expected Utility**\n- Why use average utilities not minimax? Because we are in an uncertain world\n- *Principle of maximum expected utility*\n  - A rational agent should choose the action that *maximizes its expected utility, given its knowledge*\n\n*Our goal is to **maximize expected utility***\n\n**Utilities**\n- They are functions from outcomes (states of the world) to real numbers that describe an agent's preferences\n- Any \"rational\" preferences can be summarized as a utility function\n- They have uncertain outcomes\n\n**Preferences**\n- An agent must have preference among:\n  - Prizes: A, B , etc.\n  - Lotteries: situations with uncertain prizes $L = [p,A; (1-p),B]$\n  - Notation:\n    - Preference: A>B\n    - Indifferencce: A~B\n\n**Rational Preferences**\n- *Axioms of Rationality*\n  - Orderability\n  - Transitivity\n  - Continuity \n  - Substitutability\n  - Monotonicity\n\n**Utility Scales**\n- *Normalized utilities*: u_+ = 1.0, u=0.0\n- *Micromorts*: one-millionth chance of death, useful for paying to reduce product risks, etc.\n- *QALYs*: quality-adjusted life years, useful for medical decisions involving substantial risk \n\n**Money**\n- is not a good utility function\n- is not in linear fashion\n\n## Module 8 Definitions\n* **Utility function** - Single number to express the desirability of a state\n* **Expected utility** - average utility value of the outcomes, weighted by the probabiliyt that the outcome occurs $EU(a) = \\sum_s P(RESULT(a) = s')U(s')$ \n* **Decision-theoretic agent** - Assigns a continuous range of values to states. Can more easiliy choose a better state even when no best state is available\n* **Preference elicitation** - Presenting choices and using the observed preference to pin down the underlying utility function.\n* **Sequential decision problems** - Problems in which agent's utility depends on a sequence of decisions.\n* **Policy** - Choice of action for each state\n* **Utility** - Sum of (discounted) rewards\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "chapter17_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_3 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_4 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_5 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\" \n",
        "## Reinforcement Learning \n",
        "- Basic Idea\n",
        "  - Receive feedback in the form of rewards\n",
        "  - Agent's utility is defined by the reward function\n",
        "  - Must learn to act so as to maximize expected rewards\n",
        "  - All learning is based on observed samples of outcomes\n",
        "  \n",
        "- Still assume a *MDP*\n",
        "  - a set of states\n",
        "  - a set of actions \n",
        "  - a model T(s,a,s')\n",
        "  - a reward function R(s,a,s')\n",
        "- Still looking for a policy $\\pi(s)$\n",
        "- **It doesn't know T or R**\n",
        "  - it doesn't know which states are good or what the actions do\n",
        "  - Must actually try actions and states out to learn\n",
        "  \n",
        "**Model-Based Learning**\n",
        "- Learn an approximate model based on experiences\n",
        "- Solve for values as if the learned model were correct\n",
        "- Step 1: Learn empirical MDP model\n",
        "  - Count outcomes s' for each s, a\n",
        "  - Normalize to give an estimate of T(s,a,s')\n",
        "  - Discover each R(s,a,s') when we experience (s,a,s')\n",
        "- Step 2: Solve the learned MDP\n",
        "  - For example, use value iteration, as before\n",
        "\n",
        "**Model-Free Learning**\n",
        "- 1. *Passive Reinforcement Learning*\n",
        "  - Someone else chooses the policy\n",
        "  - Input: a fixed policy $\\pi$(s)\n",
        "  - Goal: learn the state values\n",
        "  - Learner is \"along for the ride\"\n",
        "  - No choice about what actions to take\n",
        "  - Just execute the policy and learn from experience\n",
        "\n",
        "**Direct Evaluation**\n",
        "- Goal: Compute values for each state under $\\pi$\n",
        "- Idea: Average together observed sample values\n",
        "  - act according to $\\pi$\n",
        "  - Every time you visit a state, write down what the sum of discounted rewards turned out to be \n",
        "  - Average those samples\n",
        "- Pros:\n",
        "  - Easy to understand\n",
        "  - Doesn't require any knowledge of T,R\n",
        "  - It eventually computes the correct average values, using just sample transitions\n",
        "- Cons:\n",
        "  - It wastes information about state connections\n",
        "  - Each state must be learned separately\n",
        "  - So, it takes a long time to learn\n",
        "\n",
        "**Temporal Difference Learning**\n",
        "- It is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages\n",
        "- Learn from every experience instead of waiting til the end\n",
        "- Policy still fixed, still doing evaluation\n",
        "- Move values toward value of whatever successor occurs: running average\n",
        "- Update: $V^\\pi(s) <- V^\\pi(s) + \\alpha(sample - V^\\pi(s))\n",
        "- **Exponential moving average**\n",
        "  - the running interpolation update:\n",
        "  - Makes recent samples more important:\n",
        "  - Forgets abou the past (distant past values were wrong anyway)\n",
        "- Decreasing learning rate (alpha) can give converging averages\n",
        "- Start off with big alpha so that current sample worth more, and gradually decrease it\n",
        "- *Cons*\n",
        "  - We can't turn values into a new policy\n",
        "- **We have to learn the Q-values to know what's the best action**\n",
        "- **Model-free Q-Learning**\n",
        "  - $Q(s,a) <- (1-\\alpha)Q(s,a)+(\\alpha)[sample]\n",
        "\n",
        "Q-learning Properties\n",
        "- It eventually converges to optimal policy, even if you are acting suboptimally- *off-policy learning*\n",
        "\n",
        "*Active Reinforcement Learning*\n",
        "- Full reinforcement learning: optimal policies (like value iteration)\n",
        "- You don’t know the transitions T(s,a,s’) \n",
        "- You don’t know the rewards R(s,a,s’)\n",
        "- You choose the actions now\n",
        "- Goal: learn the optimal policy / values\n",
        "- Leaner makers choices\n",
        "- Fundamental tradeoff: exploration vs. exploitation\n",
        "- NOT offline planning\n",
        "\n",
        "**Exploration vs. Exploitation**\n",
        "\n",
        "**How to Explore?**\n",
        "- Simplest: random action ($\\epsilon$-greedy)\n",
        "  - every time step, flip a coin\n",
        "  - with (small) probability $\\epsilon$, act randomly\n",
        "  - with (large) probability 1-$\\epsilon$, act on current policy\n",
        "  - *Cons*: You keep thrashing aronud once learning is done\n",
        "    - One solution: lower $\\epsilon$ over time\n",
        "    - Another solution: exploration functions\n",
        "\n",
        "**Exploration Function**\n",
        "- When to explore?\n",
        "  - Random actions: explore a fixed amount\n",
        "  - Better idea: explorea areas whose badness is not established, eventually stop exploring\n",
        "- Exploration function\n",
        "  - Takes a value estimate u and a vist count n, and return an optimistic utility\n",
        "  - Regular Q-update: $Q(s,a) <- R(s,a,s') + \\gamma maxQ(s',a')$\n",
        "  - Modified Q-update: $Q(s,a) <- R(s,a,s') + \\gamma maxfF(Q(s',a'), N(s',a'))$\n",
        "\n",
        "**Regret**\n",
        "- Regret is a measure of your total mistake cost: teh difference between your expected rewards, including \\\n",
        "youthful suboptimality, and optimal (expected) rewards\n",
        "- You have to optimally learn to be optimal\n",
        "\n",
        "- Ex: Random exploration and exploration functions both end up optimal, but random exploration has higher regret\n",
        "\n",
        "**Approximate Q-Learning**\n",
        "- ***Generalizing Across States***\n",
        "- Basic Q-learning keeps a table of all q-values\n",
        "- In realistic situations, we cannot possibly learn about every single state\n",
        "- We want to generalize:\n",
        "  - Learn about some small number of training states from experience\n",
        "  - Generalize that experience to new, similar situations\n",
        "  - This is a fundamental idea in machine learning, and we'll see it over and over again\n",
        "- Intuitive interpretation:\n",
        "  - Adjust weights of active features\n",
        "E.g., if something unexpectedly bad happens, blame the features that were on: disprefer all states with that state’s features\n",
        "\n",
        "**Linear Value Functions**\n",
        "- Using a feature representation, we can write a q function (or value function) for any state using a few weights:\n",
        "- Advantage: our experience is summed up in a few powerful numbers\n",
        "- Disadvantage: states may share features but actually be very different in value!\n",
        "\n",
        "  \"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"off-policy learning\" : \"eventually converges to optimal policy, even if you are acting suboptimally\",\n",
        "}"
      ],
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "425fd5c0-72be-4312-c523-58222922dfb3"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n \n## Reinforcement Learning \n- Basic Idea\n  - Receive feedback in the form of rewards\n  - Agent's utility is defined by the reward function\n  - Must learn to act so as to maximize expected rewards\n  - All learning is based on observed samples of outcomes\n  \n- Still assume a *MDP*\n  - a set of states\n  - a set of actions \n  - a model T(s,a,s')\n  - a reward function R(s,a,s')\n- Still looking for a policy $\\pi(s)$\n- **It doesn't know T or R**\n  - it doesn't know which states are good or what the actions do\n  - Must actually try actions and states out to learn\n  \n**Model-Based Learning**\n- Learn an approximate model based on experiences\n- Solve for values as if the learned model were correct\n- Step 1: Learn empirical MDP model\n  - Count outcomes s' for each s, a\n  - Normalize to give an estimate of T(s,a,s')\n  - Discover each R(s,a,s') when we experience (s,a,s')\n- Step 2: Solve the learned MDP\n  - For example, use value iteration, as before\n\n**Model-Free Learning**\n- 1. *Passive Reinforcement Learning*\n  - Someone else chooses the policy\n  - Input: a fixed policy $\\pi$(s)\n  - Goal: learn the state values\n  - Learner is \"along for the ride\"\n  - No choice about what actions to take\n  - Just execute the policy and learn from experience\n\n**Direct Evaluation**\n- Goal: Compute values for each state under $\\pi$\n- Idea: Average together observed sample values\n  - act according to $\\pi$\n  - Every time you visit a state, write down what the sum of discounted rewards turned out to be \n  - Average those samples\n- Pros:\n  - Easy to understand\n  - Doesn't require any knowledge of T,R\n  - It eventually computes the correct average values, using just sample transitions\n- Cons:\n  - It wastes information about state connections\n  - Each state must be learned separately\n  - So, it takes a long time to learn\n\n**Temporal Difference Learning**\n- It is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages\n- Learn from every experience instead of waiting til the end\n- Policy still fixed, still doing evaluation\n- Move values toward value of whatever successor occurs: running average\n- Update: $V^\\pi(s) <- V^\\pi(s) + \u0007lpha(sample - V^\\pi(s))\n- **Exponential moving average**\n  - the running interpolation update:\n  - Makes recent samples more important:\n  - Forgets abou the past (distant past values were wrong anyway)\n- Decreasing learning rate (alpha) can give converging averages\n- Start off with big alpha so that current sample worth more, and gradually decrease it\n- *Cons*\n  - We can't turn values into a new policy\n- **We have to learn the Q-values to know what's the best action**\n- **Model-free Q-Learning**\n  - $Q(s,a) <- (1-\u0007lpha)Q(s,a)+(\u0007lpha)[sample]\n\nQ-learning Properties\n- It eventually converges to optimal policy, even if you are acting suboptimally- *off-policy learning*\n\n*Active Reinforcement Learning*\n- Full reinforcement learning: optimal policies (like value iteration)\n- You don’t know the transitions T(s,a,s’) \n- You don’t know the rewards R(s,a,s’)\n- You choose the actions now\n- Goal: learn the optimal policy / values\n- Leaner makers choices\n- Fundamental tradeoff: exploration vs. exploitation\n- NOT offline planning\n\n**Exploration vs. Exploitation**\n\n**How to Explore?**\n- Simplest: random action ($\\epsilon$-greedy)\n  - every time step, flip a coin\n  - with (small) probability $\\epsilon$, act randomly\n  - with (large) probability 1-$\\epsilon$, act on current policy\n  - *Cons*: You keep thrashing aronud once learning is done\n    - One solution: lower $\\epsilon$ over time\n    - Another solution: exploration functions\n\n**Exploration Function**\n- When to explore?\n  - Random actions: explore a fixed amount\n  - Better idea: explorea areas whose badness is not established, eventually stop exploring\n- Exploration function\n  - Takes a value estimate u and a vist count n, and return an optimistic utility\n  - Regular Q-update: $Q(s,a) <- R(s,a,s') + \\gamma maxQ(s',a')$\n  - Modified Q-update: $Q(s,a) <- R(s,a,s') + \\gamma maxfF(Q(s',a'), N(s',a'))$\n\n**Regret**\n- Regret is a measure of your total mistake cost: teh difference between your expected rewards, including youthful suboptimality, and optimal (expected) rewards\n- You have to optimally learn to be optimal\n\n- Ex: Random exploration and exploration functions both end up optimal, but random exploration has higher regret\n\n**Approximate Q-Learning**\n- ***Generalizing Across States***\n- Basic Q-learning keeps a table of all q-values\n- In realistic situations, we cannot possibly learn about every single state\n- We want to generalize:\n  - Learn about some small number of training states from experience\n  - Generalize that experience to new, similar situations\n  - This is a fundamental idea in machine learning, and we'll see it over and over again\n- Intuitive interpretation:\n  - Adjust weights of active features\nE.g., if something unexpectedly bad happens, blame the features that were on: disprefer all states with that state’s features\n\n**Linear Value Functions**\n- Using a feature representation, we can write a q function (or value function) for any state using a few weights:\n- Advantage: our experience is summed up in a few powerful numbers\n- Disadvantage: states may share features but actually be very different in value!\n\n  \n\n## Module 9 Definitions\n* **Off-policy learning** - eventually converges to optimal policy, even if you are acting suboptimally\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\" \n",
        "-Probability models allow us to quantify how likely a possible world is.\n",
        "**Uncertainty**\n",
        "- Observed variables (evidence): Agent knows certain things about the state of the world (e.g., sensor readings or symptoms)\n",
        "- Unobserved variables (states): Agent needs to reason about other aspects (e.g. where an object is or what disease is present)\n",
        "- Model: Agent knows something about how the known variables relate to the unknown variables\n",
        "\n",
        "- **Sample space** = mutually exclusive and exhaustive\n",
        "\n",
        "**Random Variables**\n",
        "- A random variable is some aspect of the world about which we (may) have uncertainty\n",
        "\n",
        "**Axioms of Probability**\n",
        "- Probability of any possible world is between 0 and 1\n",
        "- The total probability of the set of all possible worlds is 1\n",
        "\n",
        "**Probability Distributions**\n",
        "- Unobserved random variables have distrbutions\n",
        "\n",
        "**Joint Distributions**\n",
        "- A *joint distribution* over a set of random variables specifies a real number for each assignment\n",
        "- **Size of distribution if n raviables with domain sizes d** : *$d^n$*\n",
        "\n",
        "**Probabilistic Models**\n",
        "- (Random) variables with domains\n",
        "- Assignments are called outcomes\n",
        "- Joint distributions:say whether assignments (outcomes) are likely\n",
        "- *Normalized*: sum to 1.0\n",
        "- Ideally: only certain variables directly interact\n",
        "\n",
        "**Mariginal Distributions**\n",
        "- Allow us to eliminate variables that are not needed\n",
        "\n",
        "**Conditional Probabilities**\n",
        "- A simple relation between joint and conditional probabilities\n",
        "- $P(a\\b) = P(a,b)/P(b)$\n",
        "\n",
        "**Conditional Distributions**\n",
        "- Conditional distributions are probability distributions over some variables given fixed values of others\n",
        "\n",
        "**Probabilistic Inference**\n",
        "- compute a desired probability from other known probabilities (e.g. conditional from joint)\n",
        "- *Inference by Enumeration*\n",
        "  - General case:\n",
        "    - Evidence variables\n",
        "    - Query* variable:\n",
        "    - Hidden variables \n",
        "  - 1) Select the entries consistent with the evidence\n",
        "  - 2) Sum out H to get joint of Query and evidence\n",
        "  - 3) Normalize\n",
        "\n",
        "**The Product Rule**\n",
        "- $P(y)P(x|y) = P(x,y)$\n",
        "\n",
        "**The Chain Rule**\n",
        "- $P(x,y,z) = P(x)P(y|x)P(z|x,y)\n",
        "\n",
        "**Bayes' Rule**\n",
        "- $P(x,y) = P(x|y)P(y) = P(y|x)P(x)$\n",
        "- **$P(x|y) = P(y|x)*P(x)/P(y)$\n",
        "- Let's us build one conditional frm it reverse\n",
        "- Often one conditional is tricky but the other one is simple\n",
        "\n",
        "**Probabilistic Language Models**\n",
        "- *Goal*: Assign a probability to a sentence\n",
        "- Ex) Autocomplete for texting\n",
        "  - Machine Translation\n",
        "  - Spelling Correction\n",
        "  - Speech Recognition\n",
        "- We can't just conut and divide because we don't have enough data\n",
        "- *Solution*\n",
        "  - Simplifying Assumption = Markov Assumption\n",
        "  - only depends on the previous k words not the whole context\n",
        "  - *unigram* = no-history\n",
        "  - *bigram* = 1 word as history\n",
        "  - *trigram* = 2 words as history\n",
        "  - *4-gram* = 3 words as history\n",
        "\n",
        "-Naive Bayes model assumes words occur independently in documents\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"Sample space\" : \"possible worlds in probability theory\",\n",
        "\"Distribution\" : \"a table of probabilities of values\",\n",
        "\"Probabilistic Models\" : \"A probabilistic model is a joint distribution over a set of random variables\",\n",
        "\"Event\" : \"A set E of outcomes\",\n",
        "\"Marginalization (summing out)\": \"Combine collapsed rows by adding\",\n",
        "\"language model\": \"A model that computes either P(w) or P(wn|w1,w2,...)\",\n",
        "\n",
        "}"
      ],
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "6bbcc4a0-32be-4e44-cdaf-f380397e2328"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n \n-Probability models allow us to quantify how likely a possible world is.\n**Uncertainty**\n- Observed variables (evidence): Agent knows certain things about the state of the world (e.g., sensor readings or symptoms)\n- Unobserved variables (states): Agent needs to reason about other aspects (e.g. where an object is or what disease is present)\n- Model: Agent knows something about how the known variables relate to the unknown variables\n\n- **Sample space** = mutually exclusive and exhaustive\n\n**Random Variables**\n- A random variable is some aspect of the world about which we (may) have uncertainty\n\n**Axioms of Probability**\n- Probability of any possible world is between 0 and 1\n- The total probability of the set of all possible worlds is 1\n\n**Probability Distributions**\n- Unobserved random variables have distrbutions\n\n**Joint Distributions**\n- A *joint distribution* over a set of random variables specifies a real number for each assignment\n- **Size of distribution if n raviables with domain sizes d** : *$d^n$*\n\n**Probabilistic Models**\n- (Random) variables with domains\n- Assignments are called outcomes\n- Joint distributions:say whether assignments (outcomes) are likely\n- *Normalized*: sum to 1.0\n- Ideally: only certain variables directly interact\n\n**Mariginal Distributions**\n- Allow us to eliminate variables that are not needed\n\n**Conditional Probabilities**\n- A simple relation between joint and conditional probabilities\n- $P(a\b) = P(a,b)/P(b)$\n\n**Conditional Distributions**\n- Conditional distributions are probability distributions over some variables given fixed values of others\n\n**Probabilistic Inference**\n- compute a desired probability from other known probabilities (e.g. conditional from joint)\n- *Inference by Enumeration*\n  - General case:\n    - Evidence variables\n    - Query* variable:\n    - Hidden variables \n  - 1) Select the entries consistent with the evidence\n  - 2) Sum out H to get joint of Query and evidence\n  - 3) Normalize\n\n**The Product Rule**\n- $P(y)P(x|y) = P(x,y)$\n\n**The Chain Rule**\n- $P(x,y,z) = P(x)P(y|x)P(z|x,y)\n\n**Bayes' Rule**\n- $P(x,y) = P(x|y)P(y) = P(y|x)P(x)$\n- **$P(x|y) = P(y|x)*P(x)/P(y)$\n- Let's us build one conditional frm it reverse\n- Often one conditional is tricky but the other one is simple\n\n**Probabilistic Language Models**\n- *Goal*: Assign a probability to a sentence\n- Ex) Autocomplete for texting\n  - Machine Translation\n  - Spelling Correction\n  - Speech Recognition\n- We can't just conut and divide because we don't have enough data\n- *Solution*\n  - Simplifying Assumption = Markov Assumption\n  - only depends on the previous k words not the whole context\n  - *unigram* = no-history\n  - *bigram* = 1 word as history\n  - *trigram* = 2 words as history\n  - *4-gram* = 3 words as history\n\n-Naive Bayes model assumes words occur independently in documents\n\n\n## Module 10 Definitions\n* **Sample space** - possible worlds in probability theory\n* **Distribution** - a table of probabilities of values\n* **Probabilistic models** - A probabilistic model is a joint distribution over a set of random variables\n* **Event** - A set E of outcomes\n* **Marginalization (summing out)** - Combine collapsed rows by adding\n* **Language model** - A model that computes either P(w) or P(wn|w1,w2,...)\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\"\n",
        "**Probabilistic Models**\n",
        "- Describe how the world works\n",
        "- Models are always simpllifications\n",
        "\n",
        "**Independence**\n",
        "- $P(x,y) = P(x)P(y)$\n",
        "- $P(x|y) = P(x)$\n",
        "- If observing one doesn't chance the probability of the other.\n",
        "- Independence is a simplifying modeling assumption\n",
        "  - *empirical* join distributions: at best \"close\" to independent\n",
        "\n",
        "**Conditionally independent**\n",
        "- $P(x,y|z) = P(x|z)P(y|z)\n",
        "- Bayes' nets (graphical models) help us express conditional independence assumptions\n",
        "\n",
        "**Bayes' Nets**\n",
        "- Better than joint distribution which is way too big to maintain\n",
        "- *Big Picture*:\n",
        "  - It is a technique for decribing complex join distributions (models) using simple, local distributions (conditional probabilities)\n",
        "  - Describe how variables locally interact\n",
        "\n",
        "**Graphical Model Notation**\n",
        "- *nodes*: variables(with domains)\n",
        "  - assigned or unassigned\n",
        "- *arcs*: interactions\n",
        "  - indicate direct influence between variables\n",
        "\n",
        "**Bayes' Net semantics**\n",
        "- A set of nodes, one per variable X\n",
        "- A directed, acryclic graph\n",
        "- A conditional distribution for each node\n",
        "\n",
        "**A Bayes net = Topology (graph) + Local Conditional Probabilities**\n",
        "\n",
        "**Causality**\n",
        "- It is simpler and easier to think about if Bayes' nets reflect\n",
        "- It does not need to be causal\n",
        "- Topology really encodes conditional independence\n",
        "\n",
        "**Size of a Bayes' Net**\n",
        "- How big is a joint distribution over N boolean variables = $2^N$\n",
        "- How big is an N-node net if nodes have up to k parents = O(N*2^k+1)\n",
        "\n",
        "\n",
        "**D-separation Algorithm**\n",
        "- triples\n",
        "- $P(x,y,z) = P(y)P(x|y)P(z|y)$\n",
        "- Casual chain, Common cause, Common effect\n",
        "- *Common effect*\n",
        "  - Two causes are independent individually, but when given common effect, they are not.\n",
        "  - Observing an effect activates influence between possible causes\n",
        "\n",
        "- **Active/Inactive paths**\n",
        "  - X and Y are conditionally independent given Z if they are \"d-separated\" by Z\n",
        "  - Path is active if each triple is active\n",
        "  - A single inactive segment will block a path\n",
        "  - No active paths mean *independence*\n",
        "  - shaded : given \n",
        "\n",
        "**summary**\n",
        "- Bayes nets compactly encode joint distributions\n",
        "- Guaranteed independencies of distributions can be deduced from BN graph structure\n",
        "- D-separation gives precise conditional independence guarantees from graph alone\n",
        "- A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\n",
        "\n",
        "**Inference**\n",
        "-  Given unlimited time, inference in BNs is easy\n",
        "\n",
        "Why is inference by enumeration so slow?\n",
        "- You join up the whole joint distribution before you sum out the hidden variables\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"Inference\" : \"calculating some useful quantity from a joint probability distribution\",    \n",
        "}\n"
      ],
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "25ccbc91-fff2-4c6b-ecc8-1304cfcc13d0"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\n**Probabilistic Models**\n- Describe how the world works\n- Models are always simpllifications\n\n**Independence**\n- $P(x,y) = P(x)P(y)$\n- $P(x|y) = P(x)$\n- If observing one doesn't chance the probability of the other.\n- Independence is a simplifying modeling assumption\n  - *empirical* join distributions: at best \"close\" to independent\n\n**Conditionally independent**\n- $P(x,y|z) = P(x|z)P(y|z)\n- Bayes' nets (graphical models) help us express conditional independence assumptions\n\n**Bayes' Nets**\n- Better than joint distribution which is way too big to maintain\n- *Big Picture*:\n  - It is a technique for decribing complex join distributions (models) using simple, local distributions (conditional probabilities)\n  - Describe how variables locally interact\n\n**Graphical Model Notation**\n- *nodes*: variables(with domains)\n  - assigned or unassigned\n- *arcs*: interactions\n  - indicate direct influence between variables\n\n**Bayes' Net semantics**\n- A set of nodes, one per variable X\n- A directed, acryclic graph\n- A conditional distribution for each node\n\n**A Bayes net = Topology (graph) + Local Conditional Probabilities**\n\n**Causality**\n- It is simpler and easier to think about if Bayes' nets reflect\n- It does not need to be causal\n- Topology really encodes conditional independence\n\n**Size of a Bayes' Net**\n- How big is a joint distribution over N boolean variables = $2^N$\n- How big is an N-node net if nodes have up to k parents = O(N*2^k+1)\n\n\n**D-separation Algorithm**\n- triples\n- $P(x,y,z) = P(y)P(x|y)P(z|y)$\n- Casual chain, Common cause, Common effect\n- *Common effect*\n  - Two causes are independent individually, but when given common effect, they are not.\n  - Observing an effect activates influence between possible causes\n\n- **Active/Inactive paths**\n  - X and Y are conditionally independent given Z if they are \"d-separated\" by Z\n  - Path is active if each triple is active\n  - A single inactive segment will block a path\n  - No active paths mean *independence*\n  - shaded : given \n\n**summary**\n- Bayes nets compactly encode joint distributions\n- Guaranteed independencies of distributions can be deduced from BN graph structure\n- D-separation gives precise conditional independence guarantees from graph alone\n- A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\n\n**Inference**\n-  Given unlimited time, inference in BNs is easy\n\nWhy is inference by enumeration so slow?\n- You join up the whole joint distribution before you sum out the hidden variables\n\n\n\n## Module 11 Definitions\n* **Inference** - calculating some useful quantity from a joint probability distribution\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\"\n",
        "**Machine Learning Algorithms**\n",
        "1. Naive Bayes\n",
        "  - ex. Is the email message spam or not\n",
        "  - Each of the features used in the classifier corresponds to a variable and each feature is conditionally independent of every other feature.\n",
        "  - *Learn a set of probabilities*\n",
        "2. Perceptrons\n",
        "  - Have a weight associated with each feature that they use for classification decision\n",
        "  - Sigmoid neurons form the building blocks of more complex neural networks\n",
        "\n",
        "*Both use a set of labeled training data in order to learn a classification decision*\n",
        "\n",
        "*Classification*\n",
        "- Given inputs x, predict labels y\n",
        "\n",
        "**Model-Based Classification**\n",
        "- Build a modle(ex. Bayes net) where both the label and features are random variables\n",
        "- Instantiate any observed features\n",
        "- Query for the distribution of hte label conditioned on the features\n",
        "- *Challenges* : Figureing out structure, How should we learn its parameters\n",
        "\n",
        "***Naive Bayes***\n",
        "- \"Naive\": becasue we assume all features are independent effects of the label\n",
        "- *Simple digit recognition version:*\n",
        "  - Each feature will correspond to each position in the grid.\n",
        "  - On/Off based on intensity\n",
        "  - Naive Bayes Model: $P(Y|F0,0 ... F15,15) \\propto P(Y)\\prod P(Fi,j|Y)$\n",
        "- ***General Naive Bayes***\n",
        "  - $P(Y,F1,...Fn) = P(Y)\\propto P(Fi|Y)$\n",
        "  - n * |F| * |Y| parameters : Linear number of features\n",
        "  - Downside: very simplistic so might not represent the real world\n",
        "\n",
        "- *Inference for Naïve Bayes*\n",
        "  - *Goal*: compute posterior distribution over label variable Y\n",
        "  - Step1: Get joint probability of label adn evidence for each label\n",
        "  - Step2: Sum to get probability of evidence\n",
        "  - Step 3: normalize by dividing Step1 by Step2\n",
        "\n",
        "- *To use Naive Bayes*\n",
        "  - Inference method\n",
        "  - Estimates of local conditional probability tables\n",
        "    - Prior parameter P(Y)\n",
        "    - P(Fi|Y) for each feature (evidence variable) - conditional probability\n",
        "\n",
        "***Machine Learning***\n",
        "- Data: labeled instances\n",
        "  - training set, held out set, test set\n",
        "- Features: attribute-value pairs which characterize each x\n",
        "- Experimentation cycle\n",
        "  - learn parameters on training set\n",
        "  - (tune hyperparameters on held-out set)\n",
        "  - Compute accuracy on test set\n",
        "- Evaluation\n",
        "  - Accuracy: fraction of instances predicted correctly\n",
        "- Overfitting and generalization\n",
        "  - *Overfitting*: fitting the training data very closely, but not generalizing well\n",
        "  - Assigning unseen events zero probability will result in lower accuracy\n",
        "  - *To generalize better: we need to smooth or regularize the estimates*\n",
        "\n",
        "- *Parameter Estimation*\n",
        "  - **Elicitation**: ask a human\n",
        "  - **Empirically**: use training data\n",
        "    - $P(x) = count(x)/(total samples)$\n",
        "    - *Likelihood of the data* $L(x,\\theta)=\\propto P_\\theta(x_i)\n",
        "\n",
        "- *Maximum Likelihood*\n",
        "  - Relative frequencies are the maximum likelihood estimates\n",
        "  - P_ml(x) = count(x)/total samples\n",
        "\n",
        "2 ways of generalizing better\n",
        "- *Laplace Smoothing*\n",
        "  - Avoid zero probability\n",
        "  - **Laplace's estimate**: pretend you saw every outcome once more than you actually did\n",
        "  - Add k(strength of the prior) to both outcomes\n",
        "\n",
        "- *Linear Interpolation*\n",
        "  - $P_(LIN)(x|y) = \\alpha P(x|y) + (1.0-\\alpha)P(x)$\n",
        "  - \\alpha parameter\n",
        "\n",
        "**Tuning**\n",
        "- Two kinds of unknowns\n",
        "  - Parameters : P(X|Y),P(Y)\n",
        "  - Hyperparameters: $\\alpha, k$\n",
        "- *Learn parameters from training data*\n",
        "- *Tune hyperparameters on differenet data*\n",
        "- *for each value of hyperparameters, train and test on the held-out data*\n",
        "- *choose the best value and do a final test on the test data*\n",
        "\n",
        "**Dealing with Errors**\n",
        "- Need more features\n",
        "- Can add these infomration sources as new variables in the NB model\n",
        "\n",
        "**Baseline**\n",
        "- Help determine how hard the task is\n",
        "- Help know what a good accuracy is\n",
        "\n",
        "**Confidence**\n",
        "- Posterior over the top label: $confidence(x) = max P(y|x)$\n",
        "- Represents how sure the classifier is of the classification\n",
        "- Any probabilistic model will have confidences\n",
        "- No guarantee confidence is correct\n",
        "- Weak: higher confidences mean higher accuracy\n",
        "- Strong: confidence predicts accuracy rate\n",
        "\n",
        "***Perceptrons***\n",
        "- Inspired by neuron\n",
        "- Decision making device\n",
        "- *Linear classifier*\n",
        "1) Inputs: feature values\n",
        "2) Weights\n",
        "3) Weighted Sum\n",
        "4) Activation Function : if positive, 1, negative -1\n",
        "5) output\n",
        "\n",
        "*Learning*\n",
        "- Start with weights = 0\n",
        "- For each training instance:\n",
        "  - Classify with current weights\n",
        "  - If correct, no change\n",
        "  - If incorrect, adjust the weight vector\n",
        "\n",
        "*Learning: Multiclass Perceptron*\n",
        "Start with all weights = 0\n",
        "Pick up training examples one by one Predict with current weights\n",
        "If correct, no change!\n",
        "If wrong: lower score of wrong answer, raise score of right answer\n",
        "          \n",
        "**Properties of Perceptrons**\n",
        "- *Separability*: true if some parameters get the training set perfectly correct\n",
        "- *Convergence*: if the training is separable, perceptron will eventually converge (binary case)\n",
        "- *Mistake Bound*: the maximum number of mistakes (binary case) related to the margin or degree of separability\n",
        "  - $mistakes < k/(margin)^2$\n",
        "  - Bigger the margin, less mistakes we make\n",
        "\n",
        "**Problems withe the Perceptron**\n",
        "- *Noise*: if the data isn't separable, weight might thrash\n",
        "  - Averaging weight overtime\n",
        "- *Mediocre generalization*: fins a barely separating solution\n",
        "- *Overtraining*: test/held-out accuracy usually rises, then falls\n",
        "\n",
        "**Fixing the Perceptron**\n",
        "- Idea: adjust the weight update to mitigate these effects\n",
        "- *MIRA - Margin Infused Relaxed Algorithm*: chooses an update size that fixes the current mistake\n",
        "\n",
        "**Support Vector Machine**\n",
        "- *Maximizing the margin*\n",
        "- Support vector machines (SVMs) find the separator with max margin\n",
        "- MIRA where you optimize over all examples at once\n",
        "\n",
        "\n",
        "***Classification: Comparison***\n",
        "*Naïve Bayes*\n",
        "• Builds a model training data\n",
        "• Gives prediction probabilities\n",
        "• Strong assumptions about feature independence \n",
        "• One pass through data (counting)\n",
        "\n",
        "*Perceptrons / MIRA:*\n",
        "• Makes less assumptions about data\n",
        "• Mistake-driven learning\n",
        "• Multiple passes through data (prediction) \n",
        "• Often more accurate\n",
        "\n",
        "*A single neural unit cannot be used to compute the **XOR** function*\n",
        "\n",
        "**Activation Functions**\n",
        "- There are 3 commonly used non-linear functions\n",
        "The sigmoid function\n",
        "The tanh function\n",
        "The rectified linear unit ReLU\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",\n",
        "\"posterior probability\" :\"updated probability of an event occurring after taking into consideration new information\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "a4138280-1f30-42c0-c0f0-c2bd94d88fc7"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module12_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter19_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter19_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter19_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter19_4),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter19_5),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter19_6),\n",
        "  (\"SLP Chapter 4.1 Naive Bayes Classifiers\", slp_chapter4_1),\n",
        "  (\"SLP Chapter 4.2 Training the Naive Bayes Classifier\", slp_chapter4_2),\n",
        "  (\"SLP Chapter 4.3 Worked Example\", slp_chapter4_3),\n",
        "  (\"SLP Chapter 4.4 Optimizing for Sentiment Analysis\", slp_chapter4_4),\n",
        "  (\"SLP Chapter 4.5 Naive Bayes for other text classification tasks\", slp_chapter4_5),\n",
        "  (\"SLP Chapter 4.6 Naive Bayes as a Language Model\", slp_chapter4_6),\n",
        "  (\"SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\", slp_chapter4_7),\n",
        "  (\"SLP Chapter 4.8 Test sets and Cross-validation\", slp_chapter4_8),\n",
        "  (\"SLP Chapter 4.9 Statistical Significance Testing\", slp_chapter4_9),\n",
        "  (\"SLP Chapter 4.10 Avoiding Harms in Classification\", slp_chapter4_10),\n",
        "  (\"Module 12 Lecture Notes\", module12_lecture_notes),\n",
        "]\n",
        "\n",
        "module12_markdown = format_module(12, \"Naive Bayes and Perceptrons\", \n",
        "                         module12_sections, \n",
        "                         module12_definitions)\n",
        "display(Markdown(module12_markdown))"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\n**Machine Learning Algorithms**\n1. Naive Bayes\n  - ex. Is the email message spam or not\n  - Each of the features used in the classifier corresponds to a variable and each feature is conditionally independent of every other feature.\n  - *Learn a set of probabilities*\n2. Perceptrons\n  - Have a weight associated with each feature that they use for classification decision\n  - Sigmoid neurons form the building blocks of more complex neural networks\n\n*Both use a set of labeled training data in order to learn a classification decision*\n\n*Classification*\n- Given inputs x, predict labels y\n\n**Model-Based Classification**\n- Build a modle(ex. Bayes net) where both the label and features are random variables\n- Instantiate any observed features\n- Query for the distribution of hte label conditioned on the features\n- *Challenges* : Figureing out structure, How should we learn its parameters\n\n***Naive Bayes***\n- \"Naive\": becasue we assume all features are independent effects of the label\n- *Simple digit recognition version:*\n  - Each feature will correspond to each position in the grid.\n  - On/Off based on intensity\n  - Naive Bayes Model: $P(Y|F0,0 ... F15,15) \\propto P(Y)\\prod P(Fi,j|Y)$\n- ***General Naive Bayes***\n  - $P(Y,F1,...Fn) = P(Y)\\propto P(Fi|Y)$\n  - n * |F| * |Y| parameters : Linear number of features\n  - Downside: very simplistic so might not represent the real world\n\n- *Inference for Naïve Bayes*\n  - *Goal*: compute posterior distribution over label variable Y\n  - Step1: Get joint probability of label adn evidence for each label\n  - Step2: Sum to get probability of evidence\n  - Step 3: normalize by dividing Step1 by Step2\n\n- *To use Naive Bayes*\n  - Inference method\n  - Estimates of local conditional probability tables\n    - Prior parameter P(Y)\n    - P(Fi|Y) for each feature (evidence variable) - conditional probability\n\n***Machine Learning***\n- Data: labeled instances\n  - training set, held out set, test set\n- Features: attribute-value pairs which characterize each x\n- Experimentation cycle\n  - learn parameters on training set\n  - (tune hyperparameters on held-out set)\n  - Compute accuracy on test set\n- Evaluation\n  - Accuracy: fraction of instances predicted correctly\n- Overfitting and generalization\n  - *Overfitting*: fitting the training data very closely, but not generalizing well\n  - Assigning unseen events zero probability will result in lower accuracy\n  - *To generalize better: we need to smooth or regularize the estimates*\n\n- *Parameter Estimation*\n  - **Elicitation**: ask a human\n  - **Empirically**: use training data\n    - $P(x) = count(x)/(total samples)$\n    - *Likelihood of the data* $L(x,\theta)=\\propto P_\theta(x_i)\n\n- *Maximum Likelihood*\n  - Relative frequencies are the maximum likelihood estimates\n  - P_ml(x) = count(x)/total samples\n\n2 ways of generalizing better\n- *Laplace Smoothing*\n  - Avoid zero probability\n  - **Laplace's estimate**: pretend you saw every outcome once more than you actually did\n  - Add k(strength of the prior) to both outcomes\n\n- *Linear Interpolation*\n  - $P_(LIN)(x|y) = \u0007lpha P(x|y) + (1.0-\u0007lpha)P(x)$\n  - \u0007lpha parameter\n\n**Tuning**\n- Two kinds of unknowns\n  - Parameters : P(X|Y),P(Y)\n  - Hyperparameters: $\u0007lpha, k$\n- *Learn parameters from training data*\n- *Tune hyperparameters on differenet data*\n- *for each value of hyperparameters, train and test on the held-out data*\n- *choose the best value and do a final test on the test data*\n\n**Dealing with Errors**\n- Need more features\n- Can add these infomration sources as new variables in the NB model\n\n**Baseline**\n- Help determine how hard the task is\n- Help know what a good accuracy is\n\n**Confidence**\n- Posterior over the top label: $confidence(x) = max P(y|x)$\n- Represents how sure the classifier is of the classification\n- Any probabilistic model will have confidences\n- No guarantee confidence is correct\n- Weak: higher confidences mean higher accuracy\n- Strong: confidence predicts accuracy rate\n\n***Perceptrons***\n- Inspired by neuron\n- Decision making device\n- *Linear classifier*\n1) Inputs: feature values\n2) Weights\n3) Weighted Sum\n4) Activation Function : if positive, 1, negative -1\n5) output\n\n*Learning*\n- Start with weights = 0\n- For each training instance:\n  - Classify with current weights\n  - If correct, no change\n  - If incorrect, adjust the weight vector\n\n*Learning: Multiclass Perceptron*\nStart with all weights = 0\nPick up training examples one by one Predict with current weights\nIf correct, no change!\nIf wrong: lower score of wrong answer, raise score of right answer\n          \n**Properties of Perceptrons**\n- *Separability*: true if some parameters get the training set perfectly correct\n- *Convergence*: if the training is separable, perceptron will eventually converge (binary case)\n- *Mistake Bound*: the maximum number of mistakes (binary case) related to the margin or degree of separability\n  - $mistakes < k/(margin)^2$\n  - Bigger the margin, less mistakes we make\n\n**Problems withe the Perceptron**\n- *Noise*: if the data isn't separable, weight might thrash\n  - Averaging weight overtime\n- *Mediocre generalization*: fins a barely separating solution\n- *Overtraining*: test/held-out accuracy usually rises, then falls\n\n**Fixing the Perceptron**\n- Idea: adjust the weight update to mitigate these effects\n- *MIRA - Margin Infused Relaxed Algorithm*: chooses an update size that fixes the current mistake\n\n**Support Vector Machine**\n- *Maximizing the margin*\n- Support vector machines (SVMs) find the separator with max margin\n- MIRA where you optimize over all examples at once\n\n\n***Classification: Comparison***\n*Naïve Bayes*\n• Builds a model training data\n• Gives prediction probabilities\n• Strong assumptions about feature independence \n• One pass through data (counting)\n\n*Perceptrons / MIRA:*\n• Makes less assumptions about data\n• Mistake-driven learning\n• Multiple passes through data (prediction) \n• Often more accurate\n\n*A single neural unit cannot be used to compute the **XOR** function*\n\n**Activation Functions**\n- There are 3 commonly used non-linear functions\nThe sigmoid function\nThe tanh function\nThe rectified linear unit ReLU\n\n\n## Module 12 Definitions\n* **Concept** - definition\n* **Posterior probability** - updated probability of an event occurring after taking into consideration new information\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\"\n",
        "***Neural Networks***\n",
        "\n",
        "**Logistic Regression**\n",
        "1. A feature representation of the input\n",
        "2. A classification function that computes the estimated class 𝑦 via p(y|x).\n",
        "3. An objective function(loss function) for learning, usually involving minimizing error on training examples.\n",
        "4. An algorithm for optimizing the objective function.\n",
        "\n",
        "**Stochastic gradient Descent**\n",
        "- Trying to minimize loss\n",
        "- a method that finds a minimum of a function by figuring out in which direction (in the space of the parameters θ) the function’s slope is rising the most steeply, and moving in the opposite direction.\n",
        "- *Choooses a single random example at a time and updates its weights on that example. Updates can fluctuate*\n",
        "\n",
        "**Mini-batch training**\n",
        "- Computes gradient over the entire dataset\n",
        "- Gives a much better estimate of which direction to move the weights but takes a long time to compute.\n",
        "\n",
        "**Regularization**\n",
        "- A way to penalize large weights.\n",
        "- In logistic regression, if a feature only occurs in one class then it will get a high weight. \n",
        "- Term is added to the loss function\n",
        "- ex. Lasso regression L1\n",
        "      Ridge regression L2\n",
        "\n",
        "**Softmax function**\n",
        "- Generalization of the sigmoid function\n",
        "\n",
        "\n",
        "**Sentiment classifier**\n",
        "- Take an input and encode in feature that classifier can use.\n",
        "- z = w . x + b \n",
        "\n",
        "**Learning in logistic regression**\n",
        "How do we get the weights of the model?\n",
        "- We learn the parameters (weights + bias) via learning\n",
        "- This requires 2 components:\n",
        "1. A *loss function* that tells us distance between the system output and the gold output. We will use *cross-entropy* loss.\n",
        "2. An algorithm for optimizing the objective function. We will use stochastic gradient descent to minimize the loss function.\n",
        "\n",
        "**Loss function**\n",
        "- ex. Mean Squared Error : not that good for probabilistic classification\n",
        "- *Cross entropy loss function*\n",
        "  - Negative log likelihood loss\n",
        "  - Choose parameters w,b that maximize the log probabilities of the true labels in the training data.\n",
        "  - Minimize negative log probabiliity\n",
        "  - We want the loss to be smaller if the model’s estimate is close to correct, and we want the loss to be bigger if it is confused.\n",
        "\n",
        "*Logistic regression loss function is **convex**: just has **one minimum** *\n",
        "\n",
        "**Feed-Forward Neural Network**\n",
        "- Thte simplest kind of Neural network\n",
        "- *Multilayer* network, all units are usualy *fully-connected* and *no-cycles*\n",
        "- CANNOT MOVE BACK TO LOWER LAYER\n",
        "- Output h = $\\nu (Wx+b)$\n",
        "\n",
        "**Backpropagation**\n",
        "- Uses differentiation over the network to understand how each neural unit is affected by the \\\n",
        "ones that it's connected to and vice versa\n",
        "- related to backward differentiation\n",
        "\n",
        "**Computation graph**\n",
        "- Represents the process of computing a mathematical expression\n",
        "- Each operation is a node in a graph\n",
        "- h = σ(Wx+b)\n",
        "- z = Uh\n",
        "- y = softmax(z)\n",
        "\n",
        "***We use:\n",
        "A cross entropy loss function\n",
        "Gradient descent to perform optimization\n",
        "Error back propagation to compute the gradient of the loss function***\n",
        "\n",
        "**Probabilistic Language Models**\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"loss function\" : \"how wrong the model's predictions are for each item in the training\",    \n",
        "}\n"
      ],
      "execution_count": 14,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "b6e22e0f-b4f7-48d1-b9fb-ae1313855e73"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\n***Neural Networks***\n\n**Logistic Regression**\n1. A feature representation of the input\n2. A classification function that computes the estimated class 𝑦 via p(y|x).\n3. An objective function(loss function) for learning, usually involving minimizing error on training examples.\n4. An algorithm for optimizing the objective function.\n\n**Stochastic gradient Descent**\n- Trying to minimize loss\n- a method that finds a minimum of a function by figuring out in which direction (in the space of the parameters θ) the function’s slope is rising the most steeply, and moving in the opposite direction.\n- *Choooses a single random example at a time and updates its weights on that example. Updates can fluctuate*\n\n**Mini-batch training**\n- Computes gradient over the entire dataset\n- Gives a much better estimate of which direction to move the weights but takes a long time to compute.\n\n**Regularization**\n- A way to penalize large weights.\n- In logistic regression, if a feature only occurs in one class then it will get a high weight. \n- Term is added to the loss function\n- ex. Lasso regression L1\n      Ridge regression L2\n\n**Softmax function**\n- Generalization of the sigmoid function\n\n\n**Sentiment classifier**\n- Take an input and encode in feature that classifier can use.\n- z = w . x + b \n\n**Learning in logistic regression**\nHow do we get the weights of the model?\n- We learn the parameters (weights + bias) via learning\n- This requires 2 components:\n1. A *loss function* that tells us distance between the system output and the gold output. We will use *cross-entropy* loss.\n2. An algorithm for optimizing the objective function. We will use stochastic gradient descent to minimize the loss function.\n\n**Loss function**\n- ex. Mean Squared Error : not that good for probabilistic classification\n- *Cross entropy loss function*\n  - Negative log likelihood loss\n  - Choose parameters w,b that maximize the log probabilities of the true labels in the training data.\n  - Minimize negative log probabiliity\n  - We want the loss to be smaller if the model’s estimate is close to correct, and we want the loss to be bigger if it is confused.\n\n*Logistic regression loss function is **convex**: just has **one minimum** *\n\n**Feed-Forward Neural Network**\n- Thte simplest kind of Neural network\n- *Multilayer* network, all units are usualy *fully-connected* and *no-cycles*\n- CANNOT MOVE BACK TO LOWER LAYER\n- Output h = $\nu (Wx+b)$\n\n**Backpropagation**\n- Uses differentiation over the network to understand how each neural unit is affected by the ones that it's connected to and vice versa\n- related to backward differentiation\n\n**Computation graph**\n- Represents the process of computing a mathematical expression\n- Each operation is a node in a graph\n- h = σ(Wx+b)\n- z = Uh\n- y = softmax(z)\n\n***We use:\nA cross entropy loss function\nGradient descent to perform optimization\nError back propagation to compute the gradient of the loss function***\n\n**Probabilistic Language Models**\n\n\n## Module 13 Definitions\n* **Loss function** - how wrong the model's predictions are for each item in the training\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\"\n",
        "***NLP***\n",
        "- Vector space semantic model\n",
        "\n",
        "1. Synonyms – words that have similar meanings\n",
        "2. Antonyms – words that have opposite meanings\n",
        "3. Connotations – words that are positive or negative\n",
        "4. Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event\n",
        "5. Support for entailment\n",
        "\n",
        "**Language Modeling**\n",
        "- Goal: Learn a function that returns the joint probability\n",
        "- Primary difficulty:\n",
        "1. There are too many parameters to accurately estimate. This is sometimes called the “curse of dimensionality”\n",
        "2. Inn-gram-basedmodelswefailtogeneralizetorelatedwords/word sequences that we have observed.\n",
        "\n",
        "**Advantages of Neural Language models over n-gram**\n",
        "- They don't need smoothing\n",
        "- They can handle much longer histories\n",
        "- They can generalize over contexts of similar words\n",
        "- Neural LMs tend to have much higher predictive accuracy than n-gram LMs\n",
        "**Disadvantage**\n",
        "- SLower to train than traditional n-gram LMs\n",
        "\n",
        "**Neural LMs**\n",
        "- *Input*: k-gram of words w_1:K\n",
        "- *output*: a probability distribution over the next word\n",
        "- The k context words are treated as a word window. Each word is associated with an *embedding* vector\n",
        "  - The input vector x just concatenates v(w) for each of the k words.\n",
        "\n",
        "**Lexical Semantic Models**\n",
        "- Representation of meaning\n",
        "\n",
        "*Formal semantics*\n",
        "- pros: Mathematically well-understood, powerful machinery for handling logical operations\n",
        "- cons: knowledge must come from somewhere else\n",
        "\n",
        "**Vector Space Model**\n",
        "- Able to automatically extract knowleddge from corpus\n",
        "\n",
        "**Term-Document Matrix**\n",
        "-Column : document\n",
        "-row : word\n",
        "-length of document is length of the word.\n",
        "- We can measure how similar two documents are by comparing their column vectors\n",
        "- Comparing two rows show how similar two words are.\n",
        "\n",
        "**Why dense vectors?**\n",
        "• *Short vectors* may be easier to use as features in machine learning (fewer weights to tune)\n",
        "• *Dense vectors* may *generalize* better than storing explicit counts\n",
        "• They may do better at capturing synonymy:\n",
        "• car and automobile are synonyms; but are distinct dimensions in sparse vectors\n",
        "• a word with car as a neighbor and a word with automobile as a neighbor should be similar, but aren't\n",
        "• In practice, they work better\n",
        "\n",
        "*N0gram LMs represent words as a string of letters or as an index in a vocabulary list*\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 16,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "d8a8489d-b8e3-4cfd-bc7c-29a1050375b5"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module14_sections = [\n",
        "  (\"SLP Chapter 9.1 Language Models Revisited\", slp_chapter9_1),\n",
        "  (\"SLP Chapter 9.2 Recurrent Neural Networks\", slp_chapter9_2),\n",
        "  (\"SLP Chapter 9.3 RNNs as Language Models\", slp_chapter9_3),\n",
        "\n",
        "  (\"SLP Chapter 6.1 Lexical Semantics\", slp_chapter6_1),\n",
        "  (\"SLP Chapter 6.2 Vector Semantics\", slp_chapter6_2),\n",
        "  (\"SLP Chapter 6.3 Words and Vectors\", slp_chapter6_3),\n",
        "  (\"SLP Chapter 6.4 Cosine for measuring similarity\", slp_chapter6_4),\n",
        "  (\"SLP Chapter 6.8 Word2vec\", slp_chapter6_8),\n",
        "  (\"SLP Chapter 6.10 Semantic properties of embeddings\", slp_chapter6_10),\n",
        "  (\"SLP Chapter 6.11 Bias and Embeddings\", slp_chapter6_11),\n",
        "  (\"SLP Chapter 6.12 Evaluating Vector Models\", slp_chapter6_12),\n",
        "  (\"Module 13 Lecture Notes\", module14_lecture_notes),\n",
        "]\n",
        "\n",
        "module14_markdown = format_module(14, \"Natural Language Processing\", \n",
        "                         module14_sections, \n",
        "                         module14_definitions)\n",
        "display(Markdown(module14_markdown))"
      ],
      "execution_count": 19,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n\n***NLP***\n- Vector space semantic model\n\n1. Synonyms – words that have similar meanings\n2. Antonyms – words that have opposite meanings\n3. Connotations – words that are positive or negative\n4. Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event\n5. Support for entailment\n\n**Language Modeling**\n- Goal: Learn a function that returns the joint probability\n- Primary difficulty:\n1. There are too many parameters to accurately estimate. This is sometimes called the “curse of dimensionality”\n2. Inn-gram-basedmodelswefailtogeneralizetorelatedwords/word sequences that we have observed.\n\n**Advantages of Neural Language models over n-gram**\n- They don't need smoothing\n- They can handle much longer histories\n- They can generalize over contexts of similar words\n- Neural LMs tend to have much higher predictive accuracy than n-gram LMs\n**Disadvantage**\n- SLower to train than traditional n-gram LMs\n\n**Neural LMs**\n- *Input*: k-gram of words w_1:K\n- *output*: a probability distribution over the next word\n- The k context words are treated as a word window. Each word is associated with an *embedding* vector\n  - The input vector x just concatenates v(w) for each of the k words.\n\n**Lexical Semantic Models**\n- Representation of meaning\n\n*Formal semantics*\n- pros: Mathematically well-understood, powerful machinery for handling logical operations\n- cons: knowledge must come from somewhere else\n\n**Vector Space Model**\n- Able to automatically extract knowleddge from corpus\n\n**Term-Document Matrix**\n-Column : document\n-row : word\n-length of document is length of the word.\n- We can measure how similar two documents are by comparing their column vectors\n- Comparing two rows show how similar two words are.\n\n**Why dense vectors?**\n• *Short vectors* may be easier to use as features in machine learning (fewer weights to tune)\n• *Dense vectors* may *generalize* better than storing explicit counts\n• They may do better at capturing synonymy:\n• car and automobile are synonyms; but are distinct dimensions in sparse vectors\n• a word with car as a neighbor and a word with automobile as a neighbor should be similar, but aren't\n• In practice, they work better\n\n*N0gram LMs represent words as a string of letters or as an index in a vocabulary list*\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "448a0a38-713d-4f74-86f6-13f3766bd560"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module8_markdown, \n",
        "                             module9_markdown, \n",
        "                             module10_markdown, \n",
        "                             module11_markdown, \n",
        "                             module12_markdown,\n",
        "                             module13_markdown,\n",
        "                             module14_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n \n**Combining Beliefs and Desires under Uncertainty**\n- The agent's preferences are captured by a **utility function**, which assigns a single number to express the desirability of a state.\n- **Expected utility** of an action given the evidence is the average utility value fo the outcomes, weighted by the probability that the outcome occurs:\n\n**Maximum expected utility (MEU)** principle\n- a rational agent should choose the action that maximizes the agent's expected utility. \n- If an agent acts so as to maximize a utility function that correctly reflects the performance measure, then the agent will achieve the highest possible performance score.\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n **The Basis of Utility Theory**\n- ***6 Constraints that we require any reasonable preference relation to obey***\n  - *Orderability*: The agent has to decide its preference\n  - *Transitivity*: A>B, B>C, then A>C\n  - *Continuity*\n  - *Substitutability* : If the agent is indifferent about A and B, then B can substitute A\n  - *Monotonicity* : If A>B then prefer lotter with higher probability for A\n  - *Decomposability*\n\n- *value function* or *utility function* : preference ranking on states in a deterministic environment.\n\n\n## AIMA Chapter 16.3 Utility Functions\n **Utility function**\n- Must obey the 6 constraints\n- \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n\n**Markov Decision Processes**\n- A **sequential** decision problem\n- **Fully observable** environment\n- with a **stochastic** transition model\n- Has **additive rewards**\n- **Non-deterministic search problem**\n- Solve through **expectimax** search\n\nTo find MDP solution(policy),\n- We need:\n  - A set of states *S*\n  - A set of actions *A*\n  - A transition function (probability = the model) P(s’|s,a) (or T(s,a,s’))\n  - A reward function (utility function) R(s,a,s’) (and discount gamma) \n  - An initial state *S0*\n  - One or more terminal states\n\n- Policy === solution\n  - Maps from a state onto the action to take if the agent is in that state\n  - $\\pi$(s) = a\n  - $\\pi$*(s) is the *optimal policy*: maximizes the expected utility of the actions taken by the agent.\n  - Even though the policy told me to go to a certain direction, there is no guarantee that it will go there. It is **stochastic**\n  \n- We need to compute the **expected utility** of all the possible paths generated by a policy\n-\tEven if the same policy is executed multiple times by the agent, this may lead to different sequence of states and actions (environment history) and thus a different score under the reward function\n- the *performance* of an agent is the sum of the rewards for the transitions it takes.\n\n**Discounting**\n- Each time we descend a level, we multiply in the discount factor once\n- Make values of rewards decay exponentially\n- *Why?* \n  - Sooner rewards probably have higher utility than later rewards\n  - This helps our algorithms converge\n  - We want more rewards sooner because the world is uncertain.\n\n**Stationary Preferences**\n- Theorem: If we assume stationary preferences, then there are only two ways to define utilities *additive and discounted utility*\n\n**Infinite Utilities**\n- Solutions to infinite utilities\n  - Finite horizon: terminate episodes after a fixed T steps -- try to avoid this\n  - Discounting\n    - smaller gamma means smaller \"horizon\" - shorter term focus\n  - Absorbing state\n    - Guarantee that for every policy, a terminal state will eventually be reached\n    \n**Reward function** (utility function)\n  - “rewards” can be positive or negative but are bounded by some maximum value\n  - We must specify the utility function on a sequence of states and actions because the decision process is sequential\n  - The agent can receive a reward at each time step based on its transition from s to s’ via action a.\n  - R(s, a, s’)\n  - Rewards are additive\n\n**Stochastic transition function**\n  - P(s’ | s, a) or T(s,a,s’)\n  - The probability of arriving in state s’ given that we are in state s and we selected action a\n  - Transitions are Markovian: the probability of arriving in s’ only depends on   s and not the history of earlier states\n\n\n**Optimal Quantities**\n- The value (utility) of a state s:\n  - V*(s) = expected utility starting in s and acting optimally \n-\tThe value (utility) of a q-state (s,a):\n  - Q*(s,a) = expected utility starting out having taken action a from state s and acting optimally\n-\tThe optimal policy:\n  - $\\pi$*(s) = optimal action from state s\n\n**Values of States**\n-\tFundamental operation: compute the expectimax value of a state\n  - Expected utility under optimal action\n  - Average sum of discounted rewards\n  - Recursive definition of value:\n    $V*(s) = max Q*(s,a)\n- We want to find the optimal quantity\n\n**Hyperdrive Search Tree**\n- each level of tree, you get a reward\n\n**Racing Search Tree**\n\n**Bellman Equation** - characterize optimal value\n- A rule of how to be optimal/maximize utility in an uncertain world\n- Use expectimax recurrence to see a simple one-step lookahead relationship amongst optimal utility values\n- $V^*(s) = max \\sum_s' T(s,a,s')[R(s,a,s')+\\gamma V*(s')])$\n\n**Value Iteration**\n- Start with V_0(s) = 0: no time steps left means an expected reward sum of zero\n- Given vector of V_k(s) values, do one ply of expectimax from each state\n- Repeat until convergence\n- Complexity of each iteration: $O(S^2A)$\n- *Theorem*: will converge to unique optimal values\n  - basic idea: approximations get refined towards optimal values\n  - Policy may converge long before values do\n\n**Convergence**\n- *How do we know then the Vk vectors are going to converge*\n  1. If the tree has maximum depth M, then Vm holds the actual untruncated values\n  2. If the discount is less than 1\n- How fast it converges depends on *$\\gamma$ or effective depth*\n  - closer to 1, deeper the depth gets\n\n**Fixed Policies**\n- If we fix some policy $\\pi$(s) then the tree would be simpler - only one action per state\n- *Finding utilities* does not include $max$\n\n**Policy Evaluation**\n- How do we calculate the V's for a fixed policy $\\pi$\n- Idea 1: Turn recursive Bellman equations into updates (like value iteration)\n  - Efficiency: O(S^2) per iteration\n- Idea 2: Without the maxes the Bellman equations are linear system\n\n**Policy Extraction**\n  **Computing actions from values**\n  - $\\pi^*(s) = arg max \\sum_s' T(s,a,s')[R(s,a,s')+\\gamma V*(s')])$\n  - Performing one expectimax(one step)\n  - *policy extraction* = Gets the policy implied by the values\n\n  **Computing actions from Q-values**\n  - Just choose the best value\n  - $\\pi^*(s) = arg max Q^*(s,a)$\n\n**Policy Iteration**\n- *Problems with value iteration*\n  - It's slow - O(S^2A) per iteration\n  - The \"max\" at each state rarely changes\n  - The policy often converges long before the values\n- Approach\n  - Step 1: Policy evaluation: calculate utilities for some fixed policy (not optimal utilities ) until convergence\n  - Step 2: Policy improvement: update policy using one-step look-ahead with resulting converged (but not optimal) utilities as future values\n  - Repeat steps until policy converges\n- Converges faster than value iteration\n\n**Value vs. Policy Iteration**\n- Both value iteration and policy iteration compute the same thing (all optimal values)\n- In *value iteration*:\n  • Every iteration updates both the values and (implicitly) the policy\n  • We don’t track the policy, but taking the max over actions implicitly recomputes it\n- In *policy iteration*:\n  • We do several passes that update utilities with fixed policy (each pass is fast because we consider only one action, not all of them)\n  • After the policy is evaluated, a new policy is chosen (slow like a value iteration pass)\n  • The new policy will be better (or we’re done) \n- Both are dynamic programs for solving MDPs\n\n**MDP Algorithms**\n- to Compute *optimal values* : use Value iteration or policy iteration\n- to Compute values for a *particular policy*: use policy evaluation\n- to Turn your values into a policy: use policy extraction (one-step lookahead)\n\nThese all look the same!\n• They basically are – they are all variations of Bellman updates\n• They all use one-step lookahead expectimax fragments\n• They differ only in whether we plug in a fixed policy or max over actions\n\n**Maximum Expected Utility**\n- Why use average utilities not minimax? Because we are in an uncertain world\n- *Principle of maximum expected utility*\n  - A rational agent should choose the action that *maximizes its expected utility, given its knowledge*\n\n*Our goal is to **maximize expected utility***\n\n**Utilities**\n- They are functions from outcomes (states of the world) to real numbers that describe an agent's preferences\n- Any \"rational\" preferences can be summarized as a utility function\n- They have uncertain outcomes\n\n**Preferences**\n- An agent must have preference among:\n  - Prizes: A, B , etc.\n  - Lotteries: situations with uncertain prizes $L = [p,A; (1-p),B]$\n  - Notation:\n    - Preference: A>B\n    - Indifferencce: A~B\n\n**Rational Preferences**\n- *Axioms of Rationality*\n  - Orderability\n  - Transitivity\n  - Continuity \n  - Substitutability\n  - Monotonicity\n\n**Utility Scales**\n- *Normalized utilities*: u_+ = 1.0, u=0.0\n- *Micromorts*: one-millionth chance of death, useful for paying to reduce product risks, etc.\n- *QALYs*: quality-adjusted life years, useful for medical decisions involving substantial risk \n\n**Money**\n- is not a good utility function\n- is not in linear fashion\n\n## Module 8 Definitions\n* **Utility function** - Single number to express the desirability of a state\n* **Expected utility** - average utility value of the outcomes, weighted by the probabiliyt that the outcome occurs $EU(a) = \\sum_s P(RESULT(a) = s')U(s')$ \n* **Decision-theoretic agent** - Assigns a continuous range of values to states. Can more easiliy choose a better state even when no best state is available\n* **Preference elicitation** - Presenting choices and using the observed preference to pin down the underlying utility function.\n* **Sequential decision problems** - Problems in which agent's utility depends on a sequence of decisions.\n* **Policy** - Choice of action for each state\n* **Utility** - Sum of (discounted) rewards\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n \n## Reinforcement Learning \n- Basic Idea\n  - Receive feedback in the form of rewards\n  - Agent's utility is defined by the reward function\n  - Must learn to act so as to maximize expected rewards\n  - All learning is based on observed samples of outcomes\n  \n- Still assume a *MDP*\n  - a set of states\n  - a set of actions \n  - a model T(s,a,s')\n  - a reward function R(s,a,s')\n- Still looking for a policy $\\pi(s)$\n- **It doesn't know T or R**\n  - it doesn't know which states are good or what the actions do\n  - Must actually try actions and states out to learn\n  \n**Model-Based Learning**\n- Learn an approximate model based on experiences\n- Solve for values as if the learned model were correct\n- Step 1: Learn empirical MDP model\n  - Count outcomes s' for each s, a\n  - Normalize to give an estimate of T(s,a,s')\n  - Discover each R(s,a,s') when we experience (s,a,s')\n- Step 2: Solve the learned MDP\n  - For example, use value iteration, as before\n\n**Model-Free Learning**\n- 1. *Passive Reinforcement Learning*\n  - Someone else chooses the policy\n  - Input: a fixed policy $\\pi$(s)\n  - Goal: learn the state values\n  - Learner is \"along for the ride\"\n  - No choice about what actions to take\n  - Just execute the policy and learn from experience\n\n**Direct Evaluation**\n- Goal: Compute values for each state under $\\pi$\n- Idea: Average together observed sample values\n  - act according to $\\pi$\n  - Every time you visit a state, write down what the sum of discounted rewards turned out to be \n  - Average those samples\n- Pros:\n  - Easy to understand\n  - Doesn't require any knowledge of T,R\n  - It eventually computes the correct average values, using just sample transitions\n- Cons:\n  - It wastes information about state connections\n  - Each state must be learned separately\n  - So, it takes a long time to learn\n\n**Temporal Difference Learning**\n- It is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages\n- Learn from every experience instead of waiting til the end\n- Policy still fixed, still doing evaluation\n- Move values toward value of whatever successor occurs: running average\n- Update: $V^\\pi(s) <- V^\\pi(s) + \u0007lpha(sample - V^\\pi(s))\n- **Exponential moving average**\n  - the running interpolation update:\n  - Makes recent samples more important:\n  - Forgets abou the past (distant past values were wrong anyway)\n- Decreasing learning rate (alpha) can give converging averages\n- Start off with big alpha so that current sample worth more, and gradually decrease it\n- *Cons*\n  - We can't turn values into a new policy\n- **We have to learn the Q-values to know what's the best action**\n- **Model-free Q-Learning**\n  - $Q(s,a) <- (1-\u0007lpha)Q(s,a)+(\u0007lpha)[sample]\n\nQ-learning Properties\n- It eventually converges to optimal policy, even if you are acting suboptimally- *off-policy learning*\n\n*Active Reinforcement Learning*\n- Full reinforcement learning: optimal policies (like value iteration)\n- You don’t know the transitions T(s,a,s’) \n- You don’t know the rewards R(s,a,s’)\n- You choose the actions now\n- Goal: learn the optimal policy / values\n- Leaner makers choices\n- Fundamental tradeoff: exploration vs. exploitation\n- NOT offline planning\n\n**Exploration vs. Exploitation**\n\n**How to Explore?**\n- Simplest: random action ($\\epsilon$-greedy)\n  - every time step, flip a coin\n  - with (small) probability $\\epsilon$, act randomly\n  - with (large) probability 1-$\\epsilon$, act on current policy\n  - *Cons*: You keep thrashing aronud once learning is done\n    - One solution: lower $\\epsilon$ over time\n    - Another solution: exploration functions\n\n**Exploration Function**\n- When to explore?\n  - Random actions: explore a fixed amount\n  - Better idea: explorea areas whose badness is not established, eventually stop exploring\n- Exploration function\n  - Takes a value estimate u and a vist count n, and return an optimistic utility\n  - Regular Q-update: $Q(s,a) <- R(s,a,s') + \\gamma maxQ(s',a')$\n  - Modified Q-update: $Q(s,a) <- R(s,a,s') + \\gamma maxfF(Q(s',a'), N(s',a'))$\n\n**Regret**\n- Regret is a measure of your total mistake cost: teh difference between your expected rewards, including youthful suboptimality, and optimal (expected) rewards\n- You have to optimally learn to be optimal\n\n- Ex: Random exploration and exploration functions both end up optimal, but random exploration has higher regret\n\n**Approximate Q-Learning**\n- ***Generalizing Across States***\n- Basic Q-learning keeps a table of all q-values\n- In realistic situations, we cannot possibly learn about every single state\n- We want to generalize:\n  - Learn about some small number of training states from experience\n  - Generalize that experience to new, similar situations\n  - This is a fundamental idea in machine learning, and we'll see it over and over again\n- Intuitive interpretation:\n  - Adjust weights of active features\nE.g., if something unexpectedly bad happens, blame the features that were on: disprefer all states with that state’s features\n\n**Linear Value Functions**\n- Using a feature representation, we can write a q function (or value function) for any state using a few weights:\n- Advantage: our experience is summed up in a few powerful numbers\n- Disadvantage: states may share features but actually be very different in value!\n\n  \n\n## Module 9 Definitions\n* **Off-policy learning** - eventually converges to optimal policy, even if you are acting suboptimally\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n \n-Probability models allow us to quantify how likely a possible world is.\n**Uncertainty**\n- Observed variables (evidence): Agent knows certain things about the state of the world (e.g., sensor readings or symptoms)\n- Unobserved variables (states): Agent needs to reason about other aspects (e.g. where an object is or what disease is present)\n- Model: Agent knows something about how the known variables relate to the unknown variables\n\n- **Sample space** = mutually exclusive and exhaustive\n\n**Random Variables**\n- A random variable is some aspect of the world about which we (may) have uncertainty\n\n**Axioms of Probability**\n- Probability of any possible world is between 0 and 1\n- The total probability of the set of all possible worlds is 1\n\n**Probability Distributions**\n- Unobserved random variables have distrbutions\n\n**Joint Distributions**\n- A *joint distribution* over a set of random variables specifies a real number for each assignment\n- **Size of distribution if n raviables with domain sizes d** : *$d^n$*\n\n**Probabilistic Models**\n- (Random) variables with domains\n- Assignments are called outcomes\n- Joint distributions:say whether assignments (outcomes) are likely\n- *Normalized*: sum to 1.0\n- Ideally: only certain variables directly interact\n\n**Mariginal Distributions**\n- Allow us to eliminate variables that are not needed\n\n**Conditional Probabilities**\n- A simple relation between joint and conditional probabilities\n- $P(a\b) = P(a,b)/P(b)$\n\n**Conditional Distributions**\n- Conditional distributions are probability distributions over some variables given fixed values of others\n\n**Probabilistic Inference**\n- compute a desired probability from other known probabilities (e.g. conditional from joint)\n- *Inference by Enumeration*\n  - General case:\n    - Evidence variables\n    - Query* variable:\n    - Hidden variables \n  - 1) Select the entries consistent with the evidence\n  - 2) Sum out H to get joint of Query and evidence\n  - 3) Normalize\n\n**The Product Rule**\n- $P(y)P(x|y) = P(x,y)$\n\n**The Chain Rule**\n- $P(x,y,z) = P(x)P(y|x)P(z|x,y)\n\n**Bayes' Rule**\n- $P(x,y) = P(x|y)P(y) = P(y|x)P(x)$\n- **$P(x|y) = P(y|x)*P(x)/P(y)$\n- Let's us build one conditional frm it reverse\n- Often one conditional is tricky but the other one is simple\n\n**Probabilistic Language Models**\n- *Goal*: Assign a probability to a sentence\n- Ex) Autocomplete for texting\n  - Machine Translation\n  - Spelling Correction\n  - Speech Recognition\n- We can't just conut and divide because we don't have enough data\n- *Solution*\n  - Simplifying Assumption = Markov Assumption\n  - only depends on the previous k words not the whole context\n  - *unigram* = no-history\n  - *bigram* = 1 word as history\n  - *trigram* = 2 words as history\n  - *4-gram* = 3 words as history\n\n-Naive Bayes model assumes words occur independently in documents\n\n\n## Module 10 Definitions\n* **Sample space** - possible worlds in probability theory\n* **Distribution** - a table of probabilities of values\n* **Probabilistic models** - A probabilistic model is a joint distribution over a set of random variables\n* **Event** - A set E of outcomes\n* **Marginalization (summing out)** - Combine collapsed rows by adding\n* **Language model** - A model that computes either P(w) or P(wn|w1,w2,...)\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\n**Probabilistic Models**\n- Describe how the world works\n- Models are always simpllifications\n\n**Independence**\n- $P(x,y) = P(x)P(y)$\n- $P(x|y) = P(x)$\n- If observing one doesn't chance the probability of the other.\n- Independence is a simplifying modeling assumption\n  - *empirical* join distributions: at best \"close\" to independent\n\n**Conditionally independent**\n- $P(x,y|z) = P(x|z)P(y|z)\n- Bayes' nets (graphical models) help us express conditional independence assumptions\n\n**Bayes' Nets**\n- Better than joint distribution which is way too big to maintain\n- *Big Picture*:\n  - It is a technique for decribing complex join distributions (models) using simple, local distributions (conditional probabilities)\n  - Describe how variables locally interact\n\n**Graphical Model Notation**\n- *nodes*: variables(with domains)\n  - assigned or unassigned\n- *arcs*: interactions\n  - indicate direct influence between variables\n\n**Bayes' Net semantics**\n- A set of nodes, one per variable X\n- A directed, acryclic graph\n- A conditional distribution for each node\n\n**A Bayes net = Topology (graph) + Local Conditional Probabilities**\n\n**Causality**\n- It is simpler and easier to think about if Bayes' nets reflect\n- It does not need to be causal\n- Topology really encodes conditional independence\n\n**Size of a Bayes' Net**\n- How big is a joint distribution over N boolean variables = $2^N$\n- How big is an N-node net if nodes have up to k parents = O(N*2^k+1)\n\n\n**D-separation Algorithm**\n- triples\n- $P(x,y,z) = P(y)P(x|y)P(z|y)$\n- Casual chain, Common cause, Common effect\n- *Common effect*\n  - Two causes are independent individually, but when given common effect, they are not.\n  - Observing an effect activates influence between possible causes\n\n- **Active/Inactive paths**\n  - X and Y are conditionally independent given Z if they are \"d-separated\" by Z\n  - Path is active if each triple is active\n  - A single inactive segment will block a path\n  - No active paths mean *independence*\n  - shaded : given \n\n**summary**\n- Bayes nets compactly encode joint distributions\n- Guaranteed independencies of distributions can be deduced from BN graph structure\n- D-separation gives precise conditional independence guarantees from graph alone\n- A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\n\n**Inference**\n-  Given unlimited time, inference in BNs is easy\n\nWhy is inference by enumeration so slow?\n- You join up the whole joint distribution before you sum out the hidden variables\n\n\n\n## Module 11 Definitions\n* **Inference** - calculating some useful quantity from a joint probability distribution\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\n**Machine Learning Algorithms**\n1. Naive Bayes\n  - ex. Is the email message spam or not\n  - Each of the features used in the classifier corresponds to a variable and each feature is conditionally independent of every other feature.\n  - *Learn a set of probabilities*\n2. Perceptrons\n  - Have a weight associated with each feature that they use for classification decision\n  - Sigmoid neurons form the building blocks of more complex neural networks\n\n*Both use a set of labeled training data in order to learn a classification decision*\n\n*Classification*\n- Given inputs x, predict labels y\n\n**Model-Based Classification**\n- Build a modle(ex. Bayes net) where both the label and features are random variables\n- Instantiate any observed features\n- Query for the distribution of hte label conditioned on the features\n- *Challenges* : Figureing out structure, How should we learn its parameters\n\n***Naive Bayes***\n- \"Naive\": becasue we assume all features are independent effects of the label\n- *Simple digit recognition version:*\n  - Each feature will correspond to each position in the grid.\n  - On/Off based on intensity\n  - Naive Bayes Model: $P(Y|F0,0 ... F15,15) \\propto P(Y)\\prod P(Fi,j|Y)$\n- ***General Naive Bayes***\n  - $P(Y,F1,...Fn) = P(Y)\\propto P(Fi|Y)$\n  - n * |F| * |Y| parameters : Linear number of features\n  - Downside: very simplistic so might not represent the real world\n\n- *Inference for Naïve Bayes*\n  - *Goal*: compute posterior distribution over label variable Y\n  - Step1: Get joint probability of label adn evidence for each label\n  - Step2: Sum to get probability of evidence\n  - Step 3: normalize by dividing Step1 by Step2\n\n- *To use Naive Bayes*\n  - Inference method\n  - Estimates of local conditional probability tables\n    - Prior parameter P(Y)\n    - P(Fi|Y) for each feature (evidence variable) - conditional probability\n\n***Machine Learning***\n- Data: labeled instances\n  - training set, held out set, test set\n- Features: attribute-value pairs which characterize each x\n- Experimentation cycle\n  - learn parameters on training set\n  - (tune hyperparameters on held-out set)\n  - Compute accuracy on test set\n- Evaluation\n  - Accuracy: fraction of instances predicted correctly\n- Overfitting and generalization\n  - *Overfitting*: fitting the training data very closely, but not generalizing well\n  - Assigning unseen events zero probability will result in lower accuracy\n  - *To generalize better: we need to smooth or regularize the estimates*\n\n- *Parameter Estimation*\n  - **Elicitation**: ask a human\n  - **Empirically**: use training data\n    - $P(x) = count(x)/(total samples)$\n    - *Likelihood of the data* $L(x,\theta)=\\propto P_\theta(x_i)\n\n- *Maximum Likelihood*\n  - Relative frequencies are the maximum likelihood estimates\n  - P_ml(x) = count(x)/total samples\n\n2 ways of generalizing better\n- *Laplace Smoothing*\n  - Avoid zero probability\n  - **Laplace's estimate**: pretend you saw every outcome once more than you actually did\n  - Add k(strength of the prior) to both outcomes\n\n- *Linear Interpolation*\n  - $P_(LIN)(x|y) = \u0007lpha P(x|y) + (1.0-\u0007lpha)P(x)$\n  - \u0007lpha parameter\n\n**Tuning**\n- Two kinds of unknowns\n  - Parameters : P(X|Y),P(Y)\n  - Hyperparameters: $\u0007lpha, k$\n- *Learn parameters from training data*\n- *Tune hyperparameters on differenet data*\n- *for each value of hyperparameters, train and test on the held-out data*\n- *choose the best value and do a final test on the test data*\n\n**Dealing with Errors**\n- Need more features\n- Can add these infomration sources as new variables in the NB model\n\n**Baseline**\n- Help determine how hard the task is\n- Help know what a good accuracy is\n\n**Confidence**\n- Posterior over the top label: $confidence(x) = max P(y|x)$\n- Represents how sure the classifier is of the classification\n- Any probabilistic model will have confidences\n- No guarantee confidence is correct\n- Weak: higher confidences mean higher accuracy\n- Strong: confidence predicts accuracy rate\n\n***Perceptrons***\n- Inspired by neuron\n- Decision making device\n- *Linear classifier*\n1) Inputs: feature values\n2) Weights\n3) Weighted Sum\n4) Activation Function : if positive, 1, negative -1\n5) output\n\n*Learning*\n- Start with weights = 0\n- For each training instance:\n  - Classify with current weights\n  - If correct, no change\n  - If incorrect, adjust the weight vector\n\n*Learning: Multiclass Perceptron*\nStart with all weights = 0\nPick up training examples one by one Predict with current weights\nIf correct, no change!\nIf wrong: lower score of wrong answer, raise score of right answer\n          \n**Properties of Perceptrons**\n- *Separability*: true if some parameters get the training set perfectly correct\n- *Convergence*: if the training is separable, perceptron will eventually converge (binary case)\n- *Mistake Bound*: the maximum number of mistakes (binary case) related to the margin or degree of separability\n  - $mistakes < k/(margin)^2$\n  - Bigger the margin, less mistakes we make\n\n**Problems withe the Perceptron**\n- *Noise*: if the data isn't separable, weight might thrash\n  - Averaging weight overtime\n- *Mediocre generalization*: fins a barely separating solution\n- *Overtraining*: test/held-out accuracy usually rises, then falls\n\n**Fixing the Perceptron**\n- Idea: adjust the weight update to mitigate these effects\n- *MIRA - Margin Infused Relaxed Algorithm*: chooses an update size that fixes the current mistake\n\n**Support Vector Machine**\n- *Maximizing the margin*\n- Support vector machines (SVMs) find the separator with max margin\n- MIRA where you optimize over all examples at once\n\n\n***Classification: Comparison***\n*Naïve Bayes*\n• Builds a model training data\n• Gives prediction probabilities\n• Strong assumptions about feature independence \n• One pass through data (counting)\n\n*Perceptrons / MIRA:*\n• Makes less assumptions about data\n• Mistake-driven learning\n• Multiple passes through data (prediction) \n• Often more accurate\n\n*A single neural unit cannot be used to compute the **XOR** function*\n\n**Activation Functions**\n- There are 3 commonly used non-linear functions\nThe sigmoid function\nThe tanh function\nThe rectified linear unit ReLU\n\n\n## Module 12 Definitions\n* **Concept** - definition\n* **Posterior probability** - updated probability of an event occurring after taking into consideration new information\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\n***Neural Networks***\n\n**Logistic Regression**\n1. A feature representation of the input\n2. A classification function that computes the estimated class 𝑦 via p(y|x).\n3. An objective function(loss function) for learning, usually involving minimizing error on training examples.\n4. An algorithm for optimizing the objective function.\n\n**Stochastic gradient Descent**\n- Trying to minimize loss\n- a method that finds a minimum of a function by figuring out in which direction (in the space of the parameters θ) the function’s slope is rising the most steeply, and moving in the opposite direction.\n- *Choooses a single random example at a time and updates its weights on that example. Updates can fluctuate*\n\n**Mini-batch training**\n- Computes gradient over the entire dataset\n- Gives a much better estimate of which direction to move the weights but takes a long time to compute.\n\n**Regularization**\n- A way to penalize large weights.\n- In logistic regression, if a feature only occurs in one class then it will get a high weight. \n- Term is added to the loss function\n- ex. Lasso regression L1\n      Ridge regression L2\n\n**Softmax function**\n- Generalization of the sigmoid function\n\n\n**Sentiment classifier**\n- Take an input and encode in feature that classifier can use.\n- z = w . x + b \n\n**Learning in logistic regression**\nHow do we get the weights of the model?\n- We learn the parameters (weights + bias) via learning\n- This requires 2 components:\n1. A *loss function* that tells us distance between the system output and the gold output. We will use *cross-entropy* loss.\n2. An algorithm for optimizing the objective function. We will use stochastic gradient descent to minimize the loss function.\n\n**Loss function**\n- ex. Mean Squared Error : not that good for probabilistic classification\n- *Cross entropy loss function*\n  - Negative log likelihood loss\n  - Choose parameters w,b that maximize the log probabilities of the true labels in the training data.\n  - Minimize negative log probabiliity\n  - We want the loss to be smaller if the model’s estimate is close to correct, and we want the loss to be bigger if it is confused.\n\n*Logistic regression loss function is **convex**: just has **one minimum** *\n\n**Feed-Forward Neural Network**\n- Thte simplest kind of Neural network\n- *Multilayer* network, all units are usualy *fully-connected* and *no-cycles*\n- CANNOT MOVE BACK TO LOWER LAYER\n- Output h = $\nu (Wx+b)$\n\n**Backpropagation**\n- Uses differentiation over the network to understand how each neural unit is affected by the ones that it's connected to and vice versa\n- related to backward differentiation\n\n**Computation graph**\n- Represents the process of computing a mathematical expression\n- Each operation is a node in a graph\n- h = σ(Wx+b)\n- z = Uh\n- y = softmax(z)\n\n***We use:\nA cross entropy loss function\nGradient descent to perform optimization\nError back propagation to compute the gradient of the loss function***\n\n**Probabilistic Language Models**\n\n\n## Module 13 Definitions\n* **Loss function** - how wrong the model's predictions are for each item in the training\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n\n***Neural Networks***\n\n**Logistic Regression**\n1. A feature representation of the input\n2. A classification function that computes the estimated class 𝑦 via p(y|x).\n3. An objective function(loss function) for learning, usually involving minimizing error on training examples.\n4. An algorithm for optimizing the objective function.\n\n**Stochastic gradient Descent**\n- Trying to minimize loss\n- a method that finds a minimum of a function by figuring out in which direction (in the space of the parameters θ) the function’s slope is rising the most steeply, and moving in the opposite direction.\n- *Choooses a single random example at a time and updates its weights on that example. Updates can fluctuate*\n\n**Mini-batch training**\n- Computes gradient over the entire dataset\n- Gives a much better estimate of which direction to move the weights but takes a long time to compute.\n\n**Regularization**\n- A way to penalize large weights.\n- In logistic regression, if a feature only occurs in one class then it will get a high weight. \n- Term is added to the loss function\n- ex. Lasso regression L1\n      Ridge regression L2\n\n**Softmax function**\n- Generalization of the sigmoid function\n\n\n**Sentiment classifier**\n- Take an input and encode in feature that classifier can use.\n- z = w . x + b \n\n**Learning in logistic regression**\nHow do we get the weights of the model?\n- We learn the parameters (weights + bias) via learning\n- This requires 2 components:\n1. A *loss function* that tells us distance between the system output and the gold output. We will use *cross-entropy* loss.\n2. An algorithm for optimizing the objective function. We will use stochastic gradient descent to minimize the loss function.\n\n**Loss function**\n- ex. Mean Squared Error : not that good for probabilistic classification\n- *Cross entropy loss function*\n  - Negative log likelihood loss\n  - Choose parameters w,b that maximize the log probabilities of the true labels in the training data.\n  - Minimize negative log probabiliity\n  - We want the loss to be smaller if the model’s estimate is close to correct, and we want the loss to be bigger if it is confused.\n\n*Logistic regression loss function is **convex**: just has **one minimum** *\n\n**Feed-Forward Neural Network**\n- Thte simplest kind of Neural network\n- *Multilayer* network, all units are usualy *fully-connected* and *no-cycles*\n- CANNOT MOVE BACK TO LOWER LAYER\n- Output h = $\nu (Wx+b)$\n\n**Backpropagation**\n- Uses differentiation over the network to understand how each neural unit is affected by the ones that it's connected to and vice versa\n- related to backward differentiation\n\n**Computation graph**\n- Represents the process of computing a mathematical expression\n- Each operation is a node in a graph\n- h = σ(Wx+b)\n- z = Uh\n- y = softmax(z)\n\n***We use:\nA cross entropy loss function\nGradient descent to perform optimization\nError back propagation to compute the gradient of the loss function***\n\n**Probabilistic Language Models**\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}