{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "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/",
          "height": 0
        },
        "outputId": "1ee96c08-506c-4296-90e7-c3bd7207b50c"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "791a0807-8134-4d32-973c-38315179f25f"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\"The environment is assumed to be episodic:  choosing among actions based on the\n",
        "desirability of their immediate outcomes\\n \n",
        "$P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$\\n\n",
        "The agent’s preferences are captured by a utility function U(a), which assigns a single number to\n",
        "express the desirability of a state. The expected utility of an action given the evidence EU(a)\n",
        ", is just the average utility value of the outcomes, weighted by the probability that the\n",
        "outcome occurs\\n\n",
        "$EU(a) = \\sum_s' P(\\textnormal{RESULT}(a)=s')U(s')$\\n\n",
        "The principle of maximum expected utility (MEU) says that a rational agent should choose\n",
        "the action that maximizes the agent’s expected utility\"\"\"\n",
        "chapter16_2 = \"\"\" \n",
        "ORDERABILITY: Given any two lotteries, a rational agent must either prefer one or\n",
        "else rate them as equally preferable\\n\n",
        "TRANSITIVITY: Given any three lotteries, if an agent prefers to and prefers to ,\n",
        "then the agent must prefer to .\\n\n",
        "CONTINUITY: If some lottery is between and in preference, then there is some\n",
        "probability for which the rational agent will be indifferent between getting for sure\n",
        "and the lottery that yields with probability and with probability .\\n\n",
        "SUBSTITUTABILITY: If an agent is indifferent between two lotteries and , then the\n",
        "agent is indifferent between two more complex lotteries that are the same except that \n",
        "is substituted for in one of them. This holds regardless of the probabilities and the\n",
        "other outcome(s) in the lotteries\\n\n",
        "MONOTONICITY: Suppose two lotteries have the same two possible outcomes, and \n",
        ". If an agent prefers to , then the agent must prefer the lottery that has a higher\n",
        "probability for (and vice versa)\\n\n",
        "DECOMPOSABILITY: Compound lotteries can be reduced to simpler ones using the\n",
        "laws of probability.\n",
        "\n",
        "\"\"\"\n",
        "chapter16_3 = \"\"\" \n",
        "Human judgment is usually irrational.\\n\n",
        "preference elicitation: presenting choices to the human and\n",
        "using the observed preferences to pin down the underlying utility function.\\n\n",
        "the agent exhibits a monotonic preference for more money\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "BellmanEquation = r\"\"\"$U(s) = \\max_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma U(s')] = \\max_a Q(s,a)$\"\"\"\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" An optimal policy is a policy that yields the highest expected utility \\n\n",
        "Additive undiscounted rewards will generally be infinite within infinite horizons. So we use discounted rewards. \\n\n",
        "a sequential decision problem for a fully observable, stochastic environment\n",
        "with a Markovian transition model and additive rewards is called a Markov decision\n",
        "process, or MDP, and consists of a set of states (with an initial state ); a set ACTIONS(s) of\n",
        "actions in each state; a transition model ; and a reward function .\n",
        "Methods for solving MDPs usually involve dynamic programming: simplifying a problem\n",
        "by recursively breaking it into smaller pieces and remembering the optimal solutions to the\n",
        "pieces.\\n\n",
        " \"\"\" + BellmanEquation\n",
        "chapter17_2 =  r\"\"\" Value Iteration: $V_{k+1}(s) = \\max_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V_k(s')]$  Repeat until convergence Complexity of each iteration: $O(S^2A)$\n",
        "\n",
        "Policy $\\pi^*(s) = \\argmax_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V_k(s')]$\n",
        "Policy Evalutaion: $V^{\\pi_i}_{k+1}(s) = \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V^{\\pi_i}_k(s')]$\n",
        "\n",
        "\n",
        "One-step look-ahead: $\\pi_{i+1}(s) = \\argmax_a \\sum_{s'}T(s,a,s')[R(s,a, s')+\\gamma V^{\\pi}(s')]$\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\"\n",
        "Value Iteration: \\n\n",
        "V*(s) = expected utility starting in s and acting optimally; Q*(s,a) = expected utility starting out\n",
        "having taken action a from state s and (thereafter) acting optimally;π*(s) = optimal action from state s \\n\n",
        "$V*(s) = max_{a}Q*(s, a)$ \\n\n",
        "$Q*(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s')+γV*(s')] $ \\n\n",
        "$V*(s) = max_{a}\\sum_{s'}T(s,a,s')[R(s,a,s')+γV*(s')] $ \\n\n",
        "Problems with Value Iteration: slow: $O(s^2 * A)$; The 'max' at each state rarely changes; The policy often converges long before the values \\n\n",
        "Policy Iteration: \\n\n",
        "1. calculate utilities for some fixed policy (not optimal utilities!) until convergence \\n\n",
        "2. update policy using one step look ahead with resulting converged (but not optimal!) utilities as future values \\n\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\" : \"Your definition here\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "\"preference elicitation\": \"presenting choices to the human and using the observed preferences to pin down the underlying utility function.\",\n",
        "\"finite horizon\": \"there is a fixed time after which nothing matters—the game is over\",\n",
        "\"proper policy\": \"A policy that is guaranteed to reach a terminal state\",\n",
        "\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1366
        },
        "outputId": "1fc199cf-d7f3-4533-eaf1-2d154f296806"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\nThe environment is assumed to be episodic:  choosing among actions based on the\ndesirability of their immediate outcomes\n \n$P(\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$\n\nThe agent’s preferences are captured by a utility function U(a), which assigns a single number to\nexpress the desirability of a state. The expected utility of an action given the evidence EU(a)\n, is just the average utility value of the outcomes, weighted by the probability that the\noutcome occurs\n\n$EU(a) = \\sum_s' P(\textnormal{RESULT}(a)=s')U(s')$\n\nThe principle of maximum expected utility (MEU) says that a rational agent should choose\nthe action that maximizes the agent’s expected utility\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n \nORDERABILITY: Given any two lotteries, a rational agent must either prefer one or\nelse rate them as equally preferable\n\nTRANSITIVITY: Given any three lotteries, if an agent prefers to and prefers to ,\nthen the agent must prefer to .\n\nCONTINUITY: If some lottery is between and in preference, then there is some\nprobability for which the rational agent will be indifferent between getting for sure\nand the lottery that yields with probability and with probability .\n\nSUBSTITUTABILITY: If an agent is indifferent between two lotteries and , then the\nagent is indifferent between two more complex lotteries that are the same except that \nis substituted for in one of them. This holds regardless of the probabilities and the\nother outcome(s) in the lotteries\n\nMONOTONICITY: Suppose two lotteries have the same two possible outcomes, and \n. If an agent prefers to , then the agent must prefer the lottery that has a higher\nprobability for (and vice versa)\n\nDECOMPOSABILITY: Compound lotteries can be reduced to simpler ones using the\nlaws of probability.\n\n\n\n## AIMA Chapter 16.3 Utility Functions\n \nHuman judgment is usually irrational.\n\npreference elicitation: presenting choices to the human and\nusing the observed preferences to pin down the underlying utility function.\n\nthe agent exhibits a monotonic preference for more money\n\n\n## AIMA Chapter 17.1 Sequential Decision Problems\n An optimal policy is a policy that yields the highest expected utility \n\nAdditive undiscounted rewards will generally be infinite within infinite horizons. So we use discounted rewards. \n\na sequential decision problem for a fully observable, stochastic environment\nwith a Markovian transition model and additive rewards is called a Markov decision\nprocess, or MDP, and consists of a set of states (with an initial state ); a set ACTIONS(s) of\nactions in each state; a transition model ; and a reward function .\nMethods for solving MDPs usually involve dynamic programming: simplifying a problem\nby recursively breaking it into smaller pieces and remembering the optimal solutions to the\npieces.\n\n $U(s) = \\max_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma U(s')] = \\max_a Q(s,a)$\n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Value Iteration: $V_{k+1}(s) = \\max_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V_k(s')]$  Repeat until convergence Complexity of each iteration: $O(S^2A)$\n\nPolicy $\\pi^*(s) = \\argmax_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V_k(s')]$\nPolicy Evalutaion: $V^{\\pi_i}_{k+1}(s) = \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V^{\\pi_i}_k(s')]$\n\n\nOne-step look-ahead: $\\pi_{i+1}(s) = \\argmax_a \\sum_{s'}T(s,a,s')[R(s,a, s')+\\gamma V^{\\pi}(s')]$\n\n\n## Module 8 Lecture Notes\n\nValue Iteration: \n\nV*(s) = expected utility starting in s and acting optimally; Q*(s,a) = expected utility starting out\nhaving taken action a from state s and (thereafter) acting optimally;π*(s) = optimal action from state s \n\n$V*(s) = max_{a}Q*(s, a)$ \n\n$Q*(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s')+γV*(s')] $ \n\n$V*(s) = max_{a}\\sum_{s'}T(s,a,s')[R(s,a,s')+γV*(s')] $ \n\nProblems with Value Iteration: slow: $O(s^2 * A)$; The 'max' at each state rarely changes; The policy often converges long before the values \n\nPolicy Iteration: \n\n1. calculate utilities for some fixed policy (not optimal utilities!) until convergence \n\n2. update policy using one step look ahead with resulting converged (but not optimal!) utilities as future values \n\n\n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Preference elicitation** - presenting choices to the human and using the observed preferences to pin down the underlying utility function.\n* **Finite horizon** - there is a fixed time after which nothing matters—the game is over\n* **Proper policy** - A policy that is guaranteed to reach a terminal 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 =  \"\"\" Multi-armed Bandit Problem \\n\n",
        "the concept of metalevel decision problems such as deciding what\n",
        "computations to make during a game-tree search prior to making a move. A metalevel\n",
        "decision of this kind is also a selection problem rather than a bandit problem. C\\n\n",
        "An important generalization of the bandit process is the bandit superprocess or BSP, in\n",
        "which each arm is a full Markov decision process in its own right, rather than being a\n",
        "Markov reward process with only one possible action. All other properties remain the same:\n",
        "the arms are independent, only one (or a bounded number) can be worked on at a time, and\n",
        "there is a single discount factor.\\n\"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" Reinforcement learning (RL): an agent interacts with the world Reinforcement\n",
        "learning and periodically receives rewards that reflect how well it is doing \\n\n",
        "Model-based: the agent uses a transition model of the environment to make decisions and to learn utility function. \\n\n",
        "Model-free: the agent neither knows nor learns a transition model for the environment. \\n\n",
        "1. Action-utility learning (Q-learning): the agent learns a Q-function; 2. Policy search: The agent learns a policy π(s) that maps directly from states to actions.\n",
        "\"\"\"\n",
        "chapter22_2 =  \"\"\" passive reinforcement learning: has a fixed policy π as input, the goal is to learn the state value \\n\n",
        "Direct utility estimation: $ U^{π}(s) = E[\\sum_{0}^{\\inf}γ^tR(S_{t},π(S_{t}), S_{t+1})]$, drawback: wastes information about state connections \\n\n",
        "Adaptive dynamic programming(ADP) \\n \n",
        "Temporal-difference learning \\n\n",
        "exploration function f (u,n) determines how greed (preference Exploration function for high values of the utility u) \n",
        "is traded off against curiosity (preference for actions that have not been tried often and have a low count n)\n",
        "\"\"\"\n",
        "chapter22_3 =  \"\"\" exploration: GLIE scheme: must try each GLIE action in each state\n",
        "an unbounded number of times to avoid having a finite probability that an optimal action is\n",
        "missed \\n\n",
        "Temporal-difference Q-learning：\\n\n",
        "$Q(s,a)←Q(s,a)+α[R(s,a,s')+γmax_{a}Q(s',a')−Q(s,a)]$ \\n\n",
        "a TD Q-learning agent does not need a transition model \\n\n",
        "SARSA (for state, action, reward, state, action): $Q(s,a)←Q(s,a)+α[R(s,a,s')+γQ(s',a')−Q(s,a)]$ \\n\n",
        "Q-learning is an off-policy learning algorithm, SARSA is an on-policy algorithm \\n\n",
        "off-policy: Q-learning can learn the optimal Q-function without ever executing the optimal policy \\n\n",
        "\"\"\"\n",
        "chapter22_4 =  \"\"\" evaluation function:\n",
        "$V(s)=w_{1}f_{1}(s)+w_{2}f_{2}(s)+...+w_{n}f_{n}(s)$ \\n\n",
        "$Q(s,a)=w_{1}f_{1}(s,a)+w_{2}f_{2}(s,a)+...+w_{n}f_{n}(s,a)$ \\n\n",
        "advantage: our experience is summed up in a few powerful numbers\n",
        " \"\"\"\n",
        "chapter22_5 =  \"\"\" policy search:idea is to keep twiddling the policy as long as its performance improves, then stop.\\n\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\" \n",
        "Temporal Difference Learning: learn from every experience \\n\n",
        "$sample = R(s,π(s),s') + γV^π(s')$ \\n\n",
        "$update: V^π(s) ← V^π(s) + α(sample - V^π(s))$ \\n\n",
        "Random actions: explore a fixed amount; Better idea: explore areas whose badness is not (yet) established, eventually stop exploring \\n\n",
        "Exploration function: Takes a value estimate u and a visit count n, and\n",
        "returns an optimistic utility $f(u,n)=u+k/n$\\n\n",
        "The agent is in the MDP, but not given the MDP to solve\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"sparse\" : \"the vast majority of states the agent is given no informative reward signal at all\",\n",
        "\"SARSA\" : \"state, action, reward, state, action, close reletive to Q learning\",\n",
        "}"
      ],
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1226
        },
        "cellView": "form",
        "outputId": "883fd584-3582-47f4-a93a-52d1ac678096"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Multi-armed Bandit Problem \n\nthe concept of metalevel decision problems such as deciding what\ncomputations to make during a game-tree search prior to making a move. A metalevel\ndecision of this kind is also a selection problem rather than a bandit problem. C\n\nAn important generalization of the bandit process is the bandit superprocess or BSP, in\nwhich each arm is a full Markov decision process in its own right, rather than being a\nMarkov reward process with only one possible action. All other properties remain the same:\nthe arms are independent, only one (or a bounded number) can be worked on at a time, and\nthere is a single discount factor.\n\n\n## AIMA Chapter 22.1 Learning from Rewards\n Reinforcement learning (RL): an agent interacts with the world Reinforcement\nlearning and periodically receives rewards that reflect how well it is doing \n\nModel-based: the agent uses a transition model of the environment to make decisions and to learn utility function. \n\nModel-free: the agent neither knows nor learns a transition model for the environment. \n\n1. Action-utility learning (Q-learning): the agent learns a Q-function; 2. Policy search: The agent learns a policy π(s) that maps directly from states to actions.\n\n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n passive reinforcement learning: has a fixed policy π as input, the goal is to learn the state value \n\nDirect utility estimation: $ U^{π}(s) = E[\\sum_{0}^{\\inf}γ^tR(S_{t},π(S_{t}), S_{t+1})]$, drawback: wastes information about state connections \n\nAdaptive dynamic programming(ADP) \n \nTemporal-difference learning \n\nexploration function f (u,n) determines how greed (preference Exploration function for high values of the utility u) \nis traded off against curiosity (preference for actions that have not been tried often and have a low count n)\n\n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n exploration: GLIE scheme: must try each GLIE action in each state\nan unbounded number of times to avoid having a finite probability that an optimal action is\nmissed \n\nTemporal-difference Q-learning：\n\n$Q(s,a)←Q(s,a)+α[R(s,a,s')+γmax_{a}Q(s',a')−Q(s,a)]$ \n\na TD Q-learning agent does not need a transition model \n\nSARSA (for state, action, reward, state, action): $Q(s,a)←Q(s,a)+α[R(s,a,s')+γQ(s',a')−Q(s,a)]$ \n\nQ-learning is an off-policy learning algorithm, SARSA is an on-policy algorithm \n\noff-policy: Q-learning can learn the optimal Q-function without ever executing the optimal policy \n\n\n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n evaluation function:\n$V(s)=w_{1}f_{1}(s)+w_{2}f_{2}(s)+...+w_{n}f_{n}(s)$ \n\n$Q(s,a)=w_{1}f_{1}(s,a)+w_{2}f_{2}(s,a)+...+w_{n}f_{n}(s,a)$ \n\nadvantage: our experience is summed up in a few powerful numbers\n \n\n## Module 9 Lecture Notes\n \nTemporal Difference Learning: learn from every experience \n\n$sample = R(s,π(s),s') + γV^π(s')$ \n\n$update: V^π(s) ← V^π(s) + α(sample - V^π(s))$ \n\nRandom actions: explore a fixed amount; Better idea: explore areas whose badness is not (yet) established, eventually stop exploring \n\nExploration function: Takes a value estimate u and a visit count n, and\nreturns an optimistic utility $f(u,n)=u+k/n$\n\nThe agent is in the MDP, but not given the MDP to solve\n\n\n## Module 9 Definitions\n* **Sparse** - the vast majority of states the agent is given no informative reward signal at all\n* **Sarsa** - state, action, reward, state, action, close reletive to Q learning\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 = \"\"\" To make such choices, an agent must first have preferences among the different possible \n",
        "outcomes of the various plans \\n\n",
        "Decision theory = probability theory+utility theory \\n \n",
        "maximum expected utility (MEU) \\n \n",
        "\"\"\"\n",
        "chapter12_2 = \"\"\" \n",
        "product rule: P(a∧b) = P(a|b)P(b) \\n\n",
        "probability distribution, probability density function(pdf) \\n\n",
        "Kolmogorov’s axioms: P(¬a) = 1−P(a); P(a∨b) = P(a)+P(b)−P(a∧b) \\n\n",
        " \"\"\"\n",
        "chapter12_3 = \"\"\" $ P(Y) =\\sum P(Y,Z=z) $ \"\"\"\n",
        "chapter12_4 = \"\"\" \n",
        "independence: P(a|b)=P(a) or P(b|a)=P(b) or P(a∧b)=P(a)P(b) \\n\n",
        "\"\"\"\n",
        "chapter12_5 = \"\"\" Bayes’Rule: $ P(Y|X,e) = P(X|Y,e)P(Y|e)/P(X|e) $ \\n \"\"\"\n",
        "chapter12_6 = \"\"\" \n",
        "The naive Bayes model assumes the conditional independence of all effect variables,\n",
        "given a single cause variable; its size grows linearly with the number of effects \\n\n",
        "Naive Bayes Models: \\n\n",
        "$ P(Cause,Effect_1,...,Effect_n) = P(Cause)\\prod_{i}P(Effect_{i}|Cause) $ \\n\n",
        "\"\"\"\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 = \"\"\" When we use a bigram model to predict the conditional probability of the next word, we make the following approximation: \\n\n",
        "P(wn|w1:n−1) ≈ P(wn|wn−1) (Markov) \\n\n",
        "MLE(maximum likelihood estimation): Use count as probability \\n\"\"\"\n",
        "SLP_chapter3_2 = \"\"\" perplexity(PP): weighted average branching factor of a language \\n\n",
        "the higher probability in testing set, the lower PP is, the better the language model is \\n \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" OOV rate: The percentage of out of vocabulary (OOV) words \\n\n",
        "ways to train the probabilities of the unknown word model <UNK>:1.Choose a vocabulary (word list) that is fixed in advance; \n",
        "2. Convert in the training set any OOV word to token <UNK>; 3. Estimate the probabilities for <UNK> from its counts just like any other regular\n",
        "word in the training set \\n\n",
        " \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" \n",
        "smoothing/discounting: keep a language model from assigning\n",
        "zero probability to these unseen events(a known word appears after unknown context in testing) \\n\n",
        "Laplace smoothing & Add-k smoothing \\n\n",
        "Backoff and Interpolation: If we are trying to compute $P(w_{n}|w_{n-2}w{n-1})$ but we have no examples of (w_{n-2}w{n-1}w_{n}), we can instead estimate its probability by using the bigram\n",
        "probability $P(w_{n}|w{n-1})$ \\n\n",
        "backoff: only “back off” to a lower-order n-gram if we have zero evidence for a higher-order n-gram \\n\n",
        "interpolation: mix the probability estimates from all the n-gram estimators \\n\n",
        " \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\" \n",
        "The Chain Rule: $ P(x1,x2,...xn) = \\prod_{i}P(xi|x1...x_{i-1}) $ \\n\n",
        "Bayes’Rule: $ P(x|y) = P(y|x)/P(y) * P(x) $ \\n\n",
        "Practical Issues for MLE(maximum likelihood estimation): do everything in log space\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"stationary process\" : \"the conditional probability table does not change over time\",\n",
        "}"
      ],
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1585
        },
        "cellView": "form",
        "outputId": "e2542c02-a428-4b0a-ecfd-067e82f86dfd"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n To make such choices, an agent must first have preferences among the different possible \noutcomes of the various plans \n\nDecision theory = probability theory+utility theory \n \nmaximum expected utility (MEU) \n \n\n\n## AIMA Chapter 12.2 Basic Probability Notation\n \nproduct rule: P(a∧b) = P(a|b)P(b) \n\nprobability distribution, probability density function(pdf) \n\nKolmogorov’s axioms: P(¬a) = 1−P(a); P(a∨b) = P(a)+P(b)−P(a∧b) \n\n \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n $ P(Y) =\\sum P(Y,Z=z) $ \n\n## AIMA Chapter 12.4 Independence\n \nindependence: P(a|b)=P(a) or P(b|a)=P(b) or P(a∧b)=P(a)P(b) \n\n\n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Bayes’Rule: $ P(Y|X,e) = P(X|Y,e)P(Y|e)/P(X|e) $ \n \n\n## AIMA Chapter 12.6 Naive Bayes Models\n \nThe naive Bayes model assumes the conditional independence of all effect variables,\ngiven a single cause variable; its size grows linearly with the number of effects \n\nNaive Bayes Models: \n\n$ P(Cause,Effect_1,...,Effect_n) = P(Cause)\\prod_{i}P(Effect_{i}|Cause) $ \n\n\n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n When we use a bigram model to predict the conditional probability of the next word, we make the following approximation: \n\nP(wn|w1:n−1) ≈ P(wn|wn−1) (Markov) \n\nMLE(maximum likelihood estimation): Use count as probability \n\n\n## SLP Chapter 3.2 Evaluating Language Models\n perplexity(PP): weighted average branching factor of a language \n\nthe higher probability in testing set, the lower PP is, the better the language model is \n \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 OOV rate: The percentage of out of vocabulary (OOV) words \n\nways to train the probabilities of the unknown word model <UNK>:1.Choose a vocabulary (word list) that is fixed in advance; \n2. Convert in the training set any OOV word to token <UNK>; 3. Estimate the probabilities for <UNK> from its counts just like any other regular\nword in the training set \n\n \n\n## SLP Chapter 3.5 Smoothing\n \nsmoothing/discounting: keep a language model from assigning\nzero probability to these unseen events(a known word appears after unknown context in testing) \n\nLaplace smoothing & Add-k smoothing \n\nBackoff and Interpolation: If we are trying to compute $P(w_{n}|w_{n-2}w{n-1})$ but we have no examples of (w_{n-2}w{n-1}w_{n}), we can instead estimate its probability by using the bigram\nprobability $P(w_{n}|w{n-1})$ \n\nbackoff: only “back off” to a lower-order n-gram if we have zero evidence for a higher-order n-gram \n\ninterpolation: mix the probability estimates from all the n-gram estimators \n\n \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n \nThe Chain Rule: $ P(x1,x2,...xn) = \\prod_{i}P(xi|x1...x_{i-1}) $ \n\nBayes’Rule: $ P(x|y) = P(y|x)/P(y) * P(x) $ \n\nPractical Issues for MLE(maximum likelihood estimation): do everything in log space\n\n\n## Module 10 Definitions\n* **Stationary process** - the conditional probability table does not change over time\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 = \"\"\" \n",
        "Bayesian network: represent the dependencies among variables \\n\n",
        "DAG(directed acyclic graph), Each node $x_i$ has associated probability information $P(x_i| parent(x_i)$) \\n\n",
        "conditional probability table (CPT): The local probability information attached to each node(can be used only for discrete variables) \\n\n",
        " \"\"\"\n",
        "chapter13_2 = \"\"\" \n",
        "The semantics of Bayes nets defines each entry in the joint distribution: $P(x_1,\\cdots, x_n) = \\prod_{i=1}^n P(x_i|parents(x_i))$ \\n\n",
        "Conditional independence relations in Bayesian networks: \\n\n",
        "non-descendants: Each variable is conditionally independent of its non-descendants, given its parents \\n\n",
        "Markov blanket: a variable is conditionally independent of all other nodes in the network, given its Markov blanket(parents,\n",
        "children, and children’s parents)\n",
        " \"\"\"\n",
        "chapter13_3 = \"\"\"\n",
        "Inference: calculating some useful quantity from a joint probability distribution \\n\n",
        "Inference by Enumeration: \\n\n",
        "Evidence variables: $E_1, \\cdots, E_k = e_1, \\cdots e_k$ \\n\n",
        "Query variable: $Q$ \\n\n",
        "Hidden variables: $H_1, \\cdots, H_r$ \\n\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" \n",
        "A Bayes net = Topology (graph) + Local Conditional Probabilities \\n\n",
        "BNs need not actually be causal \\n\n",
        "Topology may happen to encode causal structure, Topology really encodes conditional independence \\n\n",
        "joint distribution over N Boolean variables: $2^N$ \\n\n",
        "N-node net in which nodes have up tp k parents: $N*2^{k+1}$ \\n\n",
        "Causal Chain: X->Y->Z, then $P(x,y,z)=P(x)P(y|x)P(z|y)$, this do not guaranteed X independent of Z, but guaranteed X independent of Z given Y ($P(z|x,y)=P(z|y)$) \\n\n",
        "Are X and Y conditionally independent given evidence variables {Z}?: Consider all (undirected) paths from X to Y, No active paths = independence \\n\n",
        "A path is active if each triple is active \\n\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"CPT\" : \"conditional probability table\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "4578e70c-1f05-43db-9fe8-53653590d6c5"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n \nBayesian network: represent the dependencies among variables \n\nDAG(directed acyclic graph), Each node $x_i$ has associated probability information $P(x_i| parent(x_i)$) \n\nconditional probability table (CPT): The local probability information attached to each node(can be used only for discrete variables) \n\n \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n \nThe semantics of Bayes nets defines each entry in the joint distribution: $P(x_1,\\cdots, x_n) = \\prod_{i=1}^n P(x_i|parents(x_i))$ \n\nConditional independence relations in Bayesian networks: \n\nnon-descendants: Each variable is conditionally independent of its non-descendants, given its parents \n\nMarkov blanket: a variable is conditionally independent of all other nodes in the network, given its Markov blanket(parents,\nchildren, and children’s parents)\n \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n\nInference: calculating some useful quantity from a joint probability distribution \n\nInference by Enumeration: \n\nEvidence variables: $E_1, \\cdots, E_k = e_1, \\cdots e_k$ \n\nQuery variable: $Q$ \n\nHidden variables: $H_1, \\cdots, H_r$ \n\n\n\n## Module 11 Lecture Notes\n \nA Bayes net = Topology (graph) + Local Conditional Probabilities \n\nBNs need not actually be causal \n\nTopology may happen to encode causal structure, Topology really encodes conditional independence \n\njoint distribution over N Boolean variables: $2^N$ \n\nN-node net in which nodes have up tp k parents: $N*2^{k+1}$ \n\nCausal Chain: X->Y->Z, then $P(x,y,z)=P(x)P(y|x)P(z|y)$, this do not guaranteed X independent of Z, but guaranteed X independent of Z given Y ($P(z|x,y)=P(z|y)$) \n\nAre X and Y conditionally independent given evidence variables {Z}?: Consider all (undirected) paths from X to Y, No active paths = independence \n\nA path is active if each triple is active \n\n\n\n## Module 11 Definitions\n* **Cpt** - conditional probability table\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 = \"\"\" \n",
        "supervised learning: the agent observes input-output pairs and learns a function that \n",
        "maps from input to output \\n\n",
        "unsupervised learning: the agent learns patterns in the input without any explicit feedback \\n\n",
        "reinforcement learning: the agent learns from a series of reinforcements: rewards and punishments \\n\n",
        " \"\"\"\n",
        "chapter19_2 = \"\"\" bias–variance tradeoff: a choice between more complex,hypotheses that fit the training data well and simpler, low-variance hypotheses that may generalize\n",
        "better. \\n\"\"\"\n",
        "chapter19_3 = \"\"\" \n",
        "Entropy: $ H(V) = \\sum_k P(v_k)log(1 / {P(v_k)})$ \\n\n",
        "decision tree pruning combats overfitting \n",
        "\"\"\"\n",
        "chapter19_4 = \"\"\" \n",
        "We can think of the task of finding a good hypothesis\n",
        " as two subtasks: model selection chooses a good hypothesis space, and optimization (also\n",
        "Optimization called training) finds the best hypothesis within that space. \\n\n",
        "Regularization: search for a hypothesis that directly minimizes the weighted sum of empirical\n",
        "loss and the complexity of the hypothesis \\n\n",
        "Hyperparameter tuning: hand-tuning, grid search\n",
        " \"\"\"\n",
        "chapter19_5 = \"\"\" Any hypothesis that is consistent with a sufficiently large set of training examples is unlikely to be seriously wrong: that is, it must be probably approximately correct (PAC).\n",
        " \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = r\"\"\" Naive Bayes(strong assumptions about feature independence):\n",
        "$P(Y,F_1,\\cdots, F_n) = P(Y) \\prod_i P(F_i|Y)$ \\n\n",
        "Many language processing tasks can be viewed as tasks of classification \\n\n",
        "Text categorization, in which an entire text is assigned a class from a finite set,\n",
        "includes such tasks as sentiment analysis, spam detection, language identification,\n",
        "and authorship attribution.\n",
        " \"\"\"\n",
        "slp_chapter4_2 = \"\"\" \n",
        "Naive Bayes is a generative model that makes the bag of words assumption\n",
        "(position doesn’t matter) and the conditional independence assumption (words\n",
        "are conditionally independent of each other given the class)\\n\n",
        "The unknown words or very frequently occurred words will be ignored. \"\"\"\n",
        "slp_chapter4_3 = \"\"\" maximum likelihood training \"\"\"\n",
        "slp_chapter4_4 = \"\"\" \n",
        "Trick 1: whether a word occurs or not seems to matter more than its frequency\n",
        "\n",
        "Trick 2: negation (NOT_)\n",
        "\n",
        " \"\"\"\n",
        "slp_chapter4_5 = \"\"\" A common solution here, rather than using all the words as individual features,\n",
        "is to predefine likely sets of words or phrases as features, combined with features\n",
        "that are not purely linguistic. \"\"\"\n",
        "slp_chapter4_6 = r\"\"\" $P(s|c) = \\prod_{i} P(w_i | c) $\"\"\"\n",
        "slp_chapter4_7 = r\"\"\" \n",
        "Classifiers are evaluated based on precision and recall \\n\n",
        "precision: $\\frac{TP}{TP+FP}$ recall = $\\frac{TP}{TP+FN}$ accuracy=$\\frac{TP+TN}{TP+FP+TN+FN}$ \n",
        "\n",
        "Naive Bayes algorithm is  a multi-class classification algorithm.\n",
        "\"\"\"\n",
        "slp_chapter4_8 = \"\"\" K-fold cross-validation. \"\"\"\n",
        "slp_chapter4_9 = \"\"\"\n",
        "Statistical significance tests should be used to determine whether we can be\n",
        "confident that one version of a classifier is better than another.\"\"\"\n",
        "slp_chapter4_10 = \"\"\" Designers of classifiers should carefully consider harms that may be caused\n",
        "by the model, including its training data and other components, and report\n",
        "model characteristics in a model card \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\" SVM: Maximizing the margin: good according to intuition, theory, practice; \n",
        "Only support vectors matter; other training examples are ignorable \\n\n",
        "Non-Linear Separators: mapping data to a higher-dimensional space \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"LOOCV\" : \"leave-one-out cross-validation\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1646
        },
        "cellView": "form",
        "outputId": "c55e24b3-fdc4-4d5f-b09b-5b998e25d191"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module12_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter19_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter19_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter19_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter19_4),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter19_5),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter19_6),\n",
        "  (\"SLP Chapter 4.1 Naive Bayes Classifiers\", slp_chapter4_1),\n",
        "  (\"SLP Chapter 4.2 Training the Naive Bayes Classifier\", slp_chapter4_2),\n",
        "  (\"SLP Chapter 4.3 Worked Example\", slp_chapter4_3),\n",
        "  (\"SLP Chapter 4.4 Optimizing for Sentiment Analysis\", slp_chapter4_4),\n",
        "  (\"SLP Chapter 4.5 Naive Bayes for other text classification tasks\", slp_chapter4_5),\n",
        "  (\"SLP Chapter 4.6 Naive Bayes as a Language Model\", slp_chapter4_6),\n",
        "  (\"SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\", slp_chapter4_7),\n",
        "  (\"SLP Chapter 4.8 Test sets and Cross-validation\", slp_chapter4_8),\n",
        "  (\"SLP Chapter 4.9 Statistical Significance Testing\", slp_chapter4_9),\n",
        "  (\"SLP Chapter 4.10 Avoiding Harms in Classification\", slp_chapter4_10),\n",
        "  (\"Module 12 Lecture Notes\", module12_lecture_notes),\n",
        "]\n",
        "\n",
        "module12_markdown = format_module(12, \"Naive Bayes and Perceptrons\", \n",
        "                         module12_sections, \n",
        "                         module12_definitions)\n",
        "display(Markdown(module12_markdown))"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n \nsupervised learning: the agent observes input-output pairs and learns a function that \nmaps from input to output \n\nunsupervised learning: the agent learns patterns in the input without any explicit feedback \n\nreinforcement learning: the agent learns from a series of reinforcements: rewards and punishments \n\n \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n bias–variance tradeoff: a choice between more complex,hypotheses that fit the training data well and simpler, low-variance hypotheses that may generalize\nbetter. \n\n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \nEntropy: $ H(V) = \\sum_k P(v_k)log(1 / {P(v_k)})$ \n\ndecision tree pruning combats overfitting \n\n\n## AIMA Chapter 5.5 Stochastic Games\n \nWe can think of the task of finding a good hypothesis\n as two subtasks: model selection chooses a good hypothesis space, and optimization (also\nOptimization called training) finds the best hypothesis within that space. \n\nRegularization: search for a hypothesis that directly minimizes the weighted sum of empirical\nloss and the complexity of the hypothesis \n\nHyperparameter tuning: hand-tuning, grid search\n \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Any hypothesis that is consistent with a sufficiently large set of training examples is unlikely to be seriously wrong: that is, it must be probably approximately correct (PAC).\n \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 Naive Bayes(strong assumptions about feature independence):\n$P(Y,F_1,\\cdots, F_n) = P(Y) \\prod_i P(F_i|Y)$ \\n\nMany language processing tasks can be viewed as tasks of classification \\n\nText categorization, in which an entire text is assigned a class from a finite set,\nincludes such tasks as sentiment analysis, spam detection, language identification,\nand authorship attribution.\n \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n \nNaive Bayes is a generative model that makes the bag of words assumption\n(position doesn’t matter) and the conditional independence assumption (words\nare conditionally independent of each other given the class)\n\nThe unknown words or very frequently occurred words will be ignored. \n\n## SLP Chapter 4.3 Worked Example\n maximum likelihood training \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n \nTrick 1: whether a word occurs or not seems to matter more than its frequency\n\nTrick 2: negation (NOT_)\n\n \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n A common solution here, rather than using all the words as individual features,\nis to predefine likely sets of words or phrases as features, combined with features\nthat are not purely linguistic. \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n $P(s|c) = \\prod_{i} P(w_i | c) $\n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n \nClassifiers are evaluated based on precision and recall \\n\nprecision: $\\frac{TP}{TP+FP}$ recall = $\\frac{TP}{TP+FN}$ accuracy=$\\frac{TP+TN}{TP+FP+TN+FN}$ \n\nNaive Bayes algorithm is  a multi-class classification algorithm.\n\n\n## SLP Chapter 4.8 Test sets and Cross-validation\n K-fold cross-validation. \n\n## SLP Chapter 4.9 Statistical Significance Testing\n\nStatistical significance tests should be used to determine whether we can be\nconfident that one version of a classifier is better than another.\n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Designers of classifiers should carefully consider harms that may be caused\nby the model, including its training data and other components, and report\nmodel characteristics in a model card \n\n## Module 12 Lecture Notes\n SVM: Maximizing the margin: good according to intuition, theory, practice; \nOnly support vectors matter; other training examples are ignorable \n\nNon-Linear Separators: mapping data to a higher-dimensional space \n\n## Module 12 Definitions\n* **Loocv** - leave-one-out cross-validation\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 = \"\"\"\n",
        "sigmoid: $\\sigma(z) = \\frac{1}{1+e^{-z}}$ \\n\n",
        "$1-\\sigma(x) = \\sigma(-x)$ \\n\n",
        "$\\sigma'(x) = \\sigma(x)(1-\\sigma(x))$ \\n\n",
        "\"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Cross Entropy Loss: $L(\\hat{y}, y) = -[ylog \\hat{y} + (1-y)log (1-\\hat{y})]$ where $\\hat{y}=sigmiod(wx+b)$\n",
        "\"\"\"\n",
        "slp_chapter5_4 = \"\"\" SGD(Stochastic Gradient Descent) \"\"\"\n",
        "slp_chapter5_5 = \"\"\" L2 regularization: Euclidean distance \\n\n",
        "L1 regularization: Manhattan distance \\n\n",
        "L2 prefers weight vectors with many small weights, L1 prefers sparse solutions with some larger weights but many more weights set to zero. \\n\n",
        " \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Softmax: $exp(z_i) / {\\sum_{j=1}^k exp(z_j)}$ \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Unit: $z=b+\\sum_i w_i x_i $ \"\"\"\n",
        "slp_chapter7_2 = \"\"\" 2 layer network can solve XOR \"\"\"\n",
        "slp_chapter7_3 = \"\"\" non-linear activation functions: if we did not, the resulting network is exactly equivalent to\n",
        "a single-layer network \"\"\"\n",
        "slp_chapter7_4 = \"\"\"  Neural language models represent words in this prior context by their embeddings,\n",
        "rather than just by their word identity as used in n-gram language models. \"\"\"\n",
        "slp_chapter7_5 = \"\"\" embedding layer, Multiply by W and activate, Multiply by U, Apply softmax \"\"\"\n",
        "slp_chapter7_6 = \"\"\" error backpropagation or\n",
        "backward differentiation \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Neural language models use a neural network as a probabilistic classifier, to\n",
        "compute the probability of the next word given the previous n words.  \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" Stochastic gradient descent chooses a single random example at a time and updates\n",
        "its weights on that example \\n\n",
        "batch training, which computes the gradient over the entire dataset \\n\n",
        "mini-batch training: train on a small batch each time.\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 14,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1261
        },
        "cellView": "form",
        "outputId": "f51c42bc-0394-4b7a-a572-de57317da16a"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n\nsigmoid: $\\sigma(z) = \frac{1}{1+e^{-z}}$ \n\n$1-\\sigma(x) = \\sigma(-x)$ \n\n$\\sigma'(x) = \\sigma(x)(1-\\sigma(x))$ \n\n\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 Cross Entropy Loss: $L(\\hat{y}, y) = -[ylog \\hat{y} + (1-y)log (1-\\hat{y})]$ where $\\hat{y}=sigmiod(wx+b)$\n\n\n## SLP Chapter 5.4 Gradient Descent\n SGD(Stochastic Gradient Descent) \n\n## SLP Chapter 5.5 Regularization\n L2 regularization: Euclidean distance \n\nL1 regularization: Manhattan distance \n\nL2 prefers weight vectors with many small weights, L1 prefers sparse solutions with some larger weights but many more weights set to zero. \n\n \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Softmax: $exp(z_i) / {\\sum_{j=1}^k exp(z_j)}$ \n\n## SLP Chapter 7.1 Units\n Unit: $z=b+\\sum_i w_i x_i $ \n\n## SLP Chapter 7.2 The XOR problem\n 2 layer network can solve XOR \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n non-linear activation functions: if we did not, the resulting network is exactly equivalent to\na single-layer network \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n  Neural language models represent words in this prior context by their embeddings,\nrather than just by their word identity as used in n-gram language models. \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n embedding layer, Multiply by W and activate, Multiply by U, Apply softmax \n\n## SLP Chapter 7.6 Training Neural Nets\n error backpropagation or\nbackward differentiation \n\n## SLP Chapter 7.7 Training the neural language model\n Neural language models use a neural network as a probabilistic classifier, to\ncompute the probability of the next word given the previous n words.  \n\n## Module 13 Lecture Notes\n Stochastic gradient descent chooses a single random example at a time and updates\nits weights on that example \n\nbatch training, which computes the gradient over the entire dataset \n\nmini-batch training: train on a small batch each time.\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 = r\"\"\" $PP_\\theta(w_{1:n}) = \\sqrt[n]{\\prod_{i=1}^n \\frac{1}{P_\\theta(w_i|w_{1:n-1})}}$ \"\"\"\n",
        "slp_chapter9_2 = r\"\"\" RNN: $h_i \\leftarrow g(Uh_{i-1} + W_x_i)$ \"\"\"\n",
        "slp_chapter9_3 = \"\"\" RNN language models process the input sequence one word at\n",
        "a time, attempting to predict the next word from the current word and the previous\n",
        "hidden state. RNNs don’t have the limited context problem that n-gram models\n",
        "have, since the hidden state can in principle represent information about all of the\n",
        "preceding words all the way back to the beginning of the sequence. \"\"\"\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 = \"\"\" lexical semantics：linguistics side \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Vector Semantics: math side \"\"\"\n",
        "slp_chapter6_3 = \"\"\" In a term-document matrix, each row represents a word in the vocabulary \n",
        "and each matrix column represents a document from some collection of documents. \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Word2vec embeddings are static embeddings,that learns one fixed embedding for each word in the embeddings vocabulary. \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Vector semantic models fall into two classes: sparse and dense. Word2vec algorithms\n",
        "like skip-gram are a popular way to compute dense embeddings; sparse models (tf-idf) \n",
        "\"\"\"\n",
        "slp_chapter6_12 = \"\"\" The most common metric of NLP tasks\n",
        "is to test their performance on similarity \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" Ideally, we want a meaning representation to encode:\n",
        "Synonyms – words that have similar meanings; Antonyms – words that have opposite meanings; Connotations – words that are positive or negative;\n",
        "Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event \\n\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"SGNS\" : \"skip-gram with negative sampling\", \n",
        "}\n",
        "\n"
      ],
      "execution_count": 16,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1075
        },
        "outputId": "ca84b2ed-d38d-4d2f-b612-981c9de5fda9"
      },
      "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": 17,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n $PP_\\theta(w_{1:n}) = \\sqrt[n]{\\prod_{i=1}^n \\frac{1}{P_\\theta(w_i|w_{1:n-1})}}$ \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n RNN: $h_i \\leftarrow g(Uh_{i-1} + W_x_i)$ \n\n## SLP Chapter 9.3 RNNs as Language Models\n RNN language models process the input sequence one word at\na time, attempting to predict the next word from the current word and the previous\nhidden state. RNNs don’t have the limited context problem that n-gram models\nhave, since the hidden state can in principle represent information about all of the\npreceding words all the way back to the beginning of the sequence. \n\n## SLP Chapter 6.1 Lexical Semantics\n lexical semantics：linguistics side \n\n## SLP Chapter 6.2 Vector Semantics\n Vector Semantics: math side \n\n## SLP Chapter 6.3 Words and Vectors\n In a term-document matrix, each row represents a word in the vocabulary \nand each matrix column represents a document from some collection of documents. \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Word2vec embeddings are static embeddings,that learns one fixed embedding for each word in the embeddings vocabulary. \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Vector semantic models fall into two classes: sparse and dense. Word2vec algorithms\nlike skip-gram are a popular way to compute dense embeddings; sparse models (tf-idf) \n\n\n## SLP Chapter 6.12 Evaluating Vector Models\n The most common metric of NLP tasks\nis to test their performance on similarity \n\n## Module 13 Lecture Notes\n Stochastic gradient descent chooses a single random example at a time and updates\nits weights on that example \n\nbatch training, which computes the gradient over the entire dataset \n\nmini-batch training: train on a small batch each time.\n \n\n## Module 14 Definitions\n* **Sgns** - skip-gram with negative sampling\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 8880
        },
        "id": "T3cm1WV542_a",
        "outputId": "0831c6b5-8798-4da9-e058-4cf69c528cf8"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module8_markdown, \n",
        "                             module9_markdown, \n",
        "                             module10_markdown, \n",
        "                             module11_markdown, \n",
        "                             module12_markdown,\n",
        "                             module13_markdown,\n",
        "                             module14_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\nThe environment is assumed to be episodic:  choosing among actions based on the\ndesirability of their immediate outcomes\n \n$P(\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$\n\nThe agent’s preferences are captured by a utility function U(a), which assigns a single number to\nexpress the desirability of a state. The expected utility of an action given the evidence EU(a)\n, is just the average utility value of the outcomes, weighted by the probability that the\noutcome occurs\n\n$EU(a) = \\sum_s' P(\textnormal{RESULT}(a)=s')U(s')$\n\nThe principle of maximum expected utility (MEU) says that a rational agent should choose\nthe action that maximizes the agent’s expected utility\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n \nORDERABILITY: Given any two lotteries, a rational agent must either prefer one or\nelse rate them as equally preferable\n\nTRANSITIVITY: Given any three lotteries, if an agent prefers to and prefers to ,\nthen the agent must prefer to .\n\nCONTINUITY: If some lottery is between and in preference, then there is some\nprobability for which the rational agent will be indifferent between getting for sure\nand the lottery that yields with probability and with probability .\n\nSUBSTITUTABILITY: If an agent is indifferent between two lotteries and , then the\nagent is indifferent between two more complex lotteries that are the same except that \nis substituted for in one of them. This holds regardless of the probabilities and the\nother outcome(s) in the lotteries\n\nMONOTONICITY: Suppose two lotteries have the same two possible outcomes, and \n. If an agent prefers to , then the agent must prefer the lottery that has a higher\nprobability for (and vice versa)\n\nDECOMPOSABILITY: Compound lotteries can be reduced to simpler ones using the\nlaws of probability.\n\n\n\n## AIMA Chapter 16.3 Utility Functions\n \nHuman judgment is usually irrational.\n\npreference elicitation: presenting choices to the human and\nusing the observed preferences to pin down the underlying utility function.\n\nthe agent exhibits a monotonic preference for more money\n\n\n## AIMA Chapter 17.1 Sequential Decision Problems\n An optimal policy is a policy that yields the highest expected utility \n\nAdditive undiscounted rewards will generally be infinite within infinite horizons. So we use discounted rewards. \n\na sequential decision problem for a fully observable, stochastic environment\nwith a Markovian transition model and additive rewards is called a Markov decision\nprocess, or MDP, and consists of a set of states (with an initial state ); a set ACTIONS(s) of\nactions in each state; a transition model ; and a reward function .\nMethods for solving MDPs usually involve dynamic programming: simplifying a problem\nby recursively breaking it into smaller pieces and remembering the optimal solutions to the\npieces.\n\n $U(s) = \\max_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma U(s')] = \\max_a Q(s,a)$\n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Value Iteration: $V_{k+1}(s) = \\max_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V_k(s')]$  Repeat until convergence Complexity of each iteration: $O(S^2A)$\n\nPolicy $\\pi^*(s) = \\argmax_a \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V_k(s')]$\nPolicy Evalutaion: $V^{\\pi_i}_{k+1}(s) = \\sum_{s'}P(s'|s,a)[R(s,a,s')+\\gamma V^{\\pi_i}_k(s')]$\n\n\nOne-step look-ahead: $\\pi_{i+1}(s) = \\argmax_a \\sum_{s'}T(s,a,s')[R(s,a, s')+\\gamma V^{\\pi}(s')]$\n\n\n## Module 8 Lecture Notes\n\nValue Iteration: \n\nV*(s) = expected utility starting in s and acting optimally; Q*(s,a) = expected utility starting out\nhaving taken action a from state s and (thereafter) acting optimally;π*(s) = optimal action from state s \n\n$V*(s) = max_{a}Q*(s, a)$ \n\n$Q*(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s')+γV*(s')] $ \n\n$V*(s) = max_{a}\\sum_{s'}T(s,a,s')[R(s,a,s')+γV*(s')] $ \n\nProblems with Value Iteration: slow: $O(s^2 * A)$; The 'max' at each state rarely changes; The policy often converges long before the values \n\nPolicy Iteration: \n\n1. calculate utilities for some fixed policy (not optimal utilities!) until convergence \n\n2. update policy using one step look ahead with resulting converged (but not optimal!) utilities as future values \n\n\n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Preference elicitation** - presenting choices to the human and using the observed preferences to pin down the underlying utility function.\n* **Finite horizon** - there is a fixed time after which nothing matters—the game is over\n* **Proper policy** - A policy that is guaranteed to reach a terminal state\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Multi-armed Bandit Problem \n\nthe concept of metalevel decision problems such as deciding what\ncomputations to make during a game-tree search prior to making a move. A metalevel\ndecision of this kind is also a selection problem rather than a bandit problem. C\n\nAn important generalization of the bandit process is the bandit superprocess or BSP, in\nwhich each arm is a full Markov decision process in its own right, rather than being a\nMarkov reward process with only one possible action. All other properties remain the same:\nthe arms are independent, only one (or a bounded number) can be worked on at a time, and\nthere is a single discount factor.\n\n\n## AIMA Chapter 22.1 Learning from Rewards\n Reinforcement learning (RL): an agent interacts with the world Reinforcement\nlearning and periodically receives rewards that reflect how well it is doing \n\nModel-based: the agent uses a transition model of the environment to make decisions and to learn utility function. \n\nModel-free: the agent neither knows nor learns a transition model for the environment. \n\n1. Action-utility learning (Q-learning): the agent learns a Q-function; 2. Policy search: The agent learns a policy π(s) that maps directly from states to actions.\n\n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n passive reinforcement learning: has a fixed policy π as input, the goal is to learn the state value \n\nDirect utility estimation: $ U^{π}(s) = E[\\sum_{0}^{\\inf}γ^tR(S_{t},π(S_{t}), S_{t+1})]$, drawback: wastes information about state connections \n\nAdaptive dynamic programming(ADP) \n \nTemporal-difference learning \n\nexploration function f (u,n) determines how greed (preference Exploration function for high values of the utility u) \nis traded off against curiosity (preference for actions that have not been tried often and have a low count n)\n\n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n exploration: GLIE scheme: must try each GLIE action in each state\nan unbounded number of times to avoid having a finite probability that an optimal action is\nmissed \n\nTemporal-difference Q-learning：\n\n$Q(s,a)←Q(s,a)+α[R(s,a,s')+γmax_{a}Q(s',a')−Q(s,a)]$ \n\na TD Q-learning agent does not need a transition model \n\nSARSA (for state, action, reward, state, action): $Q(s,a)←Q(s,a)+α[R(s,a,s')+γQ(s',a')−Q(s,a)]$ \n\nQ-learning is an off-policy learning algorithm, SARSA is an on-policy algorithm \n\noff-policy: Q-learning can learn the optimal Q-function without ever executing the optimal policy \n\n\n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n evaluation function:\n$V(s)=w_{1}f_{1}(s)+w_{2}f_{2}(s)+...+w_{n}f_{n}(s)$ \n\n$Q(s,a)=w_{1}f_{1}(s,a)+w_{2}f_{2}(s,a)+...+w_{n}f_{n}(s,a)$ \n\nadvantage: our experience is summed up in a few powerful numbers\n \n\n## Module 9 Lecture Notes\n \nTemporal Difference Learning: learn from every experience \n\n$sample = R(s,π(s),s') + γV^π(s')$ \n\n$update: V^π(s) ← V^π(s) + α(sample - V^π(s))$ \n\nRandom actions: explore a fixed amount; Better idea: explore areas whose badness is not (yet) established, eventually stop exploring \n\nExploration function: Takes a value estimate u and a visit count n, and\nreturns an optimistic utility $f(u,n)=u+k/n$\n\nThe agent is in the MDP, but not given the MDP to solve\n\n\n## Module 9 Definitions\n* **Sparse** - the vast majority of states the agent is given no informative reward signal at all\n* **Sarsa** - state, action, reward, state, action, close reletive to Q learning\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n To make such choices, an agent must first have preferences among the different possible \noutcomes of the various plans \n\nDecision theory = probability theory+utility theory \n \nmaximum expected utility (MEU) \n \n\n\n## AIMA Chapter 12.2 Basic Probability Notation\n \nproduct rule: P(a∧b) = P(a|b)P(b) \n\nprobability distribution, probability density function(pdf) \n\nKolmogorov’s axioms: P(¬a) = 1−P(a); P(a∨b) = P(a)+P(b)−P(a∧b) \n\n \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n $ P(Y) =\\sum P(Y,Z=z) $ \n\n## AIMA Chapter 12.4 Independence\n \nindependence: P(a|b)=P(a) or P(b|a)=P(b) or P(a∧b)=P(a)P(b) \n\n\n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Bayes’Rule: $ P(Y|X,e) = P(X|Y,e)P(Y|e)/P(X|e) $ \n \n\n## AIMA Chapter 12.6 Naive Bayes Models\n \nThe naive Bayes model assumes the conditional independence of all effect variables,\ngiven a single cause variable; its size grows linearly with the number of effects \n\nNaive Bayes Models: \n\n$ P(Cause,Effect_1,...,Effect_n) = P(Cause)\\prod_{i}P(Effect_{i}|Cause) $ \n\n\n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n When we use a bigram model to predict the conditional probability of the next word, we make the following approximation: \n\nP(wn|w1:n−1) ≈ P(wn|wn−1) (Markov) \n\nMLE(maximum likelihood estimation): Use count as probability \n\n\n## SLP Chapter 3.2 Evaluating Language Models\n perplexity(PP): weighted average branching factor of a language \n\nthe higher probability in testing set, the lower PP is, the better the language model is \n \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 OOV rate: The percentage of out of vocabulary (OOV) words \n\nways to train the probabilities of the unknown word model <UNK>:1.Choose a vocabulary (word list) that is fixed in advance; \n2. Convert in the training set any OOV word to token <UNK>; 3. Estimate the probabilities for <UNK> from its counts just like any other regular\nword in the training set \n\n \n\n## SLP Chapter 3.5 Smoothing\n \nsmoothing/discounting: keep a language model from assigning\nzero probability to these unseen events(a known word appears after unknown context in testing) \n\nLaplace smoothing & Add-k smoothing \n\nBackoff and Interpolation: If we are trying to compute $P(w_{n}|w_{n-2}w{n-1})$ but we have no examples of (w_{n-2}w{n-1}w_{n}), we can instead estimate its probability by using the bigram\nprobability $P(w_{n}|w{n-1})$ \n\nbackoff: only “back off” to a lower-order n-gram if we have zero evidence for a higher-order n-gram \n\ninterpolation: mix the probability estimates from all the n-gram estimators \n\n \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n \nThe Chain Rule: $ P(x1,x2,...xn) = \\prod_{i}P(xi|x1...x_{i-1}) $ \n\nBayes’Rule: $ P(x|y) = P(y|x)/P(y) * P(x) $ \n\nPractical Issues for MLE(maximum likelihood estimation): do everything in log space\n\n\n## Module 10 Definitions\n* **Stationary process** - the conditional probability table does not change over time\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n \nBayesian network: represent the dependencies among variables \n\nDAG(directed acyclic graph), Each node $x_i$ has associated probability information $P(x_i| parent(x_i)$) \n\nconditional probability table (CPT): The local probability information attached to each node(can be used only for discrete variables) \n\n \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n \nThe semantics of Bayes nets defines each entry in the joint distribution: $P(x_1,\\cdots, x_n) = \\prod_{i=1}^n P(x_i|parents(x_i))$ \n\nConditional independence relations in Bayesian networks: \n\nnon-descendants: Each variable is conditionally independent of its non-descendants, given its parents \n\nMarkov blanket: a variable is conditionally independent of all other nodes in the network, given its Markov blanket(parents,\nchildren, and children’s parents)\n \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n\nInference: calculating some useful quantity from a joint probability distribution \n\nInference by Enumeration: \n\nEvidence variables: $E_1, \\cdots, E_k = e_1, \\cdots e_k$ \n\nQuery variable: $Q$ \n\nHidden variables: $H_1, \\cdots, H_r$ \n\n\n\n## Module 11 Lecture Notes\n \nA Bayes net = Topology (graph) + Local Conditional Probabilities \n\nBNs need not actually be causal \n\nTopology may happen to encode causal structure, Topology really encodes conditional independence \n\njoint distribution over N Boolean variables: $2^N$ \n\nN-node net in which nodes have up tp k parents: $N*2^{k+1}$ \n\nCausal Chain: X->Y->Z, then $P(x,y,z)=P(x)P(y|x)P(z|y)$, this do not guaranteed X independent of Z, but guaranteed X independent of Z given Y ($P(z|x,y)=P(z|y)$) \n\nAre X and Y conditionally independent given evidence variables {Z}?: Consider all (undirected) paths from X to Y, No active paths = independence \n\nA path is active if each triple is active \n\n\n\n## Module 11 Definitions\n* **Cpt** - conditional probability table\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n \nsupervised learning: the agent observes input-output pairs and learns a function that \nmaps from input to output \n\nunsupervised learning: the agent learns patterns in the input without any explicit feedback \n\nreinforcement learning: the agent learns from a series of reinforcements: rewards and punishments \n\n \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n bias–variance tradeoff: a choice between more complex,hypotheses that fit the training data well and simpler, low-variance hypotheses that may generalize\nbetter. \n\n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \nEntropy: $ H(V) = \\sum_k P(v_k)log(1 / {P(v_k)})$ \n\ndecision tree pruning combats overfitting \n\n\n## AIMA Chapter 5.5 Stochastic Games\n \nWe can think of the task of finding a good hypothesis\n as two subtasks: model selection chooses a good hypothesis space, and optimization (also\nOptimization called training) finds the best hypothesis within that space. \n\nRegularization: search for a hypothesis that directly minimizes the weighted sum of empirical\nloss and the complexity of the hypothesis \n\nHyperparameter tuning: hand-tuning, grid search\n \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Any hypothesis that is consistent with a sufficiently large set of training examples is unlikely to be seriously wrong: that is, it must be probably approximately correct (PAC).\n \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 Naive Bayes(strong assumptions about feature independence):\n$P(Y,F_1,\\cdots, F_n) = P(Y) \\prod_i P(F_i|Y)$ \\n\nMany language processing tasks can be viewed as tasks of classification \\n\nText categorization, in which an entire text is assigned a class from a finite set,\nincludes such tasks as sentiment analysis, spam detection, language identification,\nand authorship attribution.\n \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n \nNaive Bayes is a generative model that makes the bag of words assumption\n(position doesn’t matter) and the conditional independence assumption (words\nare conditionally independent of each other given the class)\n\nThe unknown words or very frequently occurred words will be ignored. \n\n## SLP Chapter 4.3 Worked Example\n maximum likelihood training \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n \nTrick 1: whether a word occurs or not seems to matter more than its frequency\n\nTrick 2: negation (NOT_)\n\n \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n A common solution here, rather than using all the words as individual features,\nis to predefine likely sets of words or phrases as features, combined with features\nthat are not purely linguistic. \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n $P(s|c) = \\prod_{i} P(w_i | c) $\n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n \nClassifiers are evaluated based on precision and recall \\n\nprecision: $\\frac{TP}{TP+FP}$ recall = $\\frac{TP}{TP+FN}$ accuracy=$\\frac{TP+TN}{TP+FP+TN+FN}$ \n\nNaive Bayes algorithm is  a multi-class classification algorithm.\n\n\n## SLP Chapter 4.8 Test sets and Cross-validation\n K-fold cross-validation. \n\n## SLP Chapter 4.9 Statistical Significance Testing\n\nStatistical significance tests should be used to determine whether we can be\nconfident that one version of a classifier is better than another.\n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Designers of classifiers should carefully consider harms that may be caused\nby the model, including its training data and other components, and report\nmodel characteristics in a model card \n\n## Module 12 Lecture Notes\n SVM: Maximizing the margin: good according to intuition, theory, practice; \nOnly support vectors matter; other training examples are ignorable \n\nNon-Linear Separators: mapping data to a higher-dimensional space \n\n## Module 12 Definitions\n* **Loocv** - leave-one-out cross-validation\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n\nsigmoid: $\\sigma(z) = \frac{1}{1+e^{-z}}$ \n\n$1-\\sigma(x) = \\sigma(-x)$ \n\n$\\sigma'(x) = \\sigma(x)(1-\\sigma(x))$ \n\n\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 Cross Entropy Loss: $L(\\hat{y}, y) = -[ylog \\hat{y} + (1-y)log (1-\\hat{y})]$ where $\\hat{y}=sigmiod(wx+b)$\n\n\n## SLP Chapter 5.4 Gradient Descent\n SGD(Stochastic Gradient Descent) \n\n## SLP Chapter 5.5 Regularization\n L2 regularization: Euclidean distance \n\nL1 regularization: Manhattan distance \n\nL2 prefers weight vectors with many small weights, L1 prefers sparse solutions with some larger weights but many more weights set to zero. \n\n \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Softmax: $exp(z_i) / {\\sum_{j=1}^k exp(z_j)}$ \n\n## SLP Chapter 7.1 Units\n Unit: $z=b+\\sum_i w_i x_i $ \n\n## SLP Chapter 7.2 The XOR problem\n 2 layer network can solve XOR \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n non-linear activation functions: if we did not, the resulting network is exactly equivalent to\na single-layer network \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n  Neural language models represent words in this prior context by their embeddings,\nrather than just by their word identity as used in n-gram language models. \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n embedding layer, Multiply by W and activate, Multiply by U, Apply softmax \n\n## SLP Chapter 7.6 Training Neural Nets\n error backpropagation or\nbackward differentiation \n\n## SLP Chapter 7.7 Training the neural language model\n Neural language models use a neural network as a probabilistic classifier, to\ncompute the probability of the next word given the previous n words.  \n\n## Module 13 Lecture Notes\n Stochastic gradient descent chooses a single random example at a time and updates\nits weights on that example \n\nbatch training, which computes the gradient over the entire dataset \n\nmini-batch training: train on a small batch each time.\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 $PP_\\theta(w_{1:n}) = \\sqrt[n]{\\prod_{i=1}^n \\frac{1}{P_\\theta(w_i|w_{1:n-1})}}$ \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n RNN: $h_i \\leftarrow g(Uh_{i-1} + W_x_i)$ \n\n## SLP Chapter 9.3 RNNs as Language Models\n RNN language models process the input sequence one word at\na time, attempting to predict the next word from the current word and the previous\nhidden state. RNNs don’t have the limited context problem that n-gram models\nhave, since the hidden state can in principle represent information about all of the\npreceding words all the way back to the beginning of the sequence. \n\n## SLP Chapter 6.1 Lexical Semantics\n lexical semantics：linguistics side \n\n## SLP Chapter 6.2 Vector Semantics\n Vector Semantics: math side \n\n## SLP Chapter 6.3 Words and Vectors\n In a term-document matrix, each row represents a word in the vocabulary \nand each matrix column represents a document from some collection of documents. \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Word2vec embeddings are static embeddings,that learns one fixed embedding for each word in the embeddings vocabulary. \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Vector semantic models fall into two classes: sparse and dense. Word2vec algorithms\nlike skip-gram are a popular way to compute dense embeddings; sparse models (tf-idf) \n\n\n## SLP Chapter 6.12 Evaluating Vector Models\n The most common metric of NLP tasks\nis to test their performance on similarity \n\n## Module 13 Lecture Notes\n Stochastic gradient descent chooses a single random example at a time and updates\nits weights on that example \n\nbatch training, which computes the gradient over the entire dataset \n\nmini-batch training: train on a small batch each time.\n \n\n## Module 14 Definitions\n* **Sgns** - skip-gram with negative sampling\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}