{
  "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": "08147b3f-8a6b-4ae9-c7d5-44a6cae1acc1"
      },
      "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": 48,
      "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": "c1176ff4-9931-453c-a32a-6f2e89059b6f"
      },
      "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": 49,
      "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 = \"Yuxuan Zhang\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": 50,
      "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 = \"\"\"\n",
        "\n",
        "\"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\"\n",
        "Stochastic Transition Model: T(s,a,s’), with p(s’|s,a): The probability of arriving in state s', given that we are in state s and select action a.\\\n",
        "Reward function: agent recieves reward at each step, based on its transition from s to s’ via action a R(s,a,s’). Postivie or negative, and additive. \\\n",
        "MDP components: set of states and actions, Transition function T(s,a,s’) and p(s’|s, a), \\\n",
        "Reward function R(s, a, s), Initial state s0, one or more terminal states. \\\n",
        "The same policy may generate different (s, a) if excuted many times, thus different rewards, need expected utility of all paths generated by a policy. \\\n",
        "Performance of an agent in MDP is sum of rewards for the transitions it takes: Uh([s0, a0, s1, a1 ……, sn])=R(s0, a0, s1) + R(s1, a1, s2)+ … +R(sn-1, an-1, sn) \\\n",
        "Uh: Utility function of a history, which is a sequence of states and actions.\\\n",
        "Discounted utility: U=r0 + yr1 + y^2r2... The smaller y, the more focus on short term.\\\n",
        "Prevent infinite utilities: 1: set step limit, 2:pi depends on time left (non-stationary policy), 3: discounting, 4: Absorbing state: guarantee that for every policy,\\\n",
        "a terminal state will eventually be reached.\\\n",
        "Optimal Quantities (acting optimally): value of a state s V*(s): expected utility from s;\\\n",
        "Value of a q-state (s, a): Q*(s,a): expected utility from s having taken a.\\\n",
        "policy: pi*(s): optimal action from s.\\\n",
        "Value iteration: start with V0(s)=0, compute Vk+1(s) until convergence. Complexity: O(S^2A).\\\n",
        "Problem: Too slow, max at each state rarely changes, Policy converges long before values.\\\n",
        "Utility for a fixed policy: Vpi(x) = 1 step look-ahead Bellman Eqn with pi.\\\n",
        "Policy evaluation (using fixed policy): 1, turn recursive into updates, like value iteration: O(S^2). 2, without maxes, linear system. \\\n",
        "Policy extraction: 1, pi*(s) = argmax(a) Bellman. one-step mini-expctimax; 2, pi*(s) = argmax(a) Q*(s, a), easier to select.\\\n",
        "Policy iteration: 1, policy evaluation for some action until convergence; 2, policy improvement using Policy extraction; repeate until converge.\\\n",
        "Converge much faster.\n",
        "Lottery: L[P, A; (1-P), B]\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any bolded term in the textbook, \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",
        "\"Markovian\" : \"Prob of arriving s' only depends on s, not history.\", \n",
        "\"MDP\" : \"non-deterministic, Sequential problem, fully observable, stocastic transitoin, additive rewards.\",\n",
        "\"utility function\" : \"Function that assign a single number to express the desirability of a state\",\n",
        "\"expected utility\" : \"average utility of outcomes weighted by probability.\",\n",
        "\"Policy\": \"Solution of MDP: tells the agent what action to take at state s, 𝝿(s) = a. Optimal: 𝝿*\",\n",
        "\"Discount\" : \"rewards decay exponentially as steps being further.\",\n",
        "\"Time-limited values\" : \"Vk(s), optimal value of s if game ends in k more steps\",\n",
        "\"MEU principle\" : \"A rational agent should choose the action that maximizes its expected utility given its knowledge\",\n",
        "\"Lotteries\" : \"Lotteries: situations with uncertain prizes\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 51,
      "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": 914
        },
        "outputId": "7b0b695f-a659-4f6c-ea98-27caa44a1f84",
        "cellView": "form"
      },
      "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": 52,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n\n\n $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n\nStochastic Transition Model: T(s,a,s’), with p(s’|s,a): The probability of arriving in state s', given that we are in state s and select action a.Reward function: agent recieves reward at each step, based on its transition from s to s’ via action a R(s,a,s’). Postivie or negative, and additive. MDP components: set of states and actions, Transition function T(s,a,s’) and p(s’|s, a), Reward function R(s, a, s), Initial state s0, one or more terminal states. The same policy may generate different (s, a) if excuted many times, thus different rewards, need expected utility of all paths generated by a policy. Performance of an agent in MDP is sum of rewards for the transitions it takes: Uh([s0, a0, s1, a1 ……, sn])=R(s0, a0, s1) + R(s1, a1, s2)+ … +R(sn-1, an-1, sn) Uh: Utility function of a history, which is a sequence of states and actions.Discounted utility: U=r0 + yr1 + y^2r2... The smaller y, the more focus on short term.Prevent infinite utilities: 1: set step limit, 2:pi depends on time left (non-stationary policy), 3: discounting, 4: Absorbing state: guarantee that for every policy,a terminal state will eventually be reached.Optimal Quantities (acting optimally): value of a state s V*(s): expected utility from s;Value of a q-state (s, a): Q*(s,a): expected utility from s having taken a.policy: pi*(s): optimal action from s.Value iteration: start with V0(s)=0, compute Vk+1(s) until convergence. Complexity: O(S^2A).Problem: Too slow, max at each state rarely changes, Policy converges long before values.Utility for a fixed policy: Vpi(x) = 1 step look-ahead Bellman Eqn with pi.Policy evaluation (using fixed policy): 1, turn recursive into updates, like value iteration: O(S^2). 2, without maxes, linear system. Policy extraction: 1, pi*(s) = argmax(a) Bellman. one-step mini-expctimax; 2, pi*(s) = argmax(a) Q*(s, a), easier to select.Policy iteration: 1, policy evaluation for some action until convergence; 2, policy improvement using Policy extraction; repeate until converge.Converge much faster.\nLottery: L[P, A; (1-P), B]\n\n\n## Module 8 Definitions\n* **Markovian** - Prob of arriving s' only depends on s, not history.\n* **Mdp** - non-deterministic, Sequential problem, fully observable, stocastic transitoin, additive rewards.\n* **Utility function** - Function that assign a single number to express the desirability of a state\n* **Expected utility** - average utility of outcomes weighted by probability.\n* **Policy** - Solution of MDP: tells the agent what action to take at state s, 𝝿(s) = a. Optimal: 𝝿*\n* **Discount** - rewards decay exponentially as steps being further.\n* **Time-limited values** - Vk(s), optimal value of s if game ends in k more steps\n* **Meu principle** - A rational agent should choose the action that maximizes its expected utility given its knowledge\n* **Lotteries** - Lotteries: situations with uncertain prizes\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",
        "Basic idea: get rewards from environment, defined by reward function, maximize rewards, based on sampling.\\\n",
        "Still MDP, but don't know transition model and reward function, must try, \"online\".\\\n",
        "Model-based learning: 1, learn empirical MDP model (estimate T and R); 2, solve MDP.\\\n",
        "Passive RL: just do actions and learn from experience.\\\n",
        "Direct evaluation: according to a policy pi, average all the discounted rewards from it. Problem: waste information about state connections, takes long time.\\\n",
        "Temporal difference learning: update V(s) each time experience transition, running average. \\\n",
        "Exponential moving average (learning rate): Decreasing learning rate (alpha) can give converging averages. Problem: sunk when turn into policy. \\\n",
        "Q-learning(active RL): sample-based Q-value iteration. 1, receive sample; 2, old estimate: Q(s,a); 3, new estimate: sample = R+ymax(a')Q(s',a');\\\n",
        "4, incorporate new estimate into a running average: Q(s,a)<-(1-a)Q(s,a)+a[sample].\\\n",
        "Need to explore enough, learning rate small enough.\\\n",
        "Problem with E-greedy: may keep thrashing around once learning is done, can lower E over time, or using exploration function.\n",
        "exploration function: takes estimate U and visit count n return optimistic utility: f=u+k/n\\\n",
        "Regret:a mesure of total mistake cost. Both random exploration and exploration functions are optimal, but random exploration has higher regret.\\\n",
        "Approximate Q-learning: Q-learning has a table of all Q-valuese, cannot learn all states. Use linear Q functions. \\\n",
        "Advantage: only summing up a few powerful numbers. Disadvantage: similar states may have very different values.\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"offline planning\" : \"Solving MDP: need to know the detail, not actually playing\",\n",
        "\"onfline planning\" : \"RL: need to actually act to find details\",\n",
        "\"running interpolation update\" : \"xn=a*xn+(1-a)*x(n-1)\",\n",
        "\"Exponential moving average\" : \"xn=[a*xn+(1-a)*x(n-1)+(1-a)^2*x(n-2)..] / [1+(1-a)+(1-a)^2...], recent samples more important\",\n",
        "\"off-policy learning\" : \"Q-learning converges to optimal policy even if acting suboptimally\",\n",
        "\"E-greedy\" : \"exploration: with prob E, act randomly; with prob 1-E, act current policy.\",\n",
        "\"regret\" : \"expected rewards - optimal rewards\",\n",
        "}"
      ],
      "execution_count": 53,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 822
        },
        "cellView": "form",
        "outputId": "7e56d71b-44fd-439a-ccee-a4b18aa307bf"
      },
      "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": 54,
      "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\nBasic idea: get rewards from environment, defined by reward function, maximize rewards, based on sampling.Still MDP, but don't know transition model and reward function, must try, \"online\".Model-based learning: 1, learn empirical MDP model (estimate T and R); 2, solve MDP.Passive RL: just do actions and learn from experience.Direct evaluation: according to a policy pi, average all the discounted rewards from it. Problem: waste information about state connections, takes long time.Temporal difference learning: update V(s) each time experience transition, running average. Exponential moving average (learning rate): Decreasing learning rate (alpha) can give converging averages. Problem: sunk when turn into policy. Q-learning(active RL): sample-based Q-value iteration. 1, receive sample; 2, old estimate: Q(s,a); 3, new estimate: sample = R+ymax(a')Q(s',a');4, incorporate new estimate into a running average: Q(s,a)<-(1-a)Q(s,a)+a[sample].Need to explore enough, learning rate small enough.Problem with E-greedy: may keep thrashing around once learning is done, can lower E over time, or using exploration function.\nexploration function: takes estimate U and visit count n return optimistic utility: f=u+k/nRegret:a mesure of total mistake cost. Both random exploration and exploration functions are optimal, but random exploration has higher regret.Approximate Q-learning: Q-learning has a table of all Q-valuese, cannot learn all states. Use linear Q functions. Advantage: only summing up a few powerful numbers. Disadvantage: similar states may have very different values.\n\n\n## Module 9 Definitions\n* **Offline planning** - Solving MDP: need to know the detail, not actually playing\n* **Onfline planning** - RL: need to actually act to find details\n* **Running interpolation update** - xn=a*xn+(1-a)*x(n-1)\n* **Exponential moving average** - xn=[a*xn+(1-a)*x(n-1)+(1-a)^2*x(n-2)..] / [1+(1-a)+(1-a)^2...], recent samples more important\n* **Off-policy learning** - Q-learning converges to optimal policy even if acting suboptimally\n* **E-greedy** - exploration: with prob E, act randomly; with prob 1-E, act current policy.\n* **Regret** - expected rewards - optimal rewards\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",
        "Possible worlds also called Sample space, which is mutually exclusive and exhaustive.\\\n",
        "Axioms of prob: 0<=p<=1, sum(p(w))=1.\\\n",
        "Unobserved random variables have distributions.\\\n",
        "Joint distribution: specifies a real number for each random vars (P(X1=x1, X2=x2..)).\\\n",
        "Size of joint distribution of n random vars with domain sizes d: d^n, impractical to write out full table.\\\n",
        "Probabilistic model: random vars with domains, outcomes, joint distribution, must normalized.\\\n",
        "Conditional prob: P(a|b)=P(a,b)/p(b).\\\n",
        "Prob inference: generally compute conditional prob, observing changes with new evidence.\\\n",
        "Inference by enumeration: Vars: evidence vars E, query vars Q, hidden vars H. Want: P(Q|e1,e2..ek).\\\n",
        "Steps:1, select entries consistent with evidence; 2. sum H to get P(Q,e1,e2..ek); 3. Normalize, P(Q|e1,e2..ek)=1/Z *P(Q,e1,e2..ek).\\\n",
        "Probabilistic Language Models: goal is to compute a probability to a sentence or sequence of words: autocomplete for texing, machine translation,\\\n",
        "spelling correction, speech recognization.\\\n",
        "Computing P(W): Use Chain Rule: P(w1,w2..wn)=product(i)P(wi|w1,w2..wi-1).\\\n",
        "Problem of just count and divide: some sentences may not appear, need huge dataset.\\\n",
        "Need Markov Assumption: prob of moving to next state only depends on previous k words, not the whole context.\\\n",
        "P(won|the underdog team) ~ P(won|team), P(w1,w2..wn)~product(i)P(wi|wi-k..wi-1).\\\n",
        "Consider k words as history: k+1 gram. Unigram: no history; bigram: 1 word; trigram: 2 words.\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"Observed variables (evidence)\" : \"Certain things the agent knows about the world\",\n",
        "\"Unobserved variables (states)\" : \"Certain things the agent needs to reason about\",\n",
        "\"Model\" : \"Agent knows some relations between known and unknown variables\",\n",
        "\"Random Variables\" : \"Things with uncertainty, denoted as capital letters\",\n",
        "\"Distribution\" : \"A table of prob of values\",\n",
        "\"Probabilistic model\" : \"A joint distribution over set of random vars\",\n",
        "\"Event\" : \"A set of outcomes\",\n",
        "\"Marginal Distribution\" : \"A sub-table of summing out a variable: P(T) from P(T,W)\",\n",
        "\"Conditional Distribution\" : \"Distribution that some vars given fixed.\",\n",
        "\"Probabilistic Inference\" : \"Get desired prob from known prob (e.g. condition from joint)\",\n",
        "\"Product Rule\" : \"P(y)*P(x|y)=P(x,y)\",\n",
        "\"Chain Rule\" : \"P(x1,x2,x3)=P(x1)*P(x2|x1)*P(x3|x1,x2)\",\n",
        "\"Bayes' Rule\" : \"P(x|y)=P(y|x)/P(y) * P(x)\",\n",
        "\"Language model\" : \"Model that computes P(W1,W2,w3..) or P(Wn|W1,W2..)\",\n",
        "\"MLE\" : \"Maximum likelihood estimation\",\n",
        "}"
      ],
      "execution_count": 55,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "67e9d470-b5db-490a-ffea-89909206e262"
      },
      "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": 56,
      "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\nPossible worlds also called Sample space, which is mutually exclusive and exhaustive.Axioms of prob: 0<=p<=1, sum(p(w))=1.Unobserved random variables have distributions.Joint distribution: specifies a real number for each random vars (P(X1=x1, X2=x2..)).Size of joint distribution of n random vars with domain sizes d: d^n, impractical to write out full table.Probabilistic model: random vars with domains, outcomes, joint distribution, must normalized.Conditional prob: P(a|b)=P(a,b)/p(b).Prob inference: generally compute conditional prob, observing changes with new evidence.Inference by enumeration: Vars: evidence vars E, query vars Q, hidden vars H. Want: P(Q|e1,e2..ek).Steps:1, select entries consistent with evidence; 2. sum H to get P(Q,e1,e2..ek); 3. Normalize, P(Q|e1,e2..ek)=1/Z *P(Q,e1,e2..ek).Probabilistic Language Models: goal is to compute a probability to a sentence or sequence of words: autocomplete for texing, machine translation,spelling correction, speech recognization.Computing P(W): Use Chain Rule: P(w1,w2..wn)=product(i)P(wi|w1,w2..wi-1).Problem of just count and divide: some sentences may not appear, need huge dataset.Need Markov Assumption: prob of moving to next state only depends on previous k words, not the whole context.P(won|the underdog team) ~ P(won|team), P(w1,w2..wn)~product(i)P(wi|wi-k..wi-1).Consider k words as history: k+1 gram. Unigram: no history; bigram: 1 word; trigram: 2 words.\n\n\n## Module 10 Definitions\n* **Observed variables (evidence)** - Certain things the agent knows about the world\n* **Unobserved variables (states)** - Certain things the agent needs to reason about\n* **Model** - Agent knows some relations between known and unknown variables\n* **Random variables** - Things with uncertainty, denoted as capital letters\n* **Distribution** - A table of prob of values\n* **Probabilistic model** - A joint distribution over set of random vars\n* **Event** - A set of outcomes\n* **Marginal distribution** - A sub-table of summing out a variable: P(T) from P(T,W)\n* **Conditional distribution** - Distribution that some vars given fixed.\n* **Probabilistic inference** - Get desired prob from known prob (e.g. condition from joint)\n* **Product rule** - P(y)*P(x|y)=P(x,y)\n* **Chain rule** - P(x1,x2,x3)=P(x1)*P(x2|x1)*P(x3|x1,x2)\n* **Bayes' rule** - P(x|y)=P(y|x)/P(y) * P(x)\n* **Language model** - Model that computes P(W1,W2,w3..) or P(Wn|W1,W2..)\n* **Mle** - Maximum likelihood estimation\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",
        "(Conditinal) independence is a property of a distribution.\\\n",
        "Prob of full joint distribution: too big to represent, hard to estimate more than a few vars at a time.\\\n",
        "Bayes' nets: also called graphical models, used to describe complex joint distributions \\\n",
        "with simple local distributions (conditional probs).\\\n",
        "Node: random vars (with domains); Arc: interactions (conditional probs).\\\n",
        "Semantics: set of nodes,directed acyclic graph, conditional distribution for each node of all parents \\\n",
        "P(x|a1..an). A Bayes net=Topology(graph)+local conditional probs.\\\n",
        "To know joint distributions: compute product of local conditional probs (P(xi|parents(xi))).\\\n",
        "BN enforces certain conditional independencies, can't represent every joint distribution.\\\n",
        "BN need not actually be causal, can be correlation. Topology really encodes conditional independence.\\\n",
        "Assumptions when defining the BNs:.\\\n",
        "1. Often additional conditional independences; 2. they can be read off the graph.\\\n",
        "Causal chain/Common Cause: not guarantee X independent Z, but X independent of Z given Y.\\\n",
        "Common Effect: X, Y are independent, but not independent given Z.\\\n",
        "X,Y are conditionally independent given Z, if all paths are inactive.\\\n",
        "D(descendant)-separation algorithm: look paths between Xi and Xj, checks for inactive triples.\\\n",
        "Inference by Enumeration in BN:P(B|+j,+m) is proportional to P(B,+j,+m)=sum of hidden=sum of products of conditional probs.\\\n",
        "Can be slow, since join up whole joint distribution before suming hidden vars.\n",
        "Use Variable Elimination: interleave joining and marginalizing, faster.\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"(Unconditioanlly) Independent\" : \"iff P(x,y)=P(x)*P(y), rare\",\n",
        "\"Conditionally Independent\" : \"iff P(x,y|z)=P(x|z)*P(y|z), or P(x|z,y)=P(x|z) useful for inference\",\n",
        "\"CPT\" : \"conditional probability table\",\n",
        "\"size\" : \"Joint distribution over N vars: 2^N; N-node net up to K parents: O(N*2^(k+1))\",\n",
        "\"Causal Chain\" : \"X->Y->Z, P(x,y,z)=P(x)*P(y|x)*P(z|y)\",\n",
        "\"Common Cause\" : \"Y->X, Y->Z, P(x,y,z)=P(y)*P(x|y)*P(z|y)\",\n",
        "\"Common Effect\" : \"v-structure, X->Z, Y->Z\",\n",
        "\"Reachability\" : \"Is there's a path between 2 nodes\",\n",
        "\"Active path\" : \"every triple is active along the path\",\n",
        "\"Inference\" : \"get useful quantity from a joint prob distribution\",\n",
        "}\n"
      ],
      "execution_count": 57,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 740
        },
        "cellView": "form",
        "outputId": "0c897513-b84f-4a9b-f411-3f4fdb9caf78"
      },
      "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": 58,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\n(Conditinal) independence is a property of a distribution.Prob of full joint distribution: too big to represent, hard to estimate more than a few vars at a time.Bayes' nets: also called graphical models, used to describe complex joint distributions with simple local distributions (conditional probs).Node: random vars (with domains); Arc: interactions (conditional probs).Semantics: set of nodes,directed acyclic graph, conditional distribution for each node of all parents P(x|a1..an). A Bayes net=Topology(graph)+local conditional probs.To know joint distributions: compute product of local conditional probs (P(xi|parents(xi))).BN enforces certain conditional independencies, can't represent every joint distribution.BN need not actually be causal, can be correlation. Topology really encodes conditional independence.Assumptions when defining the BNs:.1. Often additional conditional independences; 2. they can be read off the graph.Causal chain/Common Cause: not guarantee X independent Z, but X independent of Z given Y.Common Effect: X, Y are independent, but not independent given Z.X,Y are conditionally independent given Z, if all paths are inactive.D(descendant)-separation algorithm: look paths between Xi and Xj, checks for inactive triples.Inference by Enumeration in BN:P(B|+j,+m) is proportional to P(B,+j,+m)=sum of hidden=sum of products of conditional probs.Can be slow, since join up whole joint distribution before suming hidden vars.\nUse Variable Elimination: interleave joining and marginalizing, faster.\n\n\n## Module 11 Definitions\n* **(unconditioanlly) independent** - iff P(x,y)=P(x)*P(y), rare\n* **Conditionally independent** - iff P(x,y|z)=P(x|z)*P(y|z), or P(x|z,y)=P(x|z) useful for inference\n* **Cpt** - conditional probability table\n* **Size** - Joint distribution over N vars: 2^N; N-node net up to K parents: O(N*2^(k+1))\n* **Causal chain** - X->Y->Z, P(x,y,z)=P(x)*P(y|x)*P(z|y)\n* **Common cause** - Y->X, Y->Z, P(x,y,z)=P(y)*P(x|y)*P(z|y)\n* **Common effect** - v-structure, X->Z, Y->Z\n* **Reachability** - Is there's a path between 2 nodes\n* **Active path** - every triple is active along the path\n* **Inference** - get useful quantity from a joint prob distribution\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\"\n",
        "Model-based classification: build model of label and features and instantiate observed features.\\\n",
        "Query the distribution of label on features.\\\n",
        "Naive Bayes: assume all features are independent effects of label.\\\n",
        "Need to learn priorier prob and conditional probs.\\\n",
        "General Naive Bayes model: P(Y, F1...FN)=P(Y)*product(P(Fi|Y)). |Y|*|F|^n values become.\\\n",
        "n*|F|*|Y| parameters, only need how features depends on the class and linear number, but model very simple, may be not accurate.\\\n",
        "Goal: compute posterior distribution over label Y. Steps: 1, get joint prob of label and evidence P(Y,f1..fn);\\\n",
        "2, sum to get prob of evidence: P(f1...fn); 3, normalize, divide step 1 by 2 to get P(Y|f1..fn).\\\n",
        "Use inference to estimate local conditional prob tables.\\\n",
        "Split data into training set, held out set, test set. Learn parameters from training set, turn hyperparameters on held-out set,\\\n",
        "compute accuracy of test set.\\\n",
        "Parameter estimation: estimate the distribution of a random var from training data.\\\n",
        "Maximum likelihood: P(x)=count(x)/total sample, L(x, t)=product(Pt(xi)). select t maximizes L.\\\n",
        "Problem: unseen events, use Laplase smoothing, but may performs poorly for P(x|y) when X or Y is large.\\\n",
        "Use linear interpolation: P(x|y)=aP'(x|y)+(1-a)p'(x).\\\n",
        "Tuning hyper parameters: k and a.\\\n",
        "Perceptron notation change: 1. sum(wj*xj)~W·X； 2.bias=-threshold, wx>threshold ~ w·x+b>0\n",
        "Fix features, tune weight vectors.\\\n",
        "Binary decision rule: examples are points, f·w split to positive and negative.\\\n",
        "Start with weights=0, in training if wrong adjust weight vector by add(y=1) or subtract(y=-1) feature vector.\\\n",
        "Multiclass Decision rule: weight vector for each class, score class as w·f, predict highest score wins y=argmax(y)wy·f(x).\\\n",
        "Start with weights=0, if wrong, lower/raise score of wrong/right answer.\\\n",
        "Problem of perceptron: if data isn't separable, weights might thrash: need averaging weight vectors over time;\\\n",
        "Mediocre generalization that barely separating; overtraining: early stopping.\\\n",
        "MIRA: find update size that fixes the current mistake but minimizing weight change.\\\n",
        "Maximum step size: cap the maximum possible value of tau with some constant C.\\\n",
        "Support vector machines (SVM):check separater with each items that maximize the margin.\\\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"Overfitting\" : \"Fitting the training set too closely but not generalized.\",\n",
        "\"Laplase smoothing\" : \"pretent see everything once more/k times more.\",\n",
        "\"Separability\" : \"true if some parameters get training perfectly correct\",\n",
        "\"convergence\" : \"perceptron will eventrally convergy in binary case if separable\",\n",
        "\"Mistake Bound\" : \"Max number of mistakes in binary case, related to the margin or degree of separability, mistakes<k/b^2\",\n",
        "\"MIRA\": \"Margin Infused Relaxed Algorithm\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 59,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "1b812521-6015-4eff-ba23-e4e43e32b545"
      },
      "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": 60,
      "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\nModel-based classification: build model of label and features and instantiate observed features.Query the distribution of label on features.Naive Bayes: assume all features are independent effects of label.Need to learn priorier prob and conditional probs.General Naive Bayes model: P(Y, F1...FN)=P(Y)*product(P(Fi|Y)). |Y|*|F|^n values become.n*|F|*|Y| parameters, only need how features depends on the class and linear number, but model very simple, may be not accurate.Goal: compute posterior distribution over label Y. Steps: 1, get joint prob of label and evidence P(Y,f1..fn);2, sum to get prob of evidence: P(f1...fn); 3, normalize, divide step 1 by 2 to get P(Y|f1..fn).Use inference to estimate local conditional prob tables.Split data into training set, held out set, test set. Learn parameters from training set, turn hyperparameters on held-out set,compute accuracy of test set.Parameter estimation: estimate the distribution of a random var from training data.Maximum likelihood: P(x)=count(x)/total sample, L(x, t)=product(Pt(xi)). select t maximizes L.Problem: unseen events, use Laplase smoothing, but may performs poorly for P(x|y) when X or Y is large.Use linear interpolation: P(x|y)=aP'(x|y)+(1-a)p'(x).Tuning hyper parameters: k and a.Perceptron notation change: 1. sum(wj*xj)~W·X； 2.bias=-threshold, wx>threshold ~ w·x+b>0\nFix features, tune weight vectors.Binary decision rule: examples are points, f·w split to positive and negative.Start with weights=0, in training if wrong adjust weight vector by add(y=1) or subtract(y=-1) feature vector.Multiclass Decision rule: weight vector for each class, score class as w·f, predict highest score wins y=argmax(y)wy·f(x).Start with weights=0, if wrong, lower/raise score of wrong/right answer.Problem of perceptron: if data isn't separable, weights might thrash: need averaging weight vectors over time;Mediocre generalization that barely separating; overtraining: early stopping.MIRA: find update size that fixes the current mistake but minimizing weight change.Maximum step size: cap the maximum possible value of tau with some constant C.Support vector machines (SVM):check separater with each items that maximize the margin.\n\n\n## Module 12 Definitions\n* **Overfitting** - Fitting the training set too closely but not generalized.\n* **Laplase smoothing** - pretent see everything once more/k times more.\n* **Separability** - true if some parameters get training perfectly correct\n* **Convergence** - perceptron will eventrally convergy in binary case if separable\n* **Mistake bound** - Max number of mistakes in binary case, related to the margin or degree of separability, mistakes<k/b^2\n* **Mira** - Margin Infused Relaxed Algorithm\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",
        "Components of classifier: Feature vector[x1,x2..xn], classification function computing \\\n",
        "class y^ via P(y|x), objective function for learning, algorithm for optimizing objective function. \\\n",
        "Also training corpus of M observations input/out pairs.\\\n",
        "Sentiment classifier: output 1(positive) or 0(negative). LR solves it by learning z=w·x+b.\\\n",
        "Compared to perceptron, LR squish z with sigmoid function(y=1/(1+e^-z)=1/(1+e^-(w·x+b))).\\\n",
        "Make decision: y^=1 if P(y=1|x)>0.5, 0 otherwise. 0.5 is called decision boundary.\\\n",
        "Learning weight and bias: 1, need cross-entropy loss; 2, use stochastic gradient descent to minimize the loss function.\\\n",
        "Mean Squared Error:L=1/2(y^-y)^2, not very good.\\\n",
        "Loss function for prob classification: need to choose parameters w,b that maximize the log prob of true labels.\\\n",
        "Cross entropy loss (negative log lokelihood loss):p(y|x)=y'^y * (1-y')^(1-y).\\\n",
        "Lce= -log p(y|x)= -[ylogy' + (1-y)log(1-y')], plug y'=sig(w·x+b). Want it to be small when estimate is correct,\\\n",
        "big if it's confused. Loss on all training examples: sum all Lce.\\\n",
        "Gradient descent: find weights and bias by minimizing the loss function.\\\n",
        "For LR, the loss function is convex, no local minima so guaranteed to find minimum.\\\n",
        "Size of step: learning rate eta.\\\n",
        "The gradient delta: take derivative of loss function for a single weight.\\\n",
        "What we want to minimize: Average loss.\\\n",
        "Mini-batch training: choose random example and updates weights.\\\n",
        "Regularization: penalize large weights. Lasso: L1 regularization; Ridge: L2 regularization.\\\n",
        "Multinominal LR: use softmax function.\\\n",
        "Feed-forward NN: multilayer, all units are fully-connected with no cycles. So all outputs pass to next layer.\\\n",
        "Training NN: need loss function, optimization algorithm(gradient descent), way of computing \\\n",
        "the gradient of loss function(error propagation).\\\n",
        "Compute the gradient of deep NN: look back through all the earlier layers.\\\n",
        "Error back propagation: use chain rule of derivative to compute gradient of the loss function.\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"Loss function\" : \"Determine how the classifier output differs to correct output.\",    \n",
        "\"Gradient descent\" : \"Find minimum of a function by finding which direction the slope is rising most steeply\",\n",
        "\"Smoothness\" : \"small changes in weight and bias will only cause little change to the output from neuron\",\n",
        "\"Activation function\" : \"Apply non-linear function to z=w·x+b: Sigmoid, tanh, rectified linear unit ReLU\"\n",
        "}\n"
      ],
      "execution_count": 61,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "c60015bc-dec3-4fc4-e8a7-2e4cebdf9b96"
      },
      "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": 62,
      "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\nComponents of classifier: Feature vector[x1,x2..xn], classification function computing class y^ via P(y|x), objective function for learning, algorithm for optimizing objective function. Also training corpus of M observations input/out pairs.Sentiment classifier: output 1(positive) or 0(negative). LR solves it by learning z=w·x+b.Compared to perceptron, LR squish z with sigmoid function(y=1/(1+e^-z)=1/(1+e^-(w·x+b))).Make decision: y^=1 if P(y=1|x)>0.5, 0 otherwise. 0.5 is called decision boundary.Learning weight and bias: 1, need cross-entropy loss; 2, use stochastic gradient descent to minimize the loss function.Mean Squared Error:L=1/2(y^-y)^2, not very good.Loss function for prob classification: need to choose parameters w,b that maximize the log prob of true labels.Cross entropy loss (negative log lokelihood loss):p(y|x)=y'^y * (1-y')^(1-y).Lce= -log p(y|x)= -[ylogy' + (1-y)log(1-y')], plug y'=sig(w·x+b). Want it to be small when estimate is correct,big if it's confused. Loss on all training examples: sum all Lce.Gradient descent: find weights and bias by minimizing the loss function.For LR, the loss function is convex, no local minima so guaranteed to find minimum.Size of step: learning rate eta.The gradient delta: take derivative of loss function for a single weight.What we want to minimize: Average loss.Mini-batch training: choose random example and updates weights.Regularization: penalize large weights. Lasso: L1 regularization; Ridge: L2 regularization.Multinominal LR: use softmax function.Feed-forward NN: multilayer, all units are fully-connected with no cycles. So all outputs pass to next layer.Training NN: need loss function, optimization algorithm(gradient descent), way of computing the gradient of loss function(error propagation).Compute the gradient of deep NN: look back through all the earlier layers.Error back propagation: use chain rule of derivative to compute gradient of the loss function.\n\n\n## Module 13 Definitions\n* **Loss function** - Determine how the classifier output differs to correct output.\n* **Gradient descent** - Find minimum of a function by finding which direction the slope is rising most steeply\n* **Smoothness** - small changes in weight and bias will only cause little change to the output from neuron\n* **Activation function** - Apply non-linear function to z=w·x+b: Sigmoid, tanh, rectified linear unit ReLU\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",
        "Advantages of neural LMs over n-gram LMs: don't need smoothing, handle longer histories, generalize over \n",
        "contexts of similar words, have higher predictive accuracy, better preplexity scores, larger N. Disadvantage: slower. \\\n",
        "Neural LMs: vector-represent words, express joint prob of word sequence with word vectors, \\\n",
        "learn vectors and parameters of the function. Use multi-layer, feed forward NN. \\\n",
        "Input: k-gram words w1:k, output: prob distribution over hte next word.\\\n",
        "Unseen sequences: generalizing, assign probs to similar sentences.\\\n",
        "Word meaning: synonyms(similar), antonyms(opposite), connotations(positive or negative), semantic roles(different parts of same background), entailment(dog, animal).\\\n",
        "Term-document matrix: rows are words, cols are documents, a cell represent how often that term occured in that doc.\\\n",
        "vector L2 normalization: L2 length: sqrt of sum of squares, devide each vector by L2.\\\n",
        "Cosien distance: Get cos angle between 2 vectors, Also does L2 normalization.\\\n",
        "Term-Term matrix (Term-context): words versus words, a cell represent how often a word occured in a context window surrounding the other word. Context windows: ww target_ward ww.\\\n",
        "Documents created by term-by-document or term-context matrices are long and sparse.\\\n",
        "Dense vector works better: shorter vectors are easier to use as features, generalize better, do better at capturing synonymy.\n",
        "Meaning can be lost since long distance dependencies. Use syntax to define a word's context. \\\n",
        "Alternates to word counts: transform vectors using TF-IDF or PPMI.\\\n",
        "Co-occurrence matrix: long/sparse, alternative: learn short/dence vectors. \\\n",
        "To get dense vectors: train a classifier, treat target word and a neighbor as positive, \\\n",
        "randomly sample other negative words, use LR to distinguish, use the weights as embeddings.\\\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"TF-IDF\" : \"Term frequency * inverse document frequency (1 over num of documents that it occurred in).\",\n",
        "\"Sparse/Dense vector\" : \"most elements are 0/non-0\",   \n",
        "\"vector space models\" : \"Term-document matrix\",   \n",
        "}\n",
        "\n"
      ],
      "execution_count": 63,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "236fb311-bc47-4d37-bcce-31a2aadc1f53"
      },
      "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": 64,
      "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\nAdvantages of neural LMs over n-gram LMs: don't need smoothing, handle longer histories, generalize over \ncontexts of similar words, have higher predictive accuracy, better preplexity scores, larger N. Disadvantage: slower. Neural LMs: vector-represent words, express joint prob of word sequence with word vectors, learn vectors and parameters of the function. Use multi-layer, feed forward NN. Input: k-gram words w1:k, output: prob distribution over hte next word.Unseen sequences: generalizing, assign probs to similar sentences.Word meaning: synonyms(similar), antonyms(opposite), connotations(positive or negative), semantic roles(different parts of same background), entailment(dog, animal).Term-document matrix: rows are words, cols are documents, a cell represent how often that term occured in that doc.vector L2 normalization: L2 length: sqrt of sum of squares, devide each vector by L2.Cosien distance: Get cos angle between 2 vectors, Also does L2 normalization.Term-Term matrix (Term-context): words versus words, a cell represent how often a word occured in a context window surrounding the other word. Context windows: ww target_ward ww.Documents created by term-by-document or term-context matrices are long and sparse.Dense vector works better: shorter vectors are easier to use as features, generalize better, do better at capturing synonymy.\nMeaning can be lost since long distance dependencies. Use syntax to define a word's context. Alternates to word counts: transform vectors using TF-IDF or PPMI.Co-occurrence matrix: long/sparse, alternative: learn short/dence vectors. To get dense vectors: train a classifier, treat target word and a neighbor as positive, randomly sample other negative words, use LR to distinguish, use the weights as embeddings.\n\n## Module 14 Definitions\n* **Tf-idf** - Term frequency * inverse document frequency (1 over num of documents that it occurred in).\n* **Sparse/dense vector** - most elements are 0/non-0\n* **Vector space models** - Term-document matrix\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": "75c98328-fb41-47b2-c558-cb5a4489fe1b"
      },
      "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": 65,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n\n\n $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n\nStochastic Transition Model: T(s,a,s’), with p(s’|s,a): The probability of arriving in state s', given that we are in state s and select action a.Reward function: agent recieves reward at each step, based on its transition from s to s’ via action a R(s,a,s’). Postivie or negative, and additive. MDP components: set of states and actions, Transition function T(s,a,s’) and p(s’|s, a), Reward function R(s, a, s), Initial state s0, one or more terminal states. The same policy may generate different (s, a) if excuted many times, thus different rewards, need expected utility of all paths generated by a policy. Performance of an agent in MDP is sum of rewards for the transitions it takes: Uh([s0, a0, s1, a1 ……, sn])=R(s0, a0, s1) + R(s1, a1, s2)+ … +R(sn-1, an-1, sn) Uh: Utility function of a history, which is a sequence of states and actions.Discounted utility: U=r0 + yr1 + y^2r2... The smaller y, the more focus on short term.Prevent infinite utilities: 1: set step limit, 2:pi depends on time left (non-stationary policy), 3: discounting, 4: Absorbing state: guarantee that for every policy,a terminal state will eventually be reached.Optimal Quantities (acting optimally): value of a state s V*(s): expected utility from s;Value of a q-state (s, a): Q*(s,a): expected utility from s having taken a.policy: pi*(s): optimal action from s.Value iteration: start with V0(s)=0, compute Vk+1(s) until convergence. Complexity: O(S^2A).Problem: Too slow, max at each state rarely changes, Policy converges long before values.Utility for a fixed policy: Vpi(x) = 1 step look-ahead Bellman Eqn with pi.Policy evaluation (using fixed policy): 1, turn recursive into updates, like value iteration: O(S^2). 2, without maxes, linear system. Policy extraction: 1, pi*(s) = argmax(a) Bellman. one-step mini-expctimax; 2, pi*(s) = argmax(a) Q*(s, a), easier to select.Policy iteration: 1, policy evaluation for some action until convergence; 2, policy improvement using Policy extraction; repeate until converge.Converge much faster.\nLottery: L[P, A; (1-P), B]\n\n\n## Module 8 Definitions\n* **Markovian** - Prob of arriving s' only depends on s, not history.\n* **Mdp** - non-deterministic, Sequential problem, fully observable, stocastic transitoin, additive rewards.\n* **Utility function** - Function that assign a single number to express the desirability of a state\n* **Expected utility** - average utility of outcomes weighted by probability.\n* **Policy** - Solution of MDP: tells the agent what action to take at state s, 𝝿(s) = a. Optimal: 𝝿*\n* **Discount** - rewards decay exponentially as steps being further.\n* **Time-limited values** - Vk(s), optimal value of s if game ends in k more steps\n* **Meu principle** - A rational agent should choose the action that maximizes its expected utility given its knowledge\n* **Lotteries** - Lotteries: situations with uncertain prizes\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\nBasic idea: get rewards from environment, defined by reward function, maximize rewards, based on sampling.Still MDP, but don't know transition model and reward function, must try, \"online\".Model-based learning: 1, learn empirical MDP model (estimate T and R); 2, solve MDP.Passive RL: just do actions and learn from experience.Direct evaluation: according to a policy pi, average all the discounted rewards from it. Problem: waste information about state connections, takes long time.Temporal difference learning: update V(s) each time experience transition, running average. Exponential moving average (learning rate): Decreasing learning rate (alpha) can give converging averages. Problem: sunk when turn into policy. Q-learning(active RL): sample-based Q-value iteration. 1, receive sample; 2, old estimate: Q(s,a); 3, new estimate: sample = R+ymax(a')Q(s',a');4, incorporate new estimate into a running average: Q(s,a)<-(1-a)Q(s,a)+a[sample].Need to explore enough, learning rate small enough.Problem with E-greedy: may keep thrashing around once learning is done, can lower E over time, or using exploration function.\nexploration function: takes estimate U and visit count n return optimistic utility: f=u+k/nRegret:a mesure of total mistake cost. Both random exploration and exploration functions are optimal, but random exploration has higher regret.Approximate Q-learning: Q-learning has a table of all Q-valuese, cannot learn all states. Use linear Q functions. Advantage: only summing up a few powerful numbers. Disadvantage: similar states may have very different values.\n\n\n## Module 9 Definitions\n* **Offline planning** - Solving MDP: need to know the detail, not actually playing\n* **Onfline planning** - RL: need to actually act to find details\n* **Running interpolation update** - xn=a*xn+(1-a)*x(n-1)\n* **Exponential moving average** - xn=[a*xn+(1-a)*x(n-1)+(1-a)^2*x(n-2)..] / [1+(1-a)+(1-a)^2...], recent samples more important\n* **Off-policy learning** - Q-learning converges to optimal policy even if acting suboptimally\n* **E-greedy** - exploration: with prob E, act randomly; with prob 1-E, act current policy.\n* **Regret** - expected rewards - optimal rewards\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\nPossible worlds also called Sample space, which is mutually exclusive and exhaustive.Axioms of prob: 0<=p<=1, sum(p(w))=1.Unobserved random variables have distributions.Joint distribution: specifies a real number for each random vars (P(X1=x1, X2=x2..)).Size of joint distribution of n random vars with domain sizes d: d^n, impractical to write out full table.Probabilistic model: random vars with domains, outcomes, joint distribution, must normalized.Conditional prob: P(a|b)=P(a,b)/p(b).Prob inference: generally compute conditional prob, observing changes with new evidence.Inference by enumeration: Vars: evidence vars E, query vars Q, hidden vars H. Want: P(Q|e1,e2..ek).Steps:1, select entries consistent with evidence; 2. sum H to get P(Q,e1,e2..ek); 3. Normalize, P(Q|e1,e2..ek)=1/Z *P(Q,e1,e2..ek).Probabilistic Language Models: goal is to compute a probability to a sentence or sequence of words: autocomplete for texing, machine translation,spelling correction, speech recognization.Computing P(W): Use Chain Rule: P(w1,w2..wn)=product(i)P(wi|w1,w2..wi-1).Problem of just count and divide: some sentences may not appear, need huge dataset.Need Markov Assumption: prob of moving to next state only depends on previous k words, not the whole context.P(won|the underdog team) ~ P(won|team), P(w1,w2..wn)~product(i)P(wi|wi-k..wi-1).Consider k words as history: k+1 gram. Unigram: no history; bigram: 1 word; trigram: 2 words.\n\n\n## Module 10 Definitions\n* **Observed variables (evidence)** - Certain things the agent knows about the world\n* **Unobserved variables (states)** - Certain things the agent needs to reason about\n* **Model** - Agent knows some relations between known and unknown variables\n* **Random variables** - Things with uncertainty, denoted as capital letters\n* **Distribution** - A table of prob of values\n* **Probabilistic model** - A joint distribution over set of random vars\n* **Event** - A set of outcomes\n* **Marginal distribution** - A sub-table of summing out a variable: P(T) from P(T,W)\n* **Conditional distribution** - Distribution that some vars given fixed.\n* **Probabilistic inference** - Get desired prob from known prob (e.g. condition from joint)\n* **Product rule** - P(y)*P(x|y)=P(x,y)\n* **Chain rule** - P(x1,x2,x3)=P(x1)*P(x2|x1)*P(x3|x1,x2)\n* **Bayes' rule** - P(x|y)=P(y|x)/P(y) * P(x)\n* **Language model** - Model that computes P(W1,W2,w3..) or P(Wn|W1,W2..)\n* **Mle** - Maximum likelihood estimation\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\n(Conditinal) independence is a property of a distribution.Prob of full joint distribution: too big to represent, hard to estimate more than a few vars at a time.Bayes' nets: also called graphical models, used to describe complex joint distributions with simple local distributions (conditional probs).Node: random vars (with domains); Arc: interactions (conditional probs).Semantics: set of nodes,directed acyclic graph, conditional distribution for each node of all parents P(x|a1..an). A Bayes net=Topology(graph)+local conditional probs.To know joint distributions: compute product of local conditional probs (P(xi|parents(xi))).BN enforces certain conditional independencies, can't represent every joint distribution.BN need not actually be causal, can be correlation. Topology really encodes conditional independence.Assumptions when defining the BNs:.1. Often additional conditional independences; 2. they can be read off the graph.Causal chain/Common Cause: not guarantee X independent Z, but X independent of Z given Y.Common Effect: X, Y are independent, but not independent given Z.X,Y are conditionally independent given Z, if all paths are inactive.D(descendant)-separation algorithm: look paths between Xi and Xj, checks for inactive triples.Inference by Enumeration in BN:P(B|+j,+m) is proportional to P(B,+j,+m)=sum of hidden=sum of products of conditional probs.Can be slow, since join up whole joint distribution before suming hidden vars.\nUse Variable Elimination: interleave joining and marginalizing, faster.\n\n\n## Module 11 Definitions\n* **(unconditioanlly) independent** - iff P(x,y)=P(x)*P(y), rare\n* **Conditionally independent** - iff P(x,y|z)=P(x|z)*P(y|z), or P(x|z,y)=P(x|z) useful for inference\n* **Cpt** - conditional probability table\n* **Size** - Joint distribution over N vars: 2^N; N-node net up to K parents: O(N*2^(k+1))\n* **Causal chain** - X->Y->Z, P(x,y,z)=P(x)*P(y|x)*P(z|y)\n* **Common cause** - Y->X, Y->Z, P(x,y,z)=P(y)*P(x|y)*P(z|y)\n* **Common effect** - v-structure, X->Z, Y->Z\n* **Reachability** - Is there's a path between 2 nodes\n* **Active path** - every triple is active along the path\n* **Inference** - get useful quantity from a joint prob distribution\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\nModel-based classification: build model of label and features and instantiate observed features.Query the distribution of label on features.Naive Bayes: assume all features are independent effects of label.Need to learn priorier prob and conditional probs.General Naive Bayes model: P(Y, F1...FN)=P(Y)*product(P(Fi|Y)). |Y|*|F|^n values become.n*|F|*|Y| parameters, only need how features depends on the class and linear number, but model very simple, may be not accurate.Goal: compute posterior distribution over label Y. Steps: 1, get joint prob of label and evidence P(Y,f1..fn);2, sum to get prob of evidence: P(f1...fn); 3, normalize, divide step 1 by 2 to get P(Y|f1..fn).Use inference to estimate local conditional prob tables.Split data into training set, held out set, test set. Learn parameters from training set, turn hyperparameters on held-out set,compute accuracy of test set.Parameter estimation: estimate the distribution of a random var from training data.Maximum likelihood: P(x)=count(x)/total sample, L(x, t)=product(Pt(xi)). select t maximizes L.Problem: unseen events, use Laplase smoothing, but may performs poorly for P(x|y) when X or Y is large.Use linear interpolation: P(x|y)=aP'(x|y)+(1-a)p'(x).Tuning hyper parameters: k and a.Perceptron notation change: 1. sum(wj*xj)~W·X； 2.bias=-threshold, wx>threshold ~ w·x+b>0\nFix features, tune weight vectors.Binary decision rule: examples are points, f·w split to positive and negative.Start with weights=0, in training if wrong adjust weight vector by add(y=1) or subtract(y=-1) feature vector.Multiclass Decision rule: weight vector for each class, score class as w·f, predict highest score wins y=argmax(y)wy·f(x).Start with weights=0, if wrong, lower/raise score of wrong/right answer.Problem of perceptron: if data isn't separable, weights might thrash: need averaging weight vectors over time;Mediocre generalization that barely separating; overtraining: early stopping.MIRA: find update size that fixes the current mistake but minimizing weight change.Maximum step size: cap the maximum possible value of tau with some constant C.Support vector machines (SVM):check separater with each items that maximize the margin.\n\n\n## Module 12 Definitions\n* **Overfitting** - Fitting the training set too closely but not generalized.\n* **Laplase smoothing** - pretent see everything once more/k times more.\n* **Separability** - true if some parameters get training perfectly correct\n* **Convergence** - perceptron will eventrally convergy in binary case if separable\n* **Mistake bound** - Max number of mistakes in binary case, related to the margin or degree of separability, mistakes<k/b^2\n* **Mira** - Margin Infused Relaxed Algorithm\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\nComponents of classifier: Feature vector[x1,x2..xn], classification function computing class y^ via P(y|x), objective function for learning, algorithm for optimizing objective function. Also training corpus of M observations input/out pairs.Sentiment classifier: output 1(positive) or 0(negative). LR solves it by learning z=w·x+b.Compared to perceptron, LR squish z with sigmoid function(y=1/(1+e^-z)=1/(1+e^-(w·x+b))).Make decision: y^=1 if P(y=1|x)>0.5, 0 otherwise. 0.5 is called decision boundary.Learning weight and bias: 1, need cross-entropy loss; 2, use stochastic gradient descent to minimize the loss function.Mean Squared Error:L=1/2(y^-y)^2, not very good.Loss function for prob classification: need to choose parameters w,b that maximize the log prob of true labels.Cross entropy loss (negative log lokelihood loss):p(y|x)=y'^y * (1-y')^(1-y).Lce= -log p(y|x)= -[ylogy' + (1-y)log(1-y')], plug y'=sig(w·x+b). Want it to be small when estimate is correct,big if it's confused. Loss on all training examples: sum all Lce.Gradient descent: find weights and bias by minimizing the loss function.For LR, the loss function is convex, no local minima so guaranteed to find minimum.Size of step: learning rate eta.The gradient delta: take derivative of loss function for a single weight.What we want to minimize: Average loss.Mini-batch training: choose random example and updates weights.Regularization: penalize large weights. Lasso: L1 regularization; Ridge: L2 regularization.Multinominal LR: use softmax function.Feed-forward NN: multilayer, all units are fully-connected with no cycles. So all outputs pass to next layer.Training NN: need loss function, optimization algorithm(gradient descent), way of computing the gradient of loss function(error propagation).Compute the gradient of deep NN: look back through all the earlier layers.Error back propagation: use chain rule of derivative to compute gradient of the loss function.\n\n\n## Module 13 Definitions\n* **Loss function** - Determine how the classifier output differs to correct output.\n* **Gradient descent** - Find minimum of a function by finding which direction the slope is rising most steeply\n* **Smoothness** - small changes in weight and bias will only cause little change to the output from neuron\n* **Activation function** - Apply non-linear function to z=w·x+b: Sigmoid, tanh, rectified linear unit ReLU\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\nAdvantages of neural LMs over n-gram LMs: don't need smoothing, handle longer histories, generalize over \ncontexts of similar words, have higher predictive accuracy, better preplexity scores, larger N. Disadvantage: slower. Neural LMs: vector-represent words, express joint prob of word sequence with word vectors, learn vectors and parameters of the function. Use multi-layer, feed forward NN. Input: k-gram words w1:k, output: prob distribution over hte next word.Unseen sequences: generalizing, assign probs to similar sentences.Word meaning: synonyms(similar), antonyms(opposite), connotations(positive or negative), semantic roles(different parts of same background), entailment(dog, animal).Term-document matrix: rows are words, cols are documents, a cell represent how often that term occured in that doc.vector L2 normalization: L2 length: sqrt of sum of squares, devide each vector by L2.Cosien distance: Get cos angle between 2 vectors, Also does L2 normalization.Term-Term matrix (Term-context): words versus words, a cell represent how often a word occured in a context window surrounding the other word. Context windows: ww target_ward ww.Documents created by term-by-document or term-context matrices are long and sparse.Dense vector works better: shorter vectors are easier to use as features, generalize better, do better at capturing synonymy.\nMeaning can be lost since long distance dependencies. Use syntax to define a word's context. Alternates to word counts: transform vectors using TF-IDF or PPMI.Co-occurrence matrix: long/sparse, alternative: learn short/dence vectors. To get dense vectors: train a classifier, treat target word and a neighbor as positive, randomly sample other negative words, use LR to distinguish, use the weights as embeddings.\n\n## Module 14 Definitions\n* **Tf-idf** - Term frequency * inverse document frequency (1 over num of documents that it occurred in).\n* **Sparse/dense vector** - most elements are 0/non-0\n* **Vector space models** - Term-document matrix\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}