{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "“Template_for CIS521_midterm_2_notes.ipynb”的副本",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "0fb4bd40-417f-4bd1-8d37-78edeb4dee9f"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "a82037c8-62ec-47ff-fba2-e4518d315b72"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = True"
      ],
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" Chapter 16.1 summary. \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\"Transitions are Markovian: the probability of arriving in \\\n",
        "s’ only depends on s and not the history of earlier states. \\n\n",
        "Rewards are additive. \\n\n",
        "MDP: a sequential decision problem; for a fully observable environment; \\\n",
        "with a stochastic transition model; that has additive rewards. \\n\n",
        "Define MDP: set of states S, start state S0, set of actions A, transitions, rewards. \\\n",
        "MDPs are non-deterministic search problems. One way of solving them is via \\\n",
        "expectimax search. \\n\n",
        "Find solution for MDP needs: a set of states, a set of actions, a transition \\\n",
        "function (probability is called the model), a reward function, an initial state, optional terminal states. \\n\n",
        "Solution for MDP is a policy, maps a state onto the action. \\n\n",
        "In search problem solution is plan, gives a sequence of action. \\n\n",
        "Finite horizon: terminate episodes after a fixed steps. \\n\n",
        "Gives nonsstationary policies. \\n\n",
        "Smaller gamma means smaller “horizon” – shorter term focus. \\n\n",
        "$$ V^*(s) = max_a Q^*(s,a) $$\n",
        "$$ Q^*(s,a) = \\Sigma_{s'} T(s,a,s')[R(s,a,s')+\\gamma V^*(s')] $$\n",
        "Time limited: $V_k(s)$ in k steps. \\n\n",
        "Complexity of each iteration $O(S^2A)$ \\n\n",
        "Fixed policy: $O(S^2)$ each iteration. \\n\n",
        "Policy evaluation: calculate utilities for some fixed policy until convergence. \\n\n",
        "Policy improvement: update policy using one-step look-ahead. \\n\n",
        "Repeat steps until policy converges: policy iteration, much faster. \\n\n",
        "Insensitivity to monotonic transformations: terminal function scale doesn't matter, only order need. \\n\n",
        "This is worst-case. However for average-case expectimax, magnitudes are meaningful. \\n\n",
        "Axioms of Rationality: orderability, transitivity, continuity, substitutability, monotonicity. \\n\n",
        "MEU: choose action that maximizes expected utility.\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"Sum of all rewards function values, with/out discounts\",\n",
        "\"expected utility\" : \"expected total rewards starting here\",\n",
        "\"MDP\": \"Markov decision process\",\n",
        "\"Absorbing state\": \"guarantee that for every policy, a terminal state will eventually be reached\",\n",
        "\"Bellman Equations\": \"Correct first step and keep optimal\",\n",
        "\"MEU Principle\": \"maximum expected utility principle\",\n",
        "\"Micromorts\": \"one-millionth chance of death, useful for paying to reduce product risks, etc.\",\n",
        "\"QALYs\": \"quality-adjusted life years, useful for medical decisions involving substantial risk\",\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "acff4427-3537-4222-90ed-26ecfaf387cb"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\nTransitions are Markovian: the probability of arriving in s’ only depends on s and not the history of earlier states. \n\nRewards are additive. \n\nMDP: a sequential decision problem; for a fully observable environment; with a stochastic transition model; that has additive rewards. \n\nDefine MDP: set of states S, start state S0, set of actions A, transitions, rewards. MDPs are non-deterministic search problems. One way of solving them is via expectimax search. \n\nFind solution for MDP needs: a set of states, a set of actions, a transition function (probability is called the model), a reward function, an initial state, optional terminal states. \n\nSolution for MDP is a policy, maps a state onto the action. \n\nIn search problem solution is plan, gives a sequence of action. \n\nFinite horizon: terminate episodes after a fixed steps. \n\nGives nonsstationary policies. \n\nSmaller gamma means smaller “horizon” – shorter term focus. \n\n$$ V^*(s) = max_a Q^*(s,a) $$\n$$ Q^*(s,a) = \\Sigma_{s'} T(s,a,s')[R(s,a,s')+\\gamma V^*(s')] $$\nTime limited: $V_k(s)$ in k steps. \n\nComplexity of each iteration $O(S^2A)$ \n\nFixed policy: $O(S^2)$ each iteration. \n\nPolicy evaluation: calculate utilities for some fixed policy until convergence. \n\nPolicy improvement: update policy using one-step look-ahead. \n\nRepeat steps until policy converges: policy iteration, much faster. \n\nInsensitivity to monotonic transformations: terminal function scale doesn't matter, only order need. \n\nThis is worst-case. However for average-case expectimax, magnitudes are meaningful. \n\nAxioms of Rationality: orderability, transitivity, continuity, substitutability, monotonicity. \n\nMEU: choose action that maximizes expected utility.\n\n\n## Module 8 Definitions\n* **Utility function** - Sum of all rewards function values, with/out discounts\n* **Expected utility** - expected total rewards starting here\n* **Mdp** - Markov decision process\n* **Absorbing state** - guarantee that for every policy, a terminal state will eventually be reached\n* **Bellman equations** - Correct first step and keep optimal\n* **Meu principle** - maximum expected utility principle\n* **Micromorts** - one-millionth chance of death, useful for paying to reduce product risks, etc.\n* **Qalys** - quality-adjusted life years, useful for medical decisions involving substantial risk\n",
            "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",
        "Exploration: try unknown actions to get information. \\n\n",
        "Exploitation: eventually to use what we know. \\n\n",
        "Regret: even if we learn intelligently, we make mistakes. \\n\n",
        "Sampling: because of chance, we have to try things repeatedly. \\n\n",
        "Difficulty: learning can be much harder rhan solving MDP. \\n\n",
        "Model based learning: learn approximate model, then solve using the model. \\n\n",
        "Passive reinforcement learning: fixed policy, execute and learn.\\n\n",
        "Direct evaluation: compute values for each state under pi, average together \\\n",
        "observed sample values. \\n\n",
        "Temporal difference learning: \\n\n",
        "Sample of V(s): $sample = R(s,\\pi(s), s')+\\gamma V^{\\pi}(s')$\\n\n",
        "Update to V(s): $V^{\\pi}(s)\\leftarrow (1-a)V^{\\pi}(s)+(a)sample$\\n\n",
        "Exponential moving average: $x'_n = \\frac{x_n+(1-a)x_{n-1}+(1-a)^2x_{n-2}+...}{1+(1-a)+(1-a)^2+...}$\\n\n",
        "Q-Learning: calculate Q values instead.\\n\n",
        "Q-learning converges to optimal policy, even for suboptimal actions. better than v.\\n\n",
        "off-policy learning.\\n\n",
        "Explore: simple random actions, flip a coin.\\n\n",
        "Exploration functions: takes a value estimate u and a visit count n, \\\n",
        "returns an optimistic utility. e.g. $f(u,n)=u+k/n$\\n\n",
        "Regular Q-Update: $Q(s,a)\\leftarrow_a R(s,a,s')+\\gamma max_{a'}Q(s',a')$\\n\n",
        "Modified Q-Update: $Q(s,a)\\leftarrow_a R(s,a,s')+\\gamma max_{a'}f(Q(s',a'), N(s'.a'))$\\n\n",
        "Regret is a measure of your total mistake cost: the difference between \\\n",
        "your (expected) rewards, including youthful suboptimality, and optimal (expected) rewards.\\n\n",
        "Minimizing regret required optimally learning to be optimal.\\n\n",
        "linear value functions: using weight to combine features, get values.\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"off-policy learning\" : \"learn without optimal policy\",\n",
        "}"
      ],
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "c665e854-061a-4ae7-9749-fc7e1279cc5a"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\nExploration: try unknown actions to get information. \n\nExploitation: eventually to use what we know. \n\nRegret: even if we learn intelligently, we make mistakes. \n\nSampling: because of chance, we have to try things repeatedly. \n\nDifficulty: learning can be much harder rhan solving MDP. \n\nModel based learning: learn approximate model, then solve using the model. \n\nPassive reinforcement learning: fixed policy, execute and learn.\n\nDirect evaluation: compute values for each state under pi, average together observed sample values. \n\nTemporal difference learning: \n\nSample of V(s): $sample = R(s,\\pi(s), s')+\\gamma V^{\\pi}(s')$\n\nUpdate to V(s): $V^{\\pi}(s)\\leftarrow (1-a)V^{\\pi}(s)+(a)sample$\n\nExponential moving average: $x'_n = \frac{x_n+(1-a)x_{n-1}+(1-a)^2x_{n-2}+...}{1+(1-a)+(1-a)^2+...}$\n\nQ-Learning: calculate Q values instead.\n\nQ-learning converges to optimal policy, even for suboptimal actions. better than v.\n\noff-policy learning.\n\nExplore: simple random actions, flip a coin.\n\nExploration functions: takes a value estimate u and a visit count n, returns an optimistic utility. e.g. $f(u,n)=u+k/n$\n\nRegular Q-Update: $Q(s,a)\\leftarrow_a R(s,a,s')+\\gamma max_{a'}Q(s',a')$\n\nModified Q-Update: $Q(s,a)\\leftarrow_a R(s,a,s')+\\gamma max_{a'}f(Q(s',a'), N(s'.a'))$\n\nRegret is a measure of your total mistake cost: the difference between your (expected) rewards, including youthful suboptimality, and optimal (expected) rewards.\n\nMinimizing regret required optimally learning to be optimal.\n\nlinear value functions: using weight to combine features, get values.\n\n\n## Module 9 Definitions\n* **Off-policy learning** - learn without optimal policy\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",
        "Observed variables (evidence): Agent knows certain things about the state of the world (e.g.,\n",
        "sensor readings or symptoms)\\n\n",
        "Unobserved variables (states): Agent needs to reason about other aspects (e.g. where an object\n",
        "is or what disease is present)\\n\n",
        "Model: Agent knows something about how the known variables relate to the unknown variables.\\n\n",
        "A joint distribution over a set of random variables x1, x2,..., xn \n",
        "specifies a real number for each assignment (or outcome). \\n\n",
        "MLE: maximum likelihood estimation.\\n\n",
        "Problems for MLE:\\n\n",
        "Out of vocabulary items (OOV)\\n\n",
        "<unk> to deal with OOVs\\n\n",
        "Fixed lexicon L of size V\\n\n",
        "Normalize training data by replacing any word not in L with <unk>\\n\n",
        "Avoid zeros with smoothing\\n\n",
        "Stationary process: the conditional probability table does not change over time\\n\n",
        "DBN requires: The sensor model, The transition model, The prior distribution over the state variables.\\n\n",
        "Evaluate n-gram model: perplexity on a test set.\\n\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"random variable\" : \"some aspect of the world about which we (may) have uncertainty\",\n",
        "\"distribution\": \"a TABLE of probabilities of values\",\n",
        "\"probability\": \"a single number of value\",\n",
        "\"probabilistic model\": \"a joint distribution over a set of random variables\",\n",
        "\"event\": \"a set E of outcomes\",\n",
        "\"Marginal distributions\": \"sub-tables which eliminate variables\",\n",
        "\"Marginalization\": \"Combine collapsed rows by adding\",\n",
        "\"conditional probability\": \"P(a|b)=P(a,b)/P(b)\",\n",
        "\"Conditional distributions\": \"probability distributions over some variables given fixed values of others\",\n",
        "\"Probabilistic inference\": \"compute a desired probability from other known probabilities\",\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 either the probability of a sentence / sequence of words or an upcoming word.\",\n",
        "\"MLE\": \"P(won|the underdog team)=Count(the underdog team won)/Count(the underdog team)\",\n",
        "\"Markov Assumption\": \"next word only depends on the previous k words\",\n",
        "\"DBN\": \"dynamic Bayesian model\",\n",
        "\n",
        "}"
      ],
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "f256792d-e398-43f9-a688-7ed9f8b9fb67"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n\nObserved variables (evidence): Agent knows certain things about the state of the world (e.g.,\nsensor readings or symptoms)\n\nUnobserved variables (states): Agent needs to reason about other aspects (e.g. where an object\nis or what disease is present)\n\nModel: Agent knows something about how the known variables relate to the unknown variables.\n\nA joint distribution over a set of random variables x1, x2,..., xn \nspecifies a real number for each assignment (or outcome). \n\nMLE: maximum likelihood estimation.\n\nProblems for MLE:\n\nOut of vocabulary items (OOV)\n\n<unk> to deal with OOVs\n\nFixed lexicon L of size V\n\nNormalize training data by replacing any word not in L with <unk>\n\nAvoid zeros with smoothing\n\nStationary process: the conditional probability table does not change over time\n\nDBN requires: The sensor model, The transition model, The prior distribution over the state variables.\n\nEvaluate n-gram model: perplexity on a test set.\n\n\n\n\n## Module 10 Definitions\n* **Random variable** - some aspect of the world about which we (may) have uncertainty\n* **Distribution** - a TABLE of probabilities of values\n* **Probability** - a single number of value\n* **Probabilistic model** - a joint distribution over a set of random variables\n* **Event** - a set E of outcomes\n* **Marginal distributions** - sub-tables which eliminate variables\n* **Marginalization** - Combine collapsed rows by adding\n* **Conditional probability** - P(a|b)=P(a,b)/P(b)\n* **Conditional distributions** - probability distributions over some variables given fixed values of others\n* **Probabilistic inference** - compute a desired probability from other known probabilities\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 either the probability of a sentence / sequence of words or an upcoming word.\n* **Mle** - P(won|the underdog team)=Count(the underdog team won)/Count(the underdog team)\n* **Markov assumption** - next word only depends on the previous k words\n* **Dbn** - dynamic Bayesian model\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",
        "X is conditionally independent of Y given Z\\n\n",
        "iff $v(x,y,z): P(x,y|z)=P(x|z)P(y|z)$\\n\n",
        "or equivalently, iff $v(x,y,z): P(x|z,y)=P(x|z)$\\n\n",
        "Nodes: variables (with domains), can be assigned (observed) or unassigned (unobserved),\\n\n",
        "Arcs: interactions, direct influence between variables.\\n\n",
        "A Bayes net = Topology (graph) + Local Conditional Probabilities\\n\n",
        "Bayes’ nets implicitly encode joint distributions\\n\n",
        "Not every BN can represent every joint distribution\\n\n",
        "The topology enforces certain conditional independencies\\n\n",
        "Topology really encodes conditional independence, need not to be causal.\\n\n",
        "How big is a joint distribution over N Boolean variables? 2^N\\n\n",
        "How big is an N-node net if nodes have up to k parents? $O(N*2^{k+1})$\\n\n",
        "Causal chains: x cause y cause z: x given y is independent of z\\n\n",
        "$P(x,y,z)=P(x)P(y|x)P(z|y)$\\n\n",
        "Common cause: y cause x and z: x and z independent given y\\n\n",
        "$P(x,y,z) = P(y)P(x|y)P(z|y)$\\n\n",
        "Common effect: x and y both cause z: x and y independent\\n\n",
        "If one or more active triples, not independent\\n\n",
        "All paths are inactive, independence.\\n\n",
        "Why is inference by enumeration so slow?\\n\n",
        "You join up the whole joint distribution before you sum out the hidden variables.\\n\n",
        "Advanced technique: Variable Elimination\\n\n",
        "Interleave joining and marginalizing, still NP-hard, but usually much faster\\n\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"Bayes' nets\" : \"a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities)\",    \n",
        "\"D-separation\": \"check paths for independence\",\n",
        "\n",
        "}\n"
      ],
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 963
        },
        "cellView": "form",
        "outputId": "20237528-7c88-4044-cb2c-8efd1794e9db"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\nX is conditionally independent of Y given Z\n\niff $v(x,y,z): P(x,y|z)=P(x|z)P(y|z)$\n\nor equivalently, iff $v(x,y,z): P(x|z,y)=P(x|z)$\n\nNodes: variables (with domains), can be assigned (observed) or unassigned (unobserved),\n\nArcs: interactions, direct influence between variables.\n\nA Bayes net = Topology (graph) + Local Conditional Probabilities\n\nBayes’ nets implicitly encode joint distributions\n\nNot every BN can represent every joint distribution\n\nThe topology enforces certain conditional independencies\n\nTopology really encodes conditional independence, need not to be causal.\n\nHow big is a joint distribution over N Boolean variables? 2^N\n\nHow big is an N-node net if nodes have up to k parents? $O(N*2^{k+1})$\n\nCausal chains: x cause y cause z: x given y is independent of z\n\n$P(x,y,z)=P(x)P(y|x)P(z|y)$\n\nCommon cause: y cause x and z: x and z independent given y\n\n$P(x,y,z) = P(y)P(x|y)P(z|y)$\n\nCommon effect: x and y both cause z: x and y independent\n\nIf one or more active triples, not independent\n\nAll paths are inactive, independence.\n\nWhy is inference by enumeration so slow?\n\nYou join up the whole joint distribution before you sum out the hidden variables.\n\nAdvanced technique: Variable Elimination\n\nInterleave joining and marginalizing, still NP-hard, but usually much faster\n\n\n\n## Module 11 Definitions\n* **Bayes' nets** - a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities)\n* **D-separation** - check paths for independence\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",
        "What do we need in order to use Naïve Bayes?\\n\n",
        "Inference method: \\n\n",
        "Start with a bunch of probabilities: P(Y) and the P(Fi|Y) tables,\\n\n",
        "Use standard inference to compute P(Y|F1…Fn)\\n\n",
        "Estimates of local conditional probability tables:\\n\n",
        "P(Y), the prior over labels\\n\n",
        "P(Fi|Y) for each feature (evidence variable)\\n\n",
        "These probabilities are collectively called the parameters of the model and denoted by $\\theta$\\n\n",
        "\\n\n",
        "Bag-of-words Naïve Bayes:\\n\n",
        "Features: Wi is the word at positon i\\n\n",
        "Predict label conditioned on feature variables (spam vs. ham)\\n\n",
        "Assume features are conditionally independent given label\\n\n",
        "Each Wi is identically distributed\\n\n",
        "All positions share the same conditional probs P(W|Y)\\n\n",
        "Model is insensitive to word order or reordering\\n\n",
        "Data: training set, held out set, test set.\\n\n",
        "Relative frequency parameters will overfit the training data\\n\n",
        "Relative frequencies are the maximum likelihood estimates\\n\n",
        "Laplace’s estimate: \\n\n",
        "Pretend you saw every outcome once more than you actually did.\\n\n",
        "Extended: Pretend you saw every outcome k extra times\\n\n",
        "linear interpolation: \\n\n",
        "Also get the empirical P(X) from the data, Make sure the estimate of P(X|Y) isn’t too different from the\n",
        "empirical P(X)\\n\n",
        "$P_{LIN}(x|y) = a P(x|y) + (1.0-a)P(x)$\\n\n",
        "Tuning on Held-Out Data: try different hyperparameters.\\n\n",
        "\\n\n",
        "Baselines are very simple “straw man” procedures, help determin hardness and accuracy.\\n\n",
        "Weak baseline: most frequent label classifier\\n\n",
        "The confidence of a probabilistic classifier is:\\n\n",
        "$confidence(x)=max_y P(y|x)$\\n\n",
        "Calibration:\\n\n",
        "Weak calibration: higher confidences mean higher accuracy\\n\n",
        "Strong calibration: confidence predicts accuracy rate\\n\n",
        "\\n\n",
        "Linear classifiers:\\n\n",
        "$activation_w(x) = \\Sigma_i w_i * f_i(x) = w*f(x)$\\n\n",
        "Binary Perceptron: start with weights = 0, adjust while learning.\\n\n",
        "$w=w+y^*f$, y* could be 1 or -1\\n\n",
        "For multiple classes:\\n\n",
        "Weight vector for each class $w_y$\\n\n",
        "Score (activation) of a class y: $w_y f(x)$\\n\n",
        "Prediction highest score wins: $y=argmax_y w_y f(x)$\\n\n",
        "Learn: if wrong, lover score of wrong answer, raise score of right answer:\\n\n",
        "$w_y = w_y - f(x)$, $w_{y^*} = w_{y^*} + f(x)$\\n\n",
        "Problems:\\n\n",
        "Noise: average weight vectors\\n\n",
        "Mediocre generalization: finds a barely separating solution.\\n\n",
        "Overtraining: test/held-out accuracy usually rises then falls.\\n\n",
        "Fixing:\\n\n",
        "Minimum correcting update, maximum step size, maximizing the margin.\\n\n",
        "Comparison:\\n\n",
        "NB:\\n\n",
        "Builds a model training data\\n\n",
        "Gives prediction probabilities\\n\n",
        "Strong assumptions about feature independence\\n\n",
        "One pass through data (counting)\\n\n",
        "Perceptrons/MIRA:\\n\n",
        "Makes less assumptions about data\\n\n",
        "Mistake-driven learning\\n\n",
        "Multiple passes through data (prediction)\\n\n",
        "Often more accurate\\n\n",
        "Non-linear separators:\\n\n",
        "the original feature space can always be mapped to some\n",
        "higher-dimensional feature space where the training set is separable\\n\n",
        "Three common non-linear activation functions:\\n\n",
        "The sigmoid function\\n\n",
        "The tanh function\\n\n",
        "The rectified linear unit ReLU\\n\n",
        "Higher bias value: easier for 1\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"Classification\" : \"given inputs x, predict labels y\", \n",
        "\"Features\": \"attribute-value pairs which characterize each variable\",\n",
        "\"Accuracy\": \"fraction of instances predicted correctly\",\n",
        "\"Overfitting\": \"fitting the training data very closely, but not generalizing well\",\n",
        "\"Separability\": \"true if some parameters get the training set perfectly correct\",\n",
        "\"Convergence\": \" if the training is separable, perceptron will eventually converge (binary case)\",\n",
        "\"Mistake Bound\": \"the maximum number of mistakes (binary case) related to the margin or degree of separability\",\n",
        "\"bias\": \"-1 times threshold\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "863cd6bd-f44b-4aa4-f7d0-b9044d5bcf7f"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module12_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter19_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter19_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter19_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter19_4),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter19_5),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter19_6),\n",
        "  (\"SLP Chapter 4.1 Naive Bayes Classifiers\", slp_chapter4_1),\n",
        "  (\"SLP Chapter 4.2 Training the Naive Bayes Classifier\", slp_chapter4_2),\n",
        "  (\"SLP Chapter 4.3 Worked Example\", slp_chapter4_3),\n",
        "  (\"SLP Chapter 4.4 Optimizing for Sentiment Analysis\", slp_chapter4_4),\n",
        "  (\"SLP Chapter 4.5 Naive Bayes for other text classification tasks\", slp_chapter4_5),\n",
        "  (\"SLP Chapter 4.6 Naive Bayes as a Language Model\", slp_chapter4_6),\n",
        "  (\"SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\", slp_chapter4_7),\n",
        "  (\"SLP Chapter 4.8 Test sets and Cross-validation\", slp_chapter4_8),\n",
        "  (\"SLP Chapter 4.9 Statistical Significance Testing\", slp_chapter4_9),\n",
        "  (\"SLP Chapter 4.10 Avoiding Harms in Classification\", slp_chapter4_10),\n",
        "  (\"Module 12 Lecture Notes\", module12_lecture_notes),\n",
        "]\n",
        "\n",
        "module12_markdown = format_module(12, \"Naive Bayes and Perceptrons\", \n",
        "                         module12_sections, \n",
        "                         module12_definitions)\n",
        "display(Markdown(module12_markdown))"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\nWhat do we need in order to use Naïve Bayes?\n\nInference method: \n\nStart with a bunch of probabilities: P(Y) and the P(Fi|Y) tables,\n\nUse standard inference to compute P(Y|F1…Fn)\n\nEstimates of local conditional probability tables:\n\nP(Y), the prior over labels\n\nP(Fi|Y) for each feature (evidence variable)\n\nThese probabilities are collectively called the parameters of the model and denoted by $\theta$\n\n\n\nBag-of-words Naïve Bayes:\n\nFeatures: Wi is the word at positon i\n\nPredict label conditioned on feature variables (spam vs. ham)\n\nAssume features are conditionally independent given label\n\nEach Wi is identically distributed\n\nAll positions share the same conditional probs P(W|Y)\n\nModel is insensitive to word order or reordering\n\nData: training set, held out set, test set.\n\nRelative frequency parameters will overfit the training data\n\nRelative frequencies are the maximum likelihood estimates\n\nLaplace’s estimate: \n\nPretend you saw every outcome once more than you actually did.\n\nExtended: Pretend you saw every outcome k extra times\n\nlinear interpolation: \n\nAlso get the empirical P(X) from the data, Make sure the estimate of P(X|Y) isn’t too different from the\nempirical P(X)\n\n$P_{LIN}(x|y) = a P(x|y) + (1.0-a)P(x)$\n\nTuning on Held-Out Data: try different hyperparameters.\n\n\n\nBaselines are very simple “straw man” procedures, help determin hardness and accuracy.\n\nWeak baseline: most frequent label classifier\n\nThe confidence of a probabilistic classifier is:\n\n$confidence(x)=max_y P(y|x)$\n\nCalibration:\n\nWeak calibration: higher confidences mean higher accuracy\n\nStrong calibration: confidence predicts accuracy rate\n\n\n\nLinear classifiers:\n\n$activation_w(x) = \\Sigma_i w_i * f_i(x) = w*f(x)$\n\nBinary Perceptron: start with weights = 0, adjust while learning.\n\n$w=w+y^*f$, y* could be 1 or -1\n\nFor multiple classes:\n\nWeight vector for each class $w_y$\n\nScore (activation) of a class y: $w_y f(x)$\n\nPrediction highest score wins: $y=argmax_y w_y f(x)$\n\nLearn: if wrong, lover score of wrong answer, raise score of right answer:\n\n$w_y = w_y - f(x)$, $w_{y^*} = w_{y^*} + f(x)$\n\nProblems:\n\nNoise: average weight vectors\n\nMediocre generalization: finds a barely separating solution.\n\nOvertraining: test/held-out accuracy usually rises then falls.\n\nFixing:\n\nMinimum correcting update, maximum step size, maximizing the margin.\n\nComparison:\n\nNB:\n\nBuilds a model training data\n\nGives prediction probabilities\n\nStrong assumptions about feature independence\n\nOne pass through data (counting)\n\nPerceptrons/MIRA:\n\nMakes less assumptions about data\n\nMistake-driven learning\n\nMultiple passes through data (prediction)\n\nOften more accurate\n\nNon-linear separators:\n\nthe original feature space can always be mapped to some\nhigher-dimensional feature space where the training set is separable\n\nThree common non-linear activation functions:\n\nThe sigmoid function\n\nThe tanh function\n\nThe rectified linear unit ReLU\n\nHigher bias value: easier for 1\n\n\n## Module 12 Definitions\n* **Classification** - given inputs x, predict labels y\n* **Features** - attribute-value pairs which characterize each variable\n* **Accuracy** - fraction of instances predicted correctly\n* **Overfitting** - fitting the training data very closely, but not generalizing well\n* **Separability** - true if some parameters get the training set perfectly correct\n* **Convergence** -  if the training is separable, perceptron will eventually converge (binary case)\n* **Mistake bound** - the maximum number of mistakes (binary case) related to the margin or degree of separability\n* **Bias** - -1 times threshold\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\"\n",
        "Classifier components:\\n\n",
        "1. A feature representation of the input.\\n\n",
        "2. A classification function that computes the estimated class y via p(y|x)\\n\n",
        "3. An objective function for learning, usually involving minimizing error on training examples.\\n\n",
        "4. An algorithm for optimizing the objective function.\\n\n",
        "\\n\n",
        "Sentiment classifier:\\n\n",
        "Extract feature, calculate $z=\\Sigma_i w_i x_i + b$, apply to sigmoid function, make decision.\\n\n",
        "Learning weights + bias needs:\\n\n",
        "1. An objective function or loss function that tells us distance between\n",
        "the system output and the gold output. We will use cross-entropy\n",
        "loss.\\n\n",
        "2. An algorithm for optimizing the objective function. We will use\n",
        "stochastic gradient descent to minimize the loss function.\\n\n",
        "Gradient descent is a method that finds a minimum of a function by figuring out in\n",
        "which direction (in the space of the parameters θ) the function’s slope is rising the most\n",
        "steeply, and moving in the opposite direction.\\n\n",
        "Stochastic gradient descent chooses a single random example at a time and updates\n",
        "its weights on that example. As a result the updates can fluctuate.\\n\n",
        "An alternate is batch training, which computes the gradient over the entire dataset.\n",
        "This gives a much better estimate of which direction to move the weights but takes a\n",
        "long time to compute\\n\n",
        "A commonly used compromise is mini-batch training, where we train on a small\n",
        "batch. The batch size can be 512 or 1024.\\n\n",
        "The simplest kind of NN is the Feed-Forward Neural Network\\n\n",
        "Multilayer network, all units are usually fully-connected, and no cycles.\\n\n",
        "The outputs from each layer are passed to units in the next higher layer, and no\n",
        "outputs are passed back to lower layers.\\n\n",
        "Formulas: \\n\n",
        "h = σ(Wx+b)\\n\n",
        "z = Uh\\n\n",
        "y = softmax(z)\\n\n",
        "Training NN:\\n\n",
        "A loss function – cross-entropy loss\\n\n",
        "An optimization algorithm – gradient descent\\n\n",
        "A way of computing the gradient of the loss function – error propagation\\n\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"decision boundary\" : \"yes or no boundary of the probability\",    \n",
        "}\n"
      ],
      "execution_count": 14,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "fecde559-65e9-4b48-8e48-80d40b4d87f7"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\nClassifier components:\n\n1. A feature representation of the input.\n\n2. A classification function that computes the estimated class y via p(y|x)\n\n3. An objective function for learning, usually involving minimizing error on training examples.\n\n4. An algorithm for optimizing the objective function.\n\n\n\nSentiment classifier:\n\nExtract feature, calculate $z=\\Sigma_i w_i x_i + b$, apply to sigmoid function, make decision.\n\nLearning weights + bias needs:\n\n1. An objective function or loss function that tells us distance between\nthe system output and the gold output. We will use cross-entropy\nloss.\n\n2. An algorithm for optimizing the objective function. We will use\nstochastic gradient descent to minimize the loss function.\n\nGradient descent is a method that finds a minimum of a function by figuring out in\nwhich direction (in the space of the parameters θ) the function’s slope is rising the most\nsteeply, and moving in the opposite direction.\n\nStochastic gradient descent chooses a single random example at a time and updates\nits weights on that example. As a result the updates can fluctuate.\n\nAn alternate is batch training, which computes the gradient over the entire dataset.\nThis gives a much better estimate of which direction to move the weights but takes a\nlong time to compute\n\nA commonly used compromise is mini-batch training, where we train on a small\nbatch. The batch size can be 512 or 1024.\n\nThe simplest kind of NN is the Feed-Forward Neural Network\n\nMultilayer network, all units are usually fully-connected, and no cycles.\n\nThe outputs from each layer are passed to units in the next higher layer, and no\noutputs are passed back to lower layers.\n\nFormulas: \n\nh = σ(Wx+b)\n\nz = Uh\n\ny = softmax(z)\n\nTraining NN:\n\nA loss function – cross-entropy loss\n\nAn optimization algorithm – gradient descent\n\nA way of computing the gradient of the loss function – error propagation\n\n\n\n\n## Module 13 Definitions\n* **Decision boundary** - yes or no boundary of the probability\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",
        "1. Synonyms – words that have similar meanings\\n\n",
        "2. Antonyms – words that have opposite meanings\\n\n",
        "3. Connotations – words that are positive or negative\\n\n",
        "4. Semantic Roles – buy, sell, and pay are different parts of the same underlying\n",
        "purchasing event\\n\n",
        "5. Support for entailment, belongs, includes\\n\n",
        "Term-Document matrix:\\n\n",
        "columns for documents, rows for word counts\\n\n",
        "Compare column vectors.\\n\n",
        "Vector normalization: divide vectors by its L2 length:\\n\n",
        "$||u||=sqrt(\\Sigma u_i^2)$\\n\n",
        "Then calculate their distance.\\n\n",
        "Or cosine distance.\\n\n",
        "Term-Term matrix AKA Term-context matrix:\\n\n",
        "Value in a cell indicates how often the column word appears in a context\n",
        "window surrounding row word.\\n\n",
        "\\n\n",
        "Neural Language models have several advantages over n-gram LMs:\\n\n",
        "1. They don’t need smoothing\\n\n",
        "2. They can handle much longer histories, larger N.\\n\n",
        "3. They can generalize over contexts of similar words.\\n\n",
        "4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\\n\n",
        "Disadvantage: slower to train than traditional n-gram LMs\\n\n",
        "NLM:\\n\n",
        "Input is a k-gram of words,\\n\n",
        "Output is a probability distribution over the next word.\\n\n",
        "Embeddings = vector models of meaning\\n\n",
        "More fine-grained than just a string or index\\n\n",
        "Especially good at modeling similarity/analogy\\n\n",
        "Can use sparse models (tf-idf) or dense models (word2vec, GLoVE)\\n\n",
        "Useful in practice but know they encode cultural stereotypes.\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"TF-IDF\" : \"term frequency * inverse document frequency\", \n",
        "\"TF\": \"How often a word occurred in a document\", \n",
        "\"IDF\": \"1 over the number of documents that it occurred in\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 24,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "51ee2f2f-1da5-4904-874c-2af67f56c958"
      },
      "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": 22,
      "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\n1. Synonyms – words that have similar meanings\n\n2. Antonyms – words that have opposite meanings\n\n3. Connotations – words that are positive or negative\n\n4. Semantic Roles – buy, sell, and pay are different parts of the same underlying\npurchasing event\n\n5. Support for entailment, belongs, includes\n\nTerm-Document matrix:\n\ncolumns for documents, rows for word counts\n\nCompare column vectors.\n\nVector normalization: divide vectors by its L2 length:\n\n$||u||=sqrt(\\Sigma u_i^2)$\n\nThen calculate their distance.\n\nOr cosine distance.\n\nTerm-Term matrix AKA Term-context matrix:\n\nValue in a cell indicates how often the column word appears in a context\nwindow surrounding row word.\n\n\n\nNeural Language models have several advantages over n-gram LMs:\n\n1. They don’t need smoothing\n\n2. They can handle much longer histories, larger N.\n\n3. They can generalize over contexts of similar words.\n\n4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\n\nDisadvantage: slower to train than traditional n-gram LMs\n\nNLM:\n\nInput is a k-gram of words,\n\nOutput is a probability distribution over the next word.\n\nEmbeddings = vector models of meaning\n\nMore fine-grained than just a string or index\n\nEspecially good at modeling similarity/analogy\n\nCan use sparse models (tf-idf) or dense models (word2vec, GLoVE)\n\nUseful in practice but know they encode cultural stereotypes.\n\n\n## Module 14 Definitions\n* **Tf-idf** - term frequency * inverse document frequency\n* **Tf** - How often a word occurred in a document\n* **Idf** - 1 over the number of documents that it occurred in\n* **Place** - \n\n\n\n\n\n\n\n\n\n\n\n\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": "5d2b2b1c-0214-4520-a377-57c1cc28c4cd"
      },
      "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": 25,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\nTransitions are Markovian: the probability of arriving in s’ only depends on s and not the history of earlier states. \n\nRewards are additive. \n\nMDP: a sequential decision problem; for a fully observable environment; with a stochastic transition model; that has additive rewards. \n\nDefine MDP: set of states S, start state S0, set of actions A, transitions, rewards. MDPs are non-deterministic search problems. One way of solving them is via expectimax search. \n\nFind solution for MDP needs: a set of states, a set of actions, a transition function (probability is called the model), a reward function, an initial state, optional terminal states. \n\nSolution for MDP is a policy, maps a state onto the action. \n\nIn search problem solution is plan, gives a sequence of action. \n\nFinite horizon: terminate episodes after a fixed steps. \n\nGives nonsstationary policies. \n\nSmaller gamma means smaller “horizon” – shorter term focus. \n\n$$ V^*(s) = max_a Q^*(s,a) $$\n$$ Q^*(s,a) = \\Sigma_{s'} T(s,a,s')[R(s,a,s')+\\gamma V^*(s')] $$\nTime limited: $V_k(s)$ in k steps. \n\nComplexity of each iteration $O(S^2A)$ \n\nFixed policy: $O(S^2)$ each iteration. \n\nPolicy evaluation: calculate utilities for some fixed policy until convergence. \n\nPolicy improvement: update policy using one-step look-ahead. \n\nRepeat steps until policy converges: policy iteration, much faster. \n\nInsensitivity to monotonic transformations: terminal function scale doesn't matter, only order need. \n\nThis is worst-case. However for average-case expectimax, magnitudes are meaningful. \n\nAxioms of Rationality: orderability, transitivity, continuity, substitutability, monotonicity. \n\nMEU: choose action that maximizes expected utility.\n\n\n## Module 8 Definitions\n* **Utility function** - Sum of all rewards function values, with/out discounts\n* **Expected utility** - expected total rewards starting here\n* **Mdp** - Markov decision process\n* **Absorbing state** - guarantee that for every policy, a terminal state will eventually be reached\n* **Bellman equations** - Correct first step and keep optimal\n* **Meu principle** - maximum expected utility principle\n* **Micromorts** - one-millionth chance of death, useful for paying to reduce product risks, etc.\n* **Qalys** - quality-adjusted life years, useful for medical decisions involving substantial risk\n\n\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\nExploration: try unknown actions to get information. \n\nExploitation: eventually to use what we know. \n\nRegret: even if we learn intelligently, we make mistakes. \n\nSampling: because of chance, we have to try things repeatedly. \n\nDifficulty: learning can be much harder rhan solving MDP. \n\nModel based learning: learn approximate model, then solve using the model. \n\nPassive reinforcement learning: fixed policy, execute and learn.\n\nDirect evaluation: compute values for each state under pi, average together observed sample values. \n\nTemporal difference learning: \n\nSample of V(s): $sample = R(s,\\pi(s), s')+\\gamma V^{\\pi}(s')$\n\nUpdate to V(s): $V^{\\pi}(s)\\leftarrow (1-a)V^{\\pi}(s)+(a)sample$\n\nExponential moving average: $x'_n = \frac{x_n+(1-a)x_{n-1}+(1-a)^2x_{n-2}+...}{1+(1-a)+(1-a)^2+...}$\n\nQ-Learning: calculate Q values instead.\n\nQ-learning converges to optimal policy, even for suboptimal actions. better than v.\n\noff-policy learning.\n\nExplore: simple random actions, flip a coin.\n\nExploration functions: takes a value estimate u and a visit count n, returns an optimistic utility. e.g. $f(u,n)=u+k/n$\n\nRegular Q-Update: $Q(s,a)\\leftarrow_a R(s,a,s')+\\gamma max_{a'}Q(s',a')$\n\nModified Q-Update: $Q(s,a)\\leftarrow_a R(s,a,s')+\\gamma max_{a'}f(Q(s',a'), N(s'.a'))$\n\nRegret is a measure of your total mistake cost: the difference between your (expected) rewards, including youthful suboptimality, and optimal (expected) rewards.\n\nMinimizing regret required optimally learning to be optimal.\n\nlinear value functions: using weight to combine features, get values.\n\n\n## Module 9 Definitions\n* **Off-policy learning** - learn without optimal policy\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\nObserved variables (evidence): Agent knows certain things about the state of the world (e.g.,\nsensor readings or symptoms)\n\nUnobserved variables (states): Agent needs to reason about other aspects (e.g. where an object\nis or what disease is present)\n\nModel: Agent knows something about how the known variables relate to the unknown variables.\n\nA joint distribution over a set of random variables x1, x2,..., xn \nspecifies a real number for each assignment (or outcome). \n\nMLE: maximum likelihood estimation.\n\nProblems for MLE:\n\nOut of vocabulary items (OOV)\n\n<unk> to deal with OOVs\n\nFixed lexicon L of size V\n\nNormalize training data by replacing any word not in L with <unk>\n\nAvoid zeros with smoothing\n\nStationary process: the conditional probability table does not change over time\n\nDBN requires: The sensor model, The transition model, The prior distribution over the state variables.\n\nEvaluate n-gram model: perplexity on a test set.\n\n\n\n\n## Module 10 Definitions\n* **Random variable** - some aspect of the world about which we (may) have uncertainty\n* **Distribution** - a TABLE of probabilities of values\n* **Probability** - a single number of value\n* **Probabilistic model** - a joint distribution over a set of random variables\n* **Event** - a set E of outcomes\n* **Marginal distributions** - sub-tables which eliminate variables\n* **Marginalization** - Combine collapsed rows by adding\n* **Conditional probability** - P(a|b)=P(a,b)/P(b)\n* **Conditional distributions** - probability distributions over some variables given fixed values of others\n* **Probabilistic inference** - compute a desired probability from other known probabilities\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 either the probability of a sentence / sequence of words or an upcoming word.\n* **Mle** - P(won|the underdog team)=Count(the underdog team won)/Count(the underdog team)\n* **Markov assumption** - next word only depends on the previous k words\n* **Dbn** - dynamic Bayesian model\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\nX is conditionally independent of Y given Z\n\niff $v(x,y,z): P(x,y|z)=P(x|z)P(y|z)$\n\nor equivalently, iff $v(x,y,z): P(x|z,y)=P(x|z)$\n\nNodes: variables (with domains), can be assigned (observed) or unassigned (unobserved),\n\nArcs: interactions, direct influence between variables.\n\nA Bayes net = Topology (graph) + Local Conditional Probabilities\n\nBayes’ nets implicitly encode joint distributions\n\nNot every BN can represent every joint distribution\n\nThe topology enforces certain conditional independencies\n\nTopology really encodes conditional independence, need not to be causal.\n\nHow big is a joint distribution over N Boolean variables? 2^N\n\nHow big is an N-node net if nodes have up to k parents? $O(N*2^{k+1})$\n\nCausal chains: x cause y cause z: x given y is independent of z\n\n$P(x,y,z)=P(x)P(y|x)P(z|y)$\n\nCommon cause: y cause x and z: x and z independent given y\n\n$P(x,y,z) = P(y)P(x|y)P(z|y)$\n\nCommon effect: x and y both cause z: x and y independent\n\nIf one or more active triples, not independent\n\nAll paths are inactive, independence.\n\nWhy is inference by enumeration so slow?\n\nYou join up the whole joint distribution before you sum out the hidden variables.\n\nAdvanced technique: Variable Elimination\n\nInterleave joining and marginalizing, still NP-hard, but usually much faster\n\n\n\n## Module 11 Definitions\n* **Bayes' nets** - a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities)\n* **D-separation** - check paths for independence\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\nWhat do we need in order to use Naïve Bayes?\n\nInference method: \n\nStart with a bunch of probabilities: P(Y) and the P(Fi|Y) tables,\n\nUse standard inference to compute P(Y|F1…Fn)\n\nEstimates of local conditional probability tables:\n\nP(Y), the prior over labels\n\nP(Fi|Y) for each feature (evidence variable)\n\nThese probabilities are collectively called the parameters of the model and denoted by $\theta$\n\n\n\nBag-of-words Naïve Bayes:\n\nFeatures: Wi is the word at positon i\n\nPredict label conditioned on feature variables (spam vs. ham)\n\nAssume features are conditionally independent given label\n\nEach Wi is identically distributed\n\nAll positions share the same conditional probs P(W|Y)\n\nModel is insensitive to word order or reordering\n\nData: training set, held out set, test set.\n\nRelative frequency parameters will overfit the training data\n\nRelative frequencies are the maximum likelihood estimates\n\nLaplace’s estimate: \n\nPretend you saw every outcome once more than you actually did.\n\nExtended: Pretend you saw every outcome k extra times\n\nlinear interpolation: \n\nAlso get the empirical P(X) from the data, Make sure the estimate of P(X|Y) isn’t too different from the\nempirical P(X)\n\n$P_{LIN}(x|y) = a P(x|y) + (1.0-a)P(x)$\n\nTuning on Held-Out Data: try different hyperparameters.\n\n\n\nBaselines are very simple “straw man” procedures, help determin hardness and accuracy.\n\nWeak baseline: most frequent label classifier\n\nThe confidence of a probabilistic classifier is:\n\n$confidence(x)=max_y P(y|x)$\n\nCalibration:\n\nWeak calibration: higher confidences mean higher accuracy\n\nStrong calibration: confidence predicts accuracy rate\n\n\n\nLinear classifiers:\n\n$activation_w(x) = \\Sigma_i w_i * f_i(x) = w*f(x)$\n\nBinary Perceptron: start with weights = 0, adjust while learning.\n\n$w=w+y^*f$, y* could be 1 or -1\n\nFor multiple classes:\n\nWeight vector for each class $w_y$\n\nScore (activation) of a class y: $w_y f(x)$\n\nPrediction highest score wins: $y=argmax_y w_y f(x)$\n\nLearn: if wrong, lover score of wrong answer, raise score of right answer:\n\n$w_y = w_y - f(x)$, $w_{y^*} = w_{y^*} + f(x)$\n\nProblems:\n\nNoise: average weight vectors\n\nMediocre generalization: finds a barely separating solution.\n\nOvertraining: test/held-out accuracy usually rises then falls.\n\nFixing:\n\nMinimum correcting update, maximum step size, maximizing the margin.\n\nComparison:\n\nNB:\n\nBuilds a model training data\n\nGives prediction probabilities\n\nStrong assumptions about feature independence\n\nOne pass through data (counting)\n\nPerceptrons/MIRA:\n\nMakes less assumptions about data\n\nMistake-driven learning\n\nMultiple passes through data (prediction)\n\nOften more accurate\n\nNon-linear separators:\n\nthe original feature space can always be mapped to some\nhigher-dimensional feature space where the training set is separable\n\nThree common non-linear activation functions:\n\nThe sigmoid function\n\nThe tanh function\n\nThe rectified linear unit ReLU\n\nHigher bias value: easier for 1\n\n\n## Module 12 Definitions\n* **Classification** - given inputs x, predict labels y\n* **Features** - attribute-value pairs which characterize each variable\n* **Accuracy** - fraction of instances predicted correctly\n* **Overfitting** - fitting the training data very closely, but not generalizing well\n* **Separability** - true if some parameters get the training set perfectly correct\n* **Convergence** -  if the training is separable, perceptron will eventually converge (binary case)\n* **Mistake bound** - the maximum number of mistakes (binary case) related to the margin or degree of separability\n* **Bias** - -1 times threshold\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\nClassifier components:\n\n1. A feature representation of the input.\n\n2. A classification function that computes the estimated class y via p(y|x)\n\n3. An objective function for learning, usually involving minimizing error on training examples.\n\n4. An algorithm for optimizing the objective function.\n\n\n\nSentiment classifier:\n\nExtract feature, calculate $z=\\Sigma_i w_i x_i + b$, apply to sigmoid function, make decision.\n\nLearning weights + bias needs:\n\n1. An objective function or loss function that tells us distance between\nthe system output and the gold output. We will use cross-entropy\nloss.\n\n2. An algorithm for optimizing the objective function. We will use\nstochastic gradient descent to minimize the loss function.\n\nGradient descent is a method that finds a minimum of a function by figuring out in\nwhich direction (in the space of the parameters θ) the function’s slope is rising the most\nsteeply, and moving in the opposite direction.\n\nStochastic gradient descent chooses a single random example at a time and updates\nits weights on that example. As a result the updates can fluctuate.\n\nAn alternate is batch training, which computes the gradient over the entire dataset.\nThis gives a much better estimate of which direction to move the weights but takes a\nlong time to compute\n\nA commonly used compromise is mini-batch training, where we train on a small\nbatch. The batch size can be 512 or 1024.\n\nThe simplest kind of NN is the Feed-Forward Neural Network\n\nMultilayer network, all units are usually fully-connected, and no cycles.\n\nThe outputs from each layer are passed to units in the next higher layer, and no\noutputs are passed back to lower layers.\n\nFormulas: \n\nh = σ(Wx+b)\n\nz = Uh\n\ny = softmax(z)\n\nTraining NN:\n\nA loss function – cross-entropy loss\n\nAn optimization algorithm – gradient descent\n\nA way of computing the gradient of the loss function – error propagation\n\n\n\n\n## Module 13 Definitions\n* **Decision boundary** - yes or no boundary of the probability\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\n1. Synonyms – words that have similar meanings\n\n2. Antonyms – words that have opposite meanings\n\n3. Connotations – words that are positive or negative\n\n4. Semantic Roles – buy, sell, and pay are different parts of the same underlying\npurchasing event\n\n5. Support for entailment, belongs, includes\n\nTerm-Document matrix:\n\ncolumns for documents, rows for word counts\n\nCompare column vectors.\n\nVector normalization: divide vectors by its L2 length:\n\n$||u||=sqrt(\\Sigma u_i^2)$\n\nThen calculate their distance.\n\nOr cosine distance.\n\nTerm-Term matrix AKA Term-context matrix:\n\nValue in a cell indicates how often the column word appears in a context\nwindow surrounding row word.\n\n\n\nNeural Language models have several advantages over n-gram LMs:\n\n1. They don’t need smoothing\n\n2. They can handle much longer histories, larger N.\n\n3. They can generalize over contexts of similar words.\n\n4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\n\nDisadvantage: slower to train than traditional n-gram LMs\n\nNLM:\n\nInput is a k-gram of words,\n\nOutput is a probability distribution over the next word.\n\nEmbeddings = vector models of meaning\n\nMore fine-grained than just a string or index\n\nEspecially good at modeling similarity/analogy\n\nCan use sparse models (tf-idf) or dense models (word2vec, GLoVE)\n\nUseful in practice but know they encode cultural stereotypes.\n\n\n## Module 14 Definitions\n* **Tf-idf** - term frequency * inverse document frequency\n* **Tf** - How often a word occurred in a document\n* **Idf** - 1 over the number of documents that it occurred in\n* **Place** - \n\n\n\n\n\n\n\n\n\n\n\n\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}