{
  "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": "e7da8bb1-fb57-48d2-e4df-ac984278f641"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": 48,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f804c6e3-c886-46d4-fd15-de3301ff39b8"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": 49,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = True"
      ],
      "execution_count": 50,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" Chapter 16.1 summary. \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\" \n",
        "Performance of agent in MDP is sum of rewards for \n",
        "transitions it takes. \n",
        "Games with finite steps are harder to find optimal values \n",
        "than infinite step games. \n",
        "Value of rewards decay EXPONENTIALLY.\n",
        "If game lasts forever, use FINITE HORIZON (similar to depth-limited search\n",
        "and terminate after fized T steps; SET GAMMA to 0<GAMMA<1\n",
        "SMALLER GAMMA=SMALLER HORIZON=\"Short term focus\"\n",
        "Value iteration repeated until convergence.\n",
        "Complexity: O(S^2 * A)\n",
        "Value iteration guaranteed unique OPTIMAL values.\n",
        "How do we know V_k vectors will converge?\n",
        "Case 1: If tree has max depth M, then V_M holds the actual untruncated values.\n",
        "Case 2: If discount < 1: sketch (for any state V_k and V_{k+1} can be viewed\n",
        "as depth k+1 expectimax results in nearly identical search trees); difference is \n",
        "that on bottom layer, V_{k+1} has actual rewards while V+k has 0s; last layer is \n",
        "at best R_MAX; it is at worst R_MIN; But everything is discounted by gamma^k that\n",
        "far out; so V_k and V_{k+1} are at most gamme^k max|R| different; so as k\n",
        "increases, the values converge.\n",
        "\n",
        "POLICY EVAL: O(S^2)\n",
        "Actions are easier to select from q-values than values.\n",
        "\n",
        "Policy iteration: combines idea of evaluating policy with improving a policy \n",
        "based on its values. 1) policy eval (calc utils for some fixed policy until \n",
        "convergence) + 2) policy improvement (update policy using 1-step look-ahead\n",
        "w/resulting converged (but not optimal) utils as future values); repeat until\n",
        "policy converges.  STILL OPTIMAL and; can converge much faster under some \n",
        "conditions.\n",
        "\n",
        "Problems w/ Value iteration: 1) slow: O(S^2A) per iteration; 2) \"max\" at each \n",
        "state rarely changes; 3) policy often converges long before the values\n",
        "\n",
        "For worst-case minimax reasoning, terminal function scale doesn't matter:\n",
        "we just want better states to have higher evals (get ordering right) - we call\n",
        "this INSENSITIVITY TO MONOTONIC TRANSFORMATIONS.\n",
        "For average-case expectimax reasoning, we need MAGNITUDES to be meaningful.\n",
        "\n",
        "Utilities are functions from outcomes (states of world) to real #s that describe\n",
        "an agent's preferences; they summarize agent's goals.  Any \"rational' prefs can \n",
        "be summarized as a util function.\n",
        "\n",
        "FALSE: If the only difference between two MDPs is the value of the discount \n",
        "factor then they must have the same optimal policy.\n",
        "\n",
        "TRUE:  For an infinite horizon MDP with a finite number of states and actions \n",
        "and with a discount factor γ, with 0 < γ < 1, value iteration is guaranteed to \n",
        "converge.\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"Your definition here\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "\"MDP FORMAL\" : \"set of STATES, set of ACTIONS, TRANSITION FUNCTION T (probability called MODEL), REWARD FUNCTION R(s, a, s'), INITIAL STATE, TERMINAL STATE (optional)\",\n",
        "\"Markov Decision Process\": \"MDP=SEQUENTIAL decision-problem for a FULLY-OBSERVABLE environment with STOCHASTIC transition model + ADDITIVE REWARDS; NON-DETERMINISTIC SEARCH PROBLEMS (EXPECTIMAX)\",\n",
        "\"Expectimax Node\" : \"outcome is uncertain. In expectimax search we calculate their EXPECTED UTILITIES\",\n",
        "\"policy\" : \"solution to MDP; maps from state onto action to take if agent is in that state.\",\n",
        "\"policy\" : \"pi tells agent what ACTION to take at state S\",\n",
        "\"discount\" : \"U[(1,2,3)] = 0.5*1 + 0.5^1 * 2 + 0.5^2 * 3 = 1*1 + 0.5*2 + 0.25*3\" ,\n",
        "\"principle of maximizing our expected utility\" : \"A rational agent should pick the action that maximizes the expected return for it\",\n",
        "\"axioms of rationality\" : \"orderability, transitivity, continuity, substitutability, monotonicity\",\n",
        "\n",
        "\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 51,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "3c6e2f4a-7672-4662-9a12-62ffc815c367"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": 52,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n \nPerformance of agent in MDP is sum of rewards for \ntransitions it takes. \nGames with finite steps are harder to find optimal values \nthan infinite step games. \nValue of rewards decay EXPONENTIALLY.\nIf game lasts forever, use FINITE HORIZON (similar to depth-limited search\nand terminate after fized T steps; SET GAMMA to 0<GAMMA<1\nSMALLER GAMMA=SMALLER HORIZON=\"Short term focus\"\nValue iteration repeated until convergence.\nComplexity: O(S^2 * A)\nValue iteration guaranteed unique OPTIMAL values.\nHow do we know V_k vectors will converge?\nCase 1: If tree has max depth M, then V_M holds the actual untruncated values.\nCase 2: If discount < 1: sketch (for any state V_k and V_{k+1} can be viewed\nas depth k+1 expectimax results in nearly identical search trees); difference is \nthat on bottom layer, V_{k+1} has actual rewards while V+k has 0s; last layer is \nat best R_MAX; it is at worst R_MIN; But everything is discounted by gamma^k that\nfar out; so V_k and V_{k+1} are at most gamme^k max|R| different; so as k\nincreases, the values converge.\n\nPOLICY EVAL: O(S^2)\nActions are easier to select from q-values than values.\n\nPolicy iteration: combines idea of evaluating policy with improving a policy \nbased on its values. 1) policy eval (calc utils for some fixed policy until \nconvergence) + 2) policy improvement (update policy using 1-step look-ahead\nw/resulting converged (but not optimal) utils as future values); repeat until\npolicy converges.  STILL OPTIMAL and; can converge much faster under some \nconditions.\n\nProblems w/ Value iteration: 1) slow: O(S^2A) per iteration; 2) \"max\" at each \nstate rarely changes; 3) policy often converges long before the values\n\nFor worst-case minimax reasoning, terminal function scale doesn't matter:\nwe just want better states to have higher evals (get ordering right) - we call\nthis INSENSITIVITY TO MONOTONIC TRANSFORMATIONS.\nFor average-case expectimax reasoning, we need MAGNITUDES to be meaningful.\n\nUtilities are functions from outcomes (states of world) to real #s that describe\nan agent's preferences; they summarize agent's goals.  Any \"rational' prefs can \nbe summarized as a util function.\n\nFALSE: If the only difference between two MDPs is the value of the discount \nfactor then they must have the same optimal policy.\n\nTRUE:  For an infinite horizon MDP with a finite number of states and actions \nand with a discount factor γ, with 0 < γ < 1, value iteration is guaranteed to \nconverge.\n\n\n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Mdp formal** - set of STATES, set of ACTIONS, TRANSITION FUNCTION T (probability called MODEL), REWARD FUNCTION R(s, a, s'), INITIAL STATE, TERMINAL STATE (optional)\n* **Markov decision process** - MDP=SEQUENTIAL decision-problem for a FULLY-OBSERVABLE environment with STOCHASTIC transition model + ADDITIVE REWARDS; NON-DETERMINISTIC SEARCH PROBLEMS (EXPECTIMAX)\n* **Expectimax node** - outcome is uncertain. In expectimax search we calculate their EXPECTED UTILITIES\n* **Policy** - pi tells agent what ACTION to take at state S\n* **Discount** - U[(1,2,3)] = 0.5*1 + 0.5^1 * 2 + 0.5^2 * 3 = 1*1 + 0.5*2 + 0.25*3\n* **Principle of maximizing our expected utility** - A rational agent should pick the action that maximizes the expected return for it\n* **Axioms of rationality** - orderability, transitivity, continuity, substitutability, monotonicity\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 = \"\"\"RL = receive feedback via REWARDS; agent's utility is\n",
        "defined by REWARD FUNCTION; must learn to act so as to MAXIMIZE EXPECTED REWARDS;\n",
        "all learning is based on observed samples of outcomes!  Still assume a MDP \n",
        "(states, actions, model T (not given-hidden), reward function (hidden)), so must\n",
        "try actions and states out to learn. \n",
        "\n",
        "TEMPORAL DIFFERENCE LEARNING: update V(s) each time we experience a transition\n",
        "(s, a, s', r); likely outcomes s' will contribute updates more often.\n",
        "EXAMPLE: V^pi (s) <-- (1-alpha) V^pi (s) + alpha [ R(s, pi(s), s') + gamma^pi (s')\n",
        "Temporal difference learning is a MODEL-FREE way to do policy eval, mimicking \n",
        "Bellman updates with running sample averages; but we need Q VALUES (not values).\n",
        "\n",
        "Q-VALUE ITERATION: start with Q_0(s,a)=0, given Q_k, calc depth k+1 q-vals for \n",
        "all q-states:  We're going to sum over all resulting states, S prime, modified \n",
        "by the probability of ending in S prime, times the instantaneous reward plus the\n",
        " discounted future reward, and the discounted future reward will now be just \n",
        " assume you pick the max action for the Q-state once you arrive in S prime. \n",
        " \n",
        " Learn Q(s,a) vals as you go: - receive a sample (s, a, s', r); - consider old \n",
        " estimate: Q(s, a); - consider new sample estimate: The sample, you can think \n",
        " of as being this instantaneous reward plus the discount of the future value of \n",
        " being in S prime; - incorporate new estimate into running average: take this \n",
        " sample that we just collected and the previous estimates, then update estimates \n",
        " to be some new estimates. hyperparameter Alpha, which is called the learning \n",
        " rate. That's going to allow us to adjust how much we trust this new data from \n",
        " our new sample versus the estimates that we've accrued previously. \n",
        "  If value set to be one, then that means we basically totally ignore previous \n",
        "  estimates because this would then go to zero. It'll be 0 times our previous \n",
        "  estimates, and then everything would be on the sample. We would completely update our guess at the value of being in this state just based on this. Then similarly, if we set our value instead of being equal to 1, if we set Alpha to be equal to 0, then that means we put all of the weight on our previous estimates and basically totally ignore the input from the current sample.\n",
        " COVERGES TO OPTIMAL POLICY! Explore enough, learning rate has to be small enough \n",
        " (less than 1; closer to 0 means we keep knowledge about past), and don't turn \n",
        " down too fast.\n",
        "\n",
        " HOW TO EXPLORE?  Simplest: random actions (epilson-greedy).\n",
        " small probability epsilon = act randomly; \n",
        " large probability 1-epsilon = act current policy\n",
        " \"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"exploration\" : \"have to try unknown actions to get info\",\n",
        "\"exploitation\" : \"eventually, you have to use what you know\",\n",
        "\"regret\" : \"even if you learn intelligently, you make mistakes\",\n",
        "\"sampling\" : \"due to chance, you have to try things repeatedly\",\n",
        "\"difficulty\" : \"learning can be much harder than solving a known MDP\",\n",
        "\"interpolation\" : \"the technical term for Alpha, where we're updating one component by some amount and the other component by 1 minus that amount.\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "}"
      ],
      "execution_count": 53,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "18464a1b-ea47-42f6-8d33-f42d72129160"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": 54,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\nRL = receive feedback via REWARDS; agent's utility is\ndefined by REWARD FUNCTION; must learn to act so as to MAXIMIZE EXPECTED REWARDS;\nall learning is based on observed samples of outcomes!  Still assume a MDP \n(states, actions, model T (not given-hidden), reward function (hidden)), so must\ntry actions and states out to learn. \n\nTEMPORAL DIFFERENCE LEARNING: update V(s) each time we experience a transition\n(s, a, s', r); likely outcomes s' will contribute updates more often.\nEXAMPLE: V^pi (s) <-- (1-alpha) V^pi (s) + alpha [ R(s, pi(s), s') + gamma^pi (s')\nTemporal difference learning is a MODEL-FREE way to do policy eval, mimicking \nBellman updates with running sample averages; but we need Q VALUES (not values).\n\nQ-VALUE ITERATION: start with Q_0(s,a)=0, given Q_k, calc depth k+1 q-vals for \nall q-states:  We're going to sum over all resulting states, S prime, modified \nby the probability of ending in S prime, times the instantaneous reward plus the\n discounted future reward, and the discounted future reward will now be just \n assume you pick the max action for the Q-state once you arrive in S prime. \n \n Learn Q(s,a) vals as you go: - receive a sample (s, a, s', r); - consider old \n estimate: Q(s, a); - consider new sample estimate: The sample, you can think \n of as being this instantaneous reward plus the discount of the future value of \n being in S prime; - incorporate new estimate into running average: take this \n sample that we just collected and the previous estimates, then update estimates \n to be some new estimates. hyperparameter Alpha, which is called the learning \n rate. That's going to allow us to adjust how much we trust this new data from \n our new sample versus the estimates that we've accrued previously. \n  If value set to be one, then that means we basically totally ignore previous \n  estimates because this would then go to zero. It'll be 0 times our previous \n  estimates, and then everything would be on the sample. We would completely update our guess at the value of being in this state just based on this. Then similarly, if we set our value instead of being equal to 1, if we set Alpha to be equal to 0, then that means we put all of the weight on our previous estimates and basically totally ignore the input from the current sample.\n COVERGES TO OPTIMAL POLICY! Explore enough, learning rate has to be small enough \n (less than 1; closer to 0 means we keep knowledge about past), and don't turn \n down too fast.\n\n HOW TO EXPLORE?  Simplest: random actions (epilson-greedy).\n small probability epsilon = act randomly; \n large probability 1-epsilon = act current policy\n \n\n## Module 9 Definitions\n* **Exploration** - have to try unknown actions to get info\n* **Exploitation** - eventually, you have to use what you know\n* **Regret** - even if you learn intelligently, you make mistakes\n* **Sampling** - due to chance, you have to try things repeatedly\n* **Difficulty** - learning can be much harder than solving a known MDP\n* **Interpolation** - the technical term for Alpha, where we're updating one component by some amount and the other component by 1 minus that amount.\n* **** - \n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\"\n",
        "Size of distribution for n variables with doman sizes d = d^n;\n",
        "\n",
        "Equal to 1 w/o independence: SUM_a P(A=a|B); SUM_a SUM_b P(A=a) P(B=b); \n",
        "SUM_a SUM_b P(A=a, B=b).\n",
        "\n",
        "P(A,B,C), no independence. = P(A|B,C) P(B|C) P(C); P(C|A,B) P(A,B); P(A, B|C) P(C).\n",
        "\n",
        "P(A|B,C), no independence. P(A,B,C) / SUM_a P(A=a, B,C)\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"observed variables (evidence)\" : \"agent knows certain things about state (sensors/symptoms)\",\n",
        "\"unobserved\" : \"\",\n",
        "\"unobserved variables (states)\" : \"agent needs to reason about other aspects (where an object is or what disease present)\",\n",
        "\"model\" : \"agent knows some about how known variables relates to unknown variables\",\n",
        "\"outcomes\" : \"a set of ASSIGNMENTS of values to variables\",\n",
        "\"joint distribution\" : \"how likely a particular set of assignments are.\"\n",
        "}"
      ],
      "execution_count": 55,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "a7dcf69c-4116-4ede-8f69-8728b1028b1b"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": 56,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n\nSize of distribution for n variables with doman sizes d = d^n;\n\nEqual to 1 w/o independence: SUM_a P(A=a|B); SUM_a SUM_b P(A=a) P(B=b); \nSUM_a SUM_b P(A=a, B=b).\n\nP(A,B,C), no independence. = P(A|B,C) P(B|C) P(C); P(C|A,B) P(A,B); P(A, B|C) P(C).\n\nP(A|B,C), no independence. P(A,B,C) / SUM_a P(A=a, B,C)\n\n\n\n## Module 10 Definitions\n* **Observed variables (evidence)** - agent knows certain things about state (sensors/symptoms)\n* **Unobserved** - \n* **Unobserved variables (states)** - agent needs to reason about other aspects (where an object is or what disease present)\n* **Model** - agent knows some about how known variables relates to unknown variables\n* **Outcomes** - a set of ASSIGNMENTS of values to variables\n* **Joint distribution** - how likely a particular set of assignments are.\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\"Independent=two random variables X and Y. \n",
        "Then we can say that the X and Y are independent if the joint probability of \n",
        "X and Y is equal to the to marginal probabilities of X and Y. \n",
        "\n",
        "X and Y conditionally independent given some evidence variable Z. \n",
        "That's true if they are d-separated by Z, and we're going to consider all paths \n",
        "from X to Y and then check to see if there's no active paths, and if so, we're \n",
        "going to be able to say X and Y are independent. \n",
        "\n",
        "Take all triples as a sliding thing along all paths between the variables \n",
        "of consideration. Check to see if the whole path is active. \n",
        "The whole path is active if every triple along that path is active. \n",
        "Keep track of all the triples along the path and check to see whether they're \n",
        "all active.  If all active, then the whole path is active, \n",
        "if any are inactive, then whole path is inactive.  \n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 57,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 561
        },
        "cellView": "form",
        "outputId": "f71ee795-b22c-48ae-cdf1-69b707c3a29f"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": 58,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\nIndependent=two random variables X and Y. \nThen we can say that the X and Y are independent if the joint probability of \nX and Y is equal to the to marginal probabilities of X and Y. \n\nX and Y conditionally independent given some evidence variable Z. \nThat's true if they are d-separated by Z, and we're going to consider all paths \nfrom X to Y and then check to see if there's no active paths, and if so, we're \ngoing to be able to say X and Y are independent. \n\nTake all triples as a sliding thing along all paths between the variables \nof consideration. Check to see if the whole path is active. \nThe whole path is active if every triple along that path is active. \nKeep track of all the triples along the path and check to see whether they're \nall active.  If all active, then the whole path is active, \nif any are inactive, then whole path is inactive.  \n\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 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\"The naive part of a naive Bayes classifier is to \n",
        "assume that all features to represent the inputs are independent of each other \n",
        "and  only dependent on the label. \n",
        "\n",
        "P(Y, F_1, ... F_n) = P(Y) PI_i P(F_i | Y)\n",
        "|Y| X |F|^n values; n x |F| x |Y| parameters\n",
        "\n",
        "Relative frequency parameters will OVERFIT the training data!\n",
        "In general, we cannot go around giving UNSEEN EVENTS 0 probability.\n",
        "To general better: we need to SMOOTH or REGULARIZE estimates.\n",
        "\n",
        "In practice, Laplace often performs poorly for P(X|Y): when |X| is very large, when\n",
        "|Y| is very large.\n",
        "\n",
        "Bayes' rule lets us do diagnostice queries with causal probabilities.\n",
        "Naive Bayes' assumption take all features to be independent given class label.\n",
        "\n",
        "Bias: a measure of how easy it is to get your perceptron to output a one; or \n",
        "how easy it is to get the perceptron to fire that electrical impulse onwards. \n",
        "For a perceptron with a really big bias, it's extremely easy for the perceptron \n",
        "to output a one but if the bias is negative, then it's very difficult for the \n",
        "perceptron to output a one.\n",
        "\n",
        "Binary multiclass where the negative class has weight zero.\n",
        "\n",
        "For a binary classifier, you can bound the number of mistakes by some constant k \n",
        "over the margin squared (mistakes < {k/delta^2}). If the space between the margin between those two classes \n",
        "is large, then that denominator is going to get really big. \n",
        "That means the number of mistakes will be small. \n",
        "If you can push those two classes further and further apart, increase their margin \n",
        "then the numbers are going to be small. \n",
        "Delta^2 is the margin.\n",
        "\n",
        "Problems with perceptrons\n",
        "Noise: if the data isn't separable, weights might thrash (averaging weight\n",
        "vectors over time can help (averaged perceptron))\n",
        "Mediocre generalization: finds a \"barely\" separating solution.\n",
        "Overtesting: a kind of overfitting.Test/held-out accuracy rises then falls.\n",
        "\n",
        "Fix perceptrons: MIRA = Margin Infused Relaxed Algorithm:\n",
        "instead of updating the weights by a big amount each time, update it by just \n",
        "enough to fix the current mistake and no more. When guessing y instead of y star \n",
        "the truth on some example. Then instead of subtracting out f of x, modify that \n",
        "by some scalar value tau. Scale it by tau for both subtracting from the \n",
        "incorrectly predicted class and when adding to the correctly predicted class.\n",
        "\n",
        "Support Vector Machine (SVM) is similar to MIRA, where you're trying to look at \n",
        "the margins but instead of looking at it for each item that you're classifying, \n",
        "what SVMs do is draw two additional vectors called the support vectors and then \n",
        "maximize the margin between those support vectors and the decision boundary \n",
        "classified. Instead of just updating your weights for a single item, they're \n",
        "actually going to look at all items. The intuition is that SVMs help you find \n",
        "that boundary that maximizes the margin between the two different classes. \n",
        "\n",
        "Take this one-dimensional problem and map it into a higher number of dimensions \n",
        "and oftentimes in higher number of dimensions, it is linearly separable.\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"Laplace's estimate\" : \"pretend you saw every outcome once more than you actually did\",    \n",
        "\"concept\" : \"definition\",    \n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 59,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "d49e9027-03c2-46ce-f549-06583c81a84f"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module12_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter19_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter19_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter19_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter19_4),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter19_5),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter19_6),\n",
        "  (\"SLP Chapter 4.1 Naive Bayes Classifiers\", slp_chapter4_1),\n",
        "  (\"SLP Chapter 4.2 Training the Naive Bayes Classifier\", slp_chapter4_2),\n",
        "  (\"SLP Chapter 4.3 Worked Example\", slp_chapter4_3),\n",
        "  (\"SLP Chapter 4.4 Optimizing for Sentiment Analysis\", slp_chapter4_4),\n",
        "  (\"SLP Chapter 4.5 Naive Bayes for other text classification tasks\", slp_chapter4_5),\n",
        "  (\"SLP Chapter 4.6 Naive Bayes as a Language Model\", slp_chapter4_6),\n",
        "  (\"SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\", slp_chapter4_7),\n",
        "  (\"SLP Chapter 4.8 Test sets and Cross-validation\", slp_chapter4_8),\n",
        "  (\"SLP Chapter 4.9 Statistical Significance Testing\", slp_chapter4_9),\n",
        "  (\"SLP Chapter 4.10 Avoiding Harms in Classification\", slp_chapter4_10),\n",
        "  (\"Module 12 Lecture Notes\", module12_lecture_notes),\n",
        "]\n",
        "\n",
        "module12_markdown = format_module(12, \"Naive Bayes and Perceptrons\", \n",
        "                         module12_sections, \n",
        "                         module12_definitions)\n",
        "display(Markdown(module12_markdown))"
      ],
      "execution_count": 60,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\nThe naive part of a naive Bayes classifier is to \nassume that all features to represent the inputs are independent of each other \nand  only dependent on the label. \n\nP(Y, F_1, ... F_n) = P(Y) PI_i P(F_i | Y)\n|Y| X |F|^n values; n x |F| x |Y| parameters\n\nRelative frequency parameters will OVERFIT the training data!\nIn general, we cannot go around giving UNSEEN EVENTS 0 probability.\nTo general better: we need to SMOOTH or REGULARIZE estimates.\n\nIn practice, Laplace often performs poorly for P(X|Y): when |X| is very large, when\n|Y| is very large.\n\nBayes' rule lets us do diagnostice queries with causal probabilities.\nNaive Bayes' assumption take all features to be independent given class label.\n\nBias: a measure of how easy it is to get your perceptron to output a one; or \nhow easy it is to get the perceptron to fire that electrical impulse onwards. \nFor a perceptron with a really big bias, it's extremely easy for the perceptron \nto output a one but if the bias is negative, then it's very difficult for the \nperceptron to output a one.\n\nBinary multiclass where the negative class has weight zero.\n\nFor a binary classifier, you can bound the number of mistakes by some constant k \nover the margin squared (mistakes < {k/delta^2}). If the space between the margin between those two classes \nis large, then that denominator is going to get really big. \nThat means the number of mistakes will be small. \nIf you can push those two classes further and further apart, increase their margin \nthen the numbers are going to be small. \nDelta^2 is the margin.\n\nProblems with perceptrons\nNoise: if the data isn't separable, weights might thrash (averaging weight\nvectors over time can help (averaged perceptron))\nMediocre generalization: finds a \"barely\" separating solution.\nOvertesting: a kind of overfitting.Test/held-out accuracy rises then falls.\n\nFix perceptrons: MIRA = Margin Infused Relaxed Algorithm:\ninstead of updating the weights by a big amount each time, update it by just \nenough to fix the current mistake and no more. When guessing y instead of y star \nthe truth on some example. Then instead of subtracting out f of x, modify that \nby some scalar value tau. Scale it by tau for both subtracting from the \nincorrectly predicted class and when adding to the correctly predicted class.\n\nSupport Vector Machine (SVM) is similar to MIRA, where you're trying to look at \nthe margins but instead of looking at it for each item that you're classifying, \nwhat SVMs do is draw two additional vectors called the support vectors and then \nmaximize the margin between those support vectors and the decision boundary \nclassified. Instead of just updating your weights for a single item, they're \nactually going to look at all items. The intuition is that SVMs help you find \nthat boundary that maximizes the margin between the two different classes. \n\nTake this one-dimensional problem and map it into a higher number of dimensions \nand oftentimes in higher number of dimensions, it is linearly separable.\n\n\n## Module 12 Definitions\n* **Laplace's estimate** - pretend you saw every outcome once more than you actually did\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 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\"\n",
        "P(y=1) = sigma(w @ x+b);\n",
        "P(y=0) = 1 - sigma(x @ w+b)\n",
        "\n",
        "Learning in logistic regression:\n",
        "(1) an objective function or LOSS FUNCTION that tells us DISTANCE between the \n",
        "system output and the goal output. Use CROSS-ENTROPY LOSS.\n",
        "(2) An algorithm for optimizing the objective function.  Use \n",
        "stochastic gradient descent to MINIMIZE the LOSS FUNCTION.\n",
        "\n",
        "The goal of a loss function is just to determine how close a goal standard label \n",
        "for some input item is to the output; the prediction made by our classifier. \n",
        "The correct output for a binary classification problem is only going to be one \n",
        "of two things, it's going to be one or a zero, whereas our model is going to \n",
        "output real value number between zero and one. What we want is to have the loss \n",
        "tell us how much our prediction, y hat, differs from the true y. \n",
        "One common example from machine learning is called mean squared error, where\n",
        "the difference between our prediction and the truth. We square it to make sure \n",
        "that if we're off in one direction or another, the negative sign doesn't matter.\n",
        "Technically, it is non convex, when applied to probabilistic classification. \n",
        "Mean squared error is not a particularly good objective function. \n",
        "\n",
        "P(y|x) = yhat (1-yhat)^{1-y}\n",
        "y = 1 = yhat (we want yhat to be as high as possible, as close to 1)\n",
        "y = 0 = 1-yhat (want yhat as low as possible, as close to 0)\n",
        "\n",
        "\n",
        "-log p(y|x) = - [ylogyhat + (1-y)log(1-yhat)];\n",
        "yhat = sigma(w@x)+b;\n",
        "L_CE(yhat, y) = -[ylogsigma(w@x+b)+(1-y)log(1-sigma(w@x+b))]\n",
        "\n",
        "P(sentiment=1|It's hokey...) = 0.69. Let's say y=1.\n",
        "= -[logsigma(w@x+b)]\n",
        "= - log(0.69) = 0.37\n",
        "IF y = 0;\n",
        "= -log(0.31) = 1.17\n",
        "\n",
        " If our prediction is correct, then our cross entropy loss is lower. \n",
        " If our prediction is incorrect, then our cross entropy loss is higher.\n",
        " \n",
        " A perfect classifier would assign probability 1 to the correct outcome, \n",
        " Y equals 1, or Y equals 0, and probability 0 to the incorrect outcome. \n",
        " The higher the Y-hat, the closer it is to the truth, the better the classifier. \n",
        " The lower the Y-hat, the closer it is to zero the wrong answer, the worse the classifier. \n",
        "Gradient descent: for each of our weights we're going to find the slope which way\n",
        " is down according to the loss and take a step in the downward direction. \n",
        " We're going to look at the gradient, the slope for each of our weights and \n",
        " take a step in the downward direction. \n",
        "\n",
        " For logistic regression,the loss function is CONVEX. \n",
        " There's just one minimum for logistic regression. \n",
        " There's a single point that is the minimum and there's no local minimum that \n",
        " we can get stuck in. \n",
        " As a result of this convex optimization means that gradient descent, \n",
        " starting from any point, is going to guarantee finding that minimum.\n",
        "\n",
        " STEP SIZE = The weight at each time step, at times step one is going to be the current \n",
        " weight at the previous time step minus the learning rate. \n",
        " The slope is going to be the derivative of the loss function with respect to the weight.\n",
        "\n",
        " Overfitting is going to be a problem with logistic regression and many machine \n",
        " learning models, just like with perceptrons. Too carefully model our training data \n",
        " or too closely mimicking training data and that means that it fails to generalize \n",
        " on some unseen test data. Just like with perceptron, early stopping trip where \n",
        " we look at the models' accuracy on a held-out dub set and then stop updating \n",
        " model parameters after reaching peak performance on that development set. \n",
        " Another is a process called regularization. One reason that overfitting can \n",
        " sometimes happen is you basically have a lot of features. \n",
        " If you have one feature that's on for a certain item in your training set, \n",
        " set that weight to be very high so it always predicts that particular one if it \n",
        " happens to be positive.  \n",
        "\n",
        " A loss function - cross-entropy loss;\n",
        " Optimization algo - gradient descent;\n",
        " way of computing gradient of the loss function - error propagation\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"Classifier components\" : \"\",\n",
        "\"feature representation of input\" : \"vector of features [x_1, x_2, ...X_n]\",\n",
        "\"classification function for learning\" : \"usually involves minimizing error on training examples\",\n",
        "\"objective function for learning\" : \"usually involves minimizing error on training examples\",\n",
        "\"an algorithm for optimizing the objective function\" : \"\",\n",
        "\"Gradient descent\" : \"a method that finds minimum of a function by figuring out which direction to push around each value and weight vector and bias; find our optimal values\",\n",
        "\n",
        "\n",
        "\n",
        "}\n"
      ],
      "execution_count": 61,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "7ab4737f-00ec-4700-9d5b-7a1fb81fb3f7"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": 62,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "## WARNING: Your definition of 'Gradient descent' is too long!\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\nP(y=1) = sigma(w @ x+b);\nP(y=0) = 1 - sigma(x @ w+b)\n\nLearning in logistic regression:\n(1) an objective function or LOSS FUNCTION that tells us DISTANCE between the \nsystem output and the goal output. Use CROSS-ENTROPY LOSS.\n(2) An algorithm for optimizing the objective function.  Use \nstochastic gradient descent to MINIMIZE the LOSS FUNCTION.\n\nThe goal of a loss function is just to determine how close a goal standard label \nfor some input item is to the output; the prediction made by our classifier. \nThe correct output for a binary classification problem is only going to be one \nof two things, it's going to be one or a zero, whereas our model is going to \noutput real value number between zero and one. What we want is to have the loss \ntell us how much our prediction, y hat, differs from the true y. \nOne common example from machine learning is called mean squared error, where\nthe difference between our prediction and the truth. We square it to make sure \nthat if we're off in one direction or another, the negative sign doesn't matter.\nTechnically, it is non convex, when applied to probabilistic classification. \nMean squared error is not a particularly good objective function. \n\nP(y|x) = yhat (1-yhat)^{1-y}\ny = 1 = yhat (we want yhat to be as high as possible, as close to 1)\ny = 0 = 1-yhat (want yhat as low as possible, as close to 0)\n\n\n-log p(y|x) = - [ylogyhat + (1-y)log(1-yhat)];\nyhat = sigma(w@x)+b;\nL_CE(yhat, y) = -[ylogsigma(w@x+b)+(1-y)log(1-sigma(w@x+b))]\n\nP(sentiment=1|It's hokey...) = 0.69. Let's say y=1.\n= -[logsigma(w@x+b)]\n= - log(0.69) = 0.37\nIF y = 0;\n= -log(0.31) = 1.17\n\n If our prediction is correct, then our cross entropy loss is lower. \n If our prediction is incorrect, then our cross entropy loss is higher.\n \n A perfect classifier would assign probability 1 to the correct outcome, \n Y equals 1, or Y equals 0, and probability 0 to the incorrect outcome. \n The higher the Y-hat, the closer it is to the truth, the better the classifier. \n The lower the Y-hat, the closer it is to zero the wrong answer, the worse the classifier. \nGradient descent: for each of our weights we're going to find the slope which way\n is down according to the loss and take a step in the downward direction. \n We're going to look at the gradient, the slope for each of our weights and \n take a step in the downward direction. \n\n For logistic regression,the loss function is CONVEX. \n There's just one minimum for logistic regression. \n There's a single point that is the minimum and there's no local minimum that \n we can get stuck in. \n As a result of this convex optimization means that gradient descent, \n starting from any point, is going to guarantee finding that minimum.\n\n STEP SIZE = The weight at each time step, at times step one is going to be the current \n weight at the previous time step minus the learning rate. \n The slope is going to be the derivative of the loss function with respect to the weight.\n\n Overfitting is going to be a problem with logistic regression and many machine \n learning models, just like with perceptrons. Too carefully model our training data \n or too closely mimicking training data and that means that it fails to generalize \n on some unseen test data. Just like with perceptron, early stopping trip where \n we look at the models' accuracy on a held-out dub set and then stop updating \n model parameters after reaching peak performance on that development set. \n Another is a process called regularization. One reason that overfitting can \n sometimes happen is you basically have a lot of features. \n If you have one feature that's on for a certain item in your training set, \n set that weight to be very high so it always predicts that particular one if it \n happens to be positive.  \n\n A loss function - cross-entropy loss;\n Optimization algo - gradient descent;\n way of computing gradient of the loss function - error propagation\n\n\n## Module 13 Definitions\n* **Classifier components** - \n* **Feature representation of input** - vector of features [x_1, x_2, ...X_n]\n* **Classification function for learning** - usually involves minimizing error on training examples\n* **Objective function for learning** - usually involves minimizing error on training examples\n* **An algorithm for optimizing the objective function** - \n* **Gradient descent** - a method that finds minimum of a function by figuring out which direction to push around each value and weight vector and bias; find our optimal values\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\"NLMs have advantages over n-grams: 1) no need for \n",
        "smoothing; 2) handles much longer histories; 3) generalize over contexts of \n",
        "similar words; 4) NLMs tend to have much higher predictive accuracy than n-grams.\n",
        "Con: slower to train than n-gram LMs.\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 63,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "ce6e11e4-27cf-4a9a-8036-277ea7386773"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module14_sections = [\n",
        "  (\"SLP Chapter 9.1 Language Models Revisited\", slp_chapter9_1),\n",
        "  (\"SLP Chapter 9.2 Recurrent Neural Networks\", slp_chapter9_2),\n",
        "  (\"SLP Chapter 9.3 RNNs as Language Models\", slp_chapter9_3),\n",
        "\n",
        "  (\"SLP Chapter 6.1 Lexical Semantics\", slp_chapter6_1),\n",
        "  (\"SLP Chapter 6.2 Vector Semantics\", slp_chapter6_2),\n",
        "  (\"SLP Chapter 6.3 Words and Vectors\", slp_chapter6_3),\n",
        "  (\"SLP Chapter 6.4 Cosine for measuring similarity\", slp_chapter6_4),\n",
        "  (\"SLP Chapter 6.8 Word2vec\", slp_chapter6_8),\n",
        "  (\"SLP Chapter 6.10 Semantic properties of embeddings\", slp_chapter6_10),\n",
        "  (\"SLP Chapter 6.11 Bias and Embeddings\", slp_chapter6_11),\n",
        "  (\"SLP Chapter 6.12 Evaluating Vector Models\", slp_chapter6_12),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module14_markdown = format_module(14, \"Natural Language Processing\", \n",
        "                         module14_sections, \n",
        "                         module14_definitions)\n",
        "display(Markdown(module14_markdown))"
      ],
      "execution_count": 64,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n\nP(y=1) = sigma(w @ x+b);\nP(y=0) = 1 - sigma(x @ w+b)\n\nLearning in logistic regression:\n(1) an objective function or LOSS FUNCTION that tells us DISTANCE between the \nsystem output and the goal output. Use CROSS-ENTROPY LOSS.\n(2) An algorithm for optimizing the objective function.  Use \nstochastic gradient descent to MINIMIZE the LOSS FUNCTION.\n\nThe goal of a loss function is just to determine how close a goal standard label \nfor some input item is to the output; the prediction made by our classifier. \nThe correct output for a binary classification problem is only going to be one \nof two things, it's going to be one or a zero, whereas our model is going to \noutput real value number between zero and one. What we want is to have the loss \ntell us how much our prediction, y hat, differs from the true y. \nOne common example from machine learning is called mean squared error, where\nthe difference between our prediction and the truth. We square it to make sure \nthat if we're off in one direction or another, the negative sign doesn't matter.\nTechnically, it is non convex, when applied to probabilistic classification. \nMean squared error is not a particularly good objective function. \n\nP(y|x) = yhat (1-yhat)^{1-y}\ny = 1 = yhat (we want yhat to be as high as possible, as close to 1)\ny = 0 = 1-yhat (want yhat as low as possible, as close to 0)\n\n\n-log p(y|x) = - [ylogyhat + (1-y)log(1-yhat)];\nyhat = sigma(w@x)+b;\nL_CE(yhat, y) = -[ylogsigma(w@x+b)+(1-y)log(1-sigma(w@x+b))]\n\nP(sentiment=1|It's hokey...) = 0.69. Let's say y=1.\n= -[logsigma(w@x+b)]\n= - log(0.69) = 0.37\nIF y = 0;\n= -log(0.31) = 1.17\n\n If our prediction is correct, then our cross entropy loss is lower. \n If our prediction is incorrect, then our cross entropy loss is higher.\n \n A perfect classifier would assign probability 1 to the correct outcome, \n Y equals 1, or Y equals 0, and probability 0 to the incorrect outcome. \n The higher the Y-hat, the closer it is to the truth, the better the classifier. \n The lower the Y-hat, the closer it is to zero the wrong answer, the worse the classifier. \nGradient descent: for each of our weights we're going to find the slope which way\n is down according to the loss and take a step in the downward direction. \n We're going to look at the gradient, the slope for each of our weights and \n take a step in the downward direction. \n\n For logistic regression,the loss function is CONVEX. \n There's just one minimum for logistic regression. \n There's a single point that is the minimum and there's no local minimum that \n we can get stuck in. \n As a result of this convex optimization means that gradient descent, \n starting from any point, is going to guarantee finding that minimum.\n\n STEP SIZE = The weight at each time step, at times step one is going to be the current \n weight at the previous time step minus the learning rate. \n The slope is going to be the derivative of the loss function with respect to the weight.\n\n Overfitting is going to be a problem with logistic regression and many machine \n learning models, just like with perceptrons. Too carefully model our training data \n or too closely mimicking training data and that means that it fails to generalize \n on some unseen test data. Just like with perceptron, early stopping trip where \n we look at the models' accuracy on a held-out dub set and then stop updating \n model parameters after reaching peak performance on that development set. \n Another is a process called regularization. One reason that overfitting can \n sometimes happen is you basically have a lot of features. \n If you have one feature that's on for a certain item in your training set, \n set that weight to be very high so it always predicts that particular one if it \n happens to be positive.  \n\n A loss function - cross-entropy loss;\n Optimization algo - gradient descent;\n way of computing gradient of the loss function - error propagation\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "1234018e-e794-46a6-d822-b040a54e904d"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module8_markdown, \n",
        "                             module9_markdown, \n",
        "                             module10_markdown, \n",
        "                             module11_markdown, \n",
        "                             module12_markdown,\n",
        "                             module13_markdown,\n",
        "                             module14_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": 65,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n \nPerformance of agent in MDP is sum of rewards for \ntransitions it takes. \nGames with finite steps are harder to find optimal values \nthan infinite step games. \nValue of rewards decay EXPONENTIALLY.\nIf game lasts forever, use FINITE HORIZON (similar to depth-limited search\nand terminate after fized T steps; SET GAMMA to 0<GAMMA<1\nSMALLER GAMMA=SMALLER HORIZON=\"Short term focus\"\nValue iteration repeated until convergence.\nComplexity: O(S^2 * A)\nValue iteration guaranteed unique OPTIMAL values.\nHow do we know V_k vectors will converge?\nCase 1: If tree has max depth M, then V_M holds the actual untruncated values.\nCase 2: If discount < 1: sketch (for any state V_k and V_{k+1} can be viewed\nas depth k+1 expectimax results in nearly identical search trees); difference is \nthat on bottom layer, V_{k+1} has actual rewards while V+k has 0s; last layer is \nat best R_MAX; it is at worst R_MIN; But everything is discounted by gamma^k that\nfar out; so V_k and V_{k+1} are at most gamme^k max|R| different; so as k\nincreases, the values converge.\n\nPOLICY EVAL: O(S^2)\nActions are easier to select from q-values than values.\n\nPolicy iteration: combines idea of evaluating policy with improving a policy \nbased on its values. 1) policy eval (calc utils for some fixed policy until \nconvergence) + 2) policy improvement (update policy using 1-step look-ahead\nw/resulting converged (but not optimal) utils as future values); repeat until\npolicy converges.  STILL OPTIMAL and; can converge much faster under some \nconditions.\n\nProblems w/ Value iteration: 1) slow: O(S^2A) per iteration; 2) \"max\" at each \nstate rarely changes; 3) policy often converges long before the values\n\nFor worst-case minimax reasoning, terminal function scale doesn't matter:\nwe just want better states to have higher evals (get ordering right) - we call\nthis INSENSITIVITY TO MONOTONIC TRANSFORMATIONS.\nFor average-case expectimax reasoning, we need MAGNITUDES to be meaningful.\n\nUtilities are functions from outcomes (states of world) to real #s that describe\nan agent's preferences; they summarize agent's goals.  Any \"rational' prefs can \nbe summarized as a util function.\n\nFALSE: If the only difference between two MDPs is the value of the discount \nfactor then they must have the same optimal policy.\n\nTRUE:  For an infinite horizon MDP with a finite number of states and actions \nand with a discount factor γ, with 0 < γ < 1, value iteration is guaranteed to \nconverge.\n\n\n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Mdp formal** - set of STATES, set of ACTIONS, TRANSITION FUNCTION T (probability called MODEL), REWARD FUNCTION R(s, a, s'), INITIAL STATE, TERMINAL STATE (optional)\n* **Markov decision process** - MDP=SEQUENTIAL decision-problem for a FULLY-OBSERVABLE environment with STOCHASTIC transition model + ADDITIVE REWARDS; NON-DETERMINISTIC SEARCH PROBLEMS (EXPECTIMAX)\n* **Expectimax node** - outcome is uncertain. In expectimax search we calculate their EXPECTED UTILITIES\n* **Policy** - pi tells agent what ACTION to take at state S\n* **Discount** - U[(1,2,3)] = 0.5*1 + 0.5^1 * 2 + 0.5^2 * 3 = 1*1 + 0.5*2 + 0.25*3\n* **Principle of maximizing our expected utility** - A rational agent should pick the action that maximizes the expected return for it\n* **Axioms of rationality** - orderability, transitivity, continuity, substitutability, monotonicity\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\nRL = receive feedback via REWARDS; agent's utility is\ndefined by REWARD FUNCTION; must learn to act so as to MAXIMIZE EXPECTED REWARDS;\nall learning is based on observed samples of outcomes!  Still assume a MDP \n(states, actions, model T (not given-hidden), reward function (hidden)), so must\ntry actions and states out to learn. \n\nTEMPORAL DIFFERENCE LEARNING: update V(s) each time we experience a transition\n(s, a, s', r); likely outcomes s' will contribute updates more often.\nEXAMPLE: V^pi (s) <-- (1-alpha) V^pi (s) + alpha [ R(s, pi(s), s') + gamma^pi (s')\nTemporal difference learning is a MODEL-FREE way to do policy eval, mimicking \nBellman updates with running sample averages; but we need Q VALUES (not values).\n\nQ-VALUE ITERATION: start with Q_0(s,a)=0, given Q_k, calc depth k+1 q-vals for \nall q-states:  We're going to sum over all resulting states, S prime, modified \nby the probability of ending in S prime, times the instantaneous reward plus the\n discounted future reward, and the discounted future reward will now be just \n assume you pick the max action for the Q-state once you arrive in S prime. \n \n Learn Q(s,a) vals as you go: - receive a sample (s, a, s', r); - consider old \n estimate: Q(s, a); - consider new sample estimate: The sample, you can think \n of as being this instantaneous reward plus the discount of the future value of \n being in S prime; - incorporate new estimate into running average: take this \n sample that we just collected and the previous estimates, then update estimates \n to be some new estimates. hyperparameter Alpha, which is called the learning \n rate. That's going to allow us to adjust how much we trust this new data from \n our new sample versus the estimates that we've accrued previously. \n  If value set to be one, then that means we basically totally ignore previous \n  estimates because this would then go to zero. It'll be 0 times our previous \n  estimates, and then everything would be on the sample. We would completely update our guess at the value of being in this state just based on this. Then similarly, if we set our value instead of being equal to 1, if we set Alpha to be equal to 0, then that means we put all of the weight on our previous estimates and basically totally ignore the input from the current sample.\n COVERGES TO OPTIMAL POLICY! Explore enough, learning rate has to be small enough \n (less than 1; closer to 0 means we keep knowledge about past), and don't turn \n down too fast.\n\n HOW TO EXPLORE?  Simplest: random actions (epilson-greedy).\n small probability epsilon = act randomly; \n large probability 1-epsilon = act current policy\n \n\n## Module 9 Definitions\n* **Exploration** - have to try unknown actions to get info\n* **Exploitation** - eventually, you have to use what you know\n* **Regret** - even if you learn intelligently, you make mistakes\n* **Sampling** - due to chance, you have to try things repeatedly\n* **Difficulty** - learning can be much harder than solving a known MDP\n* **Interpolation** - the technical term for Alpha, where we're updating one component by some amount and the other component by 1 minus that amount.\n* **** - \n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n\nSize of distribution for n variables with doman sizes d = d^n;\n\nEqual to 1 w/o independence: SUM_a P(A=a|B); SUM_a SUM_b P(A=a) P(B=b); \nSUM_a SUM_b P(A=a, B=b).\n\nP(A,B,C), no independence. = P(A|B,C) P(B|C) P(C); P(C|A,B) P(A,B); P(A, B|C) P(C).\n\nP(A|B,C), no independence. P(A,B,C) / SUM_a P(A=a, B,C)\n\n\n\n## Module 10 Definitions\n* **Observed variables (evidence)** - agent knows certain things about state (sensors/symptoms)\n* **Unobserved** - \n* **Unobserved variables (states)** - agent needs to reason about other aspects (where an object is or what disease present)\n* **Model** - agent knows some about how known variables relates to unknown variables\n* **Outcomes** - a set of ASSIGNMENTS of values to variables\n* **Joint distribution** - how likely a particular set of assignments are.\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\nIndependent=two random variables X and Y. \nThen we can say that the X and Y are independent if the joint probability of \nX and Y is equal to the to marginal probabilities of X and Y. \n\nX and Y conditionally independent given some evidence variable Z. \nThat's true if they are d-separated by Z, and we're going to consider all paths \nfrom X to Y and then check to see if there's no active paths, and if so, we're \ngoing to be able to say X and Y are independent. \n\nTake all triples as a sliding thing along all paths between the variables \nof consideration. Check to see if the whole path is active. \nThe whole path is active if every triple along that path is active. \nKeep track of all the triples along the path and check to see whether they're \nall active.  If all active, then the whole path is active, \nif any are inactive, then whole path is inactive.  \n\n\n## Module 11 Definitions\n* **Concept** - definition\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\nThe naive part of a naive Bayes classifier is to \nassume that all features to represent the inputs are independent of each other \nand  only dependent on the label. \n\nP(Y, F_1, ... F_n) = P(Y) PI_i P(F_i | Y)\n|Y| X |F|^n values; n x |F| x |Y| parameters\n\nRelative frequency parameters will OVERFIT the training data!\nIn general, we cannot go around giving UNSEEN EVENTS 0 probability.\nTo general better: we need to SMOOTH or REGULARIZE estimates.\n\nIn practice, Laplace often performs poorly for P(X|Y): when |X| is very large, when\n|Y| is very large.\n\nBayes' rule lets us do diagnostice queries with causal probabilities.\nNaive Bayes' assumption take all features to be independent given class label.\n\nBias: a measure of how easy it is to get your perceptron to output a one; or \nhow easy it is to get the perceptron to fire that electrical impulse onwards. \nFor a perceptron with a really big bias, it's extremely easy for the perceptron \nto output a one but if the bias is negative, then it's very difficult for the \nperceptron to output a one.\n\nBinary multiclass where the negative class has weight zero.\n\nFor a binary classifier, you can bound the number of mistakes by some constant k \nover the margin squared (mistakes < {k/delta^2}). If the space between the margin between those two classes \nis large, then that denominator is going to get really big. \nThat means the number of mistakes will be small. \nIf you can push those two classes further and further apart, increase their margin \nthen the numbers are going to be small. \nDelta^2 is the margin.\n\nProblems with perceptrons\nNoise: if the data isn't separable, weights might thrash (averaging weight\nvectors over time can help (averaged perceptron))\nMediocre generalization: finds a \"barely\" separating solution.\nOvertesting: a kind of overfitting.Test/held-out accuracy rises then falls.\n\nFix perceptrons: MIRA = Margin Infused Relaxed Algorithm:\ninstead of updating the weights by a big amount each time, update it by just \nenough to fix the current mistake and no more. When guessing y instead of y star \nthe truth on some example. Then instead of subtracting out f of x, modify that \nby some scalar value tau. Scale it by tau for both subtracting from the \nincorrectly predicted class and when adding to the correctly predicted class.\n\nSupport Vector Machine (SVM) is similar to MIRA, where you're trying to look at \nthe margins but instead of looking at it for each item that you're classifying, \nwhat SVMs do is draw two additional vectors called the support vectors and then \nmaximize the margin between those support vectors and the decision boundary \nclassified. Instead of just updating your weights for a single item, they're \nactually going to look at all items. The intuition is that SVMs help you find \nthat boundary that maximizes the margin between the two different classes. \n\nTake this one-dimensional problem and map it into a higher number of dimensions \nand oftentimes in higher number of dimensions, it is linearly separable.\n\n\n## Module 12 Definitions\n* **Laplace's estimate** - pretend you saw every outcome once more than you actually did\n* **Concept** - definition\n\n\n## WARNING: Your definition of 'Gradient descent' is too long!\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\nP(y=1) = sigma(w @ x+b);\nP(y=0) = 1 - sigma(x @ w+b)\n\nLearning in logistic regression:\n(1) an objective function or LOSS FUNCTION that tells us DISTANCE between the \nsystem output and the goal output. Use CROSS-ENTROPY LOSS.\n(2) An algorithm for optimizing the objective function.  Use \nstochastic gradient descent to MINIMIZE the LOSS FUNCTION.\n\nThe goal of a loss function is just to determine how close a goal standard label \nfor some input item is to the output; the prediction made by our classifier. \nThe correct output for a binary classification problem is only going to be one \nof two things, it's going to be one or a zero, whereas our model is going to \noutput real value number between zero and one. What we want is to have the loss \ntell us how much our prediction, y hat, differs from the true y. \nOne common example from machine learning is called mean squared error, where\nthe difference between our prediction and the truth. We square it to make sure \nthat if we're off in one direction or another, the negative sign doesn't matter.\nTechnically, it is non convex, when applied to probabilistic classification. \nMean squared error is not a particularly good objective function. \n\nP(y|x) = yhat (1-yhat)^{1-y}\ny = 1 = yhat (we want yhat to be as high as possible, as close to 1)\ny = 0 = 1-yhat (want yhat as low as possible, as close to 0)\n\n\n-log p(y|x) = - [ylogyhat + (1-y)log(1-yhat)];\nyhat = sigma(w@x)+b;\nL_CE(yhat, y) = -[ylogsigma(w@x+b)+(1-y)log(1-sigma(w@x+b))]\n\nP(sentiment=1|It's hokey...) = 0.69. Let's say y=1.\n= -[logsigma(w@x+b)]\n= - log(0.69) = 0.37\nIF y = 0;\n= -log(0.31) = 1.17\n\n If our prediction is correct, then our cross entropy loss is lower. \n If our prediction is incorrect, then our cross entropy loss is higher.\n \n A perfect classifier would assign probability 1 to the correct outcome, \n Y equals 1, or Y equals 0, and probability 0 to the incorrect outcome. \n The higher the Y-hat, the closer it is to the truth, the better the classifier. \n The lower the Y-hat, the closer it is to zero the wrong answer, the worse the classifier. \nGradient descent: for each of our weights we're going to find the slope which way\n is down according to the loss and take a step in the downward direction. \n We're going to look at the gradient, the slope for each of our weights and \n take a step in the downward direction. \n\n For logistic regression,the loss function is CONVEX. \n There's just one minimum for logistic regression. \n There's a single point that is the minimum and there's no local minimum that \n we can get stuck in. \n As a result of this convex optimization means that gradient descent, \n starting from any point, is going to guarantee finding that minimum.\n\n STEP SIZE = The weight at each time step, at times step one is going to be the current \n weight at the previous time step minus the learning rate. \n The slope is going to be the derivative of the loss function with respect to the weight.\n\n Overfitting is going to be a problem with logistic regression and many machine \n learning models, just like with perceptrons. Too carefully model our training data \n or too closely mimicking training data and that means that it fails to generalize \n on some unseen test data. Just like with perceptron, early stopping trip where \n we look at the models' accuracy on a held-out dub set and then stop updating \n model parameters after reaching peak performance on that development set. \n Another is a process called regularization. One reason that overfitting can \n sometimes happen is you basically have a lot of features. \n If you have one feature that's on for a certain item in your training set, \n set that weight to be very high so it always predicts that particular one if it \n happens to be positive.  \n\n A loss function - cross-entropy loss;\n Optimization algo - gradient descent;\n way of computing gradient of the loss function - error propagation\n\n\n## Module 13 Definitions\n* **Classifier components** - \n* **Feature representation of input** - vector of features [x_1, x_2, ...X_n]\n* **Classification function for learning** - usually involves minimizing error on training examples\n* **Objective function for learning** - usually involves minimizing error on training examples\n* **An algorithm for optimizing the objective function** - \n* **Gradient descent** - a method that finds minimum of a function by figuring out which direction to push around each value and weight vector and bias; find our optimal values\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n\nP(y=1) = sigma(w @ x+b);\nP(y=0) = 1 - sigma(x @ w+b)\n\nLearning in logistic regression:\n(1) an objective function or LOSS FUNCTION that tells us DISTANCE between the \nsystem output and the goal output. Use CROSS-ENTROPY LOSS.\n(2) An algorithm for optimizing the objective function.  Use \nstochastic gradient descent to MINIMIZE the LOSS FUNCTION.\n\nThe goal of a loss function is just to determine how close a goal standard label \nfor some input item is to the output; the prediction made by our classifier. \nThe correct output for a binary classification problem is only going to be one \nof two things, it's going to be one or a zero, whereas our model is going to \noutput real value number between zero and one. What we want is to have the loss \ntell us how much our prediction, y hat, differs from the true y. \nOne common example from machine learning is called mean squared error, where\nthe difference between our prediction and the truth. We square it to make sure \nthat if we're off in one direction or another, the negative sign doesn't matter.\nTechnically, it is non convex, when applied to probabilistic classification. \nMean squared error is not a particularly good objective function. \n\nP(y|x) = yhat (1-yhat)^{1-y}\ny = 1 = yhat (we want yhat to be as high as possible, as close to 1)\ny = 0 = 1-yhat (want yhat as low as possible, as close to 0)\n\n\n-log p(y|x) = - [ylogyhat + (1-y)log(1-yhat)];\nyhat = sigma(w@x)+b;\nL_CE(yhat, y) = -[ylogsigma(w@x+b)+(1-y)log(1-sigma(w@x+b))]\n\nP(sentiment=1|It's hokey...) = 0.69. Let's say y=1.\n= -[logsigma(w@x+b)]\n= - log(0.69) = 0.37\nIF y = 0;\n= -log(0.31) = 1.17\n\n If our prediction is correct, then our cross entropy loss is lower. \n If our prediction is incorrect, then our cross entropy loss is higher.\n \n A perfect classifier would assign probability 1 to the correct outcome, \n Y equals 1, or Y equals 0, and probability 0 to the incorrect outcome. \n The higher the Y-hat, the closer it is to the truth, the better the classifier. \n The lower the Y-hat, the closer it is to zero the wrong answer, the worse the classifier. \nGradient descent: for each of our weights we're going to find the slope which way\n is down according to the loss and take a step in the downward direction. \n We're going to look at the gradient, the slope for each of our weights and \n take a step in the downward direction. \n\n For logistic regression,the loss function is CONVEX. \n There's just one minimum for logistic regression. \n There's a single point that is the minimum and there's no local minimum that \n we can get stuck in. \n As a result of this convex optimization means that gradient descent, \n starting from any point, is going to guarantee finding that minimum.\n\n STEP SIZE = The weight at each time step, at times step one is going to be the current \n weight at the previous time step minus the learning rate. \n The slope is going to be the derivative of the loss function with respect to the weight.\n\n Overfitting is going to be a problem with logistic regression and many machine \n learning models, just like with perceptrons. Too carefully model our training data \n or too closely mimicking training data and that means that it fails to generalize \n on some unseen test data. Just like with perceptron, early stopping trip where \n we look at the models' accuracy on a held-out dub set and then stop updating \n model parameters after reaching peak performance on that development set. \n Another is a process called regularization. One reason that overfitting can \n sometimes happen is you basically have a lot of features. \n If you have one feature that's on for a certain item in your training set, \n set that weight to be very high so it always predicts that particular one if it \n happens to be positive.  \n\n A loss function - cross-entropy loss;\n Optimization algo - gradient descent;\n way of computing gradient of the loss function - error propagation\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}