{
  "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/"
        },
        "outputId": "d8efce99-33db-4fd6-e821-0fae19f62fdc"
      },
      "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": 39,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "255294bd-ef70-45f5-b02a-48986affd3a6"
      },
      "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": 40,
      "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": 41,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" Chapter 16.1 summary. \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\" \n",
        "utility or reward function: the agent can receive a reward at\n",
        "each time step, based on R(s', a, s). Rewards are additive, can be positive or negative.\n",
        "\n",
        "A Markov decision process or MDP is\n",
        "• a sequential decision problem\n",
        "• for a fully observable environment\n",
        "• with a stochastic transition model\n",
        "• that has additive rewards\n",
        "\n",
        "MDP:\n",
        "• states s ∈ S\n",
        "• actions a ∈ A\n",
        "• A transition function T(s, a, s’)\n",
        "• Probability  P(s' | s, a)\n",
        "• A reward function R(s, a, s’), or R(s) or R(s’)\n",
        "• An initial state s0\n",
        "• Optionally, one or more terminal states\n",
        "\n",
        "same policy can lead to different score due to stochastic environment.\n",
        "\n",
        "Infinite utilies: Finite horizon or discount or Absorbing state.\n",
        "\n",
        "Discounting: prefer good at first.\n",
        "\n",
        "\n",
        "Each MDP state projects an expectimax-like search tree. s is a state. (s, a) is a q-state. (s,a,s') is the line, called a transition T(s,a,s') = P(s’|s,a) * R(s,a,s')\n",
        "\n",
        "Value Iteration for Time-Limited Values: bottom V0(s) = 0, then Vk+1(s) = max_a(sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')])), Repeat until convergence\n",
        "\n",
        "O(S2A) per iteration\n",
        "\n",
        "• Policy may converge long before values do. \n",
        "The “max” at each state rarely changes\n",
        "\n",
        "convergence: maxdepth k or discount < 1\n",
        "\n",
        "Policy Evaluation: V𝝿(s) = expected total discounted rewards starting in s and following = sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')])\n",
        "\n",
        "O(S2) per iteration, a linear system.\n",
        "\n",
        "Policy improvement: update policy using one-step lookahead with resulting converged (but not optimal!) utilities as future\n",
        "values. \n",
        "• Repeat steps until policy converges\n",
        "\n",
        "add policy evaluation and improvement: policy iteration \n",
        "\n",
        "就是先用fixed policy\n",
        "\n",
        "得到一个在此policy下converge 的u\n",
        "\n",
        "然后再跑value evaluation更新policy\n",
        "\n",
        "Rational Preferences: order, trans, continu, substitu, monoto; lottery, indiffere, preferen\n",
        "\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",
        "\"transition function\": \"T(s',a, s) or as probability p(s'|s,a) which is also called model\",\n",
        "\"policy == solution\":\"maps from a state onto the action to take if the agent is in that state. 𝝿(s) = a. only one step\",\n",
        "\"optimal policy\":\"𝝿*\",\n",
        "\"utility function (reward function)\" : \"what the agent can get at each time step at s do a\",\n",
        "\"expected utility\" : \"EU(A) = SUM [ P(O(A,i)) * U(O(A,i)) ]\",\n",
        "\"utility\":\"sum of (discounted) rewards\",\n",
        "\"同上Sequences of Rewards (Utility function on an environment history)\":\"Uh([ s0, a0, s1, a1 …, sn])\",\n",
        "\"Markovian\": \"the probability of arriving in s’ only depends on s and not the history of earlier states.\",\n",
        "\"value (utility) of a state s\":\"V*(s) = expected utility starting in s and acting optimally\",\n",
        "\"value (utility) of a q-state (s,a)\":\"Q*(s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally\",\n",
        "\"Bellman equations\": \"max_a(sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')]))\",\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 42,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "5e44178b-07cd-4126-f409-f42f0f6da2ec"
      },
      "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": 43,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n \nutility or reward function: the agent can receive a reward at\neach time step, based on R(s', a, s). Rewards are additive, can be positive or negative.\n\nA Markov decision process or MDP is\n• a sequential decision problem\n• for a fully observable environment\n• with a stochastic transition model\n• that has additive rewards\n\nMDP:\n• states s ∈ S\n• actions a ∈ A\n• A transition function T(s, a, s’)\n• Probability  P(s' | s, a)\n• A reward function R(s, a, s’), or R(s) or R(s’)\n• An initial state s0\n• Optionally, one or more terminal states\n\nsame policy can lead to different score due to stochastic environment.\n\nInfinite utilies: Finite horizon or discount or Absorbing state.\n\nDiscounting: prefer good at first.\n\n\nEach MDP state projects an expectimax-like search tree. s is a state. (s, a) is a q-state. (s,a,s') is the line, called a transition T(s,a,s') = P(s’|s,a) * R(s,a,s')\n\nValue Iteration for Time-Limited Values: bottom V0(s) = 0, then Vk+1(s) = max_a(sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')])), Repeat until convergence\n\nO(S2A) per iteration\n\n• Policy may converge long before values do. \nThe “max” at each state rarely changes\n\nconvergence: maxdepth k or discount < 1\n\nPolicy Evaluation: V𝝿(s) = expected total discounted rewards starting in s and following = sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')])\n\nO(S2) per iteration, a linear system.\n\nPolicy improvement: update policy using one-step lookahead with resulting converged (but not optimal!) utilities as future\nvalues. \n• Repeat steps until policy converges\n\nadd policy evaluation and improvement: policy iteration \n\n就是先用fixed policy\n\n得到一个在此policy下converge 的u\n\n然后再跑value evaluation更新policy\n\nRational Preferences: order, trans, continu, substitu, monoto; lottery, indiffere, preferen\n\n\n\n\n## Module 8 Definitions\n* **Transition function** - T(s',a, s) or as probability p(s'|s,a) which is also called model\n* **Policy == solution** - maps from a state onto the action to take if the agent is in that state. 𝝿(s) = a. only one step\n* **Optimal policy** - 𝝿*\n* **Utility function (reward function)** - what the agent can get at each time step at s do a\n* **Expected utility** - EU(A) = SUM [ P(O(A,i)) * U(O(A,i)) ]\n* **Utility** - sum of (discounted) rewards\n* **同上sequences of rewards (utility function on an environment history)** - Uh([ s0, a0, s1, a1 …, sn])\n* **Markovian** - the probability of arriving in s’ only depends on s and not the history of earlier states.\n* **Value (utility) of a state s** - V*(s) = expected utility starting in s and acting optimally\n* **Value (utility) of a q-state (s,a)** - Q*(s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally\n* ** bellman equations** - max_a(sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')]))\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "chapter17_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_3 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_4 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_5 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\"\n",
        "MDP but probability unknown, not plan, not policy, but learning.\n",
        "\n",
        "Still assume a Markov decision process (MDP): \n",
        "A set of states s ∈ S \n",
        "A set of actions (per state) A \n",
        "A model T(s,a,s') \n",
        "A reward function R(s,a,s')\n",
        "\n",
        "Still looking for a policy π(s)\n",
        "\n",
        "But don't know T or R\n",
        "\n",
        "Problems with Direct Evaluation: wastes information about state connections, Each state must be learned separately, slow.\n",
        "\n",
        "\n",
        "\n",
        "Temporal Difference Learning is Exponential Moving Average, Decreasing learning rate (alpha) can give converging averages.\n",
        "\n",
        "But this is for value iteration, not q iteration, so hard to get policy.\n",
        "\n",
        "\n",
        "\n",
        "Active reinforcement learning, Q-Value Iteration: Start with Q0(s,a) = 0, Given Qk, calculate the depth k+1 q-values for all q-states:. Update the Qk+1 based on (1 - alpha) * Qk(s) + alpha * sample.\n",
        "\n",
        "Sample: R(s,a,s') + gamma * max Q(s',a')\n",
        "\n",
        "Q-learning converges to optimal policy -- even\n",
        "if you’re acting suboptimally!\n",
        "\n",
        "Q-learning called off-policy learning. You have to eventually make the learning rate\n",
        "small enough\n",
        "… but not decrease it too quickly.\n",
        "\n",
        "\n",
        "\n",
        "About how to banlance expolor and exploit: ε-greedy, ε act random, 1-ε exploit.\n",
        "And lower ε over time, or exploration functions.\n",
        "\n",
        "\n",
        "\n",
        "Explore areas whose badness is not (yet) established, eventually stop exploring.\n",
        "Takes a value estimate u and a visit count n, and\n",
        "returns an optimistic utility, so change the Q = R + f(u,n)\n",
        "\n",
        "\n",
        "\n",
        "Approximate Q-Learning: Basic Q-Learning keeps a table of all q-values. In realistic situations, we cannot possibly learn about every single state.\n",
        "\n",
        "Learn about some small number of training states from experience Generalize that experience to new, similar situations. Use Evaluation functions.\n",
        "\n",
        "Q(s,a) = w1 * f1(s,a) + w2 * f2(s,a) + ...\n",
        "\n",
        "wi = wi + alpha * difference * fi(s,a).    Difference = previous stored Q - current Q\n",
        "\n",
        "\n",
        "Passive Reinforcement Learning (model-free, Direct Evaluation) : Simplified task: policy evaluation. Act according to π, \n",
        "Every time you visit a state, write down what the sum of discounted rewards turned out to be. Average those samples, get V under pi\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"Exploration\": \"you have to try unknown actions to get information\",\n",
        "\"Exploitation\": \"eventually, you have to use what you know\",\n",
        "\"Regret\": \"even if you learn intelligently, you make mistakes\",\n",
        "\"Model-Based Learning\":\"Learn an approximate model based on experiences. Solve for values as if the learned model were correct, get T R\",\n",
        "\"Temporal Difference Learning\": \"Sample-Based Policy Evaluation, Vpi(s) = (1 - alpha) * Vpi(s) + alpha * sample\",\n",
        "\"Active Reinforcement Learning\": \"like value iteration, choose actions, Fundamental tradeoff: exploration vs. exploitation\",\n",
        "\"Regret\":\"a measure of your total mistake cost: the difference between your (expected) rewards, including youthful suboptimality, and optimal(expected) rewards\",\n",
        "\n",
        "}"
      ],
      "execution_count": 57,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "29cea7d9-3699-4f58-fdb5-fa72106118f8"
      },
      "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": 58,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\nMDP but probability unknown, not plan, not policy, but learning.\n\nStill assume a Markov decision process (MDP): \nA set of states s ∈ S \nA set of actions (per state) A \nA model T(s,a,s') \nA reward function R(s,a,s')\n\nStill looking for a policy π(s)\n\nBut don't know T or R\n\nProblems with Direct Evaluation: wastes information about state connections, Each state must be learned separately, slow.\n\n\n\nTemporal Difference Learning is Exponential Moving Average, Decreasing learning rate (alpha) can give converging averages.\n\nBut this is for value iteration, not q iteration, so hard to get policy.\n\n\n\nActive reinforcement learning, Q-Value Iteration: Start with Q0(s,a) = 0, Given Qk, calculate the depth k+1 q-values for all q-states:. Update the Qk+1 based on (1 - alpha) * Qk(s) + alpha * sample.\n\nSample: R(s,a,s') + gamma * max Q(s',a')\n\nQ-learning converges to optimal policy -- even\nif you’re acting suboptimally!\n\nQ-learning called off-policy learning. You have to eventually make the learning rate\nsmall enough\n… but not decrease it too quickly.\n\n\n\nAbout how to banlance expolor and exploit: ε-greedy, ε act random, 1-ε exploit.\nAnd lower ε over time, or exploration functions.\n\n\n\nExplore areas whose badness is not (yet) established, eventually stop exploring.\nTakes a value estimate u and a visit count n, and\nreturns an optimistic utility, so change the Q = R + f(u,n)\n\n\n\nApproximate Q-Learning: Basic Q-Learning keeps a table of all q-values. In realistic situations, we cannot possibly learn about every single state.\n\nLearn about some small number of training states from experience Generalize that experience to new, similar situations. Use Evaluation functions.\n\nQ(s,a) = w1 * f1(s,a) + w2 * f2(s,a) + ...\n\nwi = wi + alpha * difference * fi(s,a).    Difference = previous stored Q - current Q\n\n\nPassive Reinforcement Learning (model-free, Direct Evaluation) : Simplified task: policy evaluation. Act according to π, \nEvery time you visit a state, write down what the sum of discounted rewards turned out to be. Average those samples, get V under pi\n\n\n\n## Module 9 Definitions\n* **Exploration** - you have to try unknown actions to get information\n* **Exploitation** - eventually, you have to use what you know\n* **Regret** - a measure of your total mistake cost: the difference between your (expected) rewards, including youthful suboptimality, and optimal(expected) rewards\n* **Model-based learning** - Learn an approximate model based on experiences. Solve for values as if the learned model were correct, get T R\n* **Temporal difference learning** - Sample-Based Policy Evaluation, Vpi(s) = (1 - alpha) * Vpi(s) + alpha * sample\n* **Active reinforcement learning** - like value iteration, choose actions, Fundamental tradeoff: exploration vs. exploitation\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\"\n",
        "In probability theory, the possible worlds are called the sample space, and they mutually exclusive and exhaustive. \n",
        "\n",
        "\n",
        "\n",
        "A fully specified probability model associates a probability P(w) with each possible world w.\n",
        "\n",
        "\n",
        "\n",
        "Probabilistic models: \n",
        "• (Random) variables with domains \n",
        "• Assignments are called outcomes \n",
        "• Joint distributions: say whether \n",
        "assignments (outcomes) are likely \n",
        "• Normalized: sum to 1.0 \n",
        "• Ideally: only certain variables directly interact \n",
        "\n",
        "\n",
        "\n",
        "Conditional Probabilities: P(a|b) = P(a,b) / P(b). • These represent the agent’s beliefs given the evidence, observing new evidence causes beliefs to be update.\n",
        "\n",
        "\n",
        "\n",
        "Product rule: P(y)P(x|y) = P(x,y)\n",
        "\n",
        "\n",
        "\n",
        "Chain rule: write any joint distribution as an incremental product of conditional distributions.\n",
        "P(x1, x2, x3) = P(x1) * P(x2|x1) * P(x3|x1, x2)\n",
        "\n",
        "\n",
        "\n",
        "Bayes'Rule: P(x|y) = P(y|x) / P(y) * P(x)\n",
        "\n",
        "\n",
        "\n",
        "Simplifying Assumption = Markov Assumption for LM, K = num of context words, including the historic and the estimation. \n",
        "If 1, Unigram, no historic, but one estimation.\n",
        "If 2, Bigram, one historic.\n",
        "\n",
        "\n",
        "\n",
        "for bigram, P(wi|wi-1) = C(wi-1, wi) / C(wi-1)\n",
        "\n",
        "\n",
        "\n",
        "MLE cons: zeros. \n",
        "\n",
        "\n",
        "\n",
        "Smooth it. Also do everything in log space.\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"Observed variables (evidence)\": \"Agent knows certain things about the state of the world (e.g. sensor readings or symptoms)\",\n",
        "\"Unobserved variables (states)\": \"Agent needs to reason about other aspects (e.g. where an object is or what disease is present)\",\n",
        "\"Model\": \"Agent knows something about how the known variables relate to the unknown variables\",\n",
        "\"Event\": \"An event is a set E of outcomes\",\n",
        "\"Marginal distributions\": \"sub-tables which eliminate variables\",\n",
        "\"Probabilistic Inference\": \"compute a desired probability from other known probabilities\",\n",
        "\"language model or LM\": \"compute the probability of a sentence or sequence of words, P(wn|w1,w2…wn-1)\",\n",
        "\n",
        "\n",
        "}"
      ],
      "execution_count": 46,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "2e1c418d-ebfd-4781-a0e4-2dcc2406cb8c"
      },
      "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": 47,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n\nIn probability theory, the possible worlds are called the sample space, and they mutually exclusive and exhaustive. \n\n\n\nA fully specified probability model associates a probability P(w) with each possible world w.\n\n\n\nProbabilistic models: \n• (Random) variables with domains \n• Assignments are called outcomes \n• Joint distributions: say whether \nassignments (outcomes) are likely \n• Normalized: sum to 1.0 \n• Ideally: only certain variables directly interact \n\n\n\nConditional Probabilities: P(a|b) = P(a,b) / P(b). • These represent the agent’s beliefs given the evidence, observing new evidence causes beliefs to be update.\n\n\n\nProduct rule: P(y)P(x|y) = P(x,y)\n\n\n\nChain rule: write any joint distribution as an incremental product of conditional distributions.\nP(x1, x2, x3) = P(x1) * P(x2|x1) * P(x3|x1, x2)\n\n\n\nBayes'Rule: P(x|y) = P(y|x) / P(y) * P(x)\n\n\n\nSimplifying Assumption = Markov Assumption for LM, K = num of context words, including the historic and the estimation. \nIf 1, Unigram, no historic, but one estimation.\nIf 2, Bigram, one historic.\n\n\n\nfor bigram, P(wi|wi-1) = C(wi-1, wi) / C(wi-1)\n\n\n\nMLE cons: zeros. \n\n\n\nSmooth it. Also do everything in log space.\n\n\n\n\n## Module 10 Definitions\n* **Observed variables (evidence)** - Agent knows certain things about the state of the world (e.g. sensor readings or symptoms)\n* **Unobserved variables (states)** - Agent needs to reason about other aspects (e.g. where an object is or what disease is present)\n* **Model** - Agent knows something about how the known variables relate to the unknown variables\n* **Event** - An event is a set E of outcomes\n* **Marginal distributions** - sub-tables which eliminate variables\n* **Probabilistic inference** - compute a desired probability from other known probabilities\n* **Language model or lm** - compute the probability of a sentence or sequence of words, P(wn|w1,w2…wn-1)\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" \n",
        "Bayes’nets / graphical models help us express conditional independence assumptions\n",
        "A Bayes net = Topology (graph) + Local Conditional Probabilities\n",
        "Bayes’ nets implicitly encode joint distributions\n",
        "1. As a product of local conditional distributions\n",
        "2. To see what probability a BN gives to a full assignment, multiply all the relevant conditionals together\n",
        "3. reflect correlation or causation\n",
        "4. O(N * 2k+1) n node with up to k parents instead of O(2^N), very space-saving\n",
        "\n",
        "\n",
        "Nodes: variables (with domains)\n",
        "1. Can be assigned (observed) or unassigned (unobserved)\n",
        "\n",
        "Arcs: interactions\n",
        "1. Indicate “direct influence” between variables\n",
        "2. Formally: encode conditional independence\n",
        "\n",
        "\n",
        "\n",
        "P(x,y,z) = P(x) * P(y|x) * P(z|y) does not mean x and z are independent, but x and z are conditional independent given y\n",
        "\n",
        "\n",
        "\n",
        "D_seperation/Active / Inactive Paths: at least one inavctive = path inactive\n",
        "all active  = path active\n",
        "IF all paths inactive = independence\n",
        "\n",
        "\n",
        "\n",
        "Given a Bayes net structure, can run dseparation algorithm to build a complete list of conditional independences that are necessarily true of the form\n",
        "\n",
        "\n",
        "Inference by Enumeration vs. Variable Elimination (still NP hard, bust fast)\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"independence\" : \"P(x,y) = P(x) * P(y)  or  P(x|y) = P(x)\",   \n",
        "\"conditional independence\":\"P(x,y|z) = P(x|z) * P(y|z) if x and y are conditional independent given z\",\n",
        "\"Bayes' nets\": \"a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities)\",\n",
        "\n",
        "}\n"
      ],
      "execution_count": 48,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 790
        },
        "cellView": "form",
        "outputId": "fdb3b635-c415-404f-d90f-cd74aa674241"
      },
      "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": 49,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n \nBayes’nets / graphical models help us express conditional independence assumptions\nA Bayes net = Topology (graph) + Local Conditional Probabilities\nBayes’ nets implicitly encode joint distributions\n1. As a product of local conditional distributions\n2. To see what probability a BN gives to a full assignment, multiply all the relevant conditionals together\n3. reflect correlation or causation\n4. O(N * 2k+1) n node with up to k parents instead of O(2^N), very space-saving\n\n\nNodes: variables (with domains)\n1. Can be assigned (observed) or unassigned (unobserved)\n\nArcs: interactions\n1. Indicate “direct influence” between variables\n2. Formally: encode conditional independence\n\n\n\nP(x,y,z) = P(x) * P(y|x) * P(z|y) does not mean x and z are independent, but x and z are conditional independent given y\n\n\n\nD_seperation/Active / Inactive Paths: at least one inavctive = path inactive\nall active  = path active\nIF all paths inactive = independence\n\n\n\nGiven a Bayes net structure, can run dseparation algorithm to build a complete list of conditional independences that are necessarily true of the form\n\n\nInference by Enumeration vs. Variable Elimination (still NP hard, bust fast)\n\n\n\n \n\n## Module 11 Definitions\n* **Independence** - P(x,y) = P(x) * P(y)  or  P(x|y) = P(x)\n* **Conditional independence** - P(x,y|z) = P(x|z) * P(y|z) if x and y are conditional independent given z\n* **Bayes' nets** - a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities)\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\"\n",
        "Total number of parameters is linear in number of features\n",
        "Goal: compute posterior distribution over label variable Y\n",
        "\n",
        "\n",
        "\n",
        "“Tied” distributions and bag-of-words: \n",
        "each variable gets its own conditional probability distribution P(F|Y)\n",
        "In a bag-of-words model\n",
        "• Each position is identically distributed\n",
        "• All positions share the same conditional probs P(W|Y)\n",
        "\n",
        "\n",
        "Overfitting: smooth or regularize\n",
        "\n",
        "\n",
        "Laplace Smoothing: every count add 1 (or k), total count add X or (kX)\n",
        "\n",
        "\n",
        "Linear Interpolation: P = alpha * P + (1-alpha)*newP\n",
        "\n",
        "\n",
        "For real research, usually use previous work as a (strong) baseline\n",
        "\n",
        "\n",
        "The confidence of a probabilistic classifier:\n",
        "\n",
        "Posterior over the top label\n",
        "\n",
        "can predict accuracy, but not 100% related.\n",
        "\n",
        "\n",
        "Naïve Bayes models can incorporate a variety of features, but tend to do best in homogeneous cases (e.g. all features are\n",
        "word occurrences)\n",
        "\n",
        "\n",
        "\n",
        "perceptron: if wrong, w += f\n",
        "for multiple classes, if wrong, for the true class, w += f, for the wrong class, w -= f\n",
        "\n",
        "\n",
        "Mistake Bound: the maximum number of mistakes\n",
        "(binary case) related to the margin or degree of\n",
        "separability: mistack < k/delta^2\n",
        "\n",
        "\n",
        "MIRA = Margin Infused Relaxed Algorithm\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"Naïve Bayes\": \"Assume all features are independent effects of the label\",\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 50,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "324df021-6aa7-4747-cf9c-f75ea1e4bc40"
      },
      "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": 51,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\nTotal number of parameters is linear in number of features\nGoal: compute posterior distribution over label variable Y\n\n\n\n“Tied” distributions and bag-of-words: \neach variable gets its own conditional probability distribution P(F|Y)\nIn a bag-of-words model\n• Each position is identically distributed\n• All positions share the same conditional probs P(W|Y)\n\n\nOverfitting: smooth or regularize\n\n\nLaplace Smoothing: every count add 1 (or k), total count add X or (kX)\n\n\nLinear Interpolation: P = alpha * P + (1-alpha)*newP\n\n\nFor real research, usually use previous work as a (strong) baseline\n\n\nThe confidence of a probabilistic classifier:\n\nPosterior over the top label\n\ncan predict accuracy, but not 100% related.\n\n\nNaïve Bayes models can incorporate a variety of features, but tend to do best in homogeneous cases (e.g. all features are\nword occurrences)\n\n\n\nperceptron: if wrong, w += f\nfor multiple classes, if wrong, for the true class, w += f, for the wrong class, w -= f\n\n\nMistake Bound: the maximum number of mistakes\n(binary case) related to the margin or degree of\nseparability: mistack < k/delta^2\n\n\nMIRA = Margin Infused Relaxed Algorithm\n\n\n\n## Module 12 Definitions\n* **Naïve bayes** - Assume all features are independent effects of the label\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" \n",
        "Get z, add it to the activation function!\n",
        "\n",
        "MSE loss: 0.5 (y_pred - y)^2\n",
        "\n",
        "Conditional maximum likelihood estimation: Choose parameters w, b that maximize the (log) probabilities of the true labels in the training data.\n",
        "The resulting loss function is the negative log likelihood loss, more commonly called the cross entropy loss.\n",
        "\n",
        "the probability of the correct label p(y|x) is y_pred ^ y * (1 - y_pred) ^ (1 - y) Try to max it -> try to max its log -> try to minimize the negative log which is cross-entrop loss.\n",
        "\n",
        "On all training labels, add their loss.\n",
        "\n",
        "For logistic regression, this loss function is conveniently convex\n",
        "\n",
        "Lasso regression uses L1 regularization\n",
        "Ridge regression uses L2 regularization \n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 52,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "918d3354-82ce-4035-8c43-4aaf7c40078d"
      },
      "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": 53,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n \nGet z, add it to the activation function!\n\nMSE loss: 0.5 (y_pred - y)^2\n\nConditional maximum likelihood estimation: Choose parameters w, b that maximize the (log) probabilities of the true labels in the training data.\nThe resulting loss function is the negative log likelihood loss, more commonly called the cross entropy loss.\n\nthe probability of the correct label p(y|x) is y_pred ^ y * (1 - y_pred) ^ (1 - y) Try to max it -> try to max its log -> try to minimize the negative log which is cross-entrop loss.\n\nOn all training labels, add their loss.\n\nFor logistic regression, this loss function is conveniently convex\n\nLasso regression uses L1 regularization\nRidge regression uses L2 regularization \n\n\n\n \n\n## Module 13 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\"\n",
        "Besides N-gram, we also want to know the meanings of words, like \n",
        "1. Synonyms – words that have similar meanings \n",
        "2. Antonyms – words that have opposite meanings \n",
        "3. Connotations – words that are positive or negative \n",
        "4. Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event \n",
        "5. Support for entailment (Lexical Semantics, hierarchy, wordNet or Vector Space Models)\n",
        "\n",
        "\n",
        "\n",
        "Word simlarity is not synonym. Distributional Hypothesis. \n",
        "\n",
        "\n",
        "\n",
        "Term-Document Matrix (row-word, col-document, sparse), \n",
        "can for how similar two documents are or how similar two words are, plagiarism detection.\n",
        "\n",
        "\n",
        "\n",
        "Vector Space Models: normalization like L2 needed. Simlarity get from cosine angle or eucliedean distance.\n",
        "\n",
        "\n",
        "\n",
        "Term-Term Matrix: The value in a cell indicates how often word A appears in a context window surrounding word B (Context windows, usually +/- 2 words,) AKA Term-Context Matrix.\n",
        "Instead of window of words use more complex contexts: dependency patters. Subj-of-verb, adj-mod, obj-of-verb\n",
        "\n",
        "\n",
        "\n",
        "Besides counts of words to determine similarity, use transforms of word counts, like TF-IDF (term frequency * inverse document frequency).\n",
        "\n",
        "\n",
        "\n",
        "Co-occurrence matrix too long and sparse, an improvement is \n",
        "\n",
        "\n",
        "\n",
        "Neural Language Models\n",
        "\n",
        "\n",
        "\n",
        "n-gram cons: two many dimensions, fail to generalize to related words / word sequences that we have observed.\n",
        "\n",
        "\n",
        "\n",
        "Neural Language models have several advantages over n-gram LMs:\n",
        "1. They don't need smoothing\n",
        "2. They can handle much longer histories.\n",
        "3. They can generalize over contexts of similar words.\n",
        "4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs\n",
        "But slow.\n",
        "\n",
        "\n",
        "\n",
        "Neural LM;\n",
        "1. Associate each word in the vocabulary with a vector-representation to get similarity as well\n",
        "2. Express the joint probability function of a word sequence in terms of the word vectors for the words in that sequence. (Initialize it with singular value decomposition (SVD))\n",
        "3. Simultaneously learn the word vectors and the parameters of the function.\n",
        "Traning is to \n",
        "\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 54,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "18ab351b-5c8f-427e-9125-5c7a5385498a"
      },
      "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 14 Lecture Notes\", module14_lecture_notes),\n",
        "]\n",
        "\n",
        "module14_markdown = format_module(14, \"Natural Language Processing\", \n",
        "                         module14_sections, \n",
        "                         module14_definitions)\n",
        "display(Markdown(module14_markdown))"
      ],
      "execution_count": 55,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 14 Lecture Notes\n\nBesides N-gram, we also want to know the meanings of words, like \n1. Synonyms – words that have similar meanings \n2. Antonyms – words that have opposite meanings \n3. Connotations – words that are positive or negative \n4. Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event \n5. Support for entailment (Lexical Semantics, hierarchy, wordNet or Vector Space Models)\n\n\n\nWord simlarity is not synonym. Distributional Hypothesis. \n\n\n\nTerm-Document Matrix (row-word, col-document, sparse), \ncan for how similar two documents are or how similar two words are, plagiarism detection.\n\n\n\nVector Space Models: normalization like L2 needed. Simlarity get from cosine angle or eucliedean distance.\n\n\n\nTerm-Term Matrix: The value in a cell indicates how often word A appears in a context window surrounding word B (Context windows, usually +/- 2 words,) AKA Term-Context Matrix.\nInstead of window of words use more complex contexts: dependency patters. Subj-of-verb, adj-mod, obj-of-verb\n\n\n\nBesides counts of words to determine similarity, use transforms of word counts, like TF-IDF (term frequency * inverse document frequency).\n\n\n\nCo-occurrence matrix too long and sparse, an improvement is \n\n\n\nNeural Language Models\n\n\n\nn-gram cons: two many dimensions, fail to generalize to related words / word sequences that we have observed.\n\n\n\nNeural Language models have several advantages over n-gram LMs:\n1. They don't need smoothing\n2. They can handle much longer histories.\n3. They can generalize over contexts of similar words.\n4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs\nBut slow.\n\n\n\nNeural LM;\n1. Associate each word in the vocabulary with a vector-representation to get similarity as well\n2. Express the joint probability function of a word sequence in terms of the word vectors for the words in that sequence. (Initialize it with singular value decomposition (SVD))\n3. Simultaneously learn the word vectors and the parameters of the function.\nTraning is to \n\n\n\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "2201c661-8d36-426c-f7ac-eb683af12356"
      },
      "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": 56,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n \nutility or reward function: the agent can receive a reward at\neach time step, based on R(s', a, s). Rewards are additive, can be positive or negative.\n\nA Markov decision process or MDP is\n• a sequential decision problem\n• for a fully observable environment\n• with a stochastic transition model\n• that has additive rewards\n\nMDP:\n• states s ∈ S\n• actions a ∈ A\n• A transition function T(s, a, s’)\n• Probability  P(s' | s, a)\n• A reward function R(s, a, s’), or R(s) or R(s’)\n• An initial state s0\n• Optionally, one or more terminal states\n\nsame policy can lead to different score due to stochastic environment.\n\nInfinite utilies: Finite horizon or discount or Absorbing state.\n\nDiscounting: prefer good at first.\n\n\nEach MDP state projects an expectimax-like search tree. s is a state. (s, a) is a q-state. (s,a,s') is the line, called a transition T(s,a,s') = P(s’|s,a) * R(s,a,s')\n\nValue Iteration for Time-Limited Values: bottom V0(s) = 0, then Vk+1(s) = max_a(sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')])), Repeat until convergence\n\nO(S2A) per iteration\n\n• Policy may converge long before values do. \nThe “max” at each state rarely changes\n\nconvergence: maxdepth k or discount < 1\n\nPolicy Evaluation: V𝝿(s) = expected total discounted rewards starting in s and following = sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')])\n\nO(S2) per iteration, a linear system.\n\nPolicy improvement: update policy using one-step lookahead with resulting converged (but not optimal!) utilities as future\nvalues. \n• Repeat steps until policy converges\n\nadd policy evaluation and improvement: policy iteration \n\n就是先用fixed policy\n\n得到一个在此policy下converge 的u\n\n然后再跑value evaluation更新policy\n\nRational Preferences: order, trans, continu, substitu, monoto; lottery, indiffere, preferen\n\n\n\n\n## Module 8 Definitions\n* **Transition function** - T(s',a, s) or as probability p(s'|s,a) which is also called model\n* **Policy == solution** - maps from a state onto the action to take if the agent is in that state. 𝝿(s) = a. only one step\n* **Optimal policy** - 𝝿*\n* **Utility function (reward function)** - what the agent can get at each time step at s do a\n* **Expected utility** - EU(A) = SUM [ P(O(A,i)) * U(O(A,i)) ]\n* **Utility** - sum of (discounted) rewards\n* **同上sequences of rewards (utility function on an environment history)** - Uh([ s0, a0, s1, a1 …, sn])\n* **Markovian** - the probability of arriving in s’ only depends on s and not the history of earlier states.\n* **Value (utility) of a state s** - V*(s) = expected utility starting in s and acting optimally\n* **Value (utility) of a q-state (s,a)** - Q*(s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally\n* ** bellman equations** - max_a(sum_s'(T(s,a,s')[R(s,a,s') + gamma * Vk(s')]))\n\n\n## WARNING: Your definition of 'Passive Reinforcement Learning (model-free, Direct Evaluation)' is too long!\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\nMDP but probability unknown, not plan, not policy, but learning.\n\nStill assume a Markov decision process (MDP): \nA set of states s ∈ S \nA set of actions (per state) A \nA model T(s,a,s') \nA reward function R(s,a,s')\n\nStill looking for a policy π(s)\n\nBut don't know T or R\n\nProblems with Direct Evaluation: wastes information about state connections, Each state must be learned separately, slow.\n\n\n\nTemporal Difference Learning is Exponential Moving Average, Decreasing learning rate (alpha) can give converging averages.\n\nBut this is for value iteration, not q iteration, so hard to get policy.\n\n\n\nActive reinforcement learning, Q-Value Iteration: Start with Q0(s,a) = 0, Given Qk, calculate the depth k+1 q-values for all q-states:. Update the Qk+1 based on (1 - alpha) * Qk(s) + alpha * sample.\n\nSample: R(s,a,s') + gamma * max Q(s',a')\n\nQ-learning converges to optimal policy -- even\nif you’re acting suboptimally!\n\nQ-learning called off-policy learning. You have to eventually make the learning rate\nsmall enough\n… but not decrease it too quickly.\n\n\n\nAbout how to banlance expolor and exploit: ε-greedy, ε act random, 1-ε exploit.\nAnd lower ε over time, or exploration functions.\n\n\n\nExplore areas whose badness is not (yet) established, eventually stop exploring.\nTakes a value estimate u and a visit count n, and\nreturns an optimistic utility, so change the Q = R + f(u,n)\n\n\n\nApproximate Q-Learning: Basic Q-Learning keeps a table of all q-values. In realistic situations, we cannot possibly learn about every single state.\n\nLearn about some small number of training states from experience Generalize that experience to new, similar situations. Use Evaluation functions.\n\nQ(s,a) = w1 * f1(s,a) + w2 * f2(s,a) + ...\n\nwi = wi + alpha * difference * fi(s,a).    Difference = previous stored Q - current Q\n\n\n\n\n\n\n\n## Module 9 Definitions\n* **Exploration** - you have to try unknown actions to get information\n* **Exploitation** - eventually, you have to use what you know\n* **Regret** - a measure of your total mistake cost: the difference between your (expected) rewards, including youthful suboptimality, and optimal(expected) rewards\n* **Model-based learning** - Learn an approximate model based on experiences. Solve for values as if the learned model were correct, get T R\n* **Passive reinforcement learning (model-free, direct evaluation)** - Simplified task: policy evaluation. Act according to π, Every time you visit a state, write down what the sum of discounted rewards turned out to be. Average those samples, get V under pi\n* **Temporal difference learning** - Sample-Based Policy Evaluation, Vpi(s) = (1 - alpha) * Vpi(s) + alpha * sample\n* **Active reinforcement learning** - like value iteration, choose actions, Fundamental tradeoff: exploration vs. exploitation\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n\nIn probability theory, the possible worlds are called the sample space, and they mutually exclusive and exhaustive. \n\n\n\nA fully specified probability model associates a probability P(w) with each possible world w.\n\n\n\nProbabilistic models: \n• (Random) variables with domains \n• Assignments are called outcomes \n• Joint distributions: say whether \nassignments (outcomes) are likely \n• Normalized: sum to 1.0 \n• Ideally: only certain variables directly interact \n\n\n\nConditional Probabilities: P(a|b) = P(a,b) / P(b). • These represent the agent’s beliefs given the evidence, observing new evidence causes beliefs to be update.\n\n\n\nProduct rule: P(y)P(x|y) = P(x,y)\n\n\n\nChain rule: write any joint distribution as an incremental product of conditional distributions.\nP(x1, x2, x3) = P(x1) * P(x2|x1) * P(x3|x1, x2)\n\n\n\nBayes'Rule: P(x|y) = P(y|x) / P(y) * P(x)\n\n\n\nSimplifying Assumption = Markov Assumption for LM, K = num of context words, including the historic and the estimation. \nIf 1, Unigram, no historic, but one estimation.\nIf 2, Bigram, one historic.\n\n\n\nfor bigram, P(wi|wi-1) = C(wi-1, wi) / C(wi-1)\n\n\n\nMLE cons: zeros. \n\n\n\nSmooth it. Also do everything in log space.\n\n\n\n\n## Module 10 Definitions\n* **Observed variables (evidence)** - Agent knows certain things about the state of the world (e.g. sensor readings or symptoms)\n* **Unobserved variables (states)** - Agent needs to reason about other aspects (e.g. where an object is or what disease is present)\n* **Model** - Agent knows something about how the known variables relate to the unknown variables\n* **Event** - An event is a set E of outcomes\n* **Marginal distributions** - sub-tables which eliminate variables\n* **Probabilistic inference** - compute a desired probability from other known probabilities\n* **Language model or lm** - compute the probability of a sentence or sequence of words, P(wn|w1,w2…wn-1)\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n \nBayes’nets / graphical models help us express conditional independence assumptions\nA Bayes net = Topology (graph) + Local Conditional Probabilities\nBayes’ nets implicitly encode joint distributions\n1. As a product of local conditional distributions\n2. To see what probability a BN gives to a full assignment, multiply all the relevant conditionals together\n3. reflect correlation or causation\n4. O(N * 2k+1) n node with up to k parents instead of O(2^N), very space-saving\n\n\nNodes: variables (with domains)\n1. Can be assigned (observed) or unassigned (unobserved)\n\nArcs: interactions\n1. Indicate “direct influence” between variables\n2. Formally: encode conditional independence\n\n\n\nP(x,y,z) = P(x) * P(y|x) * P(z|y) does not mean x and z are independent, but x and z are conditional independent given y\n\n\n\nD_seperation/Active / Inactive Paths: at least one inavctive = path inactive\nall active  = path active\nIF all paths inactive = independence\n\n\n\nGiven a Bayes net structure, can run dseparation algorithm to build a complete list of conditional independences that are necessarily true of the form\n\n\nInference by Enumeration vs. Variable Elimination (still NP hard, bust fast)\n\n\n\n \n\n## Module 11 Definitions\n* **Independence** - P(x,y) = P(x) * P(y)  or  P(x|y) = P(x)\n* **Conditional independence** - P(x,y|z) = P(x|z) * P(y|z) if x and y are conditional independent given z\n* **Bayes' nets** - a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities)\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\nTotal number of parameters is linear in number of features\nGoal: compute posterior distribution over label variable Y\n\n\n\n“Tied” distributions and bag-of-words: \neach variable gets its own conditional probability distribution P(F|Y)\nIn a bag-of-words model\n• Each position is identically distributed\n• All positions share the same conditional probs P(W|Y)\n\n\nOverfitting: smooth or regularize\n\n\nLaplace Smoothing: every count add 1 (or k), total count add X or (kX)\n\n\nLinear Interpolation: P = alpha * P + (1-alpha)*newP\n\n\nFor real research, usually use previous work as a (strong) baseline\n\n\nThe confidence of a probabilistic classifier:\n\nPosterior over the top label\n\ncan predict accuracy, but not 100% related.\n\n\nNaïve Bayes models can incorporate a variety of features, but tend to do best in homogeneous cases (e.g. all features are\nword occurrences)\n\n\n\nperceptron: if wrong, w += f\nfor multiple classes, if wrong, for the true class, w += f, for the wrong class, w -= f\n\n\nMistake Bound: the maximum number of mistakes\n(binary case) related to the margin or degree of\nseparability: mistack < k/delta^2\n\n\nMIRA = Margin Infused Relaxed Algorithm\n\n\n\n## Module 12 Definitions\n* **Naïve bayes** - Assume all features are independent effects of the label\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n \nGet z, add it to the activation function!\n\nMSE loss: 0.5 (y_pred - y)^2\n\nConditional maximum likelihood estimation: Choose parameters w, b that maximize the (log) probabilities of the true labels in the training data.\nThe resulting loss function is the negative log likelihood loss, more commonly called the cross entropy loss.\n\nthe probability of the correct label p(y|x) is y_pred ^ y * (1 - y_pred) ^ (1 - y) Try to max it -> try to max its log -> try to minimize the negative log which is cross-entrop loss.\n\nOn all training labels, add their loss.\n\nFor logistic regression, this loss function is conveniently convex\n\nLasso regression uses L1 regularization\nRidge regression uses L2 regularization \n\n\n\n \n\n## Module 13 Definitions\n* **Concept** - definition\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 14 Lecture Notes\n\nBesides N-gram, we also want to know the meanings of words, like \n1. Synonyms – words that have similar meanings \n2. Antonyms – words that have opposite meanings \n3. Connotations – words that are positive or negative \n4. Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event \n5. Support for entailment (Lexical Semantics, hierarchy, wordNet or Vector Space Models)\n\n\n\nWord simlarity is not synonym. Distributional Hypothesis. \n\n\n\nTerm-Document Matrix (row-word, col-document, sparse), \ncan for how similar two documents are or how similar two words are, plagiarism detection.\n\n\n\nVector Space Models: normalization like L2 needed. Simlarity get from cosine angle or eucliedean distance.\n\n\n\nTerm-Term Matrix: The value in a cell indicates how often word A appears in a context window surrounding word B (Context windows, usually +/- 2 words,) AKA Term-Context Matrix.\nInstead of window of words use more complex contexts: dependency patters. Subj-of-verb, adj-mod, obj-of-verb\n\n\n\nBesides counts of words to determine similarity, use transforms of word counts, like TF-IDF (term frequency * inverse document frequency).\n\n\n\nCo-occurrence matrix too long and sparse, an improvement is \n\n\n\nNeural Language Models\n\n\n\nn-gram cons: two many dimensions, fail to generalize to related words / word sequences that we have observed.\n\n\n\nNeural Language models have several advantages over n-gram LMs:\n1. They don't need smoothing\n2. They can handle much longer histories.\n3. They can generalize over contexts of similar words.\n4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs\nBut slow.\n\n\n\nNeural LM;\n1. Associate each word in the vocabulary with a vector-representation to get similarity as well\n2. Express the joint probability function of a word sequence in terms of the word vectors for the words in that sequence. (Initialize it with singular value decomposition (SVD))\n3. Simultaneously learn the word vectors and the parameters of the function.\nTraning is to \n\n\n\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}