{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of Template_for 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": "13683547-3c33-4c3f-f060-05a1dedc9877"
      },
      "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": null,
      "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": "8ae44f88-dfa8-416a-89d4-ed10d44826d3"
      },
      "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": null,
      "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": null,
      "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",
        "\n",
        "chapter16_1 = \"\"\" Chapter 16.1 summary. \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 =  \"\"\" Your summary here \"\"\"\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",
        "Stochastic Transition Model: object only moves some of the time when an action is \n",
        "selected, often written as T(s, a, s'), or as the probability p(s'|s,a), meaning\n",
        "the probability of arriving in state s' given that we are in state s and we \n",
        "selected action a\n",
        "- Transitions are Markovian: the probability of arriving in s' only depends on s\n",
        "and not the history of earlier states\n",
        "\n",
        "Utility Function: also a reward function\n",
        "- rewards can be positive or negative but are bounded by some maximum value\n",
        "- since the decision process is sequential, we must specify the utility function\n",
        "on a sequence of states and actions\n",
        "- the agent can receive a reward at each time step (instead of just goal states)\n",
        "based on its transition from s to s' via action a\n",
        "- defined by a reward function R(s,a,s')\n",
        "- rewards are additive\n",
        "- reward of +1 for getting to goal and -1 all other time when trying to escape\n",
        "the maze with discount of 1\n",
        "- utility function estimate does not need to be completely accurate to get\n",
        "an optimal policy\n",
        "\n",
        "Markov Property: given the present state, the future and past are independent\n",
        "\n",
        "Markov Decision Process (MDP): a sequential decision problem for a fully \n",
        "observable environment with a stochastic transition model that has additive\n",
        "rewards\n",
        "- non-deterministic search problems\n",
        "- can solve them via expectimax search\n",
        "\n",
        "Expectimax Node: outcome is uncertain\n",
        "- in expectimax search we calculate their expected utilities\n",
        "\n",
        "To find a solution to an MDP, need to define:\n",
        "- set of states s $\\in$ S\n",
        "- set of actions a $\\in$ A\n",
        "- transition function T(s,a,s'), probability that executing action a in s will \n",
        "lead to s'P(s'|s,a), the probability is called the model\n",
        "- a reward function R(s,a,s'), sometimes just R(s) or R(s')\n",
        "- an initial state $s_0$\n",
        "- optionally, one or more terminal states\n",
        "\n",
        "The solution to an MDP is a policy.\n",
        "- a policy maps from a state onto the action to take if the agent is in that\n",
        "state\n",
        "- $\\pi$(s) = a, policy $\\pi$ tells the agent what action to take at state s\n",
        "- because of the non-determinism in MDPs we cannot simply give a sequence of\n",
        "actions\n",
        "- in search problems a solution was a plan: a sequence of actions that \n",
        "corresponded to the shortest path from the start to a goal\n",
        "\n",
        "Expected Utility: computed for all possible paths generated by a policy\n",
        "- even if the same policy is executed multiple times by the agent, this may \n",
        "lead to different sequences of states and actions (environment history), and \n",
        "thus a different score under the reward function\n",
        "- policy is optimal if it maximizes the expected utility of the actions taken\n",
        "by the agent\n",
        "\n",
        "Performance: the sum of the rewards for the transitions an agent takes in an MDP\n",
        "- U([$s_0,a_0,s_1,a_1,...,s_n$]) = R($s_0,a_0,s_1$) + R($s_1,a_1,s_2$) + ... + \n",
        "R($s_{n-1},a_{n-1},s_n$)\n",
        "- U: utility function on an environment history\n",
        "\n",
        "Discounting: values of rewards decay over time\n",
        "- each time we descend a level, we multiply in the discount once\n",
        "- helps algorithm converge\n",
        "- additive utility: U($r_0,r_1,r_2...$) = $r_0 + r_1 + r_2 + ...$\n",
        "- discounted utility: U($r_0,r_1,r_2...$) = $r_0 + \\gamma r_1 + (\\gamma)^2 r_2 + ...$\n",
        "- use $0 < \\gamma < 1$\n",
        "- smaller $\\gamma$ means smaller horizon - shorter term focus\n",
        "- absorbing state: guarantee that for every policy a terminal state will eventually\n",
        "be reached\n",
        "\n",
        "Optimal Quantities:\n",
        "- V*(s): expected utility starting in s and acting optimally\n",
        "- Q*(s,a): expected utility starting out having taken action a from state s and\n",
        "acting optimally thereafter\n",
        "- $\\pi$*(s): optimal action from state s\n",
        "- actions are easier to select from q-values than values\n",
        "\n",
        "Bellman Equations: definition of optimal utility via expectimax recurrence gives\n",
        "a simple one-step lookahead relationship amongst optimal utility values\n",
        "- $V^*(s)$ = max$_aQ^*(s,a)$\n",
        "- $Q^*(s,a)$ = $\\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma V^*(s')]$\n",
        "\n",
        "Time-Limited Values:\n",
        "- define $V_k(s)$ to be the optimal value of s if the game ends in k more time\n",
        "steps\n",
        "- what a depth-k expectimax would give from s\n",
        "\n",
        "Value Iteration:\n",
        "- start with $V_0(s)$ = 0\n",
        "- run $V_{k+1}(s)$ = max$_a \\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma V_k(s')]$\n",
        "- repeat until convergence\n",
        "- complexity of each iteration: $O(S^2A)$\n",
        "- will converge to unique optimal values\n",
        "- policy often converges long before the values\n",
        "- slow and the max at each state rarely changes\n",
        "- contraction: part of the proof of convergence for the value iteration algorithm\n",
        "\n",
        "Fixed Policies:\n",
        "- can fix some policy $\\pi (s)$ to make the tree simpler\n",
        "- usually non-optimal\n",
        "\n",
        "Policy Iteration:\n",
        "- calculate utilities for some fixed policy (not optimal utilities) until \n",
        "convergence\n",
        "- update policy using one-step lookahead with resulting converged (but not\n",
        "optimal) utilities as future values\n",
        "- repeat steps until policy converges\n",
        "- this is optimal and can converge much faster than value iteration\n",
        "- $V_{k+1}^{\\pi _i}(s)$ = $\\sum _{s'}T(s,\\pi _i(s),s')[R(s,\\pi _i(s),s') + \n",
        "\\gamma V_k^{\\pi _i}(s')]$\n",
        "- $\\pi _{i+1} (s) = $max$_a$\\sum _{s'}T(s,a,s')[R(s,a,s') + \n",
        "\\gamma V^{\\pi _i}(s')]$\n",
        "- a new policy will be better (or we're done)\n",
        "\n",
        "Summary:\n",
        "- compute optimal values: use value iteration or policy iteration\n",
        "- compute values for a particular policy: use policy evaluation\n",
        "- turn your values into a policy: use policy extraction (one-step lookahead)\n",
        "\n",
        "Principle of Maximum Expected Utility: a rational agent should choose the action that maximizes its expected utility\n",
        "given its knowledge\n",
        "\n",
        "Insensitivity to Monotonic Transformations: for worst-case minimax reasoning, \n",
        "terminal function scale doesn't matter, we just want better states to have \n",
        "higher evaluations (get the ordering right)\n",
        "\n",
        "Indifference: $A \\succ B$ or $A \\sim B$\n",
        "\n",
        "Axioms of Rationality (Rational Preferences):\n",
        "- Orderability: $(A \\succ B) \\or (B \\succ A) \\or ($A \\sim B$)$\n",
        "- Transitivity: $(A \\succ B) \\and (B \\succ C) \\Rightarrow ($A \\succ C$)$\n",
        "- Continuity: $A \\succ B \\succ C \\Rightarrow \\exists  p [p, A; 1 - p, C] \\sim B$\n",
        "- Substitutability: $A \\sim B \\Rightarrow [p, A; 1 - p, C] \\sim [p, B; 1 - p, C]$\n",
        "- Monotonicity: $A \\succ B \\Rightarrow (p \\geq q \\Leftrightarrow [p, A; 1 - p, B] \\succeq [q, A; 1 - p, B])$\n",
        "- given preferences satisfying these constraints, there exists a maximum \n",
        "expected utility\n",
        "\"\"\"\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\" : \"sum of (discounted) rewards\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "\"policy\": \"choice of action for each state\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "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/"
        },
        "outputId": "c1c37b5b-c60d-4478-afa3-30bfc0d5f812"
      },
      "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": null,
      "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 Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \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\nStochastic Transition Model: object only moves some of the time when an action is \nselected, often written as T(s, a, s'), or as the probability p(s'|s,a), meaning\nthe probability of arriving in state s' given that we are in state s and we \nselected action a\n- Transitions are Markovian: the probability of arriving in s' only depends on s\nand not the history of earlier states\n\nUtility Function: also a reward function\n- rewards can be positive or negative but are bounded by some maximum value\n- since the decision process is sequential, we must specify the utility function\non a sequence of states and actions\n- the agent can receive a reward at each time step (instead of just goal states)\nbased on its transition from s to s' via action a\n- defined by a reward function R(s,a,s')\n- rewards are additive\n- reward of +1 for getting to goal and -1 all other time when trying to escape\nthe maze with discount of 1\n- utility function estimate does not need to be completely accurate to get\nan optimal policy\n\nMarkov Property: given the present state, the future and past are independent\n\nMarkov Decision Process (MDP): a sequential decision problem for a fully \nobservable environment with a stochastic transition model that has additive\nrewards\n- non-deterministic search problems\n- can solve them via expectimax search\n\nExpectimax Node: outcome is uncertain\n- in expectimax search we calculate their expected utilities\n\nTo find a solution to an MDP, need to define:\n- set of states s $\\in$ S\n- set of actions a $\\in$ A\n- transition function T(s,a,s'), probability that executing action a in s will \nlead to s'P(s'|s,a), the probability is called the model\n- a reward function R(s,a,s'), sometimes just R(s) or R(s')\n- an initial state $s_0$\n- optionally, one or more terminal states\n\nThe solution to an MDP is a policy.\n- a policy maps from a state onto the action to take if the agent is in that\nstate\n- $\\pi$(s) = a, policy $\\pi$ tells the agent what action to take at state s\n- because of the non-determinism in MDPs we cannot simply give a sequence of\nactions\n- in search problems a solution was a plan: a sequence of actions that \ncorresponded to the shortest path from the start to a goal\n\nExpected Utility: computed for all possible paths generated by a policy\n- even if the same policy is executed multiple times by the agent, this may \nlead to different sequences of states and actions (environment history), and \nthus a different score under the reward function\n- policy is optimal if it maximizes the expected utility of the actions taken\nby the agent\n\nPerformance: the sum of the rewards for the transitions an agent takes in an MDP\n- U([$s_0,a_0,s_1,a_1,...,s_n$]) = R($s_0,a_0,s_1$) + R($s_1,a_1,s_2$) + ... + \nR($s_{n-1},a_{n-1},s_n$)\n- U: utility function on an environment history\n\nDiscounting: values of rewards decay over time\n- each time we descend a level, we multiply in the discount once\n- helps algorithm converge\n- additive utility: U($r_0,r_1,r_2...$) = $r_0 + r_1 + r_2 + ...$\n- discounted utility: U($r_0,r_1,r_2...$) = $r_0 + \\gamma r_1 + (\\gamma)^2 r_2 + ...$\n- use $0 < \\gamma < 1$\n- smaller $\\gamma$ means smaller horizon - shorter term focus\n- absorbing state: guarantee that for every policy a terminal state will eventually\nbe reached\n\nOptimal Quantities:\n- V*(s): expected utility starting in s and acting optimally\n- Q*(s,a): expected utility starting out having taken action a from state s and\nacting optimally thereafter\n- $\\pi$*(s): optimal action from state s\n- actions are easier to select from q-values than values\n\nBellman Equations: definition of optimal utility via expectimax recurrence gives\na simple one-step lookahead relationship amongst optimal utility values\n- $V^*(s)$ = max$_aQ^*(s,a)$\n- $Q^*(s,a)$ = $\\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma V^*(s')]$\n\nTime-Limited Values:\n- define $V_k(s)$ to be the optimal value of s if the game ends in k more time\nsteps\n- what a depth-k expectimax would give from s\n\nValue Iteration:\n- start with $V_0(s)$ = 0\n- run $V_{k+1}(s)$ = max$_a \\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma V_k(s')]$\n- repeat until convergence\n- complexity of each iteration: $O(S^2A)$\n- will converge to unique optimal values\n- policy often converges long before the values\n- slow and the max at each state rarely changes\n- contraction: part of the proof of convergence for the value iteration algorithm\n\nFixed Policies:\n- can fix some policy $\\pi (s)$ to make the tree simpler\n- usually non-optimal\n\nPolicy Iteration:\n- calculate utilities for some fixed policy (not optimal utilities) until \nconvergence\n- update policy using one-step lookahead with resulting converged (but not\noptimal) utilities as future values\n- repeat steps until policy converges\n- this is optimal and can converge much faster than value iteration\n- $V_{k+1}^{\\pi _i}(s)$ = $\\sum _{s'}T(s,\\pi _i(s),s')[R(s,\\pi _i(s),s') + \n\\gamma V_k^{\\pi _i}(s')]$\n- $\\pi _{i+1} (s) = $max$_a$\\sum _{s'}T(s,a,s')[R(s,a,s') + \n\\gamma V^{\\pi _i}(s')]$\n- a new policy will be better (or we're done)\n\nSummary:\n- compute optimal values: use value iteration or policy iteration\n- compute values for a particular policy: use policy evaluation\n- turn your values into a policy: use policy extraction (one-step lookahead)\n\nPrinciple of Maximum Expected Utility: a rational agent should choose the action that maximizes its expected utility\ngiven its knowledge\n\nInsensitivity to Monotonic Transformations: for worst-case minimax reasoning, \nterminal function scale doesn't matter, we just want better states to have \nhigher evaluations (get the ordering right)\n\nIndifference: $A \\succ B$ or $A \\sim B$\n\nAxioms of Rationality (Rational Preferences):\n- Orderability: $(A \\succ B) \\or (B \\succ A) \\or ($A \\sim B$)$\n- Transitivity: $(A \\succ B) \u0007nd (B \\succ C) \\Rightarrow ($A \\succ C$)$\n- Continuity: $A \\succ B \\succ C \\Rightarrow \\exists  p [p, A; 1 - p, C] \\sim B$\n- Substitutability: $A \\sim B \\Rightarrow [p, A; 1 - p, C] \\sim [p, B; 1 - p, C]$\n- Monotonicity: $A \\succ B \\Rightarrow (p \\geq q \\Leftrightarrow [p, A; 1 - p, B] \\succeq [q, A; 1 - p, B])$\n- given preferences satisfying these constraints, there exists a maximum \nexpected utility\n\n\n## Module 8 Definitions\n* **Utility function** - sum of (discounted) rewards\n* **Expected utility** - your definition here\n* **Policy** - choice of action for each state\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",
        "Offline Planning: you don't actually play the game\n",
        "- solving MDPs is offline planning\n",
        "- determine all quantities through computation\n",
        "- need to know the deails of the MDP\n",
        "\n",
        "Reinforcement Learning Ideas:\n",
        "- Exploration: have to try unknown actions to get information\n",
        "- Exploitation: eventually, have to use what you know\n",
        "- Regret: can still make mistakes\n",
        "- Sampling: have to try things repeatedly because of chance\n",
        "- Difficulty: learning can be much harder than solving a known MDP\n",
        "\n",
        "Reinforcement Learning:\n",
        "- receive feedback in the form of rewards (r)\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",
        "- still assume an MDP\n",
        "- don't know T or R (don't know which states are good or what the actions do, \n",
        "need to atually try actions and states to learn)\n",
        "\n",
        "Model-Based Learning:\n",
        "- learn an approximate model based on experiences (an empirical/observed MDP model)\n",
        "- solve for values as if the learned model were correct (can use value iteration)\n",
        "\n",
        "Passive Reinforcement Learning:\n",
        "- learner has no choice about what actions to take\n",
        "- just execute the policy and learn from experience\n",
        "- not offline planning, still takes actions in the world\n",
        "\n",
        "Direct Evaluation:\n",
        "- compute values for each state under $\\pi$\n",
        "- average together observed sample values\n",
        "- doesn't require any knowledge of T, R\n",
        "- eventually computes the correct average values, using just sample transitions\n",
        "- takes a long time to learn because each state must be learned separately\n",
        "\n",
        "Sample-Based Policy Evaluation:\n",
        "- compute V without knowing T and R\n",
        "- take samples of outcomes s' (by doing the action) and average\n",
        "- $V_{k+1}^{\\pi}(s) \\leftarrow 1/n \\sum _i sample_i$\n",
        "- $V_{k+1}^{\\pi}(s) \\leftarrow 1/n \\sum _i R(s,\\pi (s), s_i')$\n",
        "\n",
        "Temporal Difference Learning:\n",
        "- learn from every experience\n",
        "- update V(s) each time we experience a transition (s,a,s',r)\n",
        "- likely outcomes s' will contribute updates more often\n",
        "- policy still fixed, still doing evaluation\n",
        "- move values toward value of whatever successor occurs: running average\n",
        "- a model-free way to do policy evaluation, mimicking Bellman updates with \n",
        "running sample averages\n",
        "- if we want to turn values into a (new) policy, we're sunk\n",
        "- can learn q-values, not values, which makes action selection model-free too\n",
        "\n",
        "Active Reinforcement Learning:\n",
        "- full reinforcement learning: optimal policies (like value iteration)\n",
        "- don't know the transitions or rewards\n",
        "- you choose the actions\n",
        "- goal is to learn the optimal policy / values\n",
        "\n",
        "Q-Value Iteration:\n",
        "- start with $Q_0(s,a) = 0$\n",
        "- $Q_{k+1}(s,a)$ = $\\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma max_{a'} Q_k(s',a')]$\n",
        "\n",
        "Q-Learning: sample based Q-value itteration\n",
        "- learn Q(s,a) values as you go\n",
        "- receive a sample (s,a,s',r)\n",
        "- consider your old estimate: Q(s,a)\n",
        "- consider your new sample estimate: sample = $R(s,a,s') + \\gamma max_{a'} Q(s',a')$\n",
        "- incorporate the new estimate into a running average: $Q(s,a)$ = $(1 - alpha)Q(s,a) + (alpha)[sample]$\n",
        "\n",
        "Off-Policy Learning:\n",
        "- Q-learning converges to optimal policy - even if you're action suboptimally\n",
        "\n",
        "Exploration:\n",
        "- simplest scheme for forcing exploration is random actions ($\\varepsilon$-greedy)\n",
        "where at each step with small probability $\\varepsilon$ act randomly, and with\n",
        "large probability 1-$\\varepsilon$ act on current policy\n",
        "- could lower $\\varepsilon$ over time\n",
        "\n",
        "Exploration Function:\n",
        "- explore areas whose badness is not yet established, eventually stop exploring\n",
        "- takes a value estimate $u$ and a visit count $n$ and returns an optimistic\n",
        "utility: $f(u,n)=u+k/n$\n",
        "- Regular Q-Update: $Q(s,a) \\leftarrow _{alpha} R(s,a,s') + \\gamma max_{a'} Q(s',a')$\n",
        "- Modified Q-Update: $Q(s,a) \\leftarrow _{alpha} R(s,a,s') + \\gamma max_{a'} f(Q(s',a'), N(s',a'))$\n",
        "- if an agent's exploration function values curiosity, $N(s,a)$ for a state $s$\n",
        "and action $a$ would be low\n",
        "\n",
        "Regret:\n",
        "- a measure of your total mistake cost\n",
        "- the difference between your expected rewards, including youthful suboptimality,\n",
        "and optimal expected rewards\n",
        "- quantifies relative goodness of exploration procedures\n",
        "\n",
        "Generalizing Across States:\n",
        "- basic Q-Learning keeps a table of all q-values\n",
        "- in realistic situations, we cannot learn about every state\n",
        "- instead we learn about some small number of training states from experience\n",
        "and generalize that experience to new, similar situations\n",
        "\n",
        "Linear Value Functions: use feature representation to write a q function or \n",
        "value function for any state using a few weights\n",
        "- $V(s) = w_1f_1(s) + w_2f_2(s) + ... + w_nf_n(s)$\n",
        "- $Q(s,a) = w_1f_1(s,a) + w_2f_2(s,a) + ... + w_nf_n(s,a)$\n",
        "- sums up experience in a few powerful numbers\n",
        "- states may share features but actually be very different in value\n",
        "- used in approximate Q-Learning\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "outputId": "2fd0d73c-ad51-4522-b25b-bb72ec88cb70"
      },
      "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": null,
      "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\nOffline Planning: you don't actually play the game\n- solving MDPs is offline planning\n- determine all quantities through computation\n- need to know the deails of the MDP\n\nReinforcement Learning Ideas:\n- Exploration: have to try unknown actions to get information\n- Exploitation: eventually, have to use what you know\n- Regret: can still make mistakes\n- Sampling: have to try things repeatedly because of chance\n- Difficulty: learning can be much harder than solving a known MDP\n\nReinforcement Learning:\n- receive feedback in the form of rewards (r)\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- still assume an MDP\n- don't know T or R (don't know which states are good or what the actions do, \nneed to atually try actions and states to learn)\n\nModel-Based Learning:\n- learn an approximate model based on experiences (an empirical/observed MDP model)\n- solve for values as if the learned model were correct (can use value iteration)\n\nPassive Reinforcement Learning:\n- learner has no choice about what actions to take\n- just execute the policy and learn from experience\n- not offline planning, still takes actions in the world\n\nDirect Evaluation:\n- compute values for each state under $\\pi$\n- average together observed sample values\n- doesn't require any knowledge of T, R\n- eventually computes the correct average values, using just sample transitions\n- takes a long time to learn because each state must be learned separately\n\nSample-Based Policy Evaluation:\n- compute V without knowing T and R\n- take samples of outcomes s' (by doing the action) and average\n- $V_{k+1}^{\\pi}(s) \\leftarrow 1/n \\sum _i sample_i$\n- $V_{k+1}^{\\pi}(s) \\leftarrow 1/n \\sum _i R(s,\\pi (s), s_i')$\n\nTemporal Difference Learning:\n- learn from every experience\n- update V(s) each time we experience a transition (s,a,s',r)\n- likely outcomes s' will contribute updates more often\n- policy still fixed, still doing evaluation\n- move values toward value of whatever successor occurs: running average\n- a model-free way to do policy evaluation, mimicking Bellman updates with \nrunning sample averages\n- if we want to turn values into a (new) policy, we're sunk\n- can learn q-values, not values, which makes action selection model-free too\n\nActive Reinforcement Learning:\n- full reinforcement learning: optimal policies (like value iteration)\n- don't know the transitions or rewards\n- you choose the actions\n- goal is to learn the optimal policy / values\n\nQ-Value Iteration:\n- start with $Q_0(s,a) = 0$\n- $Q_{k+1}(s,a)$ = $\\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma max_{a'} Q_k(s',a')]$\n\nQ-Learning: sample based Q-value itteration\n- learn Q(s,a) values as you go\n- receive a sample (s,a,s',r)\n- consider your old estimate: Q(s,a)\n- consider your new sample estimate: sample = $R(s,a,s') + \\gamma max_{a'} Q(s',a')$\n- incorporate the new estimate into a running average: $Q(s,a)$ = $(1 - alpha)Q(s,a) + (alpha)[sample]$\n\nOff-Policy Learning:\n- Q-learning converges to optimal policy - even if you're action suboptimally\n\nExploration:\n- simplest scheme for forcing exploration is random actions ($\u000barepsilon$-greedy)\nwhere at each step with small probability $\u000barepsilon$ act randomly, and with\nlarge probability 1-$\u000barepsilon$ act on current policy\n- could lower $\u000barepsilon$ over time\n\nExploration Function:\n- explore areas whose badness is not yet established, eventually stop exploring\n- takes a value estimate $u$ and a visit count $n$ and returns an optimistic\nutility: $f(u,n)=u+k/n$\n- Regular Q-Update: $Q(s,a) \\leftarrow _{alpha} R(s,a,s') + \\gamma max_{a'} Q(s',a')$\n- Modified Q-Update: $Q(s,a) \\leftarrow _{alpha} R(s,a,s') + \\gamma max_{a'} f(Q(s',a'), N(s',a'))$\n- if an agent's exploration function values curiosity, $N(s,a)$ for a state $s$\nand action $a$ would be low\n\nRegret:\n- a measure of your total mistake cost\n- the difference between your expected rewards, including youthful suboptimality,\nand optimal expected rewards\n- quantifies relative goodness of exploration procedures\n\nGeneralizing Across States:\n- basic Q-Learning keeps a table of all q-values\n- in realistic situations, we cannot learn about every state\n- instead we learn about some small number of training states from experience\nand generalize that experience to new, similar situations\n\nLinear Value Functions: use feature representation to write a q function or \nvalue function for any state using a few weights\n- $V(s) = w_1f_1(s) + w_2f_2(s) + ... + w_nf_n(s)$\n- $Q(s,a) = w_1f_1(s,a) + w_2f_2(s,a) + ... + w_nf_n(s,a)$\n- sums up experience in a few powerful numbers\n- states may share features but actually be very different in value\n- used in approximate Q-Learning\n\n\n## Module 9 Definitions\n* **Term** - your definition here\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",
        "Sample Space: the possible worlds, are mutually exclusive and exhaustive\n",
        "\n",
        "Probability Distributions: unobserved random variables have distributions\n",
        "\n",
        "Joint Distribution: over a set of random variables, specifies a real number\n",
        "for each assignment (or outcome)\n",
        "\n",
        "Probabilistic Model: a joint distribution over a set of random variables\n",
        "- (random) variables with domains\n",
        "- assignments are called outcomes\n",
        "- joint distributions: say whether assignments (outcomes) are likely\n",
        "- normalized: sum to 1\n",
        "- ideally: only certain variables directly interact\n",
        "\n",
        "Event: a set E of outcomes\n",
        "- typically the events we care about are partial assignments, like P(T = hot)\n",
        "\n",
        "Marginal Distributions: subtables which eliminate variables\n",
        "- marginalization: summing out, combine collapsed rows by adding\n",
        "\n",
        "Conditional Probability: P(a|b) = P(a,b) / P(b)\n",
        "\n",
        "Conditional Distributions: probability distributions over some variables \n",
        "given fixed calues of other\n",
        "- ex: P(W|T = hot)\n",
        "\n",
        "Probabilistic Inference: compute a desired probability from other known \n",
        "probabilities\n",
        "- ex: conditional from joint\n",
        "- probabilities change with new evidence\n",
        "\n",
        "Inference by Enumeration Steps:\n",
        "- select the entires consistent with the evidence\n",
        "- sum out H (hidden variables) to get joint of Query* variable and evidence\n",
        "variables\n",
        "- normalize\n",
        "\n",
        "Product Rule: P(y)P(x|y) = P(x,y)\n",
        "\n",
        "Chain Rule: can always write any joint distribution as an incremental product \n",
        "of conditional distributions\n",
        "- ex: P(x,y,z) = P(x)P(y|x)P(z|x,y)\n",
        "- N! ways to apply the chain rule to a joint distribution with N random variables\n",
        "\n",
        "Bayes' Rule: two ways to factor a joint distribution over two variables\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",
        "\n",
        "Probabilistic Language Modeling: compute the probability of a sentence or \n",
        "sequence of words\n",
        "- Language Model (LM): a model that computes this or the probability of \n",
        "an upcoming word\n",
        "- probability of a sentence or sequence of words: P(W) = P($w_1,w_2,...w_n$)\n",
        "- probability of an upcoming word: P($w_5|w_1,w_2,w_3,w_4$)\n",
        "\n",
        "Markov Assumption: only depends on the previous $k$ words, not the whole context\n",
        "- $P(w_1w_2...w_n) \\simeq \\Pi _i ^n P(w_i|w_{i-k}...w_{i-1})$\n",
        "- $k$ is the number of context words that we take into account\n",
        "\n",
        "How much history to use:\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-gram models are best for language because it has long-distance dependencies\n",
        "\n",
        "Maximum Likelihood Estimate: used to estimate bigram probabilities\n",
        "- $P(w_i|w_{i-1}) = count(w_{i-1},w_i) / count(w_{i-1})$\n",
        "- $P(w_i|w_{i-1}) = c(w_{i-1},w_i) / c(w_{i-1})$\n",
        "- we do everything in log space: avoids underflow, adding is fast than multiplying\n",
        "- log($p_1p_2p_3p_4$) = log($p_1$) + log($p_2$) + log($p_3$) + log($p_4$)\n",
        "\n",
        "Out of Vocabulary Items:\n",
        "- use <unk> to deal with out of vocabulary items (OOVs)\n",
        "- fixed lexicon L of size V\n",
        "- normalize training data by replacing any word not in L with <unk>\n",
        "- avoid zeros with smoothing\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "outputId": "5c85ad72-f252-4556-f730-4ac9dd8a00fd"
      },
      "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": null,
      "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\nSample Space: the possible worlds, are mutually exclusive and exhaustive\n\nProbability Distributions: unobserved random variables have distributions\n\nJoint Distribution: over a set of random variables, specifies a real number\nfor each assignment (or outcome)\n\nProbabilistic Model: a joint distribution over a set of random variables\n- (random) variables with domains\n- assignments are called outcomes\n- joint distributions: say whether assignments (outcomes) are likely\n- normalized: sum to 1\n- ideally: only certain variables directly interact\n\nEvent: a set E of outcomes\n- typically the events we care about are partial assignments, like P(T = hot)\n\nMarginal Distributions: subtables which eliminate variables\n- marginalization: summing out, combine collapsed rows by adding\n\nConditional Probability: P(a|b) = P(a,b) / P(b)\n\nConditional Distributions: probability distributions over some variables \ngiven fixed calues of other\n- ex: P(W|T = hot)\n\nProbabilistic Inference: compute a desired probability from other known \nprobabilities\n- ex: conditional from joint\n- probabilities change with new evidence\n\nInference by Enumeration Steps:\n- select the entires consistent with the evidence\n- sum out H (hidden variables) to get joint of Query* variable and evidence\nvariables\n- normalize\n\nProduct Rule: P(y)P(x|y) = P(x,y)\n\nChain Rule: can always write any joint distribution as an incremental product \nof conditional distributions\n- ex: P(x,y,z) = P(x)P(y|x)P(z|x,y)\n- N! ways to apply the chain rule to a joint distribution with N random variables\n\nBayes' Rule: two ways to factor a joint distribution over two variables\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\nProbabilistic Language Modeling: compute the probability of a sentence or \nsequence of words\n- Language Model (LM): a model that computes this or the probability of \nan upcoming word\n- probability of a sentence or sequence of words: P(W) = P($w_1,w_2,...w_n$)\n- probability of an upcoming word: P($w_5|w_1,w_2,w_3,w_4$)\n\nMarkov Assumption: only depends on the previous $k$ words, not the whole context\n- $P(w_1w_2...w_n) \\simeq \\Pi _i ^n P(w_i|w_{i-k}...w_{i-1})$\n- $k$ is the number of context words that we take into account\n\nHow much history to use:\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-gram models are best for language because it has long-distance dependencies\n\nMaximum Likelihood Estimate: used to estimate bigram probabilities\n- $P(w_i|w_{i-1}) = count(w_{i-1},w_i) / count(w_{i-1})$\n- $P(w_i|w_{i-1}) = c(w_{i-1},w_i) / c(w_{i-1})$\n- we do everything in log space: avoids underflow, adding is fast than multiplying\n- log($p_1p_2p_3p_4$) = log($p_1$) + log($p_2$) + log($p_3$) + log($p_4$)\n\nOut of Vocabulary Items:\n- use <unk> to deal with out of vocabulary items (OOVs)\n- fixed lexicon L of size V\n- normalize training data by replacing any word not in L with <unk>\n- avoid zeros with smoothing\n\n\n## Module 10 Definitions\n* **Term** - your definition here\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",
        "Independence: two variables are independe if for each $x,y: P(x,y) = P(x)P(y)$\n",
        "- equivalent to: for each $x,y: P(x|y) = P(x)$\n",
        "- can be written as $X \\perp \\!\\!\\! \\perp Y$\n",
        "- independence is a simplifying modeling assumption\n",
        "- empirical joint distributions are at best close to independent\n",
        "\n",
        "Conditional Independence:\n",
        "- X is conditionally independent of Y given Z: $X \\perp \\!\\!\\! \\perp Y | Z$ if\n",
        "and only if for all $x,y,z: P(x,y|z) = P(x|z)P(y|z)$ or, equivalently, if and\n",
        "only if for all $x,y,z: P(x|z,y) = P(x|z)$\n",
        "\n",
        "Bayes' Nets: a technique for describing complex joint distributions (models)\n",
        "using simple, local distributions (conditional probabilities)\n",
        "- more properly called graphical models\n",
        "- we describe how variables locally interact\n",
        "- local interactions chain together to give global, indirect interactions\n",
        "\n",
        "Graphical Model Notation:\n",
        "- nodes: variables (with domains), can be assigned (observed) or unassigned\n",
        "(unobserved)\n",
        "- arcs: interactions, indicate direct influence between variables, formally \n",
        "encode conditional independence\n",
        "- only distributions whose variables are absolutely independent can be \n",
        "represented by a Bayes' net with no arcs\n",
        "\n",
        "Absolute Independence: no interactions between variables\n",
        "\n",
        "Bayes' Net Graph:\n",
        "- a set of nodes, one per variable X\n",
        "- a directed, acyclic graph\n",
        "- a conditional distribution for each node\n",
        "- Bayes' nets implicitly encode joint distributions as a product of local \n",
        "conditional distributions\n",
        "- just need the parents probability distributions to get the conditional\n",
        "probability distribution\n",
        "- $P(x_1,x_2,...,x_n) = \\Pi _{i=1} ^n P(x_i|parents(X_i))$\n",
        "- assume $P(x_i|x_1...x_{i-1}) = \\Pi _{i=1} ^n P(x_i|parents(X_i))$\n",
        "- BNs need not actually be causal - end up with arrows that reflect correlation,\n",
        "not causation\n",
        "- topology encodes conditional independence\n",
        "- topology may happen to encode causal structure\n",
        "- more than one Bayesian network can be used to represent the same joint\n",
        "distribution\n",
        "\n",
        "Size of a Bayes' Net:\n",
        "- a joint distribution over N boolean variables: $2^N$\n",
        "- an N-node net if nodes have up to $k$ parents: $O(N*2^{k+1})$\n",
        "- BNs have huge space savings\n",
        "- easier to elicit local CPTs (conditional probability tables)\n",
        "- stationary process: the CPT does not change over time\n",
        "- faster to answer queries\n",
        "\n",
        "Chain Configurations:\n",
        "- Causal Chain: X causes Y causes Z\n",
        "- Common Cause: Y causes X and Z\n",
        "- Common Effect: X and Y cause Z\n",
        "\n",
        "A path is active if each triple is active:\n",
        "- causal chain A $\\Rightarrow$ B $\\Rightarrow$ C where B is unobserved\n",
        "- common cause A $\\Leftarrow$ B $\\Rightarrow$ C where B is unobserved\n",
        "- common effect A $\\Rightarrow$ B $\\Leftarrow$ C where B or one of its \n",
        "descendents is observed\n",
        "\n",
        "X and Y are conditionally independent given evidence variables (Z) if:\n",
        "- X and Y are d-separated by Z\n",
        "- on all undirected paths from X to Y, all are inactive\n",
        "- all it takes to block a path is a single inactive segment\n",
        "\n",
        "D-Separation:\n",
        "- $X_i \\perp \\!\\!\\! \\perp X_j | \\{X_{k_1},...,X_{k_n} \\}$\n",
        "- check all undirected paths between $X_i$ and $X_j$, if all paths are inactive,\n",
        "then independence is guaranteed\n",
        "- given a Bayes Net structure, can run d-separation algorithm to build a \n",
        "complete list of conditional independences that are necessarily true of the\n",
        "form $X_i \\perp \\!\\!\\! \\perp X_j | \\{X_{k_1},...,X_{k_n} \\}$, this list\n",
        "determines the set of probability distributions that can be represented\n",
        "\n",
        "Inference: calculating some useful quantity from a joint probability \n",
        "distribution\n",
        "- evidence variables: $E_1...E_k = e_1...e_k$\n",
        "- query variable: $Q$\n",
        "- hidden variables: $H_1...H_r$\n",
        "- evidence, query, hidden variables form all variables: $X_1,X_2,...,X_n$\n",
        "- we want: $P(Q|e_1...e_k)$\n",
        "\n",
        "Variable Elimination:\n",
        "- advanced, still NP-hard, but usually much faster than inference by enumeration\n",
        "- interleave joining and marginalizing\n",
        "- inference by enumeration is slow because you join up the whole joint distribution\n",
        "before you sum out the hidden variables\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "outputId": "41719040-d22d-4c80-ff7a-83b43e3440d9"
      },
      "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": null,
      "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\nIndependence: two variables are independe if for each $x,y: P(x,y) = P(x)P(y)$\n- equivalent to: for each $x,y: P(x|y) = P(x)$\n- can be written as $X \\perp \\!\\!\\! \\perp Y$\n- independence is a simplifying modeling assumption\n- empirical joint distributions are at best close to independent\n\nConditional Independence:\n- X is conditionally independent of Y given Z: $X \\perp \\!\\!\\! \\perp Y | Z$ if\nand only if for all $x,y,z: P(x,y|z) = P(x|z)P(y|z)$ or, equivalently, if and\nonly if for all $x,y,z: P(x|z,y) = P(x|z)$\n\nBayes' Nets: a technique for describing complex joint distributions (models)\nusing simple, local distributions (conditional probabilities)\n- more properly called graphical models\n- we describe how variables locally interact\n- local interactions chain together to give global, indirect interactions\n\nGraphical Model Notation:\n- nodes: variables (with domains), can be assigned (observed) or unassigned\n(unobserved)\n- arcs: interactions, indicate direct influence between variables, formally \nencode conditional independence\n- only distributions whose variables are absolutely independent can be \nrepresented by a Bayes' net with no arcs\n\nAbsolute Independence: no interactions between variables\n\nBayes' Net Graph:\n- a set of nodes, one per variable X\n- a directed, acyclic graph\n- a conditional distribution for each node\n- Bayes' nets implicitly encode joint distributions as a product of local \nconditional distributions\n- just need the parents probability distributions to get the conditional\nprobability distribution\n- $P(x_1,x_2,...,x_n) = \\Pi _{i=1} ^n P(x_i|parents(X_i))$\n- assume $P(x_i|x_1...x_{i-1}) = \\Pi _{i=1} ^n P(x_i|parents(X_i))$\n- BNs need not actually be causal - end up with arrows that reflect correlation,\nnot causation\n- topology encodes conditional independence\n- topology may happen to encode causal structure\n- more than one Bayesian network can be used to represent the same joint\ndistribution\n\nSize of a Bayes' Net:\n- a joint distribution over N boolean variables: $2^N$\n- an N-node net if nodes have up to $k$ parents: $O(N*2^{k+1})$\n- BNs have huge space savings\n- easier to elicit local CPTs (conditional probability tables)\n- stationary process: the CPT does not change over time\n- faster to answer queries\n\nChain Configurations:\n- Causal Chain: X causes Y causes Z\n- Common Cause: Y causes X and Z\n- Common Effect: X and Y cause Z\n\nA path is active if each triple is active:\n- causal chain A $\\Rightarrow$ B $\\Rightarrow$ C where B is unobserved\n- common cause A $\\Leftarrow$ B $\\Rightarrow$ C where B is unobserved\n- common effect A $\\Rightarrow$ B $\\Leftarrow$ C where B or one of its \ndescendents is observed\n\nX and Y are conditionally independent given evidence variables (Z) if:\n- X and Y are d-separated by Z\n- on all undirected paths from X to Y, all are inactive\n- all it takes to block a path is a single inactive segment\n\nD-Separation:\n- $X_i \\perp \\!\\!\\! \\perp X_j | \\{X_{k_1},...,X_{k_n} \\}$\n- check all undirected paths between $X_i$ and $X_j$, if all paths are inactive,\nthen independence is guaranteed\n- given a Bayes Net structure, can run d-separation algorithm to build a \ncomplete list of conditional independences that are necessarily true of the\nform $X_i \\perp \\!\\!\\! \\perp X_j | \\{X_{k_1},...,X_{k_n} \\}$, this list\ndetermines the set of probability distributions that can be represented\n\nInference: calculating some useful quantity from a joint probability \ndistribution\n- evidence variables: $E_1...E_k = e_1...e_k$\n- query variable: $Q$\n- hidden variables: $H_1...H_r$\n- evidence, query, hidden variables form all variables: $X_1,X_2,...,X_n$\n- we want: $P(Q|e_1...e_k)$\n\nVariable Elimination:\n- advanced, still NP-hard, but usually much faster than inference by enumeration\n- interleave joining and marginalizing\n- inference by enumeration is slow because you join up the whole joint distribution\nbefore you sum out the hidden variables\n\n\n## Module 11 Definitions\n* **Concept** - definition\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",
        "Classification: given inputs x, predict labels y\n",
        "\n",
        "Model-Based Classification:\n",
        "- build a model (ex: Bayes' net) where both the label and features are random\n",
        "variables\n",
        "- instantiate any observed features\n",
        "- query for the distribution of the label conditioned on the features\n",
        "\n",
        "Naive Bayes: assume all features are independent effects of the label\n",
        "- models can incorporate a variety of features, but tend to do best in \n",
        "homogeneous cases\n",
        "- assumes features are conditionally independent of each other, given the class\n",
        "\n",
        "Naive Bayes for Digits:\n",
        "- one feature (variable) $F_{ij}$ for each grid position <i,j>\n",
        "- feature values are on / off based on whether intensity is more or less than\n",
        "0.5 in underlying image\n",
        "- each input maps to a feature vector\n",
        "\n",
        "General Naive Bayes:\n",
        "- $|Y|$ labels\n",
        "- $P(Y,F_1...F_n) = P(Y) \\Pi _i P(F_i|Y)$\n",
        "- $|Y||F|^n$ values\n",
        "- $n|F||Y|$ paramaters\n",
        "- we only have to specify how each feature depends on the class\n",
        "- total number of parameters is linear in number of features\n",
        "\n",
        "Inference for Naive Bayes:\n",
        "- compute posterior distribution over label variable $Y$\n",
        "- step 1: get joint probability of label and evidence for each label\n",
        "- step 2: sum to get probability of evidence\n",
        "- step 3: normalize by dividing step 1 by step 2\n",
        "\n",
        "Bag-of-Words Naive Bayes:\n",
        "- each position (word) is identically distributed\n",
        "- usually (in other cases), each variable gets its own conditional probability\n",
        "distribution $P(F|Y)$\n",
        "- in this case, all positions share the same conditional probability $P(W|Y)$\n",
        "- model is insensitive to word order or reordering\n",
        "- predicts label conditioned on feature variables\n",
        "\n",
        "Data: label instances\n",
        "- training set\n",
        "- held-out set\n",
        "- test set\n",
        "\n",
        "Features: attribute-value pairs which characterize each $x$\n",
        "\n",
        "Experimentation Cycle:\n",
        "- learn paramters (ex: model probabilities) on training set\n",
        "- tune hyperparameters on held-out set\n",
        "- compute accuracy of test set\n",
        "- never peek at the test set\n",
        "\n",
        "Evaluation Accuracy: fraction of instances predicted correctly\n",
        "\n",
        "Overfitting and Generalization:\n",
        "- want a classifier which does well on test data\n",
        "- overfitting: fitting the training data very closely, but not generalizing\n",
        "well\n",
        "- relative frequency parameters will overfit the training data\n",
        "- in general, can't give unseen events zero probability\n",
        "- we need to smooth or regularize the estimates to generalize better\n",
        "\n",
        "Parameter Estimation: estimating the distribution of a random variable\n",
        "- elicitation: ask a human\n",
        "- empirically: use training data - for each outcome x, look at the empirical\n",
        "rate of that value: $P_{ML}(x) = count(x) /$ total samples\n",
        "- the estimate that maximizes the likelihood of the data: \n",
        "$L(x, \\Theta) = \\Pi _i P_{\\Theta}(x_i)$\n",
        "\n",
        "Maximum Likelihood: relative frequencies are the maximum likelihood estimates\n",
        "- $\\Theta _{ML} = argmax _{\\Theta} P(X|\\Theta) = argmax _{\\Theta} \\Pi _i P_{\\Theta}(X_i)$\n",
        "- $P_{ML}(x) = count(x) /$ total samples\n",
        "\n",
        "Laplace Smoothing:\n",
        "- Laplace's estimate: pretend you saw every outcome once more than you actually\n",
        "did\n",
        "- Laplace's estimate (extended): pretend you saw every outcome $k$ extra times\n",
        "- $k$ is the strength of the prior\n",
        "- $P_{LAP,k}(x) = (c(x) + k)/(N + k|X|)\n",
        "\n",
        "Tuning:\n",
        "- Parameters: the probabilities $P(X|Y), P(Y)$\n",
        "- Hyperparameters: the amount / type of smoothing to do, $k$, alpha\n",
        "- learn parameters from training data\n",
        "- tune hyperparameters on different data\n",
        "- for each value of the hyperparameters, train and tset on the held-out data\n",
        "- choose the best value and do a final test on the test data\n",
        "\n",
        "Parametric Model:\n",
        "- has a fixed size on the number of parameters (this is not true for \n",
        "nonparametric models)\n",
        "\n",
        "Classifiers: let you easily add arbitrary features\n",
        "\n",
        "Baseline:\n",
        "- help determine how hard the task is\n",
        "- help know what a good accuracy is\n",
        "\n",
        "Weak Baseline: most frequent label classifier\n",
        "- gives all test instances whatever label was most common in the training set\n",
        "- accuracy might be very high if the problem is skewed\n",
        "\n",
        "Confience of a Probabilistic Classifier:\n",
        "- posterior over the top label\n",
        "- $confidence(x) = max_y 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",
        "\n",
        "Calibration:\n",
        "- weak calibration: higher confidences mean higher accuracy\n",
        "- strong calibration: confidence predicts accuracy rate\n",
        "\n",
        "Dynamic Bayes Model (DBN):\n",
        "- needs the transition model, prior distribution over the state variables, \n",
        "sensore model\n",
        "\n",
        "Summary:\n",
        "- Bayes rule lets us do diagnostic queries with causal probabilities\n",
        "- naive Bayes assumption takes all features to be independent given the class\n",
        "label\n",
        "- we can build classifiers out of a naive Bayes model using training data\n",
        "- smoothing estimates is important in real systems\n",
        "- classifier confidences are useful, when you can get them\n",
        "\n",
        "Linear Classifiers\n",
        "- inputs are feature values\n",
        "- each feature has a weight\n",
        "- sum is the activation\n",
        "- $activation_w(x) = \\Sigma _i w_i*f_i(x) = w*f(x)$\n",
        "- if the activation is positive, output +1\n",
        "- if the activation is negative, output -1\n",
        "\n",
        "Weights\n",
        "- binary case: compare features to a weight vector\n",
        "- learning: figure out the weight vector from examples\n",
        "\n",
        "Binary Decision Rule:\n",
        "- in the space of feature vectors: examples are points, any weight vector is\n",
        "a hyperplane, one side corresponds to Y=+1, other side corresponds to Y=-1\n",
        "\n",
        "Learning: Binary Perceptron\n",
        "- start with weights = 0\n",
        "- for each training instance: classify with current weights, $y = +1$ if \n",
        "$w*f(x) \\geq 0$, $y = -1$ if $w*f(x) < 0$\n",
        "- if correct (y = y*), no change\n",
        "- if wrong, adjust the weight vector by adding or subtracting \n",
        "the feature vector (subtract if y* is -1)\n",
        "- high bias value leads to more likely to output a 1\n",
        "- will not always fire if all weights are greater than or equal to 0\n",
        "\n",
        "Multiclass Decision Rule:\n",
        "- a weight vector for each class: $w_y$\n",
        "- score (activation) of a class y: $w_y*f(x)$\n",
        "- prediction highest score wins: $y = argmax_y w_y*f(x)$\n",
        "\n",
        "Learning: Multiclass Perceptron:\n",
        "- start with all weights = 0\n",
        "- pick up training examples one by one\n",
        "- predict with current weights: $y = argmax_y w_y*f(x)$\n",
        "- if correct, no change\n",
        "- if wrong: lower score of wrong answer, raise score of right answer: \n",
        "$w_y = w_y - f(x)$, $w_{y^*} = w_{y^*} + f(x)$\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\n",
        "(binary case)\n",
        "- Mistake Bound: the maximum number of mistakes (binary case) related to the \n",
        "margin or degree of separability (mistakes $< k/ \\delta ^2$)\n",
        "- perceptron converges to a minimum-error solution when the learning rate\n",
        "decreases as training time increases\n",
        "\n",
        "Problems with the Perceptron:\n",
        "- Noise: if the data isn't separable, weights might thrash\n",
        "- Averaging weight vectors over time can help (averaged perceptron)\n",
        "- Mediocre generalization: finds a barely separating solution\n",
        "- Overtraining: test / held-out accuracy usually rises, then falls, \n",
        "overtraining is a kind of overfitting\n",
        "\n",
        "Fixing the Perceptron:\n",
        "- adjust the weight update to mitigate these effects\n",
        "- MIRA*: choose an update size that fixes the current mistake, but minimizes\n",
        "the change to w\n",
        "- $min_w 1/2 \\Sigma _y ||w_y - w_y' ||^2$\n",
        "- $w_y = w_y' - \\tau f(x)$\n",
        "- $w_{y^*} = w_{y^*}' + \\tau f(x)$\n",
        "\n",
        "Maximum Step Size:\n",
        "- in practice, it's bad to make updates that are too large\n",
        "- you may not have enough features\n",
        "- solution: cap the maximum possible value of $\\tau$ with some constant C\n",
        "- corresponds to an optimization that assumes non-separable data\n",
        "- usually convergs faster than perceptron\n",
        "- usually better, especially on noisy data\n",
        "\n",
        "Support Vector Machines:\n",
        "- maximizing the margin: good according to intuition, theory, practice\n",
        "- only support vectors matterl other training examples are ignorable\n",
        "- support vector machines (SVMs) find the separator with max margin\n",
        "- SVMs are MIRA where you optimize over all examples at once\n",
        "\n",
        "Naive Bayes vs. Perceptrons / MIRA:\n",
        "- Naive Bayes: builds a model training data, gives prediction probabilities,\n",
        "strong assumptions about feature independence, one pass through data (counting)\n",
        "- Perceptrons / MIRA: makes less assumptions about data, mistake-driven \n",
        "learning, multiple passes through data (prediction), often more accurate\n",
        "\n",
        "Perceptrons for Decision Making:\n",
        "- a perceptron / the sigmoid neuron is a device that makes decisions by \n",
        "weighing up evidence\n",
        "- by varying weights and the threshold we get different models of decision\n",
        "making\n",
        "- think of the input as features representing something we want to classify\n",
        "- the feature values for inputs are fixed, but we can choose different weight\n",
        "vectors; depending on the weight vector we pick, we will get a different \n",
        "classifier\n",
        "- a complex network of perceptrons could make quite subtle decisions\n",
        "- first change: replace the weighted sum as a dot product: $w \\cdot x = \\Sigma _j w_jx_j$\n",
        "- second change: move the threshold to the other side of the inequality, and \n",
        "replace it by a bias, b = -threshold\n",
        "- output = 0 if $\\Sigma _j w_jx_j \\leq$ threshold, 1 if $\\Sigma _j w_jx_j >$ threshold\n",
        "\n",
        "Non-Linear Separators: the original feature space can always be mapped to \n",
        "some higher-dimensional feature space where the training set is separable\n",
        "\n",
        "Logical Functions:\n",
        "- networks of perceptrons to compute any logical function\n",
        "- we can build any computation up out of NAND gates\n",
        "- a single neural unit cannot be used to compute the XOR function\n",
        "\n",
        "Activation Functions: the output of a non-linear function $f$ applied by \n",
        "neuron units to $z = w \\cdot x+b$, which is a linear function of $x$\n",
        "- 3 commonly used non-linear functions used for $f$: sigmoid function, \n",
        "tanh function, rectified linear unit ReLU\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "outputId": "afb83124-aff8-4e72-d0c1-5a54c5510da6"
      },
      "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": null,
      "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\nClassification: given inputs x, predict labels y\n\nModel-Based Classification:\n- build a model (ex: Bayes' net) where both the label and features are random\nvariables\n- instantiate any observed features\n- query for the distribution of the label conditioned on the features\n\nNaive Bayes: assume all features are independent effects of the label\n- models can incorporate a variety of features, but tend to do best in \nhomogeneous cases\n\nNaive Bayes for Digits:\n- one feature (variable) $F_{ij}$ for each grid position <i,j>\n- feature values are on / off based on whether intensity is more or less than\n0.5 in underlying image\n- each input maps to a feature vector\n\nGeneral Naive Bayes:\n- $|Y|$ labels\n- $P(Y,F_1...F_n) = P(Y) \\Pi _i P(F_i|Y)$\n- $|Y||F|^n$ values\n- $n|F||Y|$ paramaters\n- we only have to specify how each feature depends on the class\n- total number of parameters is linear in number of features\n\nInference for Naive Bayes:\n- compute posterior distribution over label variable $Y$\n- step 1: get joint probability of label and evidence for each label\n- step 2: sum to get probability of evidence\n- step 3: normalize by dividing step 1 by step 2\n\nBag-of-Words Naive Bayes:\n- each position (word) is identically distributed\n- usually (in other cases), each variable gets its own conditional probability\ndistribution $P(F|Y)$\n- in this case, all positions share the same conditional probability $P(W|Y)$\n- model is insensitive to word order or reordering\n\nData: label instances\n- training set\n- held-out set\n- test set\n\nFeatures: attribute-value pairs which characterize each $x$\n\nExperimentation Cycle:\n- learn paramters (ex: model probabilities) on training set\n- tune hyperparameters on held-out set\n- compute accuracy of test set\n- never peek at the test set\n\nEvaluation Accuracy: fraction of instances predicted correctly\n\nOverfitting and Generalization:\n- want a classifier which does well on test data\n- overfitting: fitting the training data very closely, but not generalizing\nwell\n- relative frequency parameters will overfit the training data\n- in general, can't give unseen events zero probability\n- we need to smooth or regularize the estimates to generalize better\n\nParameter Estimation: estimating the distribution of a random variable\n- elicitation: ask a human\n- empirically: use training data - for each outcome x, look at the empirical\nrate of that value: $P_{ML}(x) = count(x) /$ total samples\n- the estimate that maximizes the likelihood of the data: \n$L(x, \\Theta) = \\Pi _i P_{\\Theta}(x_i)$\n\nMaximum Likelihood: relative frequencies are the maximum likelihood estimates\n- $\\Theta _{ML} = argmax _{\\Theta} P(X|\\Theta) = argmax _{\\Theta} \\Pi _i P_{\\Theta}(X_i)$\n- $P_{ML}(x) = count(x) /$ total samples\n\nLaplace Smoothing:\n- Laplace's estimate: pretend you saw every outcome once more than you actually\ndid\n- Laplace's estimate (extended): pretend you saw every outcome $k$ extra times\n- $k$ is the strength of the prior\n- $P_{LAP,k}(x) = (c(x) + k)/(N + k|X|)\n\nTuning:\n- Parameters: the probabilities $P(X|Y), P(Y)$\n- Hyperparameters: the amount / type of smoothing to do, $k$, alpha\n- learn parameters from training data\n- tune hyperparameters on different data\n- for each value of the hyperparameters, train and tset on the held-out data\n- choose the best value and do a final test on the test data\n\nClassifiers: let you easily add arbitrary features\n\nBaseline:\n- help determine how hard the task is\n- help know what a good accuracy is\n\nWeak Baseline: most frequent label classifier\n- gives all test instances whatever label was most common in the training set\n- accuracy might be very high if the problem is skewed\n\nConfience of a Probabilistic Classifier:\n- posterior over the top label\n- $confidence(x) = max_y 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\nCalibration:\n- weak calibration: higher confidences mean higher accuracy\n- strong calibration: confidence predicts accuracy rate\n\nDynamic Bayes Model (DBN):\n- needs the transition model, prior distribution over the state variables, \nsensore model\n\nSummary:\n- Bayes rule lets us do diagnostic queries with causal probabilities\n- naive Bayes assumption takes all features to be independent given the class\nlabel\n- we can build classifiers out of a naive Bayes model using training data\n- smoothing estimates is important in real systems\n- classifier confidences are useful, when you can get them\n\nLinear Classifiers\n- inputs are feature values\n- each feature has a weight\n- sum is the activation\n- $activation_w(x) = \\Sigma _i w_i*f_i(x) = w*f(x)$\n- if the activation is positive, output +1\n- if the activation is negative, output -1\n\nWeights\n- binary case: compare features to a weight vector\n- learning: figure out the weight vector from examples\n\nBinary Decision Rule:\n- in the space of feature vectors: examples are points, any weight vector is\na hyperplane, one side corresponds to Y=+1, other side corresponds to Y=-1\n\nLearning: Binary Perceptron\n- start with weights = 0\n- for each training instance: classify with current weights, $y = +1$ if \n$w*f(x) \\geq 0$, $y = -1$ if $w*f(x) < 0$\n- if correct (y = y*), no change\n- if wrong, adjust the weight vector by adding or subtracting \nthe feature vector (subtract if y* is -1)\n\nMulticlass Decision Rule:\n- a weight vector for each class: $w_y$\n- score (activation) of a class y: $w_y*f(x)$\n- prediction highest score wins: $y = argmax_y w_y*f(x)$\n\nLearning: Multiclass Perceptron:\n- start with all weights = 0\n- pick up training examples one by one\n- predict with current weights: $y = argmax_y w_y*f(x)$\n- if correct, no change\n- if wrong: lower score of wrong answer, raise score of right answer: \n$w_y = w_y - f(x)$, $w_{y^*} = w_{y^*} + f(x)$\n\nProperties 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\n(binary case)\n- Mistake Bound: the maximum number of mistakes (binary case) related to the \nmargin or degree of separability (mistakes $< k/ \\delta ^2$)\n\nProblems with the Perceptron:\n- Noise: if the data isn't separable, weights might thrash\n- Averaging weight vectors over time can help (averaged perceptron)\n- Mediocre generalization: finds a barely separating solution\n- Overtraining: test / held-out accuracy usually rises, then falls, \novertraining is a kind of overfitting\n\nFixing the Perceptron:\n- adjust the weight update to mitigate these effects\n- MIRA*: choose an update size that fixes the current mistake, but minimizes\nthe change to w\n- $min_w 1/2 \\Sigma _y ||w_y - w_y' ||^2$\n- $w_y = w_y' - \tau f(x)$\n- $w_{y^*} = w_{y^*}' + \tau f(x)$\n\nMaximum Step Size:\n- in practice, it's bad to make updates that are too large\n- you may not have enough features\n- solution: cap the maximum possible value of $\tau$ with some constant C\n- corresponds to an optimization that assumes non-separable data\n- usually convergs faster than perceptron\n- usually better, especially on noisy data\n\nSupport Vector Machines:\n- maximizing the margin: good according to intuition, theory, practice\n- only support vectors matterl other training examples are ignorable\n- support vector machines (SVMs) find the separator with max margin\n- SVMs are MIRA where you optimize over all examples at once\n\nNaive Bayes vs. Perceptrons / MIRA:\n- Naive Bayes: builds a model training data, gives prediction probabilities,\nstrong assumptions about feature independence, one pass through data (counting)\n- Perceptrons / MIRA: makes less assumptions about data, mistake-driven \nlearning, multiple passes through data (prediction), often more accurate\n\nPerceptrons for Decision Making:\n- a perceptron / the sigmoid neuron is a device that makes decisions by \nweighing up evidence\n- by varying weights and the threshold we get different models of decision\nmaking\n- think of the input as features representing something we want to classify\n- the feature values for inputs are fixed, but we can choose different weight\nvectors; depending on the weight vector we pick, we will get a different \nclassifier\n- a complex network of perceptrons could make quite subtle decisions\n- first change: replace the weighted sum as a dot product: $w \\cdot x = \\Sigma _j w_jx_j$\n- second change: move the threshold to the other side of the inequality, and \nreplace it by a bias, b = -threshold\n- output = 0 if $\\Sigma _j w_jx_j \\leq$ threshold, 1 if $\\Sigma _j w_jx_j >$ threshold\n\nNon-Linear Separators: the original feature space can always be mapped to \nsome higher-dimensional feature space where the training set is separable\n\nLogical Functions:\n- networks of perceptrons to compute any logical function\n- we can build any computation up out of NAND gates\n- a single neural unit cannot be used to compute the XOR function\n\nActivation Functions: the output of a non-linear function $f$ applied by \nneuron units to $z = w \\cdot x+b$, which is a linear function of $x$\n- 3 commonly used non-linear functions used for $f$: sigmoid function, \ntanh function, rectified linear unit ReLU\n\n\n## Module 12 Definitions\n* **Concept** - definition\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",
        "Classifier Components: machine learning classifiers require a training \n",
        "corpus of $M$ observations input/output pairs $(x^{(i)},y^{(i)})$\n",
        "- feature representation of the input: for each input oobservation $x^{(i)}$,\n",
        "this will be a vector of features [$x_1,x_2,...,x_n$]\n",
        "- classification function: computes the estimated class $\\hat{y}$ via $p(y|x)$\n",
        "- objective function: for learning, usually involving minimizing error on\n",
        "training examples\n",
        "- an algorithm for optimizing the objective function\n",
        "\n",
        "Sentiment Classifier:\n",
        "- input observation $x$ represented by a vector of features $[x_1,x_2,...,x_n]$\n",
        "- classifier output $y$ can be 1 (positive sentiment) or 0 (negative sentiment)\n",
        "- want to estimate $P(y=1|x)$, yes if greater than 0.5, no otherwise (we call\n",
        "0.5 the decision boundary)\n",
        "- logistic regression solves this task by learning, from a training set, a \n",
        "vector of weights and a bias term: $z = w \\cdot x + b$\n",
        "\n",
        "Learning in Logistic Regression:\n",
        "- get the weights and bias of the mdoel via learning\n",
        "- requires an objective function or loss function that tells distance between\n",
        "the system output and the gold output; we will use cross-entropy loss\n",
        "- requires an algorithm for optimizing the objective function; we will\n",
        "use stochastic gradient descent to minimize the loss function\n",
        "\n",
        "Loss Function: determines for some observation $x$ how close the classifier\n",
        "output is to the correct output\n",
        "- $L(\\hat{y},y)$ = how much $\\hat{y}$ differs from the true $y$\n",
        "- Mean Squared Error: $L_{MSE}(\\hat{y},y) = 1/2(\\hat{y}-y)^2$\n",
        "- Cross Entropy Loss: negative log likelihood loss; the resulting loss function\n",
        "of choosing parameters $w,b$ that maximize the log probabilities of the true \n",
        "labels in the training data; prefers (maximizes) the correct class labels of the training\n",
        "example to be more likely; want loss to be smaller if the model's estimate\n",
        "is close to correct, and bigger if it is confused\n",
        "\n",
        "Gradient Descent: finds a minimum of a function by figuring out in which\n",
        "direction (in the space of the parameters $\\Theta$) the function's slope\n",
        "is rising the most steeply, and moving in the opposite direction\n",
        "- used to find good settings for our weights and bias by minimizing the loss\n",
        "function\n",
        "- for logistic regression, this loss function is convex\n",
        "- convex function has one minimum, so no local minima to get stuck in\n",
        "- gradient descent starting from any point is guaranteed to find the \n",
        "minimum\n",
        "- should move at the value of the slope weighted by a learning rate $\\eta$\n",
        "- a higher / faster learning rate means we should move $w$ more on each step\n",
        "\n",
        "The Gradient:\n",
        "- the difference between the true $y$ and our estimate for $x$, multiplied by\n",
        "the corresponding input value $x_j$\n",
        "- the loss for a batch of data or an entire dataset is the average loss\n",
        "over the $m$ examples\n",
        "- the gradient for multiple data points is the sum of the individual gradients\n",
        "\n",
        "Stochastic Gradient Descent: chooses a single random example at a time and \n",
        "updates its weights on that example\n",
        "- as a result the updates can fluctuate\n",
        "\n",
        "Batch Training: computes the gradient over the entire dataset\n",
        "- alternate to stochastic gradient descent\n",
        "- gives a better estimate of which direction to move the weights\n",
        "- takes longer to compute\n",
        "\n",
        "Mini-Batch Training: train on a small batch\n",
        "- compromise of batch traning and stochastic gradient descent\n",
        "- batch size can be 512 or 1024 so that all examples in the mini-batch can\n",
        "be processed in parallel\n",
        "- loss is then accumulated\n",
        "\n",
        "Overfitting:\n",
        "- a problem with many machine learning models\n",
        "- results in poor generalization and poor performance on unseen test set\n",
        "\n",
        "Regularization: a way to penalize large weights\n",
        "- a regularization term is added to the loss function\n",
        "- in logistic regression, if a feature only occurs in one class then it will \n",
        "get a high weight\n",
        "\n",
        "Multinomial Logistic Regression:\n",
        "- when we want more than two classes (ex: adding neutral to sentiment \n",
        "classification)\n",
        "- want to know the probability of $y$ for each class $c \\in C$, $p(y = c|x)$\n",
        "- use a generalization of the sigmoid function called the softmax function to\n",
        "get a proper probability\n",
        "\n",
        "Softmax Function:\n",
        "- takes in an input vector $z=[z_1,z_2,...,z_k]$\n",
        "- outputs a vector of values normalized into probabilities\n",
        "- softmax($z$) = $[e^{z_1}/ \\Sigma _{i=1}^k e^{z_i}, ... , e^{z_k}/ \\Sigma _{i=1}^k e^{z_i}]$\n",
        "\n",
        "Neural Networks:\n",
        "- built of single computational units\n",
        "- a unit takes a set of real valued numbers as input, performs some computation\n",
        "- gains power from stacking of layers\n",
        "- used non-linear activation functions in multi-layer neural network\n",
        "\n",
        "Perceptron -> Logistic Regression:\n",
        "- like the perceptron, logistic regression uses a vector of weights and a bias\n",
        "term\n",
        "- $z = w \\cdot x + b$\n",
        "- instead of outputting z directly, logistic regression transforms it with the\n",
        "sigmoid function $\\sigma (z)$\n",
        "\n",
        "Linear Functions:\n",
        "- when using the perceptron learning rule, the weights are updated when the\n",
        "actual output does not match the hypothesis output\n",
        "\n",
        "Smoothness:\n",
        "- smoothness of $\\sigma$ means that small changes in the weights $w_j$ and in\n",
        "the bias $b$ will produce a small change in the output from the neuron\n",
        "- $\\Delta$output is a linear function of the changes $\\Delta w_j$ and $\\Delta b$\n",
        "- makes it easy to choose small changes in the weights and biases to achieve\n",
        "any desired small change in the output\n",
        "\n",
        "Feed-Forward Neural Network:\n",
        "- simplest kind of neural network\n",
        "- multilayer network, all units are usually fully-connected, and no cycles\n",
        "- outputs from each layer are passed to units in the next higher layer, and\n",
        "no outputs are passed back to lower layers\n",
        "- represent the parameters for the entire hidden layer by combining the weight\n",
        "vector $w_i$ and bias $b_i$ for each unit $i$ into a single weight matrix $W$\n",
        "and a single bias vector $b$ for the whole layer\n",
        "- hidden layer computation: multiply weight matrix by the input vector $x$,\n",
        "adding the bias vector $b$, and applying the activation function $g$ (such\n",
        "as Sigmoid); the output of the hidden layer is $h = \\sigma (Wx+b)$\n",
        "- ouput layer has a weight matrix $U$, output is $z = Uh$\n",
        "- feedforward network has a single hidden layer, which takes an input vector\n",
        "$x$, outputs a probability distribution $y$, and is parameterized by weight\n",
        "matrices $W$ and $U$ and a bias vector $b$\n",
        "- $y = softmax(z)$\n",
        "- softmax normalizes the output and turns it into a probability distribution\n",
        "\n",
        "Training Neural Nets:\n",
        "- needs a loss function (cross-entropy loss)\n",
        "- needs an optimization algorithm (gradient descent, to perform optimization)\n",
        "- needs a way of computing the gradient of the loss function (error propagation)\n",
        "\n",
        "Computation Graph: represents the process of computing a mathematical \n",
        "expression\n",
        "- computation is broken down into separate operations\n",
        "- each operation is a node in a graph\n",
        "- backpropagation was invented for neural nets, and is related to a general\n",
        "procedure called backward differentiation, which depends on the notion of\n",
        "computation graphs\n",
        "- backward pass is used to compute the derivates that we'll need for the weight\n",
        "update\n",
        "- importance of the computation graph comes from the backward pass\n",
        "- use error back propagation to compute the gradient of the loss function and \n",
        "correctly update all layers in the neural network\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "outputId": "285cc951-da76-4975-d11e-ea70ffc3c9f9"
      },
      "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": null,
      "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\nClassifier Components: machine learning classifiers require a training \ncorpus of $M$ observations input/output pairs $(x^{(i)},y^{(i)})$\n- feature representation of the input: for each input oobservation $x^{(i)}$,\nthis will be a vector of features [$x_1,x_2,...,x_n$]\n- classification function: computes the estimated class $\\hat{y}$ via $p(y|x)$\n- objective function: for learning, usually involving minimizing error on\ntraining examples\n- an algorithm for optimizing the objective function\n\nSentiment Classifier:\n- input observation $x$ represented by a vector of features $[x_1,x_2,...,x_n]$\n- classifier output $y$ can be 1 (positive sentiment) or 0 (negative sentiment)\n- want to estimate $P(y=1|x)$, yes if greater than 0.5, no otherwise (we call\n0.5 the decision boundary)\n- logistic regression solves this task by learning, from a training set, a \nvector of weights and a bias term: $z = w \\cdot x + b$\n\nLearning in Logistic Regression:\n- get the weights and bias of the mdoel via learning\n- requires an objective function or loss function that tells distance between\nthe system output and the gold output; we will use cross-entropy loss\n- requires an algorithm for optimizing the objective function; we will\nuse stochastic gradient descent to minimize the loss function\n\nLoss Function: determines for some observation $x$ how close the classifier\noutput is to the correct output\n- $L(\\hat{y},y)$ = how much $\\hat{y}$ differs from the true $y$\n- Mean Squared Error: $L_{MSE}(\\hat{y},y) = 1/2(\\hat{y}-y)^2$\n- Cross Entropy Loss: negative log likelihood loss; the resulting loss function\nof choosing parameters $w,b$ that maximize the log probabilities of the true \nlabels in the training data; prefers (maximizes) the correct class labels of the training\nexample to be more likely; want loss to be smaller if the model's estimate\nis close to correct, and bigger if it is confused\n\nGradient Descent: finds a minimum of a function by figuring out in which\ndirection (in the space of the parameters $\\Theta$) the function's slope\nis rising the most steeply, and moving in the opposite direction\n- used to find good settings for our weights and bias by minimizing the loss\nfunction\n- for logistic regression, this loss function is convex\n- convex function has one minimum, so no local minima to get stuck in\n- gradient descent starting from any point is guaranteed to find the \nminimum\n- should move at the value of the slope weighted by a learning rate $\\eta$\n- a higher / faster learning rate means we should move $w$ more on each step\n\nThe Gradient:\n- the difference between the true $y$ and our estimate for $x$, multiplied by\nthe corresponding input value $x_j$\n- the loss for a batch of data or an entire dataset is the average loss\nover the $m$ examples\n- the gradient for multiple data points is the sum of the individual gradients\n\nStochastic Gradient Descent: chooses a single random example at a time and \nupdates its weights on that example\n- as a result the updates can fluctuate\n\nBatch Training: computes the gradient over the entire dataset\n- alternate to stochastic gradient descent\n- gives a better estimate of which direction to move the weights\n- takes longer to compute\n\nMini-Batch Training: train on a small batch\n- compromise of batch traning and stochastic gradient descent\n- batch size can be 512 or 1024 so that all examples in the mini-batch can\nbe processed in parallel\n- loss is then accumulated\n\nOverfitting:\n- a problem with many machine learning models\n- results in poor generalization and poor performance on unseen test set\n\nRegularization: a way to penalize large weights\n- a regularization term is added to the loss function\n- in logistic regression, if a feature only occurs in one class then it will \nget a high weight\n\nMultinomial Logistic Regression:\n- when we want more than two classes (ex: adding neutral to sentiment \nclassification)\n- want to know the probability of $y$ for each class $c \\in C$, $p(y = c|x)$\n- use a generalization of the sigmoid function called the softmax function to\nget a proper probability\n\nSoftmax Function:\n- takes in an input vector $z=[z_1,z_2,...,z_k]$\n- outputs a vector of values normalized into probabilities\n- softmax($z$) = $[e^{z_1}/ \\Sigma _{i=1}^k e^{z_i}, ... , e^{z_k}/ \\Sigma _{i=1}^k e^{z_i}]$\n\nNeural Networks:\n- built of single computational units\n- a unit takes a set of real valued numbers as input, performs some computation\n\nPerceptron -> Logistic Regression:\n- like the perceptron, logistic regression uses a vector of weights and a bias\nterm\n- $z = w \\cdot x + b$\n- instead of outputting z directly, logistic regression transforms it with the\nsigmoid function $\\sigma (z)$\n\nSmoothness:\n- smoothness of $\\sigma$ means that small changes in the weights $w_j$ and in\nthe bias $b$ will produce a small change in the output from the neuron\n- $\\Delta$output is a linear function of the changes $\\Delta w_j$ and $\\Delta b$\n- makes it easy to choose small changes in the weights and biases to achieve\nany desired small change in the output\n\nFeed-Forward Neural Network:\n- simplest kind of neural network\n- multilayer network, all units are usually fully-connected, and no cycles\n- outputs from each layer are passed to units in the next higher layer, and\nno outputs are passed back to lower layers\n- represent the parameters for the entire hidden layer by combining the weight\nvector $w_i$ and bias $b_i$ for each unit $i$ into a single weight matrix $W$\nand a single bias vector $b$ for the whole layer\n- hidden layer computation: multiply weight matrix by the input vector $x$,\nadding the bias vector $b$, and applying the activation function $g$ (such\nas Sigmoid); the output of the hidden layer is $h = \\sigma (Wx+b)$\n- ouput layer has a weight matrix $U$, output is $z = Uh$\n- feedforward network has a single hidden layer, which takes an input vector\n$x$, outputs a probability distribution $y$, and is parameterized by weight\nmatrices $W$ and $U$ and a bias vector $b$\n- $y = softmax(z)$\n- softmax normalizes the output and turns it into a probability distribution\n\nTraining Neural Nets:\n- needs a loss function (cross-entropy loss)\n- needs an optimization algorithm (gradient descent, to perform optimization)\n- needs a way of computing the gradient of the loss function (error propagation)\n\nComputation Graph: represents the process of computing a mathematical \nexpression\n- computation is broken down into separate operations\n- each operation is a node in a graph\n- backpropagation was invented for neural nets, and is related to a general\nprocedure called backward differentiation, which depends on the notion of\ncomputation graphs\n- backward pass is used to compute the derivates that we'll need for the weight\nupdate\n- importance of the computation graph comes from the backward pass\n- use error back propagation to compute the gradient of the loss function\n\n\n## Module 13 Definitions\n* **Concept** - definition\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",
        "Distributional Word Similarity: two words are similar if they have similar\n",
        "word contexts\n",
        "\n",
        "Context Windows: words within +/- 2 words in the same sentence, in the same\n",
        "document give context to the meaning of the word\n",
        "- raw word frequency is not a great measure of association between words,\n",
        "skewed with \"the\" and \"of\"\n",
        "- instead of using raw counts, common to transform vectors using TF-IDF\n",
        "or PPMI\n",
        "\n",
        "TF-IDF: term frequency * inverse document frequency\n",
        "- term frequency: how often a word occurred in a document\n",
        "- inverse document frequency: 1 over the number of documents that it \n",
        "occurred in\n",
        "- in term-document matrix, if two documents have similar words, the column\n",
        "vectors would be similar as well\n",
        "- in term-document matrix, a cell represents how often a word occurs in a \n",
        "document\n",
        "\n",
        "Language Modeling:\n",
        "- goal: learn a function that returns the joint probability\n",
        "- use chain rule to get conditional probability of the next word in the\n",
        "sequence given all of the previous words\n",
        "- use tables to look up the probability of seeing a word given a history\n",
        "- when we have new (unseen) combination of n words: back off, smoothing / \n",
        "interpolation - basically stitching together short sequences of observed\n",
        "words\n",
        "\n",
        "N-Gram Language Models:\n",
        "- Markov assumption is it makes it possible to estimate the probabilities from\n",
        "data\n",
        "- typically evaluated by perplexity on a test set\n",
        "\n",
        "Neural Language Models:\n",
        "- advantages over n-gram LMs:\n",
        "- they don't need smoothing\n",
        "- can handle much longer histories\n",
        "- can generalize over contexts of similar words\n",
        "- neural LMs tend to have much higher predictive accuracy than n-gram LMs\n",
        "- disadvantage: slower to train than traditional n-gram LMs\n",
        "\n",
        "Neural LMs:\n",
        "- associate each word in the vocabulary with a vector representation, \n",
        "thereby creating a notion of similarity between words\n",
        "- express the joint probability function of a word sequence in terms of \n",
        "the word vectors for the words in that sequence\n",
        "- simultaneously learn the word vectors and the parameters of the \n",
        "function\n",
        "- the word vectors are low-dimensional (d=30 to d=100) dense vectors\n",
        "- probability function is expressed as the product of conditional \n",
        "probabilities of the next word given the previous word, using a multi-layer,\n",
        "feed forward neural network\n",
        "- input: k-gram of words $w_{1:k}$\n",
        "- output: probability distribution over the next word\n",
        "- the $k$ context words are treated as a word window, each word is \n",
        "associated with an embedding vector\n",
        "\n",
        "Advantages of NN LMs:\n",
        "- better results\n",
        "- larger N\n",
        "- generalize across contexts\n",
        "- a by-product of training are word embeddings\n",
        "\n",
        "Neural Probabilistic LM:\n",
        "- use a vector space model where the words are vectors with real values,\n",
        "$R^m$, $m=30,60,100$, this gives a way to compute words similarity\n",
        "- define a function that returns a joint probability of words in a \n",
        "sequence based on a sequence of these vectors\n",
        "- simultaneously learn the word representations and the probability\n",
        "function from data\n",
        "\n",
        "Word2Vec:\n",
        "- learn embeddings as part of the process of word prediction\n",
        "- train a classifier to predict neighboring words\n",
        "- inspired by neural net language models\n",
        "- learn dense embeddings for the words in the training corpus\n",
        "- fast, easy to train (much faster than SVD)\n",
        "\n",
        "Embeddings: vector models of meaning\n",
        "- capture relational meanings\n",
        "- more fine-grained than just a string or index\n",
        "- especially good at modeling similarity / analogy\n",
        "- can use sparse models (tf-idf) or dense models (word2vec, GLoVE)\n",
        "\n",
        "Sparse Vectors: most elements are zero, usually long\n",
        "- also called locally structured\n",
        "- the structure grows linearly in complexity (rather than exponentially)\n",
        "\n",
        "Dense Vectors: most elements are non-zero, usually short\n",
        "- short vectors are easier to use as features in machine learning (fewer\n",
        "weights to tune)\n",
        "- dense vectors may generalize better than storing explicit counts\n",
        "- may do better at capturing synonyms\n",
        "- in practice, work better\n",
        "\n",
        "Skip-Gram Algorithm:\n",
        "- treat target word and a neighboring context word as positive examples\n",
        "- randomly sample other words int he lexicon to get negative samples\n",
        "- use logistic regression to train a classifier to distinguish\n",
        "those two cases\n",
        "- use the weights as the embeddings\n",
        "- returns the probability that the context is a real context word\n",
        "- assume all context words are independent\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ca7034fd-3cd0-4eac-dbf4-1bc256466cd9"
      },
      "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\", module13_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": null,
      "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\nClassifier Components: machine learning classifiers require a training \ncorpus of $M$ observations input/output pairs $(x^{(i)},y^{(i)})$\n- feature representation of the input: for each input oobservation $x^{(i)}$,\nthis will be a vector of features [$x_1,x_2,...,x_n$]\n- classification function: computes the estimated class $\\hat{y}$ via $p(y|x)$\n- objective function: for learning, usually involving minimizing error on\ntraining examples\n- an algorithm for optimizing the objective function\n\nSentiment Classifier:\n- input observation $x$ represented by a vector of features $[x_1,x_2,...,x_n]$\n- classifier output $y$ can be 1 (positive sentiment) or 0 (negative sentiment)\n- want to estimate $P(y=1|x)$, yes if greater than 0.5, no otherwise (we call\n0.5 the decision boundary)\n- logistic regression solves this task by learning, from a training set, a \nvector of weights and a bias term: $z = w \\cdot x + b$\n\nLearning in Logistic Regression:\n- get the weights and bias of the mdoel via learning\n- requires an objective function or loss function that tells distance between\nthe system output and the gold output; we will use cross-entropy loss\n- requires an algorithm for optimizing the objective function; we will\nuse stochastic gradient descent to minimize the loss function\n\nLoss Function: determines for some observation $x$ how close the classifier\noutput is to the correct output\n- $L(\\hat{y},y)$ = how much $\\hat{y}$ differs from the true $y$\n- Mean Squared Error: $L_{MSE}(\\hat{y},y) = 1/2(\\hat{y}-y)^2$\n- Cross Entropy Loss: negative log likelihood loss; the resulting loss function\nof choosing parameters $w,b$ that maximize the log probabilities of the true \nlabels in the training data; prefers (maximizes) the correct class labels of the training\nexample to be more likely; want loss to be smaller if the model's estimate\nis close to correct, and bigger if it is confused\n\nGradient Descent: finds a minimum of a function by figuring out in which\ndirection (in the space of the parameters $\\Theta$) the function's slope\nis rising the most steeply, and moving in the opposite direction\n- used to find good settings for our weights and bias by minimizing the loss\nfunction\n- for logistic regression, this loss function is convex\n- convex function has one minimum, so no local minima to get stuck in\n- gradient descent starting from any point is guaranteed to find the \nminimum\n- should move at the value of the slope weighted by a learning rate $\\eta$\n- a higher / faster learning rate means we should move $w$ more on each step\n\nThe Gradient:\n- the difference between the true $y$ and our estimate for $x$, multiplied by\nthe corresponding input value $x_j$\n- the loss for a batch of data or an entire dataset is the average loss\nover the $m$ examples\n- the gradient for multiple data points is the sum of the individual gradients\n\nStochastic Gradient Descent: chooses a single random example at a time and \nupdates its weights on that example\n- as a result the updates can fluctuate\n\nBatch Training: computes the gradient over the entire dataset\n- alternate to stochastic gradient descent\n- gives a better estimate of which direction to move the weights\n- takes longer to compute\n\nMini-Batch Training: train on a small batch\n- compromise of batch traning and stochastic gradient descent\n- batch size can be 512 or 1024 so that all examples in the mini-batch can\nbe processed in parallel\n- loss is then accumulated\n\nOverfitting:\n- a problem with many machine learning models\n- results in poor generalization and poor performance on unseen test set\n\nRegularization: a way to penalize large weights\n- a regularization term is added to the loss function\n- in logistic regression, if a feature only occurs in one class then it will \nget a high weight\n\nMultinomial Logistic Regression:\n- when we want more than two classes (ex: adding neutral to sentiment \nclassification)\n- want to know the probability of $y$ for each class $c \\in C$, $p(y = c|x)$\n- use a generalization of the sigmoid function called the softmax function to\nget a proper probability\n\nSoftmax Function:\n- takes in an input vector $z=[z_1,z_2,...,z_k]$\n- outputs a vector of values normalized into probabilities\n- softmax($z$) = $[e^{z_1}/ \\Sigma _{i=1}^k e^{z_i}, ... , e^{z_k}/ \\Sigma _{i=1}^k e^{z_i}]$\n\nNeural Networks:\n- built of single computational units\n- a unit takes a set of real valued numbers as input, performs some computation\n\nPerceptron -> Logistic Regression:\n- like the perceptron, logistic regression uses a vector of weights and a bias\nterm\n- $z = w \\cdot x + b$\n- instead of outputting z directly, logistic regression transforms it with the\nsigmoid function $\\sigma (z)$\n\nSmoothness:\n- smoothness of $\\sigma$ means that small changes in the weights $w_j$ and in\nthe bias $b$ will produce a small change in the output from the neuron\n- $\\Delta$output is a linear function of the changes $\\Delta w_j$ and $\\Delta b$\n- makes it easy to choose small changes in the weights and biases to achieve\nany desired small change in the output\n\nFeed-Forward Neural Network:\n- simplest kind of neural network\n- multilayer network, all units are usually fully-connected, and no cycles\n- outputs from each layer are passed to units in the next higher layer, and\nno outputs are passed back to lower layers\n- represent the parameters for the entire hidden layer by combining the weight\nvector $w_i$ and bias $b_i$ for each unit $i$ into a single weight matrix $W$\nand a single bias vector $b$ for the whole layer\n- hidden layer computation: multiply weight matrix by the input vector $x$,\nadding the bias vector $b$, and applying the activation function $g$ (such\nas Sigmoid); the output of the hidden layer is $h = \\sigma (Wx+b)$\n- ouput layer has a weight matrix $U$, output is $z = Uh$\n- feedforward network has a single hidden layer, which takes an input vector\n$x$, outputs a probability distribution $y$, and is parameterized by weight\nmatrices $W$ and $U$ and a bias vector $b$\n- $y = softmax(z)$\n- softmax normalizes the output and turns it into a probability distribution\n\nTraining Neural Nets:\n- needs a loss function (cross-entropy loss)\n- needs an optimization algorithm (gradient descent, to perform optimization)\n- needs a way of computing the gradient of the loss function (error propagation)\n\nComputation Graph: represents the process of computing a mathematical \nexpression\n- computation is broken down into separate operations\n- each operation is a node in a graph\n- backpropagation was invented for neural nets, and is related to a general\nprocedure called backward differentiation, which depends on the notion of\ncomputation graphs\n- backward pass is used to compute the derivates that we'll need for the weight\nupdate\n- importance of the computation graph comes from the backward pass\n- use error back propagation to compute the gradient of the loss function\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/"
        },
        "id": "T3cm1WV542_a",
        "outputId": "2b193203-96a4-42e4-c65b-e5d8c14d5487"
      },
      "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": null,
      "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 Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \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\nStochastic Transition Model: object only moves some of the time when an action is \nselected, often written as T(s, a, s'), or as the probability p(s'|s,a), meaning\nthe probability of arriving in state s' given that we are in state s and we \nselected action a\n- Transitions are Markovian: the probability of arriving in s' only depends on s\nand not the history of earlier states\n\nUtility Function: also a reward function\n- rewards can be positive or negative but are bounded by some maximum value\n- since the decision process is sequential, we must specify the utility function\non a sequence of states and actions\n- the agent can receive a reward at each time step (instead of just goal states)\nbased on its transition from s to s' via action a\n- defined by a reward function R(s,a,s')\n- rewards are additive\n- reward of +1 for getting to goal and -1 all other time when trying to escape\nthe maze with discount of 1\n- utility function estimate does not need to be completely accurate to get\nan optimal policy\n\nMarkov Property: given the present state, the future and past are independent\n\nMarkov Decision Process (MDP): a sequential decision problem for a fully \nobservable environment with a stochastic transition model that has additive\nrewards\n- non-deterministic search problems\n- can solve them via expectimax search\n\nExpectimax Node: outcome is uncertain\n- in expectimax search we calculate their expected utilities\n\nTo find a solution to an MDP, need to define:\n- set of states s $\\in$ S\n- set of actions a $\\in$ A\n- transition function T(s,a,s'), probability that executing action a in s will \nlead to s'P(s'|s,a), the probability is called the model\n- a reward function R(s,a,s'), sometimes just R(s) or R(s')\n- an initial state $s_0$\n- optionally, one or more terminal states\n\nThe solution to an MDP is a policy.\n- a policy maps from a state onto the action to take if the agent is in that\nstate\n- $\\pi$(s) = a, policy $\\pi$ tells the agent what action to take at state s\n- because of the non-determinism in MDPs we cannot simply give a sequence of\nactions\n- in search problems a solution was a plan: a sequence of actions that \ncorresponded to the shortest path from the start to a goal\n\nExpected Utility: computed for all possible paths generated by a policy\n- even if the same policy is executed multiple times by the agent, this may \nlead to different sequences of states and actions (environment history), and \nthus a different score under the reward function\n- policy is optimal if it maximizes the expected utility of the actions taken\nby the agent\n\nPerformance: the sum of the rewards for the transitions an agent takes in an MDP\n- U([$s_0,a_0,s_1,a_1,...,s_n$]) = R($s_0,a_0,s_1$) + R($s_1,a_1,s_2$) + ... + \nR($s_{n-1},a_{n-1},s_n$)\n- U: utility function on an environment history\n\nDiscounting: values of rewards decay over time\n- each time we descend a level, we multiply in the discount once\n- helps algorithm converge\n- additive utility: U($r_0,r_1,r_2...$) = $r_0 + r_1 + r_2 + ...$\n- discounted utility: U($r_0,r_1,r_2...$) = $r_0 + \\gamma r_1 + (\\gamma)^2 r_2 + ...$\n- use $0 < \\gamma < 1$\n- smaller $\\gamma$ means smaller horizon - shorter term focus\n- absorbing state: guarantee that for every policy a terminal state will eventually\nbe reached\n\nOptimal Quantities:\n- V*(s): expected utility starting in s and acting optimally\n- Q*(s,a): expected utility starting out having taken action a from state s and\nacting optimally thereafter\n- $\\pi$*(s): optimal action from state s\n- actions are easier to select from q-values than values\n\nBellman Equations: definition of optimal utility via expectimax recurrence gives\na simple one-step lookahead relationship amongst optimal utility values\n- $V^*(s)$ = max$_aQ^*(s,a)$\n- $Q^*(s,a)$ = $\\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma V^*(s')]$\n\nTime-Limited Values:\n- define $V_k(s)$ to be the optimal value of s if the game ends in k more time\nsteps\n- what a depth-k expectimax would give from s\n\nValue Iteration:\n- start with $V_0(s)$ = 0\n- run $V_{k+1}(s)$ = max$_a \\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma V_k(s')]$\n- repeat until convergence\n- complexity of each iteration: $O(S^2A)$\n- will converge to unique optimal values\n- policy often converges long before the values\n- slow and the max at each state rarely changes\n- contraction: part of the proof of convergence for the value iteration algorithm\n\nFixed Policies:\n- can fix some policy $\\pi (s)$ to make the tree simpler\n- usually non-optimal\n\nPolicy Iteration:\n- calculate utilities for some fixed policy (not optimal utilities) until \nconvergence\n- update policy using one-step lookahead with resulting converged (but not\noptimal) utilities as future values\n- repeat steps until policy converges\n- this is optimal and can converge much faster than value iteration\n- $V_{k+1}^{\\pi _i}(s)$ = $\\sum _{s'}T(s,\\pi _i(s),s')[R(s,\\pi _i(s),s') + \n\\gamma V_k^{\\pi _i}(s')]$\n- $\\pi _{i+1} (s) = $max$_a$\\sum _{s'}T(s,a,s')[R(s,a,s') + \n\\gamma V^{\\pi _i}(s')]$\n- a new policy will be better (or we're done)\n\nSummary:\n- compute optimal values: use value iteration or policy iteration\n- compute values for a particular policy: use policy evaluation\n- turn your values into a policy: use policy extraction (one-step lookahead)\n\nPrinciple of Maximum Expected Utility: a rational agent should choose the action that maximizes its expected utility\ngiven its knowledge\n\nInsensitivity to Monotonic Transformations: for worst-case minimax reasoning, \nterminal function scale doesn't matter, we just want better states to have \nhigher evaluations (get the ordering right)\n\nIndifference: $A \\succ B$ or $A \\sim B$\n\nAxioms of Rationality (Rational Preferences):\n- Orderability: $(A \\succ B) \\or (B \\succ A) \\or ($A \\sim B$)$\n- Transitivity: $(A \\succ B) \u0007nd (B \\succ C) \\Rightarrow ($A \\succ C$)$\n- Continuity: $A \\succ B \\succ C \\Rightarrow \\exists  p [p, A; 1 - p, C] \\sim B$\n- Substitutability: $A \\sim B \\Rightarrow [p, A; 1 - p, C] \\sim [p, B; 1 - p, C]$\n- Monotonicity: $A \\succ B \\Rightarrow (p \\geq q \\Leftrightarrow [p, A; 1 - p, B] \\succeq [q, A; 1 - p, B])$\n- given preferences satisfying these constraints, there exists a maximum \nexpected utility\n\n\n## Module 8 Definitions\n* **Utility function** - sum of (discounted) rewards\n* **Expected utility** - your definition here\n* **Policy** - choice of action for each state\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\nOffline Planning: you don't actually play the game\n- solving MDPs is offline planning\n- determine all quantities through computation\n- need to know the deails of the MDP\n\nReinforcement Learning Ideas:\n- Exploration: have to try unknown actions to get information\n- Exploitation: eventually, have to use what you know\n- Regret: can still make mistakes\n- Sampling: have to try things repeatedly because of chance\n- Difficulty: learning can be much harder than solving a known MDP\n\nReinforcement Learning:\n- receive feedback in the form of rewards (r)\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- still assume an MDP\n- don't know T or R (don't know which states are good or what the actions do, \nneed to atually try actions and states to learn)\n\nModel-Based Learning:\n- learn an approximate model based on experiences (an empirical/observed MDP model)\n- solve for values as if the learned model were correct (can use value iteration)\n\nPassive Reinforcement Learning:\n- learner has no choice about what actions to take\n- just execute the policy and learn from experience\n- not offline planning, still takes actions in the world\n\nDirect Evaluation:\n- compute values for each state under $\\pi$\n- average together observed sample values\n- doesn't require any knowledge of T, R\n- eventually computes the correct average values, using just sample transitions\n- takes a long time to learn because each state must be learned separately\n\nSample-Based Policy Evaluation:\n- compute V without knowing T and R\n- take samples of outcomes s' (by doing the action) and average\n- $V_{k+1}^{\\pi}(s) \\leftarrow 1/n \\sum _i sample_i$\n- $V_{k+1}^{\\pi}(s) \\leftarrow 1/n \\sum _i R(s,\\pi (s), s_i')$\n\nTemporal Difference Learning:\n- learn from every experience\n- update V(s) each time we experience a transition (s,a,s',r)\n- likely outcomes s' will contribute updates more often\n- policy still fixed, still doing evaluation\n- move values toward value of whatever successor occurs: running average\n- a model-free way to do policy evaluation, mimicking Bellman updates with \nrunning sample averages\n- if we want to turn values into a (new) policy, we're sunk\n- can learn q-values, not values, which makes action selection model-free too\n\nActive Reinforcement Learning:\n- full reinforcement learning: optimal policies (like value iteration)\n- don't know the transitions or rewards\n- you choose the actions\n- goal is to learn the optimal policy / values\n\nQ-Value Iteration:\n- start with $Q_0(s,a) = 0$\n- $Q_{k+1}(s,a)$ = $\\sum _{s'}T(s,a,s')[R(s,a,s') + \\gamma max_{a'} Q_k(s',a')]$\n\nQ-Learning: sample based Q-value itteration\n- learn Q(s,a) values as you go\n- receive a sample (s,a,s',r)\n- consider your old estimate: Q(s,a)\n- consider your new sample estimate: sample = $R(s,a,s') + \\gamma max_{a'} Q(s',a')$\n- incorporate the new estimate into a running average: $Q(s,a)$ = $(1 - alpha)Q(s,a) + (alpha)[sample]$\n\nOff-Policy Learning:\n- Q-learning converges to optimal policy - even if you're action suboptimally\n\nExploration:\n- simplest scheme for forcing exploration is random actions ($\u000barepsilon$-greedy)\nwhere at each step with small probability $\u000barepsilon$ act randomly, and with\nlarge probability 1-$\u000barepsilon$ act on current policy\n- could lower $\u000barepsilon$ over time\n\nExploration Function:\n- explore areas whose badness is not yet established, eventually stop exploring\n- takes a value estimate $u$ and a visit count $n$ and returns an optimistic\nutility: $f(u,n)=u+k/n$\n- Regular Q-Update: $Q(s,a) \\leftarrow _{alpha} R(s,a,s') + \\gamma max_{a'} Q(s',a')$\n- Modified Q-Update: $Q(s,a) \\leftarrow _{alpha} R(s,a,s') + \\gamma max_{a'} f(Q(s',a'), N(s',a'))$\n- if an agent's exploration function values curiosity, $N(s,a)$ for a state $s$\nand action $a$ would be low\n\nRegret:\n- a measure of your total mistake cost\n- the difference between your expected rewards, including youthful suboptimality,\nand optimal expected rewards\n- quantifies relative goodness of exploration procedures\n\nGeneralizing Across States:\n- basic Q-Learning keeps a table of all q-values\n- in realistic situations, we cannot learn about every state\n- instead we learn about some small number of training states from experience\nand generalize that experience to new, similar situations\n\nLinear Value Functions: use feature representation to write a q function or \nvalue function for any state using a few weights\n- $V(s) = w_1f_1(s) + w_2f_2(s) + ... + w_nf_n(s)$\n- $Q(s,a) = w_1f_1(s,a) + w_2f_2(s,a) + ... + w_nf_n(s,a)$\n- sums up experience in a few powerful numbers\n- states may share features but actually be very different in value\n- used in approximate Q-Learning\n\n\n## Module 9 Definitions\n* **Term** - your definition here\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\nSample Space: the possible worlds, are mutually exclusive and exhaustive\n\nProbability Distributions: unobserved random variables have distributions\n\nJoint Distribution: over a set of random variables, specifies a real number\nfor each assignment (or outcome)\n\nProbabilistic Model: a joint distribution over a set of random variables\n- (random) variables with domains\n- assignments are called outcomes\n- joint distributions: say whether assignments (outcomes) are likely\n- normalized: sum to 1\n- ideally: only certain variables directly interact\n\nEvent: a set E of outcomes\n- typically the events we care about are partial assignments, like P(T = hot)\n\nMarginal Distributions: subtables which eliminate variables\n- marginalization: summing out, combine collapsed rows by adding\n\nConditional Probability: P(a|b) = P(a,b) / P(b)\n\nConditional Distributions: probability distributions over some variables \ngiven fixed calues of other\n- ex: P(W|T = hot)\n\nProbabilistic Inference: compute a desired probability from other known \nprobabilities\n- ex: conditional from joint\n- probabilities change with new evidence\n\nInference by Enumeration Steps:\n- select the entires consistent with the evidence\n- sum out H (hidden variables) to get joint of Query* variable and evidence\nvariables\n- normalize\n\nProduct Rule: P(y)P(x|y) = P(x,y)\n\nChain Rule: can always write any joint distribution as an incremental product \nof conditional distributions\n- ex: P(x,y,z) = P(x)P(y|x)P(z|x,y)\n- N! ways to apply the chain rule to a joint distribution with N random variables\n\nBayes' Rule: two ways to factor a joint distribution over two variables\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\nProbabilistic Language Modeling: compute the probability of a sentence or \nsequence of words\n- Language Model (LM): a model that computes this or the probability of \nan upcoming word\n- probability of a sentence or sequence of words: P(W) = P($w_1,w_2,...w_n$)\n- probability of an upcoming word: P($w_5|w_1,w_2,w_3,w_4$)\n\nMarkov Assumption: only depends on the previous $k$ words, not the whole context\n- $P(w_1w_2...w_n) \\simeq \\Pi _i ^n P(w_i|w_{i-k}...w_{i-1})$\n- $k$ is the number of context words that we take into account\n\nHow much history to use:\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-gram models are best for language because it has long-distance dependencies\n\nMaximum Likelihood Estimate: used to estimate bigram probabilities\n- $P(w_i|w_{i-1}) = count(w_{i-1},w_i) / count(w_{i-1})$\n- $P(w_i|w_{i-1}) = c(w_{i-1},w_i) / c(w_{i-1})$\n- we do everything in log space: avoids underflow, adding is fast than multiplying\n- log($p_1p_2p_3p_4$) = log($p_1$) + log($p_2$) + log($p_3$) + log($p_4$)\n\nOut of Vocabulary Items:\n- use <unk> to deal with out of vocabulary items (OOVs)\n- fixed lexicon L of size V\n- normalize training data by replacing any word not in L with <unk>\n- avoid zeros with smoothing\n\n\n## Module 10 Definitions\n* **Term** - your definition here\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\nIndependence: two variables are independe if for each $x,y: P(x,y) = P(x)P(y)$\n- equivalent to: for each $x,y: P(x|y) = P(x)$\n- can be written as $X \\perp \\!\\!\\! \\perp Y$\n- independence is a simplifying modeling assumption\n- empirical joint distributions are at best close to independent\n\nConditional Independence:\n- X is conditionally independent of Y given Z: $X \\perp \\!\\!\\! \\perp Y | Z$ if\nand only if for all $x,y,z: P(x,y|z) = P(x|z)P(y|z)$ or, equivalently, if and\nonly if for all $x,y,z: P(x|z,y) = P(x|z)$\n\nBayes' Nets: a technique for describing complex joint distributions (models)\nusing simple, local distributions (conditional probabilities)\n- more properly called graphical models\n- we describe how variables locally interact\n- local interactions chain together to give global, indirect interactions\n\nGraphical Model Notation:\n- nodes: variables (with domains), can be assigned (observed) or unassigned\n(unobserved)\n- arcs: interactions, indicate direct influence between variables, formally \nencode conditional independence\n- only distributions whose variables are absolutely independent can be \nrepresented by a Bayes' net with no arcs\n\nAbsolute Independence: no interactions between variables\n\nBayes' Net Graph:\n- a set of nodes, one per variable X\n- a directed, acyclic graph\n- a conditional distribution for each node\n- Bayes' nets implicitly encode joint distributions as a product of local \nconditional distributions\n- just need the parents probability distributions to get the conditional\nprobability distribution\n- $P(x_1,x_2,...,x_n) = \\Pi _{i=1} ^n P(x_i|parents(X_i))$\n- assume $P(x_i|x_1...x_{i-1}) = \\Pi _{i=1} ^n P(x_i|parents(X_i))$\n- BNs need not actually be causal - end up with arrows that reflect correlation,\nnot causation\n- topology encodes conditional independence\n- topology may happen to encode causal structure\n- more than one Bayesian network can be used to represent the same joint\ndistribution\n\nSize of a Bayes' Net:\n- a joint distribution over N boolean variables: $2^N$\n- an N-node net if nodes have up to $k$ parents: $O(N*2^{k+1})$\n- BNs have huge space savings\n- easier to elicit local CPTs (conditional probability tables)\n- stationary process: the CPT does not change over time\n- faster to answer queries\n\nChain Configurations:\n- Causal Chain: X causes Y causes Z\n- Common Cause: Y causes X and Z\n- Common Effect: X and Y cause Z\n\nA path is active if each triple is active:\n- causal chain A $\\Rightarrow$ B $\\Rightarrow$ C where B is unobserved\n- common cause A $\\Leftarrow$ B $\\Rightarrow$ C where B is unobserved\n- common effect A $\\Rightarrow$ B $\\Leftarrow$ C where B or one of its \ndescendents is observed\n\nX and Y are conditionally independent given evidence variables (Z) if:\n- X and Y are d-separated by Z\n- on all undirected paths from X to Y, all are inactive\n- all it takes to block a path is a single inactive segment\n\nD-Separation:\n- $X_i \\perp \\!\\!\\! \\perp X_j | \\{X_{k_1},...,X_{k_n} \\}$\n- check all undirected paths between $X_i$ and $X_j$, if all paths are inactive,\nthen independence is guaranteed\n- given a Bayes Net structure, can run d-separation algorithm to build a \ncomplete list of conditional independences that are necessarily true of the\nform $X_i \\perp \\!\\!\\! \\perp X_j | \\{X_{k_1},...,X_{k_n} \\}$, this list\ndetermines the set of probability distributions that can be represented\n\nInference: calculating some useful quantity from a joint probability \ndistribution\n- evidence variables: $E_1...E_k = e_1...e_k$\n- query variable: $Q$\n- hidden variables: $H_1...H_r$\n- evidence, query, hidden variables form all variables: $X_1,X_2,...,X_n$\n- we want: $P(Q|e_1...e_k)$\n\nVariable Elimination:\n- advanced, still NP-hard, but usually much faster than inference by enumeration\n- interleave joining and marginalizing\n- inference by enumeration is slow because you join up the whole joint distribution\nbefore you sum out the hidden variables\n\n\n## Module 11 Definitions\n* **Concept** - definition\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\nClassification: given inputs x, predict labels y\n\nModel-Based Classification:\n- build a model (ex: Bayes' net) where both the label and features are random\nvariables\n- instantiate any observed features\n- query for the distribution of the label conditioned on the features\n\nNaive Bayes: assume all features are independent effects of the label\n- models can incorporate a variety of features, but tend to do best in \nhomogeneous cases\n\nNaive Bayes for Digits:\n- one feature (variable) $F_{ij}$ for each grid position <i,j>\n- feature values are on / off based on whether intensity is more or less than\n0.5 in underlying image\n- each input maps to a feature vector\n\nGeneral Naive Bayes:\n- $|Y|$ labels\n- $P(Y,F_1...F_n) = P(Y) \\Pi _i P(F_i|Y)$\n- $|Y||F|^n$ values\n- $n|F||Y|$ paramaters\n- we only have to specify how each feature depends on the class\n- total number of parameters is linear in number of features\n\nInference for Naive Bayes:\n- compute posterior distribution over label variable $Y$\n- step 1: get joint probability of label and evidence for each label\n- step 2: sum to get probability of evidence\n- step 3: normalize by dividing step 1 by step 2\n\nBag-of-Words Naive Bayes:\n- each position (word) is identically distributed\n- usually (in other cases), each variable gets its own conditional probability\ndistribution $P(F|Y)$\n- in this case, all positions share the same conditional probability $P(W|Y)$\n- model is insensitive to word order or reordering\n\nData: label instances\n- training set\n- held-out set\n- test set\n\nFeatures: attribute-value pairs which characterize each $x$\n\nExperimentation Cycle:\n- learn paramters (ex: model probabilities) on training set\n- tune hyperparameters on held-out set\n- compute accuracy of test set\n- never peek at the test set\n\nEvaluation Accuracy: fraction of instances predicted correctly\n\nOverfitting and Generalization:\n- want a classifier which does well on test data\n- overfitting: fitting the training data very closely, but not generalizing\nwell\n- relative frequency parameters will overfit the training data\n- in general, can't give unseen events zero probability\n- we need to smooth or regularize the estimates to generalize better\n\nParameter Estimation: estimating the distribution of a random variable\n- elicitation: ask a human\n- empirically: use training data - for each outcome x, look at the empirical\nrate of that value: $P_{ML}(x) = count(x) /$ total samples\n- the estimate that maximizes the likelihood of the data: \n$L(x, \\Theta) = \\Pi _i P_{\\Theta}(x_i)$\n\nMaximum Likelihood: relative frequencies are the maximum likelihood estimates\n- $\\Theta _{ML} = argmax _{\\Theta} P(X|\\Theta) = argmax _{\\Theta} \\Pi _i P_{\\Theta}(X_i)$\n- $P_{ML}(x) = count(x) /$ total samples\n\nLaplace Smoothing:\n- Laplace's estimate: pretend you saw every outcome once more than you actually\ndid\n- Laplace's estimate (extended): pretend you saw every outcome $k$ extra times\n- $k$ is the strength of the prior\n- $P_{LAP,k}(x) = (c(x) + k)/(N + k|X|)\n\nTuning:\n- Parameters: the probabilities $P(X|Y), P(Y)$\n- Hyperparameters: the amount / type of smoothing to do, $k$, alpha\n- learn parameters from training data\n- tune hyperparameters on different data\n- for each value of the hyperparameters, train and tset on the held-out data\n- choose the best value and do a final test on the test data\n\nClassifiers: let you easily add arbitrary features\n\nBaseline:\n- help determine how hard the task is\n- help know what a good accuracy is\n\nWeak Baseline: most frequent label classifier\n- gives all test instances whatever label was most common in the training set\n- accuracy might be very high if the problem is skewed\n\nConfience of a Probabilistic Classifier:\n- posterior over the top label\n- $confidence(x) = max_y 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\nCalibration:\n- weak calibration: higher confidences mean higher accuracy\n- strong calibration: confidence predicts accuracy rate\n\nDynamic Bayes Model (DBN):\n- needs the transition model, prior distribution over the state variables, \nsensore model\n\nSummary:\n- Bayes rule lets us do diagnostic queries with causal probabilities\n- naive Bayes assumption takes all features to be independent given the class\nlabel\n- we can build classifiers out of a naive Bayes model using training data\n- smoothing estimates is important in real systems\n- classifier confidences are useful, when you can get them\n\nLinear Classifiers\n- inputs are feature values\n- each feature has a weight\n- sum is the activation\n- $activation_w(x) = \\Sigma _i w_i*f_i(x) = w*f(x)$\n- if the activation is positive, output +1\n- if the activation is negative, output -1\n\nWeights\n- binary case: compare features to a weight vector\n- learning: figure out the weight vector from examples\n\nBinary Decision Rule:\n- in the space of feature vectors: examples are points, any weight vector is\na hyperplane, one side corresponds to Y=+1, other side corresponds to Y=-1\n\nLearning: Binary Perceptron\n- start with weights = 0\n- for each training instance: classify with current weights, $y = +1$ if \n$w*f(x) \\geq 0$, $y = -1$ if $w*f(x) < 0$\n- if correct (y = y*), no change\n- if wrong, adjust the weight vector by adding or subtracting \nthe feature vector (subtract if y* is -1)\n\nMulticlass Decision Rule:\n- a weight vector for each class: $w_y$\n- score (activation) of a class y: $w_y*f(x)$\n- prediction highest score wins: $y = argmax_y w_y*f(x)$\n\nLearning: Multiclass Perceptron:\n- start with all weights = 0\n- pick up training examples one by one\n- predict with current weights: $y = argmax_y w_y*f(x)$\n- if correct, no change\n- if wrong: lower score of wrong answer, raise score of right answer: \n$w_y = w_y - f(x)$, $w_{y^*} = w_{y^*} + f(x)$\n\nProperties 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\n(binary case)\n- Mistake Bound: the maximum number of mistakes (binary case) related to the \nmargin or degree of separability (mistakes $< k/ \\delta ^2$)\n\nProblems with the Perceptron:\n- Noise: if the data isn't separable, weights might thrash\n- Averaging weight vectors over time can help (averaged perceptron)\n- Mediocre generalization: finds a barely separating solution\n- Overtraining: test / held-out accuracy usually rises, then falls, \novertraining is a kind of overfitting\n\nFixing the Perceptron:\n- adjust the weight update to mitigate these effects\n- MIRA*: choose an update size that fixes the current mistake, but minimizes\nthe change to w\n- $min_w 1/2 \\Sigma _y ||w_y - w_y' ||^2$\n- $w_y = w_y' - \tau f(x)$\n- $w_{y^*} = w_{y^*}' + \tau f(x)$\n\nMaximum Step Size:\n- in practice, it's bad to make updates that are too large\n- you may not have enough features\n- solution: cap the maximum possible value of $\tau$ with some constant C\n- corresponds to an optimization that assumes non-separable data\n- usually convergs faster than perceptron\n- usually better, especially on noisy data\n\nSupport Vector Machines:\n- maximizing the margin: good according to intuition, theory, practice\n- only support vectors matterl other training examples are ignorable\n- support vector machines (SVMs) find the separator with max margin\n- SVMs are MIRA where you optimize over all examples at once\n\nNaive Bayes vs. Perceptrons / MIRA:\n- Naive Bayes: builds a model training data, gives prediction probabilities,\nstrong assumptions about feature independence, one pass through data (counting)\n- Perceptrons / MIRA: makes less assumptions about data, mistake-driven \nlearning, multiple passes through data (prediction), often more accurate\n\nPerceptrons for Decision Making:\n- a perceptron / the sigmoid neuron is a device that makes decisions by \nweighing up evidence\n- by varying weights and the threshold we get different models of decision\nmaking\n- think of the input as features representing something we want to classify\n- the feature values for inputs are fixed, but we can choose different weight\nvectors; depending on the weight vector we pick, we will get a different \nclassifier\n- a complex network of perceptrons could make quite subtle decisions\n- first change: replace the weighted sum as a dot product: $w \\cdot x = \\Sigma _j w_jx_j$\n- second change: move the threshold to the other side of the inequality, and \nreplace it by a bias, b = -threshold\n- output = 0 if $\\Sigma _j w_jx_j \\leq$ threshold, 1 if $\\Sigma _j w_jx_j >$ threshold\n\nNon-Linear Separators: the original feature space can always be mapped to \nsome higher-dimensional feature space where the training set is separable\n\nLogical Functions:\n- networks of perceptrons to compute any logical function\n- we can build any computation up out of NAND gates\n- a single neural unit cannot be used to compute the XOR function\n\nActivation Functions: the output of a non-linear function $f$ applied by \nneuron units to $z = w \\cdot x+b$, which is a linear function of $x$\n- 3 commonly used non-linear functions used for $f$: sigmoid function, \ntanh function, rectified linear unit ReLU\n\n\n## Module 12 Definitions\n* **Concept** - definition\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\nClassifier Components: machine learning classifiers require a training \ncorpus of $M$ observations input/output pairs $(x^{(i)},y^{(i)})$\n- feature representation of the input: for each input oobservation $x^{(i)}$,\nthis will be a vector of features [$x_1,x_2,...,x_n$]\n- classification function: computes the estimated class $\\hat{y}$ via $p(y|x)$\n- objective function: for learning, usually involving minimizing error on\ntraining examples\n- an algorithm for optimizing the objective function\n\nSentiment Classifier:\n- input observation $x$ represented by a vector of features $[x_1,x_2,...,x_n]$\n- classifier output $y$ can be 1 (positive sentiment) or 0 (negative sentiment)\n- want to estimate $P(y=1|x)$, yes if greater than 0.5, no otherwise (we call\n0.5 the decision boundary)\n- logistic regression solves this task by learning, from a training set, a \nvector of weights and a bias term: $z = w \\cdot x + b$\n\nLearning in Logistic Regression:\n- get the weights and bias of the mdoel via learning\n- requires an objective function or loss function that tells distance between\nthe system output and the gold output; we will use cross-entropy loss\n- requires an algorithm for optimizing the objective function; we will\nuse stochastic gradient descent to minimize the loss function\n\nLoss Function: determines for some observation $x$ how close the classifier\noutput is to the correct output\n- $L(\\hat{y},y)$ = how much $\\hat{y}$ differs from the true $y$\n- Mean Squared Error: $L_{MSE}(\\hat{y},y) = 1/2(\\hat{y}-y)^2$\n- Cross Entropy Loss: negative log likelihood loss; the resulting loss function\nof choosing parameters $w,b$ that maximize the log probabilities of the true \nlabels in the training data; prefers (maximizes) the correct class labels of the training\nexample to be more likely; want loss to be smaller if the model's estimate\nis close to correct, and bigger if it is confused\n\nGradient Descent: finds a minimum of a function by figuring out in which\ndirection (in the space of the parameters $\\Theta$) the function's slope\nis rising the most steeply, and moving in the opposite direction\n- used to find good settings for our weights and bias by minimizing the loss\nfunction\n- for logistic regression, this loss function is convex\n- convex function has one minimum, so no local minima to get stuck in\n- gradient descent starting from any point is guaranteed to find the \nminimum\n- should move at the value of the slope weighted by a learning rate $\\eta$\n- a higher / faster learning rate means we should move $w$ more on each step\n\nThe Gradient:\n- the difference between the true $y$ and our estimate for $x$, multiplied by\nthe corresponding input value $x_j$\n- the loss for a batch of data or an entire dataset is the average loss\nover the $m$ examples\n- the gradient for multiple data points is the sum of the individual gradients\n\nStochastic Gradient Descent: chooses a single random example at a time and \nupdates its weights on that example\n- as a result the updates can fluctuate\n\nBatch Training: computes the gradient over the entire dataset\n- alternate to stochastic gradient descent\n- gives a better estimate of which direction to move the weights\n- takes longer to compute\n\nMini-Batch Training: train on a small batch\n- compromise of batch traning and stochastic gradient descent\n- batch size can be 512 or 1024 so that all examples in the mini-batch can\nbe processed in parallel\n- loss is then accumulated\n\nOverfitting:\n- a problem with many machine learning models\n- results in poor generalization and poor performance on unseen test set\n\nRegularization: a way to penalize large weights\n- a regularization term is added to the loss function\n- in logistic regression, if a feature only occurs in one class then it will \nget a high weight\n\nMultinomial Logistic Regression:\n- when we want more than two classes (ex: adding neutral to sentiment \nclassification)\n- want to know the probability of $y$ for each class $c \\in C$, $p(y = c|x)$\n- use a generalization of the sigmoid function called the softmax function to\nget a proper probability\n\nSoftmax Function:\n- takes in an input vector $z=[z_1,z_2,...,z_k]$\n- outputs a vector of values normalized into probabilities\n- softmax($z$) = $[e^{z_1}/ \\Sigma _{i=1}^k e^{z_i}, ... , e^{z_k}/ \\Sigma _{i=1}^k e^{z_i}]$\n\nNeural Networks:\n- built of single computational units\n- a unit takes a set of real valued numbers as input, performs some computation\n\nPerceptron -> Logistic Regression:\n- like the perceptron, logistic regression uses a vector of weights and a bias\nterm\n- $z = w \\cdot x + b$\n- instead of outputting z directly, logistic regression transforms it with the\nsigmoid function $\\sigma (z)$\n\nSmoothness:\n- smoothness of $\\sigma$ means that small changes in the weights $w_j$ and in\nthe bias $b$ will produce a small change in the output from the neuron\n- $\\Delta$output is a linear function of the changes $\\Delta w_j$ and $\\Delta b$\n- makes it easy to choose small changes in the weights and biases to achieve\nany desired small change in the output\n\nFeed-Forward Neural Network:\n- simplest kind of neural network\n- multilayer network, all units are usually fully-connected, and no cycles\n- outputs from each layer are passed to units in the next higher layer, and\nno outputs are passed back to lower layers\n- represent the parameters for the entire hidden layer by combining the weight\nvector $w_i$ and bias $b_i$ for each unit $i$ into a single weight matrix $W$\nand a single bias vector $b$ for the whole layer\n- hidden layer computation: multiply weight matrix by the input vector $x$,\nadding the bias vector $b$, and applying the activation function $g$ (such\nas Sigmoid); the output of the hidden layer is $h = \\sigma (Wx+b)$\n- ouput layer has a weight matrix $U$, output is $z = Uh$\n- feedforward network has a single hidden layer, which takes an input vector\n$x$, outputs a probability distribution $y$, and is parameterized by weight\nmatrices $W$ and $U$ and a bias vector $b$\n- $y = softmax(z)$\n- softmax normalizes the output and turns it into a probability distribution\n\nTraining Neural Nets:\n- needs a loss function (cross-entropy loss)\n- needs an optimization algorithm (gradient descent, to perform optimization)\n- needs a way of computing the gradient of the loss function (error propagation)\n\nComputation Graph: represents the process of computing a mathematical \nexpression\n- computation is broken down into separate operations\n- each operation is a node in a graph\n- backpropagation was invented for neural nets, and is related to a general\nprocedure called backward differentiation, which depends on the notion of\ncomputation graphs\n- backward pass is used to compute the derivates that we'll need for the weight\nupdate\n- importance of the computation graph comes from the backward pass\n- use error back propagation to compute the gradient of the loss function\n\n\n## Module 13 Definitions\n* **Concept** - definition\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\nClassifier Components: machine learning classifiers require a training \ncorpus of $M$ observations input/output pairs $(x^{(i)},y^{(i)})$\n- feature representation of the input: for each input oobservation $x^{(i)}$,\nthis will be a vector of features [$x_1,x_2,...,x_n$]\n- classification function: computes the estimated class $\\hat{y}$ via $p(y|x)$\n- objective function: for learning, usually involving minimizing error on\ntraining examples\n- an algorithm for optimizing the objective function\n\nSentiment Classifier:\n- input observation $x$ represented by a vector of features $[x_1,x_2,...,x_n]$\n- classifier output $y$ can be 1 (positive sentiment) or 0 (negative sentiment)\n- want to estimate $P(y=1|x)$, yes if greater than 0.5, no otherwise (we call\n0.5 the decision boundary)\n- logistic regression solves this task by learning, from a training set, a \nvector of weights and a bias term: $z = w \\cdot x + b$\n\nLearning in Logistic Regression:\n- get the weights and bias of the mdoel via learning\n- requires an objective function or loss function that tells distance between\nthe system output and the gold output; we will use cross-entropy loss\n- requires an algorithm for optimizing the objective function; we will\nuse stochastic gradient descent to minimize the loss function\n\nLoss Function: determines for some observation $x$ how close the classifier\noutput is to the correct output\n- $L(\\hat{y},y)$ = how much $\\hat{y}$ differs from the true $y$\n- Mean Squared Error: $L_{MSE}(\\hat{y},y) = 1/2(\\hat{y}-y)^2$\n- Cross Entropy Loss: negative log likelihood loss; the resulting loss function\nof choosing parameters $w,b$ that maximize the log probabilities of the true \nlabels in the training data; prefers (maximizes) the correct class labels of the training\nexample to be more likely; want loss to be smaller if the model's estimate\nis close to correct, and bigger if it is confused\n\nGradient Descent: finds a minimum of a function by figuring out in which\ndirection (in the space of the parameters $\\Theta$) the function's slope\nis rising the most steeply, and moving in the opposite direction\n- used to find good settings for our weights and bias by minimizing the loss\nfunction\n- for logistic regression, this loss function is convex\n- convex function has one minimum, so no local minima to get stuck in\n- gradient descent starting from any point is guaranteed to find the \nminimum\n- should move at the value of the slope weighted by a learning rate $\\eta$\n- a higher / faster learning rate means we should move $w$ more on each step\n\nThe Gradient:\n- the difference between the true $y$ and our estimate for $x$, multiplied by\nthe corresponding input value $x_j$\n- the loss for a batch of data or an entire dataset is the average loss\nover the $m$ examples\n- the gradient for multiple data points is the sum of the individual gradients\n\nStochastic Gradient Descent: chooses a single random example at a time and \nupdates its weights on that example\n- as a result the updates can fluctuate\n\nBatch Training: computes the gradient over the entire dataset\n- alternate to stochastic gradient descent\n- gives a better estimate of which direction to move the weights\n- takes longer to compute\n\nMini-Batch Training: train on a small batch\n- compromise of batch traning and stochastic gradient descent\n- batch size can be 512 or 1024 so that all examples in the mini-batch can\nbe processed in parallel\n- loss is then accumulated\n\nOverfitting:\n- a problem with many machine learning models\n- results in poor generalization and poor performance on unseen test set\n\nRegularization: a way to penalize large weights\n- a regularization term is added to the loss function\n- in logistic regression, if a feature only occurs in one class then it will \nget a high weight\n\nMultinomial Logistic Regression:\n- when we want more than two classes (ex: adding neutral to sentiment \nclassification)\n- want to know the probability of $y$ for each class $c \\in C$, $p(y = c|x)$\n- use a generalization of the sigmoid function called the softmax function to\nget a proper probability\n\nSoftmax Function:\n- takes in an input vector $z=[z_1,z_2,...,z_k]$\n- outputs a vector of values normalized into probabilities\n- softmax($z$) = $[e^{z_1}/ \\Sigma _{i=1}^k e^{z_i}, ... , e^{z_k}/ \\Sigma _{i=1}^k e^{z_i}]$\n\nNeural Networks:\n- built of single computational units\n- a unit takes a set of real valued numbers as input, performs some computation\n\nPerceptron -> Logistic Regression:\n- like the perceptron, logistic regression uses a vector of weights and a bias\nterm\n- $z = w \\cdot x + b$\n- instead of outputting z directly, logistic regression transforms it with the\nsigmoid function $\\sigma (z)$\n\nSmoothness:\n- smoothness of $\\sigma$ means that small changes in the weights $w_j$ and in\nthe bias $b$ will produce a small change in the output from the neuron\n- $\\Delta$output is a linear function of the changes $\\Delta w_j$ and $\\Delta b$\n- makes it easy to choose small changes in the weights and biases to achieve\nany desired small change in the output\n\nFeed-Forward Neural Network:\n- simplest kind of neural network\n- multilayer network, all units are usually fully-connected, and no cycles\n- outputs from each layer are passed to units in the next higher layer, and\nno outputs are passed back to lower layers\n- represent the parameters for the entire hidden layer by combining the weight\nvector $w_i$ and bias $b_i$ for each unit $i$ into a single weight matrix $W$\nand a single bias vector $b$ for the whole layer\n- hidden layer computation: multiply weight matrix by the input vector $x$,\nadding the bias vector $b$, and applying the activation function $g$ (such\nas Sigmoid); the output of the hidden layer is $h = \\sigma (Wx+b)$\n- ouput layer has a weight matrix $U$, output is $z = Uh$\n- feedforward network has a single hidden layer, which takes an input vector\n$x$, outputs a probability distribution $y$, and is parameterized by weight\nmatrices $W$ and $U$ and a bias vector $b$\n- $y = softmax(z)$\n- softmax normalizes the output and turns it into a probability distribution\n\nTraining Neural Nets:\n- needs a loss function (cross-entropy loss)\n- needs an optimization algorithm (gradient descent, to perform optimization)\n- needs a way of computing the gradient of the loss function (error propagation)\n\nComputation Graph: represents the process of computing a mathematical \nexpression\n- computation is broken down into separate operations\n- each operation is a node in a graph\n- backpropagation was invented for neural nets, and is related to a general\nprocedure called backward differentiation, which depends on the notion of\ncomputation graphs\n- backward pass is used to compute the derivates that we'll need for the weight\nupdate\n- importance of the computation graph comes from the backward pass\n- use error back propagation to compute the gradient of the loss function\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}