{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of Template_for CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "9aab70f7-9bfd-4dbe-e03a-e42013db1718"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "de2015e9-c3cd-4335-b05b-acb80851e793"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = True"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" goal-based agent vs. decision-theoretic agent. Basic principle of decision theory: max of expected utility. A rational agent should choose the action\n",
        "that maximizes the exptected utility. \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" constraints on rational preferences. Axiom of rationality. Assuming the constraints on rational preferences a utility function exists for any rational agent. \"\"\"\n",
        "chapter16_3 =  \"\"\" utility function is a map from states to real numbers. \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" sequential decision problem, fully observable, stochastic environment with Markovian transition model and additive rewards - MDP.  \"\"\"\n",
        "chapter17_2 =  \"\"\" Algos for MDP: value iteration; policy iteration; linear programming, and Monte Carlo planning \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\" MDPS are useful for fully observable task environments where we have to make a sequence of decisions, and where the outcome for actions we take are \n",
        "non-deterministic. The transition function is sometimes written as T(s, a, s'), or explicitly as a probability p(s'|s, a). Rewards can be positive or negative but are bounded by \n",
        "some maximum value. Rewards are additive. MDP is a sequential decision problem  for a fully observable environment with a stochastic transition model that has additive rewards. \n",
        "Even if the same policy is executed multiple times by the agent, this may lead to different sequence of states and actions (environment history), and thus a different score under \n",
        "the reward function. We need to compute the expected utility of all the possible paths generated by a policy. Finite horizons: An optimal action can depend on how much time is left. \n",
        "Policies that depend on time are called nonstationary. Infinite horizons: The optimal policy is stationary. Infinite horizons are therefore easier. Prefer reward earlier than later.\n",
        "values of rewards decay exponentially. Theorem: if we assume stationary preferences then there are only two ways to define utilities. Additive and discounted. Solutions for infinite\n",
        "utilities. 1. Finite horizon. 2. Discounting. 3. Absorbing states. Value iteration: Theorem: will converge to unique optimal values. Basic idea: approximations get refined towards \n",
        "optimal values. Policy may converge long before values do. Policy valuation. Fixed policy. Important lesson: actions are easier to select from q-values than values!\n",
        "Problems with Value Iteration: 1. it is slow O(S^2A). 2. The max at each state rarely changes. 3. The policy often converges long before the values. Better option: policy iteration.\n",
        "Policy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence. 2: Policy improvement: update policy using one-step look-ahead with resulting \n",
        "converged (but not optimal!) utilities as future values. Repeat steps until policy converges. Still optimal and Can converge (much) faster under some conditions.\n",
        "Both value iteration and policy iteration compute the same thing (all optimal values). In value iteration: 1. Every iteration updates both the values and (implicitly) the policy\n",
        "2. We don’t track the policy, but taking the max over actions implicitly recomputes it. \n",
        "In policy iteration: 1. We do several passes that update utilities with fixed policy (each pass is fast because we consider only one action, not all of them). 2. After the policy \n",
        "is evaluated, a new policy is chosen (slow like a value iteration pass). 3. The new policy will be better (or we’re done). Both are dynamic programs for solving MDPs.\n",
        "A rational agent should choose the action that maximizes its expected utility, given its knowledge\"\"\"\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\" : \"maps states/outcomes to real numbers\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "\"etc.\": \"your definition here\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 910
        },
        "outputId": "b41f145d-5fb2-478c-cff0-cca6bd63815f"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n goal-based agent vs. decision-theoretic agent. Basic principle of decision theory: max of expected utility. A rational agent should choose the action\nthat maximizes the exptected utility.  $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 constraints on rational preferences. Axiom of rationality. Assuming the constraints on rational preferences a utility function exists for any rational agent. \n\n## AIMA Chapter 16.3 Utility Functions\n utility function is a map from states to real numbers. \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n sequential decision problem, fully observable, stochastic environment with Markovian transition model and additive rewards - MDP.  \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Algos for MDP: value iteration; policy iteration; linear programming, and Monte Carlo planning \n\n## Module 8 Lecture Notes\n MDPS are useful for fully observable task environments where we have to make a sequence of decisions, and where the outcome for actions we take are \nnon-deterministic. The transition function is sometimes written as T(s, a, s'), or explicitly as a probability p(s'|s, a). Rewards can be positive or negative but are bounded by \nsome maximum value. Rewards are additive. MDP is a sequential decision problem  for a fully observable environment with a stochastic transition model that has additive rewards. \nEven if the same policy is executed multiple times by the agent, this may lead to different sequence of states and actions (environment history), and thus a different score under \nthe reward function. We need to compute the expected utility of all the possible paths generated by a policy. Finite horizons: An optimal action can depend on how much time is left. \nPolicies that depend on time are called nonstationary. Infinite horizons: The optimal policy is stationary. Infinite horizons are therefore easier. Prefer reward earlier than later.\nvalues of rewards decay exponentially. Theorem: if we assume stationary preferences then there are only two ways to define utilities. Additive and discounted. Solutions for infinite\nutilities. 1. Finite horizon. 2. Discounting. 3. Absorbing states. Value iteration: Theorem: will converge to unique optimal values. Basic idea: approximations get refined towards \noptimal values. Policy may converge long before values do. Policy valuation. Fixed policy. Important lesson: actions are easier to select from q-values than values!\nProblems with Value Iteration: 1. it is slow O(S^2A). 2. The max at each state rarely changes. 3. The policy often converges long before the values. Better option: policy iteration.\nPolicy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence. 2: Policy improvement: update policy using one-step look-ahead with resulting \nconverged (but not optimal!) utilities as future values. Repeat steps until policy converges. Still optimal and Can converge (much) faster under some conditions.\nBoth value iteration and policy iteration compute the same thing (all optimal values). In value iteration: 1. Every iteration updates both the values and (implicitly) the policy\n2. We don’t track the policy, but taking the max over actions implicitly recomputes it. \nIn policy iteration: 1. We do several passes that update utilities with fixed policy (each pass is fast because we consider only one action, not all of them). 2. After the policy \nis evaluated, a new policy is chosen (slow like a value iteration pass). 3. The new policy will be better (or we’re done). Both are dynamic programs for solving MDPs.\nA rational agent should choose the action that maximizes its expected utility, given its knowledge\n\n## Module 8 Definitions\n* **Utility function** - maps states/outcomes to real numbers\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\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 = \"\"\" Reinforcement learning is similar to MDPs but the transition and the reward function are not given to to the agent.  Instead they must be learned \n",
        "through interaction with the world. In reinforcement learning, every time an agent takes an action, it receives feedback in the form of a reward, and so the agent wants to \n",
        "maximize its expected rewards. quantify how good different exploration strategies are using regret. Solving MDPs is offline planning. You determine all quantities through computation.\n",
        "You need to know the details of the MDP. You do not actually play the game! But reinforcement learning is online learning. Important ideas in reinforcement learning. \n",
        "1. Exploration: you have to try unknown actions to get information. 2. Exploitation: eventually, you have to use what you know. 3 Regret: even if you learn intelligently, \n",
        "you make mistakes. 4. Sampling: because of chance, you have to try things repeatedly. 5. Difficulty: learning can be much harder than solving a known MDP.\n",
        "Basic idea: 1. Receive feedback in the form of rewards. 2. Agent’s utility is defined by the reward function. 3. Must (learn to) act so as to maximize expected rewards.\n",
        "4. All learning is based on observed samples of outcomes!\n",
        "Model-Based learning idea: 1. Learn an approximate model based on experiences 2. Solve for values as if the learned model were correct\n",
        "Model free learning. Full reinforcement learning: optimal policies (like value iteration) 1. don’t know the transitions T(s,a,s’). 2. don’t know the rewards R(s,a,s’)\n",
        "3. choose the actions now. 4. Goal: learn the optimal policy / values. Fundamental tradeoff: exploration vs. exploitation. \n",
        "Q-learning converges to optimal policy -- even if you’re acting suboptimally! This is called off-policy learning. Caveats: have to explore enough; have to eventually make the \n",
        "learning rate small enough but not decrease it too quickly. Even if you learn the optimal policy, still make mistakes along the way! Regret is a measure of total mistake cost: \n",
        "the difference between expected rewards and optimal (expected) rewards. Minimizing regret goes beyond learning to be optimal – it requires optimally learning to be optimal. \n",
        "Example: random exploration and exploration functions both end up optimal, but random exploration has higher regret. Approximate Q-learning. use features of states. \n",
        "Advantage: our experience is summed up in a few powerful numbers. Disadvantage: states may share features but actually be very different in value!. \n",
        "Problems with direct evaluation: wastes information about state connections; Each state must be learned separately; so it takes a long time to learn. \n",
        "TD value leaning is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages. However, if we want to turn values into a (new) policy, \n",
        "we’re sunk. Idea: learn Q-values not values. \"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 870
        },
        "outputId": "be7154e0-6357-4a38-a32c-7a38cf4d582c"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n Reinforcement learning is similar to MDPs but the transition and the reward function are not given to to the agent.  Instead they must be learned \nthrough interaction with the world. In reinforcement learning, every time an agent takes an action, it receives feedback in the form of a reward, and so the agent wants to \nmaximize its expected rewards. quantify how good different exploration strategies are using regret. Solving MDPs is offline planning. You determine all quantities through computation.\nYou need to know the details of the MDP. You do not actually play the game! But reinforcement learning is online learning. Important ideas in reinforcement learning. \n1. Exploration: you have to try unknown actions to get information. 2. Exploitation: eventually, you have to use what you know. 3 Regret: even if you learn intelligently, \nyou make mistakes. 4. Sampling: because of chance, you have to try things repeatedly. 5. Difficulty: learning can be much harder than solving a known MDP.\nBasic idea: 1. Receive feedback in the form of rewards. 2. Agent’s utility is defined by the reward function. 3. Must (learn to) act so as to maximize expected rewards.\n4. All learning is based on observed samples of outcomes!\nModel-Based learning idea: 1. Learn an approximate model based on experiences 2. Solve for values as if the learned model were correct\nModel free learning. Full reinforcement learning: optimal policies (like value iteration) 1. don’t know the transitions T(s,a,s’). 2. don’t know the rewards R(s,a,s’)\n3. choose the actions now. 4. Goal: learn the optimal policy / values. Fundamental tradeoff: exploration vs. exploitation. \nQ-learning converges to optimal policy -- even if you’re acting suboptimally! This is called off-policy learning. Caveats: have to explore enough; have to eventually make the \nlearning rate small enough but not decrease it too quickly. Even if you learn the optimal policy, still make mistakes along the way! Regret is a measure of total mistake cost: \nthe difference between expected rewards and optimal (expected) rewards. Minimizing regret goes beyond learning to be optimal – it requires optimally learning to be optimal. \nExample: random exploration and exploration functions both end up optimal, but random exploration has higher regret. Approximate Q-learning. use features of states. \nAdvantage: our experience is summed up in a few powerful numbers. Disadvantage: states may share features but actually be very different in value!\n\n## Module 9 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" speech recognition; spelling correction; grammatical error correction all need probabilities. Models that assign probabilities to sequences of words are called \n",
        "language model or LM. N-gram model. Markov assumption. In practice it is more common to use 3 or 4 grams rather than 2 grams. Use log probabilities to avoid underflow.\"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Evaluation: perplexity; can also be thought as the weighted average branching factor of a language. The branching factor of a language is the number \n",
        "of possible next words that can follow any word \"\"\"\n",
        "SLP_chapter3_3 = \"\"\"  Sampling sentences from a language model \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Generalization and Zeros. OOV: 1. unknown words using <UNK>  \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Smoothing. Laplace (add 1). A related way to view smoothing is as discounting (lowering) \n",
        "some non-zero counts in order to get the probability mass that will be assigned to the zero counts. \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Huge Language Models and Stupid Backoff. If a higher-order n-gram has a zero count, we simply backoff to a\n",
        "lower order n-gram, weighed by a fixed (context-independent) weight. \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\" Observed variables (evidence); Unobserved variables (states); Model: Agent knows something about how the known variables relate to the unknown variables.\n",
        "Probabilistic Language Models. One goal: assign a probability to a sentence. Autocomplete for texting; Machine Translation; Spelling Correction; Speech Recognition. \n",
        "Related task: probability of an upcoming word. Simplifying Assumption = Markov Assumption. Only depends on the previous k words not the entire context.\n",
        "N-gram model in general is an insufficient model of language because language has long-distance dependencies. Problems with MLE: Out of vocabulary. <unk> to deal with OOV.\n",
        "Avoid zeros with smoothing. Use log space to avoid underflow. \"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "5e1c0032-5202-44f9-d3ce-439dd03f0592"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n speech recognition; spelling correction; grammatical error correction all need probabilities. Models that assign probabilities to sequences of words are called \nlanguage model or LM. N-gram model. Markov assumption. In practice it is more common to use 3 or 4 grams rather than 2 grams. Use log probabilities to avoid underflow.\n\n## SLP Chapter 3.2 Evaluating Language Models\n Evaluation: perplexity; can also be thought as the weighted average branching factor of a language. The branching factor of a language is the number \nof possible next words that can follow any word \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n  Sampling sentences from a language model \n\n## SLP Chapter 3.4 Generalization and Zeros\n Generalization and Zeros. OOV: 1. unknown words using <UNK>  \n\n## SLP Chapter 3.5 Smoothing\n Smoothing. Laplace (add 1). A related way to view smoothing is as discounting (lowering) \nsome non-zero counts in order to get the probability mass that will be assigned to the zero counts. \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Huge Language Models and Stupid Backoff. If a higher-order n-gram has a zero count, we simply backoff to a\nlower order n-gram, weighed by a fixed (context-independent) weight. \n\n## Module 10 Lecture Notes\n Observed variables (evidence); Unobserved variables (states); Model: Agent knows something about how the known variables relate to the unknown variables.\nProbabilistic Language Models. One goal: assign a probability to a sentence. Autocomplete for texting; Machine Translation; Spelling Correction; Speech Recognition. \nRelated task: probability of an upcoming word. Simplifying Assumption = Markov Assumption. Only depends on the previous k words not the entire context.\nN-gram model in general is an insufficient model of language because language has long-distance dependencies. Problems with MLE: Out of vocabulary. <unk> to deal with OOV.\nAvoid zeros with smoothing. Use log space to avoid underflow. \n\n## Module 10 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Bayes Nets: complete; nonredundant and compact. Locally structured (sparse) system: linear growth. \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" Conditional independence. Conditional independence is our most basic and robust form of knowledge about uncertain environments.\n",
        "Bayes Nets are directed acyclic graphs, where the nodes represent random variables in our probability model, and the arcs encode our assumption about how the variables are \n",
        "related to each other. Bayes Nets are compact representations that allow us to encode independence assumptions between variables. \n",
        "Bayes’ nets: a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities). Nodes: variables; arcs: interactions\n",
        "A Bayes net = Topology (graph) + Local Conditional Probabilities. A set of nodes, one per variable X. A directed, acyclic graph. A conditional distribution for each node.\n",
        "Bayes’ nets implicitly encode joint distributions. BNs need not actually be causal, could reflect correlation. Topology really encodes conditional independence. \n",
        "Size of a joint distribution over N Boolean variables is 2^N. Size of an N-node net if nodes have up to k parents is O(N * 2(k+1))\n",
        "D-separation: causal chain: x->y->z. Evidence along the chain blocks the influence; common cause: Observing the cause blocks influence between effects. common effect: \n",
        "Observing an effect activates influence between possible causes. Any complex example can be broken into repetitions of the three canonical cases. \n",
        "if X and Y are d-separated by Z then X and Y are conditionally independent given evidence variables Z. Consider all (undirected) paths from X to Y, No active paths = independence!\n",
        "A path is active if each triple is active: Causal chain A → B → C where B is unobserved (either direction). Common cause A ← B → C where B is unobserved. Common effect (v-structure)\n",
        "A → B ← C where B or one of its descendants is observed. All it takes to block a path is a single inactive segment. \n",
        "Inference: calculating some useful quantity from a joint probability distribution. join up the whole joint distribution before summing out the hidden variables. slow\n",
        "Variable elimination: Interleave joining and marginalizing. still NP-hard but faster than inference by enumeration.\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 636
        },
        "outputId": "eb8be4b0-9d6e-4d71-cbdb-6ef55ba438ee"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Bayes Nets: complete; nonredundant and compact. Locally structured (sparse) system: linear growth. \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 Conditional independence. Conditional independence is our most basic and robust form of knowledge about uncertain environments.\nBayes Nets are directed acyclic graphs, where the nodes represent random variables in our probability model, and the arcs encode our assumption about how the variables are \nrelated to each other. Bayes Nets are compact representations that allow us to encode independence assumptions between variables. \nBayes’ nets: a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities). Nodes: variables; arcs: interactions\nA Bayes net = Topology (graph) + Local Conditional Probabilities. A set of nodes, one per variable X. A directed, acyclic graph. A conditional distribution for each node.\nBayes’ nets implicitly encode joint distributions. BNs need not actually be causal, could reflect correlation. Topology really encodes conditional independence. \nSize of a joint distribution over N Boolean variables is 2^N. Size of an N-node net if nodes have up to k parents is O(N * 2(k+1))\nD-separation: causal chain: x->y->z. Evidence along the chain blocks the influence; common cause: Observing the cause blocks influence between effects. common effect: \nObserving an effect activates influence between possible causes. Any complex example can be broken into repetitions of the three canonical cases. \nif X and Y are d-separated by Z then X and Y are conditionally independent given evidence variables Z. Consider all (undirected) paths from X to Y, No active paths = independence!\nA path is active if each triple is active: Causal chain A → B → C where B is unobserved (either direction). Common cause A ← B → C where B is unobserved. Common effect (v-structure)\nA → B ← C where B or one of its descendants is observed. All it takes to block a path is a single inactive segment. \nInference: calculating some useful quantity from a joint probability distribution. join up the whole joint distribution before summing out the hidden variables. slow\nVariable elimination: Interleave joining and marginalizing. still NP-hard but faster than inference by enumeration.\n\n## Module 11 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" subject category classification is the task for which the naive Bayes algorithm was invented in 1961.  A probabilistic classifier additionally will tell us the \n",
        "probability of the observation being in the class. Generative classifiers like naive Bayes build a model of how a class could generate some input data. Given an observation, \n",
        "they return the class most likely to have generated the observation. Discriminative classifiers like logistic regression instead learn what features from the input are most useful \n",
        "to discriminate between the different possible classes. Naive Bayes is a probabilistic classifier, meaning that for a document d, out of all classes c ∈ C the classifier returns \n",
        "the class c_hat which has the maximum posterior probability given the document. Naive Bayes classifiers make two simplifying assumptions. The first is the bag of words assumption: \n",
        "position doesn’t matter. The second is called the naive Bayes assumption: this is the conditional independence assumption that the probabilities P(fi|c) are independent given\n",
        "the class c. P(f1, f2,...., fn|c) = P(f1|c)·P(f2|c)· ... ·P(fn|c). The solution for such unknown words is to ignore them—remove them from the test document and not include any \n",
        "probability for them at all.\"\"\"\n",
        "slp_chapter4_2 = \"\"\" Training the Naive Bayes Classifier \"\"\"\n",
        "slp_chapter4_3 = \"\"\" An example \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Optimizing for Sentiment Analysis. For sentiment classification and some other text classification tasks, whether a word occurs or not seems to matter \n",
        "more than its frequency so it often improves performance to clip the word counts in each document at 1. This is called binary NB. A second important addition commonly made \n",
        "is to deal with negation. A very simple baseline to deal with negation is the following: during text normalization, prepend the prefix NOT to every word after a token of logical \n",
        "negation (n’t, not, no, never) until the next punctuation mark. \"didn’t like this movie , but I\" changes to \"didn’t NOT_like NOT_this NOT_movie , but I\". When training data is \n",
        "sparse or not representative of the test set, using dense lexicon features instead of sparse individual-word features\n",
        "may generalize better\"\"\"\n",
        "slp_chapter4_5 = \"\"\" spam detection; text classification \"\"\"\n",
        "slp_chapter4_6 = \"\"\" a naive Bayes model can be viewed as a set of class-specific unigram language models, in which the model for each class instantiates a unigram language model.\n",
        " \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Evaluation: Precision, Recall, F-measure. Harmonic mean is used because it is a conservative metric; the harmonic mean of two values is closer to the minimum \n",
        "of the two values than the arithmetic mean is. Thus it weighs the lower of the two numbers more heavily. In macroaveraging, we compute the performance for each class, and then \n",
        "average over classes. In microaveraging, we collect the decisions for all classes into a single confusion matrix, and then compute precision and recall from that table. \n",
        "The macroaverage better reflects the statistics of the smaller classes, and so is more appropriate when performance on all the classes is equally important\"\"\"\n",
        "slp_chapter4_8 = \"\"\" Test and cross validation \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Statistical Significance Testing. There are two common non-parametric tests used in NLP: approximate randomization and the bootstrap test. Paired bootstrap test:\n",
        "compare two sets of observations that are aligned: each observation in one set can be paired with an observation in another. when comparing the performance of two systems on the \n",
        "same test set; we can pair the performance of system A on an individual observation xi with the performance of system B on the same xi. The intuition of the bootstrap test is that \n",
        "we can create many virtual test sets from an observed test set by repeatedly sampling from it.\"\"\"\n",
        "slp_chapter4_10 = \"\"\" avoid harms, bias \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\" Machine Learning = a computer observes data; builds a model; uses the model as a hypothesis about the world and as software that can solve problems.\n",
        "Naive Bayes: assume all features are independent effects of the label. only have to specify how each feature depends on the class. Total number of parameters is linear in number \n",
        "of features. Inference for naive bayes: compute posterior distribution over label variable Y. Assume features are conditionally independent given label. Overfitting issues.\n",
        "Laplace smoothing for unseen values (Pretend you saw every outcome once more than you actually did). Naive Bayes models can incorporate a variety of features, but tend to do best \n",
        "in homogeneous cases (e.g. all features are word occurrences). Perceptron: linear classifier; activation is the sum. >=0 then +1, otherwise -1. Learning: if wrong: adjust the weight \n",
        "vector by adding or subtracting the feature vector. W=W+y_hat*f. For multi-class perceptron: if wrong: lower score of wrong answer, raise score of right answer. \n",
        "Convergence: if the training is separable, perceptron will eventually converge (binary case). Mistake Bound: the maximum number of mistakes (binary case) related to the margin or \n",
        "degree of separability. Problems with perceptrons: Noise: if the data isn’t separable, weights might thrash. Averaging weight vectors over time can help (averaged perceptron). \n",
        "Mediocre generalization: finds a “barely” separating solution. Overtraining: test / held-out accuracy usually rises, then falls. MIRA = Margin Infused Relaxed Algorithm. \n",
        "Choose an update size that fixes the current mistake but minimizes the change to w \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "eefd9139-e9d8-4aa7-d11f-3c057a95e3a0"
      },
      "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 19.1 Forms of Learning\", chapter19_1),\n",
        "  (\"AIMA Chapter 19.2 Supervised Learning\", chapter19_2),\n",
        "  (\"AIMA Chapter 19.3 Learning Decision Trees\", chapter19_3),\n",
        "  (\"AIMA Chapter 19.4 Model Selection and Optimization\", chapter19_4),\n",
        "  (\"AIMA Chapter 19.5 The Theory of Learning\", chapter19_5),\n",
        "  (\"AIMA Chapter 19.6 Linear Regression and Classification\", chapter19_6),\n",
        "  (\"SLP Chapter 4.1 Naive Bayes Classifiers\", slp_chapter4_1),\n",
        "  (\"SLP Chapter 4.2 Training the Naive Bayes Classifier\", slp_chapter4_2),\n",
        "  (\"SLP Chapter 4.3 Worked Example\", slp_chapter4_3),\n",
        "  (\"SLP Chapter 4.4 Optimizing for Sentiment Analysis\", slp_chapter4_4),\n",
        "  (\"SLP Chapter 4.5 Naive Bayes for other text classification tasks\", slp_chapter4_5),\n",
        "  (\"SLP Chapter 4.6 Naive Bayes as a Language Model\", slp_chapter4_6),\n",
        "  (\"SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\", slp_chapter4_7),\n",
        "  (\"SLP Chapter 4.8 Test sets and Cross-validation\", slp_chapter4_8),\n",
        "  (\"SLP Chapter 4.9 Statistical Significance Testing\", slp_chapter4_9),\n",
        "  (\"SLP Chapter 4.10 Avoiding Harms in Classification\", slp_chapter4_10),\n",
        "  (\"Module 12 Lecture Notes\", module12_lecture_notes),\n",
        "]\n",
        "\n",
        "module12_markdown = format_module(12, \"Naive Bayes and Perceptrons\", \n",
        "                         module12_sections, \n",
        "                         module12_definitions)\n",
        "display(Markdown(module12_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 19.1 Forms of Learning\n Your summary here \n\n## AIMA Chapter 19.2 Supervised Learning\n Your summary here \n\n## AIMA Chapter 19.3 Learning Decision Trees\n Your summary here \n\n## AIMA Chapter 19.4 Model Selection and Optimization\n Your summary here \n\n## AIMA Chapter 19.5 The Theory of Learning\n Your summary here \n\n## AIMA Chapter 19.6 Linear Regression and Classification\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n subject category classification is the task for which the naive Bayes algorithm was invented in 1961.  A probabilistic classifier additionally will tell us the \nprobability of the observation being in the class. Generative classifiers like naive Bayes build a model of how a class could generate some input data. Given an observation, \nthey return the class most likely to have generated the observation. Discriminative classifiers like logistic regression instead learn what features from the input are most useful \nto discriminate between the different possible classes. Naive Bayes is a probabilistic classifier, meaning that for a document d, out of all classes c ∈ C the classifier returns \nthe class c_hat which has the maximum posterior probability given the document. Naive Bayes classifiers make two simplifying assumptions. The first is the bag of words assumption: \nposition doesn’t matter. The second is called the naive Bayes assumption: this is the conditional independence assumption that the probabilities P(fi|c) are independent given\nthe class c. P(f1, f2,...., fn|c) = P(f1|c)·P(f2|c)· ... ·P(fn|c). The solution for such unknown words is to ignore them—remove them from the test document and not include any \nprobability for them at all.\n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Training the Naive Bayes Classifier \n\n## SLP Chapter 4.3 Worked Example\n An example \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Optimizing for Sentiment Analysis. For sentiment classification and some other text classification tasks, whether a word occurs or not seems to matter \nmore than its frequency so it often improves performance to clip the word counts in each document at 1. This is called binary NB. A second important addition commonly made \nis to deal with negation. A very simple baseline to deal with negation is the following: during text normalization, prepend the prefix NOT to every word after a token of logical \nnegation (n’t, not, no, never) until the next punctuation mark. \"didn’t like this movie , but I\" changes to \"didn’t NOT_like NOT_this NOT_movie , but I\". When training data is \nsparse or not representative of the test set, using dense lexicon features instead of sparse individual-word features\nmay generalize better\n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n spam detection; text classification \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n a naive Bayes model can be viewed as a set of class-specific unigram language models, in which the model for each class instantiates a unigram language model.\n \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Evaluation: Precision, Recall, F-measure. Harmonic mean is used because it is a conservative metric; the harmonic mean of two values is closer to the minimum \nof the two values than the arithmetic mean is. Thus it weighs the lower of the two numbers more heavily. In macroaveraging, we compute the performance for each class, and then \naverage over classes. In microaveraging, we collect the decisions for all classes into a single confusion matrix, and then compute precision and recall from that table. \nThe macroaverage better reflects the statistics of the smaller classes, and so is more appropriate when performance on all the classes is equally important\n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Test and cross validation \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Statistical Significance Testing. There are two common non-parametric tests used in NLP: approximate randomization and the bootstrap test. Paired bootstrap test:\ncompare two sets of observations that are aligned: each observation in one set can be paired with an observation in another. when comparing the performance of two systems on the \nsame test set; we can pair the performance of system A on an individual observation xi with the performance of system B on the same xi. The intuition of the bootstrap test is that \nwe can create many virtual test sets from an observed test set by repeatedly sampling from it.\n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n avoid harms, bias \n\n## Module 12 Lecture Notes\n Machine Learning = a computer observes data; builds a model; uses the model as a hypothesis about the world and as software that can solve problems.\nNaive Bayes: assume all features are independent effects of the label. only have to specify how each feature depends on the class. Total number of parameters is linear in number \nof features. Inference for naive bayes: compute posterior distribution over label variable Y. Assume features are conditionally independent given label. Overfitting issues.\nLaplace smoothing for unseen values (Pretend you saw every outcome once more than you actually did). Naive Bayes models can incorporate a variety of features, but tend to do best \nin homogeneous cases (e.g. all features are word occurrences). Perceptron: linear classifier; activation is the sum. >=0 then +1, otherwise -1. Learning: if wrong: adjust the weight \nvector by adding or subtracting the feature vector. W=W+y_hat*f. For multi-class perceptron: if wrong: lower score of wrong answer, raise score of right answer. \nConvergence: if the training is separable, perceptron will eventually converge (binary case). Mistake Bound: the maximum number of mistakes (binary case) related to the margin or \ndegree of separability. Problems with perceptrons: Noise: if the data isn’t separable, weights might thrash. Averaging weight vectors over time can help (averaged perceptron). \nMediocre generalization: finds a “barely” separating solution. Overtraining: test / held-out accuracy usually rises, then falls. MIRA = Margin Infused Relaxed Algorithm. \nChoose an update size that fixes the current mistake but minimizes the change to w \n\n## Module 12 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" The most important difference between naive Bayes and logistic regression is that logistic regression is a discriminative classifier while naive Bayes is a \n",
        "generative classifier. 4 components: feature representation; classification function; objective function; optimization algo. In order to avoid the extensive human effort of feature \n",
        "design, recent research in NLP has focused on representation learning: ways to learn features automatically in an unsupervised way from the input\n",
        " \"\"\"\n",
        "slp_chapter5_2 = \"\"\" learning in logistic regression \"\"\"\n",
        "slp_chapter5_3 = \"\"\" coss entropy loss function. a loss function that prefers the correct class labels of the training examples to be more likely - conditional maximum likelihood\n",
        "estimation. gradient with respect to a single weight has a very intuitive value: the difference between the true y and our estimated for that observation, multiplied by the \n",
        "corresponding input value  \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Gradien descent.  \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Regularization. L2 regularization is a quadratic function of the weight values. L1 regularization is a linear function of the weight values, the sum of the \n",
        "absolute values of the weights.  L1 regularization can be viewed as a Laplace prior on the weights. L2 regularization corresponds to assuming that weights are distributed according \n",
        "to a Gaussian distribution with mean 0. \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Multinomial logistic regression. Features in multinomial logistic regression function similarly to binary logistic regression, but need separate weight vectors \n",
        "(and biases) for each of the K classes \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Neural units. deep neural nets are the right tool for large scale problems that offer sufficient data to learn features automatically. a neural unit is taking \n",
        "a weighted sum of its inputs, with one additional bias term. Activation: the sigmoid, the tanh,and the rectified linear ReLU. Vanishing gradient problem.\"\"\"\n",
        "slp_chapter7_2 = \"\"\" The XOR problem. the power of neural networks comes from combining neural units into larger networks. XOR Not linearly separable. not possible to build \n",
        "a perceptron to compute logical XOR. While the XOR function cannot be calculated by a single perceptron, it can be calculated by a layered network of units. we can view the hidden \n",
        "layer of the network as forming a representation for the input. That neural networks can automatically learn useful representations of the input is one of the key advantages. \n",
        "a network formed by many layers of purely linear units can always be reduced to a single layer of linear units with appropriate weights. \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Feedforward network. A feedforward network is a multilayer network in which the units are connected with no cycles; the outputs from units in each layer \n",
        "are passed to units in the next higher layer, and no outputs are passed back to lower layers.  \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Feedforward networks for NLP: Classification.  Instead of using hand-built human-engineered features as the input to the classifier, draw on deep\n",
        "learning’s ability to learn features from the data by representing words as word2vec or GloVe embeddings. The idea of relying on another algorithm to have already learned\n",
        "an embedding representation for the input words is called pretraining  \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Feedforward Neural Language Modeling.  Compared to n-gram models, neural language models can handle much longer histories, can generalize better over \n",
        "contexts of similar words, and are more accurate at word-prediction. A feedforward neural LM is a feedforward network that takes as input at time t a representation of \n",
        "some number of previous words and outputs a probability distribution over possible next words.  \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Training. Computation Graphs. Optimization in neural networks is a non-convex optimization problem, more complex than for logistic regression.  \n",
        "In neural networks, we initialize the weights with small random numbers. It’s also helpful to normalize the input values to have 0 mean and unit variance.\"\"\"\n",
        "slp_chapter7_7 = \"\"\" Training the neural language model. Besides weight matrices and bias also learn embedding matrix E. \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" Conditional maximum likelihood estimation: Choose parameters w, b that maximize the (log) probabilities of the true labels in the training data.\n",
        "The resulting loss function is the negative log likelihood loss, more commonly called the cross entropy loss. Loss function of logistic regression is convex. A convex function \n",
        "has just one minimum, so no local minima to get stuck in. Mini-batch training: train on a small batch. The batch size can be 512 or 1024, often selected based on computational\n",
        "resources, so that all examples in the mini-batch can be processed in parallel. The loss is then accumulated. Lasso regression uses L1 regularization. Ridge regression uses \n",
        "L2 regularization. Softmax for multinomial classification. The building block of a neural network is a single computational unit which takes a set of real valued numbers as input, \n",
        "performs some computation. Perptron: z=wx+b. Step function. outpu 1 if z>0, otherwise 0. Sigmoid neuron. tanh, reLU. The advantage of using a single matrix W for the weights of \n",
        "the entire layer is the hidden layer computation can be done efficiently with simple matrix operations. \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "f6e4069e-cb7b-47e6-bd1f-12743ab5400a"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n The most important difference between naive Bayes and logistic regression is that logistic regression is a discriminative classifier while naive Bayes is a \ngenerative classifier. 4 components: feature representation; classification function; objective function; optimization algo. In order to avoid the extensive human effort of feature \ndesign, recent research in NLP has focused on representation learning: ways to learn features automatically in an unsupervised way from the input\n \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n learning in logistic regression \n\n## SLP Chapter 5.3 The cross-entropy loss function\n coss entropy loss function. a loss function that prefers the correct class labels of the training examples to be more likely - conditional maximum likelihood\nestimation. gradient with respect to a single weight has a very intuitive value: the difference between the true y and our estimated for that observation, multiplied by the \ncorresponding input value  \n\n## SLP Chapter 5.4 Gradient Descent\n Gradien descent.  \n\n## SLP Chapter 5.5 Regularization\n Regularization. L2 regularization is a quadratic function of the weight values. L1 regularization is a linear function of the weight values, the sum of the \nabsolute values of the weights.  L1 regularization can be viewed as a Laplace prior on the weights. L2 regularization corresponds to assuming that weights are distributed according \nto a Gaussian distribution with mean 0. \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Multinomial logistic regression. Features in multinomial logistic regression function similarly to binary logistic regression, but need separate weight vectors \n(and biases) for each of the K classes \n\n## SLP Chapter 7.1 Units\n Neural units. deep neural nets are the right tool for large scale problems that offer sufficient data to learn features automatically. a neural unit is taking \na weighted sum of its inputs, with one additional bias term. Activation: the sigmoid, the tanh,and the rectified linear ReLU. Vanishing gradient problem.\n\n## SLP Chapter 7.2 The XOR problem\n The XOR problem. the power of neural networks comes from combining neural units into larger networks. XOR Not linearly separable. not possible to build \na perceptron to compute logical XOR. While the XOR function cannot be calculated by a single perceptron, it can be calculated by a layered network of units. we can view the hidden \nlayer of the network as forming a representation for the input. That neural networks can automatically learn useful representations of the input is one of the key advantages. \na network formed by many layers of purely linear units can always be reduced to a single layer of linear units with appropriate weights. \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Feedforward network. A feedforward network is a multilayer network in which the units are connected with no cycles; the outputs from units in each layer \nare passed to units in the next higher layer, and no outputs are passed back to lower layers.  \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Feedforward networks for NLP: Classification.  Instead of using hand-built human-engineered features as the input to the classifier, draw on deep\nlearning’s ability to learn features from the data by representing words as word2vec or GloVe embeddings. The idea of relying on another algorithm to have already learned\nan embedding representation for the input words is called pretraining  \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Feedforward Neural Language Modeling.  Compared to n-gram models, neural language models can handle much longer histories, can generalize better over \ncontexts of similar words, and are more accurate at word-prediction. A feedforward neural LM is a feedforward network that takes as input at time t a representation of \nsome number of previous words and outputs a probability distribution over possible next words.  \n\n## SLP Chapter 7.6 Training Neural Nets\n Training. Computation Graphs. Optimization in neural networks is a non-convex optimization problem, more complex than for logistic regression.  \nIn neural networks, we initialize the weights with small random numbers. It’s also helpful to normalize the input values to have 0 mean and unit variance.\n\n## SLP Chapter 7.7 Training the neural language model\n Training the neural language model. Besides weight matrices and bias also learn embedding matrix E. \n\n## Module 13 Lecture Notes\n Conditional maximum likelihood estimation: Choose parameters w, b that maximize the (log) probabilities of the true labels in the training data.\nThe resulting loss function is the negative log likelihood loss, more commonly called the cross entropy loss. Loss function of logistic regression is convex. A convex function \nhas just one minimum, so no local minima to get stuck in. Mini-batch training: train on a small batch. The batch size can be 512 or 1024, often selected based on computational\nresources, so that all examples in the mini-batch can be processed in parallel. The loss is then accumulated. Lasso regression uses L1 regularization. Ridge regression uses \nL2 regularization. Softmax for multinomial classification. The building block of a neural network is a single computational unit which takes a set of real valued numbers as input, \nperforms some computation. Perptron: z=wx+b. Step function. outpu 1 if z>0, otherwise 0. Sigmoid neuron. tanh, reLU. The advantage of using a single matrix W for the weights of \nthe entire layer is the hidden layer computation can be done efficiently with simple matrix operations. \n\n## Module 13 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" two important deep learning architectures: recurrent neural networks and transformer networks. Both approaches have mechanisms to deal directly with the \n",
        "sequential nature of language that allow them to capture and exploit the temporal nature of language. Recap probabilistic language models. Perplexity for metric. \"\"\"\n",
        "slp_chapter9_2 = \"\"\" RNN: any network that contains a cycle within its network connections, meaning that the value of some unit is directly, or indirectly, dependent on its own \n",
        "earlier outputs as an input. The hidden layer from the previous time step serves as a form of memory, or context that encodes earlier processing and informs the decisions to be \n",
        "made at later points in time. RNN does not impose a fixed-length limit on this prior context; the context embodied in the previous hidden layer can include information extending \n",
        "back to the beginning of the sequence. The sequential nature of simple recurrent networks can be seen as unrolling the network (for loop). two-pass algorithm for training the weights.\n",
        "In the first pass, perform forward inference, computing ht, yt, accumulating the loss at each step in time, saving the value of the hidden layer at each step for use at the next time step. \n",
        "In the second phase, process the sequence in reverse, computing the required gradients, computing and saving the error term for use in the hidden layer for each step\n",
        "backward in time. Backpropagation Through Time\"\"\"\n",
        "slp_chapter9_3 = \"\"\" To train an RNN, use a corpus of text as training material, having the model predict the next word at each time step t. train the model to minimize the error \n",
        "in predicting the true next word in the training sequence, using cross-entropy as the loss function. The weights in the network are adjusted to minimize the average CE loss over \n",
        "the training sequence via gradient descent. \"\"\"\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 = \"\"\" The link between similarity in how words are distributed and similarity in what they mean is called the distributional hypothesis. \n",
        "vector semantics learns representations of the meaning of words, called embeddings, directly from their distributions in texts. One kind of word relatedness is if they belong to \n",
        "the same semantic field semantic field. A semantic field is a set of words which cover a particular semantic domain and bear structured relations with each other (hospital, surgeons). \n",
        " Semantic fields are also related to topic models, like LDA, which apply unsupervised learning on large sets of texts to induce sets of associated words from text. A semantic frame is a set of words that denote perspectives or\n",
        "participants in a particular type of event (buy, sell, pay)  \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Vectors semantics is the standard way to represent word meaning in NLP. The idea of vector semantics is to represent a word as a point in a multidimensional \n",
        "semantic space that is derived from the distributions of word neighbors. Vectors for representing words are called embeddings. \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Vector or distributional models of meaning are generally based on a co-occurrence matrix, a way of representing how often words co-occur. the term-document matrix \n",
        "and the term-term matrix. Common to use smaller contexts, generally a window around the word (4 words to the left and 4 words to the right), in which case the cell represents \n",
        "the number of times (in some training corpus) the column word occurs in such a ±4 word window around the row word.\"\"\"\n",
        "slp_chapter6_4 = \"\"\" the most common similarity metric is the cosine of the angle between the vectors.  Need a similarity metric that tells us how similar two words are \n",
        "regardless of their frequency. raw frequency values are non-negative, the cosine for these vectors ranges from 0–1  \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Word2vec. a more powerful word representation: embeddings, short dense vector. embeddings are short, with number of dimensions d ranging from 50-1000, \n",
        "rather than the much larger vocabulary size |V| or number of documents D. Advantages of dense vectors over sparse: fewer parameters to train; better than capturing synonymy.\n",
        "skip-gramwith negative sampling, SGNS, is one of two algorithms in word2vec - static embeddings. (compared to dynamic contextual embeddings like the popular family of BERT \n",
        "representations). 1. Treat the target word and a neighboring context word as positive examples.2. Randomly sample other words in the lexicon to get negative samples.\n",
        "3. Use logistic regression to train a classifier to distinguish those two cases. 4. Use the learned weights as the embeddings. Fasttext addresses a problem with word2vec \n",
        ": it has no good way to deal with unknown words. solution by Fasttext: using subword models, representing each word as itself plus a bag of constituent n-grams. For example:\n",
        "word where would be represented by the sequence <where> plus the character n-grams: <wh, whe, her, ere, re>. Then a skipgram embedding is learned for each constituent n-gram, \n",
        "and the word where is represented by the sum of all of the embeddings of its constituent n-grams. Unknown words can then be presented only by the sum of the constituent n-grams.\n",
        "GloVec: Global Vectors, based on capturing global corpus statistics; based on ratios of probabilities from the word-word cooccurrence matrix, combining the intuitions of count-based \n",
        "models like PPMI while also capturing the linear structures used by methods like word2vec.\n",
        " \"\"\"\n",
        "slp_chapter6_10 = \"\"\"Different types of similarity or association: One parameter of vector semantic models that is relevant to both sparse tf-idf vectors and dense word2vec vectors \n",
        "is the size of the context window used to collect counts. Shorter context windows tend to lead to representations that are a bit more syntactic. Longer windows lead to the highest \n",
        "cosine words to a target word w tend to be words that are topically related but not similar. Analogy/Relational Similarity: Another semantic property of embeddings is their\n",
        "ability to capture relational meanings (King/man; queen/woman). \"\"\"\n",
        "slp_chapter6_11 = \"\"\" In addition to their ability to learn word meaning from text, embeddings also reproduce the implicit biases and stereotypes that were latent in the text.\"\"\"\n",
        "slp_chapter6_12 = \"\"\" Intrinsic evaluations. The most common metric is to test their performance on similarity, computing the correlation between an algorithm’s word similarity \n",
        "scores and word similarity ratings assigned by humans. All embedding algorithms suffer from inherent variability. For example because of randomness in the initialization and the \n",
        "random negative sampling, algorithms like word2vec may produce different results even from the same dataset, and individual documents in a collection may strongly impact the \n",
        "resulting embeddings\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" NN and NLM. activation(WX+b). Cross-entropy loss: -[y*log(y_hat)+(1-y)*log(1-y_hat)]. Computation graph. \n",
        "Language Models: estimate the prob of a sentence consisting of word sequence w1:n. Advantages over n-gram: don’t need smoothing; handle much longer history; \n",
        "can generalize over context of similar words; higher predictive accuracy but takes longer to train. In neural LMs, prior context are represented by embeddings. \n",
        "Use a vector space model where the words are vectors with real values (dim = 30, 60, 100). This gives a way to compute word similarity. \n",
        "Define a function that returns a joint probability of words in a sequence based on a sequence of these vectors. Simultaneously learn the word representations and \n",
        "the probability function from data. Vector semantics: we want to encode synonyms; antonyms; connotations (valence; arousal, dominance); semantic roles; support for entailment. \n",
        "A word that has multiple meanings is called polysemous (word sense). Similar words; related words. \n",
        "Sparse (term-by-document or term-context matrices) vs dense vectors (Word2Vec, GloVe). Word2Vec: train a classifier on a binary prediction task: \n",
        "is w likely to show up near \"apricot\"? We don’t actually care about this task but we'll take the learned classifier weights as the word embeddings. \n",
        "Word2vec provides a variety of options such as “skip-gram with negative sampling\" (SGNS). Embeddings = vector models of meaning.\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"valence\" : \"the pleasantness of the stimulus; happy vs. unhappy\",\n",
        "\"arousal\" : \"the intensity of emotion provoked by the stimulus; excited vs. calm\", \n",
        "\"dominance\" : \"the degree of control exerted by the stimulus; controlling vs. influenced\",     \n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "d5508dcd-3398-437d-bf09-c31388f233e1"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n two important deep learning architectures: recurrent neural networks and transformer networks. Both approaches have mechanisms to deal directly with the \nsequential nature of language that allow them to capture and exploit the temporal nature of language. Recap probabilistic language models. Perplexity for metric. \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n RNN: any network that contains a cycle within its network connections, meaning that the value of some unit is directly, or indirectly, dependent on its own \nearlier outputs as an input. The hidden layer from the previous time step serves as a form of memory, or context that encodes earlier processing and informs the decisions to be \nmade at later points in time. RNN does not impose a fixed-length limit on this prior context; the context embodied in the previous hidden layer can include information extending \nback to the beginning of the sequence. The sequential nature of simple recurrent networks can be seen as unrolling the network (for loop). two-pass algorithm for training the weights.\nIn the first pass, perform forward inference, computing ht, yt, accumulating the loss at each step in time, saving the value of the hidden layer at each step for use at the next time step. \nIn the second phase, process the sequence in reverse, computing the required gradients, computing and saving the error term for use in the hidden layer for each step\nbackward in time. Backpropagation Through Time\n\n## SLP Chapter 9.3 RNNs as Language Models\n To train an RNN, use a corpus of text as training material, having the model predict the next word at each time step t. train the model to minimize the error \nin predicting the true next word in the training sequence, using cross-entropy as the loss function. The weights in the network are adjusted to minimize the average CE loss over \nthe training sequence via gradient descent. \n\n## SLP Chapter 6.1 Lexical Semantics\n The link between similarity in how words are distributed and similarity in what they mean is called the distributional hypothesis. \nvector semantics learns representations of the meaning of words, called embeddings, directly from their distributions in texts. One kind of word relatedness is if they belong to \nthe same semantic field semantic field. A semantic field is a set of words which cover a particular semantic domain and bear structured relations with each other (hospital, surgeons). \n Semantic fields are also related to topic models, like LDA, which apply unsupervised learning on large sets of texts to induce sets of associated words from text. A semantic frame is a set of words that denote perspectives or\nparticipants in a particular type of event (buy, sell, pay)  \n\n## SLP Chapter 6.2 Vector Semantics\n Vectors semantics is the standard way to represent word meaning in NLP. The idea of vector semantics is to represent a word as a point in a multidimensional \nsemantic space that is derived from the distributions of word neighbors. Vectors for representing words are called embeddings. \n\n## SLP Chapter 6.3 Words and Vectors\n Vector or distributional models of meaning are generally based on a co-occurrence matrix, a way of representing how often words co-occur. the term-document matrix \nand the term-term matrix. Common to use smaller contexts, generally a window around the word (4 words to the left and 4 words to the right), in which case the cell represents \nthe number of times (in some training corpus) the column word occurs in such a ±4 word window around the row word.\n\n## SLP Chapter 6.4 Cosine for measuring similarity\n the most common similarity metric is the cosine of the angle between the vectors.  Need a similarity metric that tells us how similar two words are \nregardless of their frequency. raw frequency values are non-negative, the cosine for these vectors ranges from 0–1  \n\n## SLP Chapter 6.8 Word2vec\n Word2vec. a more powerful word representation: embeddings, short dense vector. embeddings are short, with number of dimensions d ranging from 50-1000, \nrather than the much larger vocabulary size |V| or number of documents D. Advantages of dense vectors over sparse: fewer parameters to train; better than capturing synonymy.\nskip-gramwith negative sampling, SGNS, is one of two algorithms in word2vec - static embeddings. (compared to dynamic contextual embeddings like the popular family of BERT \nrepresentations). 1. Treat the target word and a neighboring context word as positive examples.2. Randomly sample other words in the lexicon to get negative samples.\n3. Use logistic regression to train a classifier to distinguish those two cases. 4. Use the learned weights as the embeddings. Fasttext addresses a problem with word2vec \n: it has no good way to deal with unknown words. solution by Fasttext: using subword models, representing each word as itself plus a bag of constituent n-grams. For example:\nword where would be represented by the sequence <where> plus the character n-grams: <wh, whe, her, ere, re>. Then a skipgram embedding is learned for each constituent n-gram, \nand the word where is represented by the sum of all of the embeddings of its constituent n-grams. Unknown words can then be presented only by the sum of the constituent n-grams.\nGloVec: Global Vectors, based on capturing global corpus statistics; based on ratios of probabilities from the word-word cooccurrence matrix, combining the intuitions of count-based \nmodels like PPMI while also capturing the linear structures used by methods like word2vec.\n \n\n## SLP Chapter 6.10 Semantic properties of embeddings\nDifferent types of similarity or association: One parameter of vector semantic models that is relevant to both sparse tf-idf vectors and dense word2vec vectors \nis the size of the context window used to collect counts. Shorter context windows tend to lead to representations that are a bit more syntactic. Longer windows lead to the highest \ncosine words to a target word w tend to be words that are topically related but not similar. Analogy/Relational Similarity: Another semantic property of embeddings is their\nability to capture relational meanings (King/man; queen/woman). \n\n## SLP Chapter 6.11 Bias and Embeddings\n In addition to their ability to learn word meaning from text, embeddings also reproduce the implicit biases and stereotypes that were latent in the text.\n\n## SLP Chapter 6.12 Evaluating Vector Models\n Intrinsic evaluations. The most common metric is to test their performance on similarity, computing the correlation between an algorithm’s word similarity \nscores and word similarity ratings assigned by humans. All embedding algorithms suffer from inherent variability. For example because of randomness in the initialization and the \nrandom negative sampling, algorithms like word2vec may produce different results even from the same dataset, and individual documents in a collection may strongly impact the \nresulting embeddings\n\n## Module 14 Lecture Notes\n NN and NLM. activation(WX+b). Cross-entropy loss: -[y*log(y_hat)+(1-y)*log(1-y_hat)]. Computation graph. \nLanguage Models: estimate the prob of a sentence consisting of word sequence w1:n. Advantages over n-gram: don’t need smoothing; handle much longer history; \ncan generalize over context of similar words; higher predictive accuracy but takes longer to train. In neural LMs, prior context are represented by embeddings. \nUse a vector space model where the words are vectors with real values (dim = 30, 60, 100). This gives a way to compute word similarity. \nDefine a function that returns a joint probability of words in a sequence based on a sequence of these vectors. Simultaneously learn the word representations and \nthe probability function from data. Vector semantics: we want to encode synonyms; antonyms; connotations (valence; arousal, dominance); semantic roles; support for entailment. \nA word that has multiple meanings is called polysemous (word sense). Similar words; related words. \nSparse (term-by-document or term-context matrices) vs dense vectors (Word2Vec, GloVe). Word2Vec: train a classifier on a binary prediction task: \nis w likely to show up near \"apricot\"? We don’t actually care about this task but we'll take the learned classifier weights as the word embeddings. \nWord2vec provides a variety of options such as “skip-gram with negative sampling\" (SGNS). Embeddings = vector models of meaning.\n\n## Module 14 Definitions\n* **Valence** - the pleasantness of the stimulus; happy vs. unhappy\n* **Arousal** - the intensity of emotion provoked by the stimulus; excited vs. calm\n* **Dominance** - the degree of control exerted by the stimulus; controlling vs. influenced\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": "41c34de9-c711-452f-9ed1-550755113918"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module8_markdown, \n",
        "                             module9_markdown, \n",
        "                             module10_markdown, \n",
        "                             module11_markdown, \n",
        "                             module12_markdown,\n",
        "                             module13_markdown,\n",
        "                             module14_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n goal-based agent vs. decision-theoretic agent. Basic principle of decision theory: max of expected utility. A rational agent should choose the action\nthat maximizes the exptected utility.  $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 constraints on rational preferences. Axiom of rationality. Assuming the constraints on rational preferences a utility function exists for any rational agent. \n\n## AIMA Chapter 16.3 Utility Functions\n utility function is a map from states to real numbers. \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n sequential decision problem, fully observable, stochastic environment with Markovian transition model and additive rewards - MDP.  \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Algos for MDP: value iteration; policy iteration; linear programming, and Monte Carlo planning \n\n## Module 8 Lecture Notes\n MDPS are useful for fully observable task environments where we have to make a sequence of decisions, and where the outcome for actions we take are \nnon-deterministic. The transition function is sometimes written as T(s, a, s'), or explicitly as a probability p(s'|s, a). Rewards can be positive or negative but are bounded by \nsome maximum value. Rewards are additive. MDP is a sequential decision problem  for a fully observable environment with a stochastic transition model that has additive rewards. \nEven if the same policy is executed multiple times by the agent, this may lead to different sequence of states and actions (environment history), and thus a different score under \nthe reward function. We need to compute the expected utility of all the possible paths generated by a policy. Finite horizons: An optimal action can depend on how much time is left. \nPolicies that depend on time are called nonstationary. Infinite horizons: The optimal policy is stationary. Infinite horizons are therefore easier. Prefer reward earlier than later.\nvalues of rewards decay exponentially. Theorem: if we assume stationary preferences then there are only two ways to define utilities. Additive and discounted. Solutions for infinite\nutilities. 1. Finite horizon. 2. Discounting. 3. Absorbing states. Value iteration: Theorem: will converge to unique optimal values. Basic idea: approximations get refined towards \noptimal values. Policy may converge long before values do. Policy valuation. Fixed policy. Important lesson: actions are easier to select from q-values than values!\nProblems with Value Iteration: 1. it is slow O(S^2A). 2. The max at each state rarely changes. 3. The policy often converges long before the values. Better option: policy iteration.\nPolicy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence. 2: Policy improvement: update policy using one-step look-ahead with resulting \nconverged (but not optimal!) utilities as future values. Repeat steps until policy converges. Still optimal and Can converge (much) faster under some conditions.\nBoth value iteration and policy iteration compute the same thing (all optimal values). In value iteration: 1. Every iteration updates both the values and (implicitly) the policy\n2. We don’t track the policy, but taking the max over actions implicitly recomputes it. \nIn policy iteration: 1. We do several passes that update utilities with fixed policy (each pass is fast because we consider only one action, not all of them). 2. After the policy \nis evaluated, a new policy is chosen (slow like a value iteration pass). 3. The new policy will be better (or we’re done). Both are dynamic programs for solving MDPs.\nA rational agent should choose the action that maximizes its expected utility, given its knowledge\n\n## Module 8 Definitions\n* **Utility function** - maps states/outcomes to real numbers\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\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 Reinforcement learning is similar to MDPs but the transition and the reward function are not given to to the agent.  Instead they must be learned \nthrough interaction with the world. In reinforcement learning, every time an agent takes an action, it receives feedback in the form of a reward, and so the agent wants to \nmaximize its expected rewards. quantify how good different exploration strategies are using regret. Solving MDPs is offline planning. You determine all quantities through computation.\nYou need to know the details of the MDP. You do not actually play the game! But reinforcement learning is online learning. Important ideas in reinforcement learning. \n1. Exploration: you have to try unknown actions to get information. 2. Exploitation: eventually, you have to use what you know. 3 Regret: even if you learn intelligently, \nyou make mistakes. 4. Sampling: because of chance, you have to try things repeatedly. 5. Difficulty: learning can be much harder than solving a known MDP.\nBasic idea: 1. Receive feedback in the form of rewards. 2. Agent’s utility is defined by the reward function. 3. Must (learn to) act so as to maximize expected rewards.\n4. All learning is based on observed samples of outcomes!\nModel-Based learning idea: 1. Learn an approximate model based on experiences 2. Solve for values as if the learned model were correct\nModel free learning. Full reinforcement learning: optimal policies (like value iteration) 1. don’t know the transitions T(s,a,s’). 2. don’t know the rewards R(s,a,s’)\n3. choose the actions now. 4. Goal: learn the optimal policy / values. Fundamental tradeoff: exploration vs. exploitation. \nQ-learning converges to optimal policy -- even if you’re acting suboptimally! This is called off-policy learning. Caveats: have to explore enough; have to eventually make the \nlearning rate small enough but not decrease it too quickly. Even if you learn the optimal policy, still make mistakes along the way! Regret is a measure of total mistake cost: \nthe difference between expected rewards and optimal (expected) rewards. Minimizing regret goes beyond learning to be optimal – it requires optimally learning to be optimal. \nExample: random exploration and exploration functions both end up optimal, but random exploration has higher regret. Approximate Q-learning. use features of states. \nAdvantage: our experience is summed up in a few powerful numbers. Disadvantage: states may share features but actually be very different in value!\n\n## Module 9 Definitions\n* **Term** - your definition here\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n speech recognition; spelling correction; grammatical error correction all need probabilities. Models that assign probabilities to sequences of words are called \nlanguage model or LM. N-gram model. Markov assumption. In practice it is more common to use 3 or 4 grams rather than 2 grams. Use log probabilities to avoid underflow.\n\n## SLP Chapter 3.2 Evaluating Language Models\n Evaluation: perplexity; can also be thought as the weighted average branching factor of a language. The branching factor of a language is the number \nof possible next words that can follow any word \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n  Sampling sentences from a language model \n\n## SLP Chapter 3.4 Generalization and Zeros\n Generalization and Zeros. OOV: 1. unknown words using <UNK>  \n\n## SLP Chapter 3.5 Smoothing\n Smoothing. Laplace (add 1). A related way to view smoothing is as discounting (lowering) \nsome non-zero counts in order to get the probability mass that will be assigned to the zero counts. \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Huge Language Models and Stupid Backoff. If a higher-order n-gram has a zero count, we simply backoff to a\nlower order n-gram, weighed by a fixed (context-independent) weight. \n\n## Module 10 Lecture Notes\n Observed variables (evidence); Unobserved variables (states); Model: Agent knows something about how the known variables relate to the unknown variables.\nProbabilistic Language Models. One goal: assign a probability to a sentence. Autocomplete for texting; Machine Translation; Spelling Correction; Speech Recognition. \nRelated task: probability of an upcoming word. Simplifying Assumption = Markov Assumption. Only depends on the previous k words not the entire context.\nN-gram model in general is an insufficient model of language because language has long-distance dependencies. Problems with MLE: Out of vocabulary. <unk> to deal with OOV.\nAvoid zeros with smoothing. Use log space to avoid underflow. \n\n## Module 10 Definitions\n* **Term** - your definition here\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Bayes Nets: complete; nonredundant and compact. Locally structured (sparse) system: linear growth. \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 Conditional independence. Conditional independence is our most basic and robust form of knowledge about uncertain environments.\nBayes Nets are directed acyclic graphs, where the nodes represent random variables in our probability model, and the arcs encode our assumption about how the variables are \nrelated to each other. Bayes Nets are compact representations that allow us to encode independence assumptions between variables. \nBayes’ nets: a technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities). Nodes: variables; arcs: interactions\nA Bayes net = Topology (graph) + Local Conditional Probabilities. A set of nodes, one per variable X. A directed, acyclic graph. A conditional distribution for each node.\nBayes’ nets implicitly encode joint distributions. BNs need not actually be causal, could reflect correlation. Topology really encodes conditional independence. \nSize of a joint distribution over N Boolean variables is 2^N. Size of an N-node net if nodes have up to k parents is O(N * 2(k+1))\nD-separation: causal chain: x->y->z. Evidence along the chain blocks the influence; common cause: Observing the cause blocks influence between effects. common effect: \nObserving an effect activates influence between possible causes. Any complex example can be broken into repetitions of the three canonical cases. \nif X and Y are d-separated by Z then X and Y are conditionally independent given evidence variables Z. Consider all (undirected) paths from X to Y, No active paths = independence!\nA path is active if each triple is active: Causal chain A → B → C where B is unobserved (either direction). Common cause A ← B → C where B is unobserved. Common effect (v-structure)\nA → B ← C where B or one of its descendants is observed. All it takes to block a path is a single inactive segment. \nInference: calculating some useful quantity from a joint probability distribution. join up the whole joint distribution before summing out the hidden variables. slow\nVariable elimination: Interleave joining and marginalizing. still NP-hard but faster than inference by enumeration.\n\n## Module 11 Definitions\n* **Concept** - definition\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 19.1 Forms of Learning\n Your summary here \n\n## AIMA Chapter 19.2 Supervised Learning\n Your summary here \n\n## AIMA Chapter 19.3 Learning Decision Trees\n Your summary here \n\n## AIMA Chapter 19.4 Model Selection and Optimization\n Your summary here \n\n## AIMA Chapter 19.5 The Theory of Learning\n Your summary here \n\n## AIMA Chapter 19.6 Linear Regression and Classification\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n subject category classification is the task for which the naive Bayes algorithm was invented in 1961.  A probabilistic classifier additionally will tell us the \nprobability of the observation being in the class. Generative classifiers like naive Bayes build a model of how a class could generate some input data. Given an observation, \nthey return the class most likely to have generated the observation. Discriminative classifiers like logistic regression instead learn what features from the input are most useful \nto discriminate between the different possible classes. Naive Bayes is a probabilistic classifier, meaning that for a document d, out of all classes c ∈ C the classifier returns \nthe class c_hat which has the maximum posterior probability given the document. Naive Bayes classifiers make two simplifying assumptions. The first is the bag of words assumption: \nposition doesn’t matter. The second is called the naive Bayes assumption: this is the conditional independence assumption that the probabilities P(fi|c) are independent given\nthe class c. P(f1, f2,...., fn|c) = P(f1|c)·P(f2|c)· ... ·P(fn|c). The solution for such unknown words is to ignore them—remove them from the test document and not include any \nprobability for them at all.\n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Training the Naive Bayes Classifier \n\n## SLP Chapter 4.3 Worked Example\n An example \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Optimizing for Sentiment Analysis. For sentiment classification and some other text classification tasks, whether a word occurs or not seems to matter \nmore than its frequency so it often improves performance to clip the word counts in each document at 1. This is called binary NB. A second important addition commonly made \nis to deal with negation. A very simple baseline to deal with negation is the following: during text normalization, prepend the prefix NOT to every word after a token of logical \nnegation (n’t, not, no, never) until the next punctuation mark. \"didn’t like this movie , but I\" changes to \"didn’t NOT_like NOT_this NOT_movie , but I\". When training data is \nsparse or not representative of the test set, using dense lexicon features instead of sparse individual-word features\nmay generalize better\n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n spam detection; text classification \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n a naive Bayes model can be viewed as a set of class-specific unigram language models, in which the model for each class instantiates a unigram language model.\n \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Evaluation: Precision, Recall, F-measure. Harmonic mean is used because it is a conservative metric; the harmonic mean of two values is closer to the minimum \nof the two values than the arithmetic mean is. Thus it weighs the lower of the two numbers more heavily. In macroaveraging, we compute the performance for each class, and then \naverage over classes. In microaveraging, we collect the decisions for all classes into a single confusion matrix, and then compute precision and recall from that table. \nThe macroaverage better reflects the statistics of the smaller classes, and so is more appropriate when performance on all the classes is equally important\n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Test and cross validation \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Statistical Significance Testing. There are two common non-parametric tests used in NLP: approximate randomization and the bootstrap test. Paired bootstrap test:\ncompare two sets of observations that are aligned: each observation in one set can be paired with an observation in another. when comparing the performance of two systems on the \nsame test set; we can pair the performance of system A on an individual observation xi with the performance of system B on the same xi. The intuition of the bootstrap test is that \nwe can create many virtual test sets from an observed test set by repeatedly sampling from it.\n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n avoid harms, bias \n\n## Module 12 Lecture Notes\n Machine Learning = a computer observes data; builds a model; uses the model as a hypothesis about the world and as software that can solve problems.\nNaive Bayes: assume all features are independent effects of the label. only have to specify how each feature depends on the class. Total number of parameters is linear in number \nof features. Inference for naive bayes: compute posterior distribution over label variable Y. Assume features are conditionally independent given label. Overfitting issues.\nLaplace smoothing for unseen values (Pretend you saw every outcome once more than you actually did). Naive Bayes models can incorporate a variety of features, but tend to do best \nin homogeneous cases (e.g. all features are word occurrences). Perceptron: linear classifier; activation is the sum. >=0 then +1, otherwise -1. Learning: if wrong: adjust the weight \nvector by adding or subtracting the feature vector. W=W+y_hat*f. For multi-class perceptron: if wrong: lower score of wrong answer, raise score of right answer. \nConvergence: if the training is separable, perceptron will eventually converge (binary case). Mistake Bound: the maximum number of mistakes (binary case) related to the margin or \ndegree of separability. Problems with perceptrons: Noise: if the data isn’t separable, weights might thrash. Averaging weight vectors over time can help (averaged perceptron). \nMediocre generalization: finds a “barely” separating solution. Overtraining: test / held-out accuracy usually rises, then falls. MIRA = Margin Infused Relaxed Algorithm. \nChoose an update size that fixes the current mistake but minimizes the change to w \n\n## Module 12 Definitions\n* **Concept** - definition\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n The most important difference between naive Bayes and logistic regression is that logistic regression is a discriminative classifier while naive Bayes is a \ngenerative classifier. 4 components: feature representation; classification function; objective function; optimization algo. In order to avoid the extensive human effort of feature \ndesign, recent research in NLP has focused on representation learning: ways to learn features automatically in an unsupervised way from the input\n \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n learning in logistic regression \n\n## SLP Chapter 5.3 The cross-entropy loss function\n coss entropy loss function. a loss function that prefers the correct class labels of the training examples to be more likely - conditional maximum likelihood\nestimation. gradient with respect to a single weight has a very intuitive value: the difference between the true y and our estimated for that observation, multiplied by the \ncorresponding input value  \n\n## SLP Chapter 5.4 Gradient Descent\n Gradien descent.  \n\n## SLP Chapter 5.5 Regularization\n Regularization. L2 regularization is a quadratic function of the weight values. L1 regularization is a linear function of the weight values, the sum of the \nabsolute values of the weights.  L1 regularization can be viewed as a Laplace prior on the weights. L2 regularization corresponds to assuming that weights are distributed according \nto a Gaussian distribution with mean 0. \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Multinomial logistic regression. Features in multinomial logistic regression function similarly to binary logistic regression, but need separate weight vectors \n(and biases) for each of the K classes \n\n## SLP Chapter 7.1 Units\n Neural units. deep neural nets are the right tool for large scale problems that offer sufficient data to learn features automatically. a neural unit is taking \na weighted sum of its inputs, with one additional bias term. Activation: the sigmoid, the tanh,and the rectified linear ReLU. Vanishing gradient problem.\n\n## SLP Chapter 7.2 The XOR problem\n The XOR problem. the power of neural networks comes from combining neural units into larger networks. XOR Not linearly separable. not possible to build \na perceptron to compute logical XOR. While the XOR function cannot be calculated by a single perceptron, it can be calculated by a layered network of units. we can view the hidden \nlayer of the network as forming a representation for the input. That neural networks can automatically learn useful representations of the input is one of the key advantages. \na network formed by many layers of purely linear units can always be reduced to a single layer of linear units with appropriate weights. \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Feedforward network. A feedforward network is a multilayer network in which the units are connected with no cycles; the outputs from units in each layer \nare passed to units in the next higher layer, and no outputs are passed back to lower layers.  \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Feedforward networks for NLP: Classification.  Instead of using hand-built human-engineered features as the input to the classifier, draw on deep\nlearning’s ability to learn features from the data by representing words as word2vec or GloVe embeddings. The idea of relying on another algorithm to have already learned\nan embedding representation for the input words is called pretraining  \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Feedforward Neural Language Modeling.  Compared to n-gram models, neural language models can handle much longer histories, can generalize better over \ncontexts of similar words, and are more accurate at word-prediction. A feedforward neural LM is a feedforward network that takes as input at time t a representation of \nsome number of previous words and outputs a probability distribution over possible next words.  \n\n## SLP Chapter 7.6 Training Neural Nets\n Training. Computation Graphs. Optimization in neural networks is a non-convex optimization problem, more complex than for logistic regression.  \nIn neural networks, we initialize the weights with small random numbers. It’s also helpful to normalize the input values to have 0 mean and unit variance.\n\n## SLP Chapter 7.7 Training the neural language model\n Training the neural language model. Besides weight matrices and bias also learn embedding matrix E. \n\n## Module 13 Lecture Notes\n Conditional maximum likelihood estimation: Choose parameters w, b that maximize the (log) probabilities of the true labels in the training data.\nThe resulting loss function is the negative log likelihood loss, more commonly called the cross entropy loss. Loss function of logistic regression is convex. A convex function \nhas just one minimum, so no local minima to get stuck in. Mini-batch training: train on a small batch. The batch size can be 512 or 1024, often selected based on computational\nresources, so that all examples in the mini-batch can be processed in parallel. The loss is then accumulated. Lasso regression uses L1 regularization. Ridge regression uses \nL2 regularization. Softmax for multinomial classification. The building block of a neural network is a single computational unit which takes a set of real valued numbers as input, \nperforms some computation. Perptron: z=wx+b. Step function. outpu 1 if z>0, otherwise 0. Sigmoid neuron. tanh, reLU. The advantage of using a single matrix W for the weights of \nthe entire layer is the hidden layer computation can be done efficiently with simple matrix operations. \n\n## Module 13 Definitions\n* **Concept** - definition\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n two important deep learning architectures: recurrent neural networks and transformer networks. Both approaches have mechanisms to deal directly with the \nsequential nature of language that allow them to capture and exploit the temporal nature of language. Recap probabilistic language models. Perplexity for metric. \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n RNN: any network that contains a cycle within its network connections, meaning that the value of some unit is directly, or indirectly, dependent on its own \nearlier outputs as an input. The hidden layer from the previous time step serves as a form of memory, or context that encodes earlier processing and informs the decisions to be \nmade at later points in time. RNN does not impose a fixed-length limit on this prior context; the context embodied in the previous hidden layer can include information extending \nback to the beginning of the sequence. The sequential nature of simple recurrent networks can be seen as unrolling the network (for loop). two-pass algorithm for training the weights.\nIn the first pass, perform forward inference, computing ht, yt, accumulating the loss at each step in time, saving the value of the hidden layer at each step for use at the next time step. \nIn the second phase, process the sequence in reverse, computing the required gradients, computing and saving the error term for use in the hidden layer for each step\nbackward in time. Backpropagation Through Time\n\n## SLP Chapter 9.3 RNNs as Language Models\n To train an RNN, use a corpus of text as training material, having the model predict the next word at each time step t. train the model to minimize the error \nin predicting the true next word in the training sequence, using cross-entropy as the loss function. The weights in the network are adjusted to minimize the average CE loss over \nthe training sequence via gradient descent. \n\n## SLP Chapter 6.1 Lexical Semantics\n The link between similarity in how words are distributed and similarity in what they mean is called the distributional hypothesis. \nvector semantics learns representations of the meaning of words, called embeddings, directly from their distributions in texts. One kind of word relatedness is if they belong to \nthe same semantic field semantic field. A semantic field is a set of words which cover a particular semantic domain and bear structured relations with each other (hospital, surgeons). \n Semantic fields are also related to topic models, like LDA, which apply unsupervised learning on large sets of texts to induce sets of associated words from text. A semantic frame is a set of words that denote perspectives or\nparticipants in a particular type of event (buy, sell, pay)  \n\n## SLP Chapter 6.2 Vector Semantics\n Vectors semantics is the standard way to represent word meaning in NLP. The idea of vector semantics is to represent a word as a point in a multidimensional \nsemantic space that is derived from the distributions of word neighbors. Vectors for representing words are called embeddings. \n\n## SLP Chapter 6.3 Words and Vectors\n Vector or distributional models of meaning are generally based on a co-occurrence matrix, a way of representing how often words co-occur. the term-document matrix \nand the term-term matrix. Common to use smaller contexts, generally a window around the word (4 words to the left and 4 words to the right), in which case the cell represents \nthe number of times (in some training corpus) the column word occurs in such a ±4 word window around the row word.\n\n## SLP Chapter 6.4 Cosine for measuring similarity\n the most common similarity metric is the cosine of the angle between the vectors.  Need a similarity metric that tells us how similar two words are \nregardless of their frequency. raw frequency values are non-negative, the cosine for these vectors ranges from 0–1  \n\n## SLP Chapter 6.8 Word2vec\n Word2vec. a more powerful word representation: embeddings, short dense vector. embeddings are short, with number of dimensions d ranging from 50-1000, \nrather than the much larger vocabulary size |V| or number of documents D. Advantages of dense vectors over sparse: fewer parameters to train; better than capturing synonymy.\nskip-gramwith negative sampling, SGNS, is one of two algorithms in word2vec - static embeddings. (compared to dynamic contextual embeddings like the popular family of BERT \nrepresentations). 1. Treat the target word and a neighboring context word as positive examples.2. Randomly sample other words in the lexicon to get negative samples.\n3. Use logistic regression to train a classifier to distinguish those two cases. 4. Use the learned weights as the embeddings. Fasttext addresses a problem with word2vec \n: it has no good way to deal with unknown words. solution by Fasttext: using subword models, representing each word as itself plus a bag of constituent n-grams. For example:\nword where would be represented by the sequence <where> plus the character n-grams: <wh, whe, her, ere, re>. Then a skipgram embedding is learned for each constituent n-gram, \nand the word where is represented by the sum of all of the embeddings of its constituent n-grams. Unknown words can then be presented only by the sum of the constituent n-grams.\nGloVec: Global Vectors, based on capturing global corpus statistics; based on ratios of probabilities from the word-word cooccurrence matrix, combining the intuitions of count-based \nmodels like PPMI while also capturing the linear structures used by methods like word2vec.\n \n\n## SLP Chapter 6.10 Semantic properties of embeddings\nDifferent types of similarity or association: One parameter of vector semantic models that is relevant to both sparse tf-idf vectors and dense word2vec vectors \nis the size of the context window used to collect counts. Shorter context windows tend to lead to representations that are a bit more syntactic. Longer windows lead to the highest \ncosine words to a target word w tend to be words that are topically related but not similar. Analogy/Relational Similarity: Another semantic property of embeddings is their\nability to capture relational meanings (King/man; queen/woman). \n\n## SLP Chapter 6.11 Bias and Embeddings\n In addition to their ability to learn word meaning from text, embeddings also reproduce the implicit biases and stereotypes that were latent in the text.\n\n## SLP Chapter 6.12 Evaluating Vector Models\n Intrinsic evaluations. The most common metric is to test their performance on similarity, computing the correlation between an algorithm’s word similarity \nscores and word similarity ratings assigned by humans. All embedding algorithms suffer from inherent variability. For example because of randomness in the initialization and the \nrandom negative sampling, algorithms like word2vec may produce different results even from the same dataset, and individual documents in a collection may strongly impact the \nresulting embeddings\n\n## Module 14 Lecture Notes\n NN and NLM. activation(WX+b). Cross-entropy loss: -[y*log(y_hat)+(1-y)*log(1-y_hat)]. Computation graph. \nLanguage Models: estimate the prob of a sentence consisting of word sequence w1:n. Advantages over n-gram: don’t need smoothing; handle much longer history; \ncan generalize over context of similar words; higher predictive accuracy but takes longer to train. In neural LMs, prior context are represented by embeddings. \nUse a vector space model where the words are vectors with real values (dim = 30, 60, 100). This gives a way to compute word similarity. \nDefine a function that returns a joint probability of words in a sequence based on a sequence of these vectors. Simultaneously learn the word representations and \nthe probability function from data. Vector semantics: we want to encode synonyms; antonyms; connotations (valence; arousal, dominance); semantic roles; support for entailment. \nA word that has multiple meanings is called polysemous (word sense). Similar words; related words. \nSparse (term-by-document or term-context matrices) vs dense vectors (Word2Vec, GloVe). Word2Vec: train a classifier on a binary prediction task: \nis w likely to show up near \"apricot\"? We don’t actually care about this task but we'll take the learned classifier weights as the word embeddings. \nWord2vec provides a variety of options such as “skip-gram with negative sampling\" (SGNS). Embeddings = vector models of meaning.\n\n## Module 14 Definitions\n* **Valence** - the pleasantness of the stimulus; happy vs. unhappy\n* **Arousal** - the intensity of emotion provoked by the stimulus; excited vs. calm\n* **Dominance** - the degree of control exerted by the stimulus; controlling vs. influenced\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}