{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": [
        "cw5IpDLCZa4W",
        "s3Uk9gQTevcj",
        "9xRbdqDox2zD"
      ]
    },
    "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": "50bfc95c-760a-4fe5-d506-28283a52680f"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "d2f79f15-285e-4549-b2e0-53bd1b7747ca"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = True"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" 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",
        "- MDP is for **non-deterministic** (unkown outcome) problems.\n",
        "- **stochastic**- outputs have probability, non-deterministic with probabilities\n",
        "- Stochastic Transition Model: p(s' | s,a), probability of arriving in state s' given that we are in state s and selected action a\n",
        "  - **Markovian** b/c we are ignoring previous states\n",
        "- **utility/reward function**- gives reward with each step taken\n",
        "  - can be positive or negative\n",
        "  - process is **sequential** so takes into account past actions\n",
        "  - R(s, a, s') \n",
        "- **Markov Decision Process**(MDP):\n",
        "  - a **sequential** decision problem\n",
        "  - for **fully observable** environments\n",
        "  - with a **stochastic** transition model\n",
        "  - has **additive rewards**\n",
        "  - **non-deterministic search problem** (expictimax can solve them)\n",
        "  - Must have:\n",
        "    - **A set of states**\n",
        "    - **A set of actions**\n",
        "    - **Transition Function** T(s, a, s')\n",
        "    - **Reward Function** R(s, a, s')\n",
        "    - **initial state** s_0\n",
        "    - **Terminal States**- optional, can be one or more\n",
        "- Solution == Policy\n",
        "  - maps state to action if agent is an that state\n",
        "  - **Pi**(s) = a, action to take at state s\n",
        "  - **Pi*** is optimal policy\n",
        "- **Discounting**\n",
        "  - max sum of rewards\n",
        "  - prefer rewards no \n",
        "  - values of rewards decay exponentially\n",
        "- Solutions to Infinite Utilities (bouncing around to constantly collect reward)\n",
        "  - Finite Horizon- terminate after fixed T steps, gives nonstationar policy (pi depends on time left)\n",
        "  - Discounting- 0< gamma<1, smaller gamma --> smaller horzizon\n",
        "- Using expectimax causes repeat states\n",
        "- **Value Iteration**: \n",
        "  - Complexity: O(S^2 * A)- slow\n",
        "  - Guarenteed to converge on unique optimal values\n",
        "- **Policy Evaluation**\n",
        "  - Use recursive Bellman equations \n",
        "    - Efficiency: O(s^2) per iteration\n",
        "  - Without maxes, Bellman eq's are linear (solve with Matlab)\n",
        "  - Pi*(s) = maxQ*(s,a)\n",
        "    - Actions are easier to select from q-values than values\n",
        "  - Need T and R\n",
        "- **Policy Iteration**\n",
        "  1. (Policy Evaluation)For fixed current policy pi, find values with policy evaluaition\n",
        "  2. (Policy Improvement) For fixed values, get a better policy using policy extraction\n",
        "Summary:\n",
        "- Compute optimal values: use value or policy iteration\n",
        "- Compute values for specific policy: use policy evaluation\n",
        "- Turn values into a policy: use policy extraction (one-step lookahead)\n",
        "\n",
        "- **Maximum Expected Utilities**(MEU):\n",
        "  - Utility- map from state to real number that describes agent preferences\n",
        "- Rationality\n",
        "  - 5 axioms of rationality\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",
        "\"etc.\": \"your definition here\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "07688d3b-3b28-4f6e-dd00-a82fdf7a5f6b"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n 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\n- MDP is for **non-deterministic** (unkown outcome) problems.\n- **stochastic**- outputs have probability, non-deterministic with probabilities\n- Stochastic Transition Model: p(s' | s,a), probability of arriving in state s' given that we are in state s and selected action a\n  - **Markovian** b/c we are ignoring previous states\n- **utility/reward function**- gives reward with each step taken\n  - can be positive or negative\n  - process is **sequential** so takes into account past actions\n  - R(s, a, s') \n- **Markov Decision Process**(MDP):\n  - a **sequential** decision problem\n  - for **fully observable** environments\n  - with a **stochastic** transition model\n  - has **additive rewards**\n  - **non-deterministic search problem** (expictimax can solve them)\n  - Must have:\n    - **A set of states**\n    - **A set of actions**\n    - **Transition Function** T(s, a, s')\n    - **Reward Function** R(s, a, s')\n    - **initial state** s_0\n    - **Terminal States**- optional, can be one or more\n- Solution == Policy\n  - maps state to action if agent is an that state\n  - **Pi**(s) = a, action to take at state s\n  - **Pi*** is optimal policy\n- **Discounting**\n  - max sum of rewards\n  - prefer rewards no \n  - values of rewards decay exponentially\n- Solutions to Infinite Utilities (bouncing around to constantly collect reward)\n  - Finite Horizon- terminate after fixed T steps, gives nonstationar policy (pi depends on time left)\n  - Discounting- 0< gamma<1, smaller gamma --> smaller horzizon\n- Using expectimax causes repeat states\n- **Value Iteration**: \n  - Complexity: O(S^2 * A)- slow\n  - Guarenteed to converge on unique optimal values\n- **Policy Evaluation**\n  - Use recursive Bellman equations \n    - Efficiency: O(s^2) per iteration\n  - Without maxes, Bellman eq's are linear (solve with Matlab)\n  - Pi*(s) = maxQ*(s,a)\n    - Actions are easier to select from q-values than values\n  - Need T and R\n- **Policy Iteration**\n  1. (Policy Evaluation)For fixed current policy pi, find values with policy evaluaition\n  2. (Policy Improvement) For fixed values, get a better policy using policy extraction\nSummary:\n- Compute optimal values: use value or policy iteration\n- Compute values for specific policy: use policy evaluation\n- Turn values into a policy: use policy extraction (one-step lookahead)\n\n- **Maximum Expected Utilities**(MEU):\n  - Utility- map from state to real number that describes agent preferences\n- Rationality\n  - 5 axioms of rationality\n \n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "chapter17_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_3 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_4 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_5 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\"\n",
        "- **Reinforcement Learning**\n",
        "  - **Exploration**- try unkown actions\n",
        "  - **Exploitation**- eventually, use what you know\n",
        "  - **Regret**- make mistakes\n",
        "  - **Sampling**- because of chance, must try things repeatedly\n",
        "- Basic Idea: Receive feedback in form of reward, utility defined by reward function, must act to maximize expected rewards, learning based on observed samples\n",
        "- **Model-Based Learning**- learn approximate model based on experiences, solve for values as if learned model was correct\n",
        "  1. Learn emprical MDP model\n",
        "    - Get estimate of T, discover R from experience\n",
        "  2. Solve learned MDP (use value iteration)\n",
        "- Offline (MDP)- know what happens when you take action (R)\n",
        "- Online (RL)- don't know outcome so must try action to figure out if bad/good\n",
        "- **Passive Reinforcement Learning**- no choice about actions, execute and learn from experience\n",
        "  - Input: fixed policy pi(s)\n",
        "  - Unkowns: Transitons T(s,a,s'), Rewards R(s,a,s')\n",
        "  - Goal: learn state values\n",
        "  - Exploitation\n",
        "- **Direct Evaluation**- \n",
        "  - Goal: compute values for each state in pi\n",
        "  - Method:\n",
        "    - Act according to pi\n",
        "    - Every time a state is visited, remember sum of discounted rewards\n",
        "    - Avergae these samples\n",
        "  - Pros:\n",
        "    - Does not require T, R\n",
        "    - Computes the correct avergae values\n",
        "  - Cons:\n",
        "    - Slow\n",
        "      - Waste info about state connections\n",
        "      - Each state is learned seperatley \n",
        "- **Temporal Difference Learning**\n",
        "  - Update V(s) each time we perform transition\n",
        "    - More likely states updated more often\n",
        "  - Exponential moving average- recent samples more important\n",
        "  - **Learning Rate** (alpha)- weight of recent samples\n",
        "  - Model Free\n",
        "- **Active Reinforcement Learning**\n",
        "  - Unkowns: Transitions, T(s,a,s'), Rewarss R(s,a,s')\n",
        "  - Choose actions \n",
        "  - Goal: Learn optimal policy/values\n",
        "  - Exploration\n",
        "  - NOT offline planning\n",
        "- **Q-Learning**\n",
        "  - Learn Q(s,a) values as you go\n",
        "  - Get a sample (s,a,s',r)\n",
        "  - Consider old estimate\n",
        "  - Incorporate new estimate into running average\n",
        "  - Properties\n",
        "    - Converges to optimal policy- EVEN if acting suboptimally\n",
        "      - This is **off-policy learning**\n",
        "  - Cons:\n",
        "    - Must explore enough\n",
        "    - Eventually makelearning rate small enough (but not decrease too quickly)\n",
        "- How to Explore\n",
        "  - Random (episolon-greedy)\n",
        "    - (small) probability epsilon, act randomly\n",
        "    - (large) probability 1-epsilon, act on current policy\n",
        "  - Cons:\n",
        "    - Eventually explore whole space but continue to be random after learning is done\n",
        "      - Solution: lower epsilon over time\n",
        "      - Solution: explore functions\n",
        "- **Exploration Functions**\n",
        "  - Explore areas whose badness not yet know, eventually stop\n",
        "- **Regret**- measure of total mistake cost\n",
        "  - To minimize regret must optimally learn to be optimal\n",
        "- Generalizing across states\n",
        "  - Too many states to visit in training so must generalize experience to new, similar situations\n",
        "  \n",
        " \"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ffafcd05-0611-47f5-93be-a13409cf64c1"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\n- **Reinforcement Learning**\n  - **Exploration**- try unkown actions\n  - **Exploitation**- eventually, use what you know\n  - **Regret**- make mistakes\n  - **Sampling**- because of chance, must try things repeatedly\n- Basic Idea: Receive feedback in form of reward, utility defined by reward function, must act to maximize expected rewards, learning based on observed samples\n- **Model-Based Learning**- learn approximate model based on experiences, solve for values as if learned model was correct\n  1. Learn emprical MDP model\n    - Get estimate of T, discover R from experience\n  2. Solve learned MDP (use value iteration)\n- Offline (MDP)- know what happens when you take action (R)\n- Online (RL)- don't know outcome so must try action to figure out if bad/good\n- **Passive Reinforcement Learning**- no choice about actions, execute and learn from experience\n  - Input: fixed policy pi(s)\n  - Unkowns: Transitons T(s,a,s'), Rewards R(s,a,s')\n  - Goal: learn state values\n  - Exploitation\n- **Direct Evaluation**- \n  - Goal: compute values for each state in pi\n  - Method:\n    - Act according to pi\n    - Every time a state is visited, remember sum of discounted rewards\n    - Avergae these samples\n  - Pros:\n    - Does not require T, R\n    - Computes the correct avergae values\n  - Cons:\n    - Slow\n      - Waste info about state connections\n      - Each state is learned seperatley \n- **Temporal Difference Learning**\n  - Update V(s) each time we perform transition\n    - More likely states updated more often\n  - Exponential moving average- recent samples more important\n  - **Learning Rate** (alpha)- weight of recent samples\n  - Model Free\n- **Active Reinforcement Learning**\n  - Unkowns: Transitions, T(s,a,s'), Rewarss R(s,a,s')\n  - Choose actions \n  - Goal: Learn optimal policy/values\n  - Exploration\n  - NOT offline planning\n- **Q-Learning**\n  - Learn Q(s,a) values as you go\n  - Get a sample (s,a,s',r)\n  - Consider old estimate\n  - Incorporate new estimate into running average\n  - Properties\n    - Converges to optimal policy- EVEN if acting suboptimally\n      - This is **off-policy learning**\n  - Cons:\n    - Must explore enough\n    - Eventually makelearning rate small enough (but not decrease too quickly)\n- How to Explore\n  - Random (episolon-greedy)\n    - (small) probability epsilon, act randomly\n    - (large) probability 1-epsilon, act on current policy\n  - Cons:\n    - Eventually explore whole space but continue to be random after learning is done\n      - Solution: lower epsilon over time\n      - Solution: explore functions\n- **Exploration Functions**\n  - Explore areas whose badness not yet know, eventually stop\n- **Regret**- measure of total mistake cost\n  - To minimize regret must optimally learn to be optimal\n- Generalizing across states\n  - Too many states to visit in training so must generalize experience to new, similar situations\n  \n \n\n## Module 9 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" 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",
        "- **Uncertainty**\n",
        "  - **Observed Variables (evidence)**- agent knows certain things about state (ex. sensor readings)\n",
        "  - **Unobserved variables (states)**- agent needs to reason about other aspects (ex. where an object is)\n",
        "  - **Model**- agent knows something about how known variables relate to unkown variables\n",
        "- Probabilities quantify how like a **possible world** is\n",
        "- **Sample space**- possible worlds\n",
        "  - **Mutually exclusive**\n",
        "  - **Exhaustive**\n",
        "  - P(w), probobility with each possible world w\n",
        "- **Random variables**, R- some aspect of the world that is uncertain (ex. is it raining)\n",
        "- **Axioms of Probability**\n",
        "  - Probability of any possible world is between 0 and 1\n",
        "  - Total probability of the set of all possible worlds is 1\n",
        "- **Probability Distribution**- table of probability values\n",
        "- **Joint Distributions**- specifies a real number for each outcome (ex. cold and sunny)\n",
        "- **Probabilistic Model**- a joint distribution over a set of random variables\n",
        "  - (Random) variables with domains\n",
        "  - Assignment are call **outcomes**\n",
        "  - Joint distributions tell likelihood of outcome\n",
        "  - **Normalized**- sum to 1.0\n",
        "  - Ideally only certain variables interact\n",
        "- **Event**- set of outcomes, can calculate probability of event using joint distribution\n",
        "- **Marginal Distributions**- sub-tables that eliminate variables by summing together (**marginalization**)\n",
        "- **Condiitonal Probabilities**:\n",
        "  P(a|b) = P(a,b)/P(b)\n",
        "  - Probability of a given b = Prob of a and b / Prob of b\n",
        "- **Conditional Distributions**- probability distribution over some variables guven fixed values of the other\n",
        "- **Probabilistice Inference**- compute a desired probability from other know probabilities\n",
        "- **Inference by Enumeration**\n",
        "  1. Select entries consistent with evidence\n",
        "  2. Sum out H to get joint of Query and evidence\n",
        "  3. Normalize\n",
        "- **Product Rule**\n",
        "  - P(x,y) = P(y)*P(x|y)\n",
        "  - Probability of x and y = probability of y * probability of x given y\n",
        "- **Chain Rule**\n",
        "  P(x1, x2, x3) = P(x1)P(x2|x1)P(x3|x1,x2)\n",
        "- **Bayes' Rule**\n",
        "  P(x,y) = P(x|y)P(y) = P(y|x)P(x)\n",
        "  P(x,y) = P(y|x) * P(x) / P(y)\n",
        "  - Useful b/c build one conditional from another\n",
        "- **Probabilistic Language Models**\n",
        "  - Goal: assign a probability to a sentence or sequence of words\n",
        "  - **Language Model**(LM) P(W)\n",
        "- Use chain rule\n",
        "  - **Maximum likelihood estimation** (MLE)- count the amount of times something appears and dividing\n",
        "    - Con: Need huge data set and possible sentence is not in it (data constraint)\n",
        "  - Simplifying assumption- Markov Assumption\n",
        "    - Only depends on previous k words, not entire context\n",
        "      - Unigram- no history\n",
        "      - Bigram- 1 word history (p(w_i | w_i-1) = count(w_i-1*w_i)/count(w_i-1))\n",
        "      - trigram- 2 word history\n",
        "      - 4-gram- 3 word history\n",
        "- Problems for MLE:\n",
        "  - Out of vocabulary item(OOV)\n",
        "  - Fixed lexicon L of size V\n",
        "  - Normalize training data by replacing any word not in L with <unk>\n",
        "  - Avoid zeros with smoothing\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "08311253-43a9-41f8-e919-f87e6c56482a"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n 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 \n- **Uncertainty**\n  - **Observed Variables (evidence)**- agent knows certain things about state (ex. sensor readings)\n  - **Unobserved variables (states)**- agent needs to reason about other aspects (ex. where an object is)\n  - **Model**- agent knows something about how known variables relate to unkown variables\n- Probabilities quantify how like a **possible world** is\n- **Sample space**- possible worlds\n  - **Mutually exclusive**\n  - **Exhaustive**\n  - P(w), probobility with each possible world w\n- **Random variables**, R- some aspect of the world that is uncertain (ex. is it raining)\n- **Axioms of Probability**\n  - Probability of any possible world is between 0 and 1\n  - Total probability of the set of all possible worlds is 1\n- **Probability Distribution**- table of probability values\n- **Joint Distributions**- specifies a real number for each outcome (ex. cold and sunny)\n- **Probabilistic Model**- a joint distribution over a set of random variables\n  - (Random) variables with domains\n  - Assignment are call **outcomes**\n  - Joint distributions tell likelihood of outcome\n  - **Normalized**- sum to 1.0\n  - Ideally only certain variables interact\n- **Event**- set of outcomes, can calculate probability of event using joint distribution\n- **Marginal Distributions**- sub-tables that eliminate variables by summing together (**marginalization**)\n- **Condiitonal Probabilities**:\n  P(a|b) = P(a,b)/P(b)\n  - Probability of a given b = Prob of a and b / Prob of b\n- **Conditional Distributions**- probability distribution over some variables guven fixed values of the other\n- **Probabilistice Inference**- compute a desired probability from other know probabilities\n- **Inference by Enumeration**\n  1. Select entries consistent with evidence\n  2. Sum out H to get joint of Query and evidence\n  3. Normalize\n- **Product Rule**\n  - P(x,y) = P(y)*P(x|y)\n  - Probability of x and y = probability of y * probability of x given y\n- **Chain Rule**\n  P(x1, x2, x3) = P(x1)P(x2|x1)P(x3|x1,x2)\n- **Bayes' Rule**\n  P(x,y) = P(x|y)P(y) = P(y|x)P(x)\n  P(x,y) = P(y|x) * P(x) / P(y)\n  - Useful b/c build one conditional from another\n- **Probabilistic Language Models**\n  - Goal: assign a probability to a sentence or sequence of words\n  - **Language Model**(LM) P(W)\n- Use chain rule\n  - **Maximum likelihood estimation** (MLE)- count the amount of times something appears and dividing\n    - Con: Need huge data set and possible sentence is not in it (data constraint)\n  - Simplifying assumption- Markov Assumption\n    - Only depends on previous k words, not entire context\n      - Unigram- no history\n      - Bigram- 1 word history (p(w_i | w_i-1) = count(w_i-1*w_i)/count(w_i-1))\n      - trigram- 2 word history\n      - 4-gram- 3 word history\n- Problems for MLE:\n  - Out of vocabulary item(OOV)\n  - Fixed lexicon L of size V\n  - Normalize training data by replacing any word not in L with <unk>\n  - Avoid zeros with smoothing\n\n\n\n\n## Module 10 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-zYA-Q-Wafte"
      },
      "source": [
        ""
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\"\n",
        "- **Probabilistic Models**\n",
        "  - Models describe how (a portion of) the world works\n",
        "- **Conditional Independence**- property of a distribution\n",
        "  - if and only if: P(x,y|z) = P(x|z)P(y|z)\n",
        "  - or: P(x|z,y) = P(x|z)\n",
        "  Ex) Trivial Decomposition: P(traffic, rain, umbrella) = P(rain)P(Traffic|Rain)P(umbrella|rain,traffic)\n",
        "      Assuming conditional indpendence: P(traffic, rain, umbrella) = P(rain)P(traffic|rain)P(umbrella|rain)\n",
        "- **Bayes Nets**- technique for describing complex joint distribution models using simple, local distribution (condtional probabilities)\n",
        "  - aka **Graphical Models**\n",
        "  - Describe how variables locally interact\n",
        "  - Local interactions chain together to give global, indirect interaction\n",
        "- **Graphical Model Notation**\n",
        "  - Nodes: variables (with domains)\n",
        "    - **observed**- assigned\n",
        "    - **Unobserved**- unassigned\n",
        "  - Arcs: interactions\n",
        "    - indicate **direct influence** between variables\n",
        "    - Encode conditional independence\n",
        "- Bayes' Net Semantics\n",
        "  - A set of nodes, one per variable X\n",
        "  - A directed, acyclic graph\n",
        "  - Conditional distribution for each node\n",
        "    - CPT: conditional probability table\n",
        "  - Bayes Net = Topology (graph) + Local Conditional Probabilities\n",
        "- Probabilities in BN's\n",
        "  - BNs implicitly encode joint distributions\n",
        "- Size of Bayes' Net\n",
        "  - Joint distribution over N boolean variables: 2^N\n",
        "  - N-node net if nodes have up to k parents: O(N * 2^(k+1))\n",
        "  - Both bbig space sacers\n",
        "  - Easier to elecit local CPTs \n",
        "  - Faster to answer queries\n",
        "- Bayes Nets Assumptions\n",
        "  - P(x_i | x_1...x_i-1) = P(x_i|parents(X_i))\n",
        "- **D-separation: Outline**\n",
        "- **Causal Chains**\n",
        "  - X: Low pressure --> Y: Rain --> Z: Traffic\n",
        "  - P(x,y,z) + P(x)P(y|x)P(z|y)\n",
        "  - Guarenteed X independent of Z? NO\n",
        "  - Guarenteed X independednt of Z given Y? YES\n",
        "    - Evidence along the chain \"blocks\" the influence\n",
        "- How to check if 2 vars are independent in BN:\n",
        "  - Analyze Graph (look at truples)\n",
        "    - If no active paths between X and Y --> independent\n",
        "  - Active path- each triple is active\n",
        "    - Causal chain A -> B -> C (B is unobserved)\n",
        "    - Common cause A <- B -> C (B is unobserved)\n",
        "    - Common effect (aka v-structure) A -> B <- C (B or one of its descendants is oberves)\n",
        "    - Single inactive segment blocks path\n",
        "- **D-Seperation**\n",
        "  - If all paths are inactive then independence is guarenteed\n",
        "  - To be active, all paths must be active\n",
        "- **Structure Implications**\n",
        "  - Given a BN structure, can run d-seperation algorithm to build a complete list of coditional independences that are necessarily true of the form\n",
        "  - This ist determines the set of probability distribution that can be represented\n",
        "- BN Summary:\n",
        "  - Compactly encodes joint distributions\n",
        "  - Can deduce guarenteed independencies of distributions from graph structure\n",
        "  - D-seperation gives precise condition independence guarentees from graph alone\n",
        "  - a BN join distribution may have faurther (conditional) independence that isnot detectable until you inspect is specific distribution\n",
        "- **Inference**- caluclation some useful quantity from a join probability distribution\n",
        "- **Inference by Enumeration** \n",
        "  - Evidence variables: E_1...E_k = e_1...e_k\n",
        "  - Query* variable: Q\n",
        "  - Hidden variables: H_1...H_r\n",
        "  - We want: P(Q|e_1...e_k)\n",
        "  1. Select the entries consistent with evidence\n",
        "  2. Sum out H to get joint of Query and evidence\n",
        "  3. Normalize\n",
        "\n",
        "  - In BN:\n",
        "    - Given unlimited time, inference is easy\n",
        "- Inference by Enumeration vs Variable Elimination\n",
        "  - Why enumeration slow? You join up the whole joint distribution before you sum out the hidden variables\n",
        "  - Variable Elimination\n",
        "    - Interleave joining and marginalizing\n",
        "    - Still NP_hard, but usually much faster than inference by enumeration\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "09e49f97-7eb9-4c83-e53a-90c78b94a246"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\n- **Probabilistic Models**\n  - Models describe how (a portion of) the world works\n- **Conditional Independence**- property of a distribution\n  - if and only if: P(x,y|z) = P(x|z)P(y|z)\n  - or: P(x|z,y) = P(x|z)\n  Ex) Trivial Decomposition: P(traffic, rain, umbrella) = P(rain)P(Traffic|Rain)P(umbrella|rain,traffic)\n      Assuming conditional indpendence: P(traffic, rain, umbrella) = P(rain)P(traffic|rain)P(umbrella|rain)\n- **Bayes Nets**- technique for describing complex joint distribution models using simple, local distribution (condtional probabilities)\n  - aka **Graphical Models**\n  - Describe how variables locally interact\n  - Local interactions chain together to give global, indirect interaction\n- **Graphical Model Notation**\n  - Nodes: variables (with domains)\n    - **observed**- assigned\n    - **Unobserved**- unassigned\n  - Arcs: interactions\n    - indicate **direct influence** between variables\n    - Encode conditional independence\n- Bayes' Net Semantics\n  - A set of nodes, one per variable X\n  - A directed, acyclic graph\n  - Conditional distribution for each node\n    - CPT: conditional probability table\n  - Bayes Net = Topology (graph) + Local Conditional Probabilities\n- Probabilities in BN's\n  - BNs implicitly encode joint distributions\n- Size of Bayes' Net\n  - Joint distribution over N boolean variables: 2^N\n  - N-node net if nodes have up to k parents: O(N * 2^(k+1))\n  - Both bbig space sacers\n  - Easier to elecit local CPTs \n  - Faster to answer queries\n- Bayes Nets Assumptions\n  - P(x_i | x_1...x_i-1) = P(x_i|parents(X_i))\n- **D-separation: Outline**\n- **Causal Chains**\n  - X: Low pressure --> Y: Rain --> Z: Traffic\n  - P(x,y,z) + P(x)P(y|x)P(z|y)\n  - Guarenteed X independent of Z? NO\n  - Guarenteed X independednt of Z given Y? YES\n    - Evidence along the chain \"blocks\" the influence\n- How to check if 2 vars are independent in BN:\n  - Analyze Graph (look at truples)\n    - If no active paths between X and Y --> independent\n  - Active path- each triple is active\n    - Causal chain A -> B -> C (B is unobserved)\n    - Common cause A <- B -> C (B is unobserved)\n    - Common effect (aka v-structure) A -> B <- C (B or one of its descendants is oberves)\n    - Single inactive segment blocks path\n- **D-Seperation**\n  - If all paths are inactive then independence is guarenteed\n  - To be active, all paths must be active\n- **Structure Implications**\n  - Given a BN structure, can run d-seperation algorithm to build a complete list of coditional independences that are necessarily true of the form\n  - This ist determines the set of probability distribution that can be represented\n- BN Summary:\n  - Compactly encodes joint distributions\n  - Can deduce guarenteed independencies of distributions from graph structure\n  - D-seperation gives precise condition independence guarentees from graph alone\n  - a BN join distribution may have faurther (conditional) independence that isnot detectable until you inspect is specific distribution\n- **Inference**- caluclation some useful quantity from a join probability distribution\n- **Inference by Enumeration** \n  - Evidence variables: E_1...E_k = e_1...e_k\n  - Query* variable: Q\n  - Hidden variables: H_1...H_r\n  - We want: P(Q|e_1...e_k)\n  1. Select the entries consistent with evidence\n  2. Sum out H to get joint of Query and evidence\n  3. Normalize\n\n  - In BN:\n    - Given unlimited time, inference is easy\n- Inference by Enumeration vs Variable Elimination\n  - Why enumeration slow? You join up the whole joint distribution before you sum out the hidden variables\n  - Variable Elimination\n    - Interleave joining and marginalizing\n    - Still NP_hard, but usually much faster than inference by enumeration\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 = \"\"\"\n",
        "- **Machine Learning**- acquire a model from data/experience\n",
        "  - **Learning parameters** (ex. probabilities)\n",
        "  - **Learning structure** (ex. BN graphs)\n",
        "  - **Learning hidden concepts** (ex. clustering)\n",
        "- **Classification**- given inputs x, predict labels y\n",
        "  - Examples:\n",
        "    - Spam detection (input: document, output: spam)\n",
        "    - Automatic essay grading (input: document, output: grade)\n",
        "- **Model-Based Classification**\n",
        "  - Build a model (ex. Bayes' net) where both label and features are random variables\n",
        "  - Instantiate any observed features\n",
        "  - Query for th distribution of the label conditioned on the features\n",
        "  - Challenges: Structure of BN? How to learn paremeters?\n",
        "- **Naive Bayes**- assume all features are independent effects of the label\n",
        "  - Only need to specify how each featur depends on the class\n",
        "  - n x |F| x |Y| \n",
        "    - Linear number of features\n",
        "  - Cons: Model is simplistic\n",
        "- **Inference for Naive Bayes**\n",
        "  - Goal: compute posterior distribution over label variable Y\n",
        "    1. get joint probability of label and evidence for each label\n",
        "    2. Sum to get probability of evidence\n",
        "    3. Normalize by dividing Step 1 by Step 2\n",
        "- Needed for Naive Bayes\n",
        "  - Inference method\n",
        "    - start with a bunch of probabilities: P(Y) and the P(F_1 | Y) tables\n",
        "    - Use standard inference to compute P(Y|F_1...F_n)\n",
        "  - Estimates of local condition probability tabels\n",
        "    - **Parameters** (theta): P(Y) and P(F_i | Y) \n",
        "- Data- labeled instance\n",
        "  - Training set- examples with labels\n",
        "  - Held out set- if there are hyper parameters, optomize using this\n",
        "  - Test set- examples no labels\n",
        "- Features- attribute-value pairs which characterise eachx\n",
        "- Experimentation cycle:\n",
        "  - Learn paramters (ex. model probabilites) using training set\n",
        "  - Tune hyperparameters on held out set\n",
        "  - Compute accuracy using test set\n",
        "  - Never \"peek\" at test set- no overlaps between training and test data\n",
        "- Evaluation\n",
        "  - accuracy- fraction of instance predicted correctly\n",
        "- **Overfitting**- too closely model training data and don't generalize\n",
        "  - Can't give unseen events zero probability\n",
        "  - In order to generalize must **smooth** or **regularize** estimates\n",
        "- **Relative probabilites**- odds ratios \n",
        "  - ex. P(W|spam)/P(W|ham)\n",
        "- **Parameter Estimation**\n",
        "  - **Elicitation**- ask a human (expert)\n",
        "  - **Empirically**- use training data (learning)\n",
        "  P_ML(x) = count(x)/total samples\n",
        "    - Maximize the likelihood of data\n",
        "- **Maximum Likelihood**\n",
        "  - probem- unseen events (give likelihood of 0)\n",
        "- **Laplace smoothing**- pretend you saw every outcome once more than you actually did\n",
        "  - can change laplace strength, k\n",
        "  - Performs poorly for P(X|Y) when:\n",
        "    - |X| is very large\n",
        "    - |Y| is very large\n",
        "- **Interpolation**\n",
        "  - P_lin(x|y) = allpha*P(x|y) = (1.0 - alpha)*P(x)\n",
        "    - alpha is hyperparameter\n",
        "- Must tune hyperparameters on different data set because otherwise they will not help generalize\n",
        "- What to about errors\n",
        "  - Add more features\n",
        "    - ex. For spam emails maybe words aren't enough- have you emailed the sender? Is it in all caps?\n",
        "- **Baseline**- help determine how good task is\n",
        "  - Ex. assume all emails are not spam- get 66% accuracy. Classifier that gets 70% correct isn't that good then.\n",
        "  - For research, compare to previous work\n",
        "Summary:\n",
        "  - Bayes rule lets us do diagnostic quieries with causal probabilities\n",
        "  - We build classifiers out of a naive Bayes model using training data\n",
        "- **Perceptron**- learns through error driven learning\n",
        "  - Inputs, multiplied by a weight and summed, if past a threshold take action\n",
        "  - ex. weather good? have a friend with you? Festival near you? Take bus\n",
        "  - changing weights, changes model\n",
        "- **Bias**- how easy it is very a perceptron to fire\n",
        "  - equal to -1*threshold\n",
        "- Inputs- features (ex. emails- your name, quantity of words)\n",
        "  - **Hyperplane** - orthogonal to weight vector, decision plane\n",
        "    - Bias changes hyperplane\n",
        "- Learn weights through **error driven learning**\n",
        "  1. Start with weights = 0\n",
        "  2. Classify with current weights\n",
        "  3. If correct- no change\n",
        "  4. If wrong- adjust weight\n",
        "- **Multiclass Decision Rule**\n",
        "  - If we have multiple classes\n",
        "    - calculate activation score of each class\n",
        "    - Which every has the highest prediction score, it is in that class\n",
        "  - Learning- if wrong, lower score of wrong asnwer, raise score of right answe\n",
        "- Properties of Perceptrons\n",
        "  - **Separability**- true if some parameters the training set perfectly correct\n",
        "  - **Convergence**- if training is seperable, perceptron will eventually converge\n",
        "  - **Mistake Bound**- mac number of mustakes relating to the margin or degree of separability\n",
        "    - mistakes < k/delta^2 (delat is margin)\n",
        "- Problems with Peceptrons\n",
        "  - If data isn't seperable, weight verctors will constantly change\n",
        "  - Mediocre generalization finds a \"barely\" seperating solution\n",
        "  - **Overtraining**- test/held-out accuracy rises then falls\n",
        "  - Fixing:\n",
        "    - MIRA- Margin Infused Relaxed Algorithm\n",
        "      - Choose an updated size that fixes the current mistake but minimizes change to w\n",
        "      - Bad to make updates too large, cap max possible value\n",
        "- **Support Vector Machines**- find seperator with max margin\n",
        "  - Maximize margin\n",
        "  - Onlysupport vectors matter\n",
        "- Non-linear seperators- mapping to higher dimensions allows data to become linear seperable\n",
        "  - original feature space can always be mapped to some high-dimensional feature space where the training set is seperable\n",
        "- Naive Bays vs Perceptrons/MIRA:\n",
        "  - NB:\n",
        "    - Builds a model using training data\n",
        "    - gives prediction proabbilities\n",
        "    - Strong assumptions about feature independence\n",
        "  - Perceptrons/MIRA:\n",
        "    - makes less assumptions about data\n",
        "    - mistake-driven learning\n",
        "    - Multiple passes through data\n",
        "    - Often more accurate\n",
        "- **activation value**, a\n",
        "  - nueron units apply a non-linear fucntion f to z\n",
        "  - y, output of nueral network so if if activation of a nod is the final output of a netowkr then\n",
        "  y = a = f(z)\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "39709b9d-7b6e-422f-ae94-3bd1a5dfeccd"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\n- **Machine Learning**- acquire a model from data/experience\n  - **Learning parameters** (ex. probabilities)\n  - **Learning structure** (ex. BN graphs)\n  - **Learning hidden concepts** (ex. clustering)\n- **Classification**- given inputs x, predict labels y\n  - Examples:\n    - Spam detection (input: document, output: spam)\n    - Automatic essay grading (input: document, output: grade)\n- **Model-Based Classification**\n  - Build a model (ex. Bayes' net) where both label and features are random variables\n  - Instantiate any observed features\n  - Query for th distribution of the label conditioned on the features\n  - Challenges: Structure of BN? How to learn paremeters?\n- **Naive Bayes**- assume all features are independent effects of the label\n  - Only need to specify how each featur depends on the class\n  - n x |F| x |Y| \n    - Linear number of features\n  - Cons: Model is simplistic\n- **Inference for Naive Bayes**\n  - Goal: compute posterior distribution over label variable Y\n    1. get joint probability of label and evidence for each label\n    2. Sum to get probability of evidence\n    3. Normalize by dividing Step 1 by Step 2\n- Needed for Naive Bayes\n  - Inference method\n    - start with a bunch of probabilities: P(Y) and the P(F_1 | Y) tables\n    - Use standard inference to compute P(Y|F_1...F_n)\n  - Estimates of local condition probability tabels\n    - **Parameters** (theta): P(Y) and P(F_i | Y) \n- Data- labeled instance\n  - Training set- examples with labels\n  - Held out set- if there are hyper parameters, optomize using this\n  - Test set- examples no labels\n- Features- attribute-value pairs which characterise eachx\n- Experimentation cycle:\n  - Learn paramters (ex. model probabilites) using training set\n  - Tune hyperparameters on held out set\n  - Compute accuracy using test set\n  - Never \"peek\" at test set- no overlaps between training and test data\n- Evaluation\n  - accuracy- fraction of instance predicted correctly\n- **Overfitting**- too closely model training data and don't generalize\n  - Can't give unseen events zero probability\n  - In order to generalize must **smooth** or **regularize** estimates\n- **Relative probabilites**- odds ratios \n  - ex. P(W|spam)/P(W|ham)\n- **Parameter Estimation**\n  - **Elicitation**- ask a human (expert)\n  - **Empirically**- use training data (learning)\n  P_ML(x) = count(x)/total samples\n    - Maximize the likelihood of data\n- **Maximum Likelihood**\n  - probem- unseen events (give likelihood of 0)\n- **Laplace smoothing**- pretend you saw every outcome once more than you actually did\n  - can change laplace strength, k\n  - Performs poorly for P(X|Y) when:\n    - |X| is very large\n    - |Y| is very large\n- **Interpolation**\n  - P_lin(x|y) = allpha*P(x|y) = (1.0 - alpha)*P(x)\n    - alpha is hyperparameter\n- Must tune hyperparameters on different data set because otherwise they will not help generalize\n- What to about errors\n  - Add more features\n    - ex. For spam emails maybe words aren't enough- have you emailed the sender? Is it in all caps?\n- **Baseline**- help determine how good task is\n  - Ex. assume all emails are not spam- get 66% accuracy. Classifier that gets 70% correct isn't that good then.\n  - For research, compare to previous work\nSummary:\n  - Bayes rule lets us do diagnostic quieries with causal probabilities\n  - We build classifiers out of a naive Bayes model using training data\n- **Perceptron**- learns through error driven learning\n  - Inputs, multiplied by a weight and summed, if past a threshold take action\n  - ex. weather good? have a friend with you? Festival near you? Take bus\n  - changing weights, changes model\n- **Bias**- how easy it is very a perceptron to fire\n  - equal to -1*threshold\n- Inputs- features (ex. emails- your name, quantity of words)\n  - **Hyperplane** - orthogonal to weight vector, decision plane\n    - Bias changes hyperplane\n- Learn weights through **error driven learning**\n  1. Start with weights = 0\n  2. Classify with current weights\n  3. If correct- no change\n  4. If wrong- adjust weight\n- **Multiclass Decision Rule**\n  - If we have multiple classes\n    - calculate activation score of each class\n    - Which every has the highest prediction score, it is in that class\n  - Learning- if wrong, lower score of wrong asnwer, raise score of right answe\n- Properties of Perceptrons\n  - **Separability**- true if some parameters the training set perfectly correct\n  - **Convergence**- if training is seperable, perceptron will eventually converge\n  - **Mistake Bound**- mac number of mustakes relating to the margin or degree of separability\n    - mistakes < k/delta^2 (delat is margin)\n- Problems with Peceptrons\n  - If data isn't seperable, weight verctors will constantly change\n  - Mediocre generalization finds a \"barely\" seperating solution\n  - **Overtraining**- test/held-out accuracy rises then falls\n  - Fixing:\n    - MIRA- Margin Infused Relaxed Algorithm\n      - Choose an updated size that fixes the current mistake but minimizes change to w\n      - Bad to make updates too large, cap max possible value\n- **Support Vector Machines**- find seperator with max margin\n  - Maximize margin\n  - Onlysupport vectors matter\n- Non-linear seperators- mapping to higher dimensions allows data to become linear seperable\n  - original feature space can always be mapped to some high-dimensional feature space where the training set is seperable\n- Naive Bays vs Perceptrons/MIRA:\n  - NB:\n    - Builds a model using training data\n    - gives prediction proabbilities\n    - Strong assumptions about feature independence\n  - Perceptrons/MIRA:\n    - makes less assumptions about data\n    - mistake-driven learning\n    - Multiple passes through data\n    - Often more accurate\n- **activation value**, a\n  - nueron units apply a non-linear fucntion f to z\n  - y, output of nueral network so if if activation of a nod is the final output of a netowkr then\n  y = a = f(z)\n\n\n## Module 12 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" 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",
        "- **Logistic Regression**\n",
        "- **Classifier Components**- machine learning classifiers require a training corpus of M observations input/output pairs (x,y)\n",
        "  1. **feature representation**- a vectir if features [x1, x2,...,xn]\n",
        "  2. **classification function**- computes estamted class, y, via p(y|x)\n",
        "  3. **objective function**- for learning, involves minimizing error on training examples\n",
        "  4. An algorithm for **optimizing** the objective function\n",
        "- **sentiment classifier**- take in text, decide whether there is positive or negative sentiment\n",
        "- **Sigmoid funciton**- bounds output range from 0-1\n",
        "- **Decision Boundary**- the probability needed to take a certain action\n",
        "- Extract features and associate weight to them\n",
        "- Learning in logistic regression\n",
        "  - **loss function** (objective function)- distance between the system output and the gold output, reward model for being more certain\n",
        "    - **cross-entropy loss**\n",
        "  - An algorithm for optomizing the objective function- use stochastic gradient descent to minimize the loss function\n",
        "- **Loss Function** L(y-hat, y)\n",
        "  - **mean squared error**- hard to optomize\n",
        "  - **Cross Entropy Loss** (negatiev log likelihood loss)- maximize probability of true gold labels\n",
        "- p(y|x) = yhat^y * (1 - yhat)^(1-y)\n",
        "- Finding good parameters\n",
        "  - theta represents all parameters (weight vector, bias term)\n",
        "  - good theta minimizes cross-entropy loss\n",
        "- **Gradient Descent**- method that finds a minimum of a function by figuring out in which direction the functions slop is rising the most steeply, and moving in the opposite direction\n",
        "  - Loss function is **convex**- one minimum \n",
        "  - Guarenteed to find minimum\n",
        "- **Gradient**- the difference between the true y and our estimate for x, multiplied by the corresponding input value x_j\n",
        "- Mini-batch training\n",
        "  - **Stochastic Gradient Descent**- chooses single random example at a time and updates its on that example\n",
        "    - Updates fluctuate\n",
        "  - **Batch training**- computes gradient over entire dataset.\n",
        "    - Gives better estimate of which direction to move the weights but takes a long time to compute\n",
        "  - **Mini-batch training**- train on small batch (512 or 1024 depending on computation resources)\n",
        "    - Loss is accumulated\n",
        "- Regularization\n",
        "  - **Overfitting** - poro generalization and poor performance on unseen test set\n",
        "  - In logistic regression, if feature occurs in only one class it will get hight weight \n",
        "  - **Regularization**- penalizes large weights\n",
        "- **Softmax Function**- generalization of the sigmoid function\n",
        "  - Input: vector z = [z1,z2,...,zn]\n",
        "  - Output: Vector of values normalized in probabilities\n",
        "- **Nueral Networks**\n",
        "  - Building blockis a single computation unit\n",
        "  - Unit takes a set of real valued numbers as input, performs some computation\n",
        "  - Input -> Perceptron -> Output\n",
        "  - aka multi-layer perceptron\n",
        "- Logistiv regression uses a vector of **weights** and a **bias term**\n",
        "- **Sigmoid Nuerons**\n",
        "  - Solve problem of a small change in weights or bias in any single perceptron can cause output to flip from 0 to 1\n",
        "  - Smoothness is crucial- small changes in weight or bias will produce small change in output\n",
        "- **Activation function**- takes in input and decides what to do \n",
        "  - Nueron units apply a non-linear function f to z\n",
        "  - output is **activation value**, a\n",
        "  - output of nueral network is y\n",
        "  - y = a = f(z)\n",
        "  - 3 Non-linear functions\n",
        "    1. sigmoid func\n",
        "    2. tanh func\n",
        "    3. rectified linear unit ReLU\n",
        "- **Feed-Forward Nueral Network**\n",
        "  - **Multilayer**\n",
        "  - Each computation unit is **fully-connected**\n",
        "  - **no cycles**\n",
        "- **Equations for feedforward network**\n",
        "  -  **w**- weight vector\n",
        "  - **b**- the bias scalar\n",
        "  - combine into single weight matrix **W**- more efficeint\n",
        "  1. multiply weight matrix by input vector, x\n",
        "  2. Add the bias vector b\n",
        "  3. Apply activation function g(ex. Sigmoid)\n",
        "  4. Output h\n",
        "  h = sigma(Wx + b)\n",
        "  - Output layer has a weight matrix **U**\n",
        "    - This weight matrix is multiplied by input vector **h** to produce intermediate output, **Z**\n",
        "    - z = Uh\n",
        "  - y = softmax(z)\n",
        "- **Training Nueral Nets**\n",
        "  - Needed:\n",
        "    - **Loss Function**- cross-entropy loss\n",
        "    - **Optomization Algorithm**- gradient descent\n",
        "    - **Way of computing gradient of loss function**- error propagation\n",
        "- **Computation graphs**- represtn process of computing a mathematical expression. Computation is broken down into seperate operations. Each operation is a node in a graph.\n",
        "- **Backward differentiation**\n",
        "  - uses **chain rule**\n",
        "- Summary\n",
        "  - Learn best parameters for the neural net to make its predictions yhat as close to possible as the gold standard labels in our training data y.\n",
        "  - Use:\n",
        "    - Cross-entrop loss function\n",
        "    - Gradient descent for optimization\n",
        "    - Error back propagation to compute the gradient of the loss function\n",
        "  - More parameters allws us to train systems to perform even more sophisticated tasks\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "14e08782-8139-4df9-db10-ff0d69895eb6"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n 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\n- **Logistic Regression**\n- **Classifier Components**- machine learning classifiers require a training corpus of M observations input/output pairs (x,y)\n  1. **feature representation**- a vectir if features [x1, x2,...,xn]\n  2. **classification function**- computes estamted class, y, via p(y|x)\n  3. **objective function**- for learning, involves minimizing error on training examples\n  4. An algorithm for **optimizing** the objective function\n- **sentiment classifier**- take in text, decide whether there is positive or negative sentiment\n- **Sigmoid funciton**- bounds output range from 0-1\n- **Decision Boundary**- the probability needed to take a certain action\n- Extract features and associate weight to them\n- Learning in logistic regression\n  - **loss function** (objective function)- distance between the system output and the gold output, reward model for being more certain\n    - **cross-entropy loss**\n  - An algorithm for optomizing the objective function- use stochastic gradient descent to minimize the loss function\n- **Loss Function** L(y-hat, y)\n  - **mean squared error**- hard to optomize\n  - **Cross Entropy Loss** (negatiev log likelihood loss)- maximize probability of true gold labels\n- p(y|x) = yhat^y * (1 - yhat)^(1-y)\n- Finding good parameters\n  - theta represents all parameters (weight vector, bias term)\n  - good theta minimizes cross-entropy loss\n- **Gradient Descent**- method that finds a minimum of a function by figuring out in which direction the functions slop is rising the most steeply, and moving in the opposite direction\n  - Loss function is **convex**- one minimum \n  - Guarenteed to find minimum\n- **Gradient**- the difference between the true y and our estimate for x, multiplied by the corresponding input value x_j\n- Mini-batch training\n  - **Stochastic Gradient Descent**- chooses single random example at a time and updates its on that example\n    - Updates fluctuate\n  - **Batch training**- computes gradient over entire dataset.\n    - Gives better estimate of which direction to move the weights but takes a long time to compute\n  - **Mini-batch training**- train on small batch (512 or 1024 depending on computation resources)\n    - Loss is accumulated\n- Regularization\n  - **Overfitting** - poro generalization and poor performance on unseen test set\n  - In logistic regression, if feature occurs in only one class it will get hight weight \n  - **Regularization**- penalizes large weights\n- **Softmax Function**- generalization of the sigmoid function\n  - Input: vector z = [z1,z2,...,zn]\n  - Output: Vector of values normalized in probabilities\n- **Nueral Networks**\n  - Building blockis a single computation unit\n  - Unit takes a set of real valued numbers as input, performs some computation\n  - Input -> Perceptron -> Output\n  - aka multi-layer perceptron\n- Logistiv regression uses a vector of **weights** and a **bias term**\n- **Sigmoid Nuerons**\n  - Solve problem of a small change in weights or bias in any single perceptron can cause output to flip from 0 to 1\n  - Smoothness is crucial- small changes in weight or bias will produce small change in output\n- **Activation function**- takes in input and decides what to do \n  - Nueron units apply a non-linear function f to z\n  - output is **activation value**, a\n  - output of nueral network is y\n  - y = a = f(z)\n  - 3 Non-linear functions\n    1. sigmoid func\n    2. tanh func\n    3. rectified linear unit ReLU\n- **Feed-Forward Nueral Network**\n  - **Multilayer**\n  - Each computation unit is **fully-connected**\n  - **no cycles**\n- **Equations for feedforward network**\n  -  **w**- weight vector\n  - **b**- the bias scalar\n  - combine into single weight matrix **W**- more efficeint\n  1. multiply weight matrix by input vector, x\n  2. Add the bias vector b\n  3. Apply activation function g(ex. Sigmoid)\n  4. Output h\n  h = sigma(Wx + b)\n  - Output layer has a weight matrix **U**\n    - This weight matrix is multiplied by input vector **h** to produce intermediate output, **Z**\n    - z = Uh\n  - y = softmax(z)\n- **Training Nueral Nets**\n  - Needed:\n    - **Loss Function**- cross-entropy loss\n    - **Optomization Algorithm**- gradient descent\n    - **Way of computing gradient of loss function**- error propagation\n- **Computation graphs**- represtn process of computing a mathematical expression. Computation is broken down into seperate operations. Each operation is a node in a graph.\n- **Backward differentiation**\n  - uses **chain rule**\n- Summary\n  - Learn best parameters for the neural net to make its predictions yhat as close to possible as the gold standard labels in our training data y.\n  - Use:\n    - Cross-entrop loss function\n    - Gradient descent for optimization\n    - Error back propagation to compute the gradient of the loss function\n  - More parameters allws us to train systems to perform even more sophisticated tasks\n\n\n\n## Module 13 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" \n",
        "- **Nueral Language Models**\n",
        "  - Pros:\n",
        "    - Dont need smoothing\n",
        "    - Can handle much longer histories\n",
        "    - Generalize over contexts of similar words\n",
        "    - Higher predictive accuracy\n",
        "  - Cons:\n",
        "    - Slower to train than traditional n-gram models\n",
        "- Steps:\n",
        "  1. Associate each word in the vocabulary with a vector-representation, thereby creating an otion of similarity between words\n",
        "  2. Express the joint probability function of a word sequence in terms of the word vectors for the words in that sequence\n",
        "  3. Simultaneously learn the word vectors and parameters of the function\n",
        "  - product of conditional probabilities given the previous word using a multi-layer, feed forward nueral network\n",
        "- **Input**- k-gram of words\n",
        "- **Output**- probability distribution over the next word\n",
        "- k context words are treated as a **word window**\n",
        "  - Each word associated with an **embedding** vector:\n",
        "    - Input vector, x, just concatenates v(w) for each of the k words\n",
        "- **corpus**- large collection of texts\n",
        "- Learns to generalize\n",
        "- **Word Meaning**\n",
        "  - In n-grame LM words are just a string of letters\n",
        "  - Want meaning\n",
        "    1. **synonyms**- words that have similar meanings\n",
        "    2. **antonyms**- words that have opposite meanings\n",
        "    3. **connotations**- words that are positive or negative\n",
        "    4. **semantic roles**- buy, sell, and pay are different parts of the same underlying purchasing event\n",
        "    5. Support for **entailment**\n",
        "      ex. dog is entailed by animal\n",
        "      - Pros:\n",
        "        - mathematically well-understodod\n",
        "        - poweful machinery for handling logical operations\n",
        "      - Cons:\n",
        "        - knowledge must come from somehwere else\n",
        "- **word similarity**- cat and dog are not synonyms but they are similar\n",
        "- **vector L2 normalization**- solves problem of words that are said more frequently are going to be closer together\n",
        "- **term-term matric**- cell represents how often a word appears in a certain context window\n",
        "  - **context window**- from corpus, find all word instances and look at all words a certain distance to its left and right\n",
        "  - instead of window words, use more complex contexts such as sub-of-verb, adj-mod\n",
        "    - allow for long distance dependenceis\n",
        "- **TF-IDF**(Term frequency * inverse document frequency)\n",
        "  - Term frequency- how often a word occured in a document\n",
        "  - inverse document frequency- number of documents that it occured in\n",
        "- **Sparse v Dense Vectors**\n",
        "  - co-occurnece matrix (weighted by TF-IDF or mutual info)\n",
        "    - **Long** (length |V| = 50,000+)\n",
        "    - *Sparse**- most elements are zeros\n",
        "  - Lean vectors that are\n",
        "    - **Short** (length 200-1000)\n",
        "    - **Dense**- most elements are non-zero\n",
        "- How to get dennse vector- train classifier\n",
        "  1. Treat the target word and a neighboring context word as positive examples\n",
        "  2. Randomly sample other words in the lexicon to get negatice samples\n",
        "  3. Use logistic regression to train a classifier to distinguish those two cases\n",
        "  4. Use the weights as the embeddings\n",
        "- **word2Vex**\n",
        "  - pros: fast, easy to train\n",
        "- embeddings capture relational meanings\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "8699d80f-01e9-4c6b-b086-79fcf71b2251"
      },
      "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": null,
      "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\n- **Logistic Regression**\n- **Classifier Components**- machine learning classifiers require a training corpus of M observations input/output pairs (x,y)\n  1. **feature representation**- a vectir if features [x1, x2,...,xn]\n  2. **classification function**- computes estamted class, y, via p(y|x)\n  3. **objective function**- for learning, involves minimizing error on training examples\n  4. An algorithm for **optimizing** the objective function\n- **sentiment classifier**- take in text, decide whether there is positive or negative sentiment\n- **Sigmoid funciton**- bounds output range from 0-1\n- **Decision Boundary**- the probability needed to take a certain action\n- Extract features and associate weight to them\n- Learning in logistic regression\n  - **loss function** (objective function)- distance between the system output and the gold output, reward model for being more certain\n    - **cross-entropy loss**\n  - An algorithm for optomizing the objective function- use stochastic gradient descent to minimize the loss function\n- **Loss Function** L(y-hat, y)\n  - **mean squared error**- hard to optomize\n  - **Cross Entropy Loss** (negatiev log likelihood loss)- maximize probability of true gold labels\n- p(y|x) = yhat^y * (1 - yhat)^(1-y)\n- Finding good parameters\n  - theta represents all parameters (weight vector, bias term)\n  - good theta minimizes cross-entropy loss\n- **Gradient Descent**- method that finds a minimum of a function by figuring out in which direction the functions slop is rising the most steeply, and moving in the opposite direction\n  - Loss function is **convex**- one minimum \n  - Guarenteed to find minimum\n- **Gradient**- the difference between the true y and our estimate for x, multiplied by the corresponding input value x_j\n- Mini-batch training\n  - **Stochastic Gradient Descent**- chooses single random example at a time and updates its on that example\n    - Updates fluctuate\n  - **Batch training**- computes gradient over entire dataset.\n    - Gives better estimate of which direction to move the weights but takes a long time to compute\n  - **Mini-batch training**- train on small batch (512 or 1024 depending on computation resources)\n    - Loss is accumulated\n- Regularization\n  - **Overfitting** - poro generalization and poor performance on unseen test set\n  - In logistic regression, if feature occurs in only one class it will get hight weight \n  - **Regularization**- penalizes large weights\n- **Softmax Function**- generalization of the sigmoid function\n  - Input: vector z = [z1,z2,...,zn]\n  - Output: Vector of values normalized in probabilities\n- **Nueral Networks**\n  - Building blockis a single computation unit\n  - Unit takes a set of real valued numbers as input, performs some computation\n  - Input -> Perceptron -> Output\n  - aka multi-layer perceptron\n- Logistiv regression uses a vector of **weights** and a **bias term**\n- **Sigmoid Nuerons**\n  - Solve problem of a small change in weights or bias in any single perceptron can cause output to flip from 0 to 1\n  - Smoothness is crucial- small changes in weight or bias will produce small change in output\n- **Activation function**- takes in input and decides what to do \n  - Nueron units apply a non-linear function f to z\n  - output is **activation value**, a\n  - output of nueral network is y\n  - y = a = f(z)\n  - 3 Non-linear functions\n    1. sigmoid func\n    2. tanh func\n    3. rectified linear unit ReLU\n- **Feed-Forward Nueral Network**\n  - **Multilayer**\n  - Each computation unit is **fully-connected**\n  - **no cycles**\n- **Equations for feedforward network**\n  -  **w**- weight vector\n  - **b**- the bias scalar\n  - combine into single weight matrix **W**- more efficeint\n  1. multiply weight matrix by input vector, x\n  2. Add the bias vector b\n  3. Apply activation function g(ex. Sigmoid)\n  4. Output h\n  h = sigma(Wx + b)\n  - Output layer has a weight matrix **U**\n    - This weight matrix is multiplied by input vector **h** to produce intermediate output, **Z**\n    - z = Uh\n  - y = softmax(z)\n- **Training Nueral Nets**\n  - Needed:\n    - **Loss Function**- cross-entropy loss\n    - **Optomization Algorithm**- gradient descent\n    - **Way of computing gradient of loss function**- error propagation\n- **Computation graphs**- represtn process of computing a mathematical expression. Computation is broken down into seperate operations. Each operation is a node in a graph.\n- **Backward differentiation**\n  - uses **chain rule**\n- Summary\n  - Learn best parameters for the neural net to make its predictions yhat as close to possible as the gold standard labels in our training data y.\n  - Use:\n    - Cross-entrop loss function\n    - Gradient descent for optimization\n    - Error back propagation to compute the gradient of the loss function\n  - More parameters allws us to train systems to perform even more sophisticated tasks\n\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "c887030d-d494-4bc5-d796-dba47da7d556"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module8_markdown, \n",
        "                             module9_markdown, \n",
        "                             module10_markdown, \n",
        "                             module11_markdown, \n",
        "                             module12_markdown,\n",
        "                             module13_markdown,\n",
        "                             module14_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n 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\n- MDP is for **non-deterministic** (unkown outcome) problems.\n- **stochastic**- outputs have probability, non-deterministic with probabilities\n- Stochastic Transition Model: p(s' | s,a), probability of arriving in state s' given that we are in state s and selected action a\n  - **Markovian** b/c we are ignoring previous states\n- **utility/reward function**- gives reward with each step taken\n  - can be positive or negative\n  - process is **sequential** so takes into account past actions\n  - R(s, a, s') \n- **Markov Decision Process**(MDP):\n  - a **sequential** decision problem\n  - for **fully observable** environments\n  - with a **stochastic** transition model\n  - has **additive rewards**\n  - **non-deterministic search problem** (expictimax can solve them)\n  - Must have:\n    - **A set of states**\n    - **A set of actions**\n    - **Transition Function** T(s, a, s')\n    - **Reward Function** R(s, a, s')\n    - **initial state** s_0\n    - **Terminal States**- optional, can be one or more\n- Solution == Policy\n  - maps state to action if agent is an that state\n  - **Pi**(s) = a, action to take at state s\n  - **Pi*** is optimal policy\n- **Discounting**\n  - max sum of rewards\n  - prefer rewards no \n  - values of rewards decay exponentially\n- Solutions to Infinite Utilities (bouncing around to constantly collect reward)\n  - Finite Horizon- terminate after fixed T steps, gives nonstationar policy (pi depends on time left)\n  - Discounting- 0< gamma<1, smaller gamma --> smaller horzizon\n- Using expectimax causes repeat states\n- **Value Iteration**: \n  - Complexity: O(S^2 * A)- slow\n  - Guarenteed to converge on unique optimal values\n- **Policy Evaluation**\n  - Use recursive Bellman equations \n    - Efficiency: O(s^2) per iteration\n  - Without maxes, Bellman eq's are linear (solve with Matlab)\n  - Pi*(s) = maxQ*(s,a)\n    - Actions are easier to select from q-values than values\n  - Need T and R\n- **Policy Iteration**\n  1. (Policy Evaluation)For fixed current policy pi, find values with policy evaluaition\n  2. (Policy Improvement) For fixed values, get a better policy using policy extraction\nSummary:\n- Compute optimal values: use value or policy iteration\n- Compute values for specific policy: use policy evaluation\n- Turn values into a policy: use policy extraction (one-step lookahead)\n\n- **Maximum Expected Utilities**(MEU):\n  - Utility- map from state to real number that describes agent preferences\n- Rationality\n  - 5 axioms of rationality\n \n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\n- **Reinforcement Learning**\n  - **Exploration**- try unkown actions\n  - **Exploitation**- eventually, use what you know\n  - **Regret**- make mistakes\n  - **Sampling**- because of chance, must try things repeatedly\n- Basic Idea: Receive feedback in form of reward, utility defined by reward function, must act to maximize expected rewards, learning based on observed samples\n- **Model-Based Learning**- learn approximate model based on experiences, solve for values as if learned model was correct\n  1. Learn emprical MDP model\n    - Get estimate of T, discover R from experience\n  2. Solve learned MDP (use value iteration)\n- Offline (MDP)- know what happens when you take action (R)\n- Online (RL)- don't know outcome so must try action to figure out if bad/good\n- **Passive Reinforcement Learning**- no choice about actions, execute and learn from experience\n  - Input: fixed policy pi(s)\n  - Unkowns: Transitons T(s,a,s'), Rewards R(s,a,s')\n  - Goal: learn state values\n  - Exploitation\n- **Direct Evaluation**- \n  - Goal: compute values for each state in pi\n  - Method:\n    - Act according to pi\n    - Every time a state is visited, remember sum of discounted rewards\n    - Avergae these samples\n  - Pros:\n    - Does not require T, R\n    - Computes the correct avergae values\n  - Cons:\n    - Slow\n      - Waste info about state connections\n      - Each state is learned seperatley \n- **Temporal Difference Learning**\n  - Update V(s) each time we perform transition\n    - More likely states updated more often\n  - Exponential moving average- recent samples more important\n  - **Learning Rate** (alpha)- weight of recent samples\n  - Model Free\n- **Active Reinforcement Learning**\n  - Unkowns: Transitions, T(s,a,s'), Rewarss R(s,a,s')\n  - Choose actions \n  - Goal: Learn optimal policy/values\n  - Exploration\n  - NOT offline planning\n- **Q-Learning**\n  - Learn Q(s,a) values as you go\n  - Get a sample (s,a,s',r)\n  - Consider old estimate\n  - Incorporate new estimate into running average\n  - Properties\n    - Converges to optimal policy- EVEN if acting suboptimally\n      - This is **off-policy learning**\n  - Cons:\n    - Must explore enough\n    - Eventually makelearning rate small enough (but not decrease too quickly)\n- How to Explore\n  - Random (episolon-greedy)\n    - (small) probability epsilon, act randomly\n    - (large) probability 1-epsilon, act on current policy\n  - Cons:\n    - Eventually explore whole space but continue to be random after learning is done\n      - Solution: lower epsilon over time\n      - Solution: explore functions\n- **Exploration Functions**\n  - Explore areas whose badness not yet know, eventually stop\n- **Regret**- measure of total mistake cost\n  - To minimize regret must optimally learn to be optimal\n- Generalizing across states\n  - Too many states to visit in training so must generalize experience to new, similar situations\n  \n \n\n## Module 9 Definitions\n* **Term** - your definition here\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n 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 \n- **Uncertainty**\n  - **Observed Variables (evidence)**- agent knows certain things about state (ex. sensor readings)\n  - **Unobserved variables (states)**- agent needs to reason about other aspects (ex. where an object is)\n  - **Model**- agent knows something about how known variables relate to unkown variables\n- Probabilities quantify how like a **possible world** is\n- **Sample space**- possible worlds\n  - **Mutually exclusive**\n  - **Exhaustive**\n  - P(w), probobility with each possible world w\n- **Random variables**, R- some aspect of the world that is uncertain (ex. is it raining)\n- **Axioms of Probability**\n  - Probability of any possible world is between 0 and 1\n  - Total probability of the set of all possible worlds is 1\n- **Probability Distribution**- table of probability values\n- **Joint Distributions**- specifies a real number for each outcome (ex. cold and sunny)\n- **Probabilistic Model**- a joint distribution over a set of random variables\n  - (Random) variables with domains\n  - Assignment are call **outcomes**\n  - Joint distributions tell likelihood of outcome\n  - **Normalized**- sum to 1.0\n  - Ideally only certain variables interact\n- **Event**- set of outcomes, can calculate probability of event using joint distribution\n- **Marginal Distributions**- sub-tables that eliminate variables by summing together (**marginalization**)\n- **Condiitonal Probabilities**:\n  P(a|b) = P(a,b)/P(b)\n  - Probability of a given b = Prob of a and b / Prob of b\n- **Conditional Distributions**- probability distribution over some variables guven fixed values of the other\n- **Probabilistice Inference**- compute a desired probability from other know probabilities\n- **Inference by Enumeration**\n  1. Select entries consistent with evidence\n  2. Sum out H to get joint of Query and evidence\n  3. Normalize\n- **Product Rule**\n  - P(x,y) = P(y)*P(x|y)\n  - Probability of x and y = probability of y * probability of x given y\n- **Chain Rule**\n  P(x1, x2, x3) = P(x1)P(x2|x1)P(x3|x1,x2)\n- **Bayes' Rule**\n  P(x,y) = P(x|y)P(y) = P(y|x)P(x)\n  P(x,y) = P(y|x) * P(x) / P(y)\n  - Useful b/c build one conditional from another\n- **Probabilistic Language Models**\n  - Goal: assign a probability to a sentence or sequence of words\n  - **Language Model**(LM) P(W)\n- Use chain rule\n  - **Maximum likelihood estimation** (MLE)- count the amount of times something appears and dividing\n    - Con: Need huge data set and possible sentence is not in it (data constraint)\n  - Simplifying assumption- Markov Assumption\n    - Only depends on previous k words, not entire context\n      - Unigram- no history\n      - Bigram- 1 word history (p(w_i | w_i-1) = count(w_i-1*w_i)/count(w_i-1))\n      - trigram- 2 word history\n      - 4-gram- 3 word history\n- Problems for MLE:\n  - Out of vocabulary item(OOV)\n  - Fixed lexicon L of size V\n  - Normalize training data by replacing any word not in L with <unk>\n  - Avoid zeros with smoothing\n\n\n\n\n## Module 10 Definitions\n* **Term** - your definition here\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\n- **Probabilistic Models**\n  - Models describe how (a portion of) the world works\n- **Conditional Independence**- property of a distribution\n  - if and only if: P(x,y|z) = P(x|z)P(y|z)\n  - or: P(x|z,y) = P(x|z)\n  Ex) Trivial Decomposition: P(traffic, rain, umbrella) = P(rain)P(Traffic|Rain)P(umbrella|rain,traffic)\n      Assuming conditional indpendence: P(traffic, rain, umbrella) = P(rain)P(traffic|rain)P(umbrella|rain)\n- **Bayes Nets**- technique for describing complex joint distribution models using simple, local distribution (condtional probabilities)\n  - aka **Graphical Models**\n  - Describe how variables locally interact\n  - Local interactions chain together to give global, indirect interaction\n- **Graphical Model Notation**\n  - Nodes: variables (with domains)\n    - **observed**- assigned\n    - **Unobserved**- unassigned\n  - Arcs: interactions\n    - indicate **direct influence** between variables\n    - Encode conditional independence\n- Bayes' Net Semantics\n  - A set of nodes, one per variable X\n  - A directed, acyclic graph\n  - Conditional distribution for each node\n    - CPT: conditional probability table\n  - Bayes Net = Topology (graph) + Local Conditional Probabilities\n- Probabilities in BN's\n  - BNs implicitly encode joint distributions\n- Size of Bayes' Net\n  - Joint distribution over N boolean variables: 2^N\n  - N-node net if nodes have up to k parents: O(N * 2^(k+1))\n  - Both bbig space sacers\n  - Easier to elecit local CPTs \n  - Faster to answer queries\n- Bayes Nets Assumptions\n  - P(x_i | x_1...x_i-1) = P(x_i|parents(X_i))\n- **D-separation: Outline**\n- **Causal Chains**\n  - X: Low pressure --> Y: Rain --> Z: Traffic\n  - P(x,y,z) + P(x)P(y|x)P(z|y)\n  - Guarenteed X independent of Z? NO\n  - Guarenteed X independednt of Z given Y? YES\n    - Evidence along the chain \"blocks\" the influence\n- How to check if 2 vars are independent in BN:\n  - Analyze Graph (look at truples)\n    - If no active paths between X and Y --> independent\n  - Active path- each triple is active\n    - Causal chain A -> B -> C (B is unobserved)\n    - Common cause A <- B -> C (B is unobserved)\n    - Common effect (aka v-structure) A -> B <- C (B or one of its descendants is oberves)\n    - Single inactive segment blocks path\n- **D-Seperation**\n  - If all paths are inactive then independence is guarenteed\n  - To be active, all paths must be active\n- **Structure Implications**\n  - Given a BN structure, can run d-seperation algorithm to build a complete list of coditional independences that are necessarily true of the form\n  - This ist determines the set of probability distribution that can be represented\n- BN Summary:\n  - Compactly encodes joint distributions\n  - Can deduce guarenteed independencies of distributions from graph structure\n  - D-seperation gives precise condition independence guarentees from graph alone\n  - a BN join distribution may have faurther (conditional) independence that isnot detectable until you inspect is specific distribution\n- **Inference**- caluclation some useful quantity from a join probability distribution\n- **Inference by Enumeration** \n  - Evidence variables: E_1...E_k = e_1...e_k\n  - Query* variable: Q\n  - Hidden variables: H_1...H_r\n  - We want: P(Q|e_1...e_k)\n  1. Select the entries consistent with evidence\n  2. Sum out H to get joint of Query and evidence\n  3. Normalize\n\n  - In BN:\n    - Given unlimited time, inference is easy\n- Inference by Enumeration vs Variable Elimination\n  - Why enumeration slow? You join up the whole joint distribution before you sum out the hidden variables\n  - Variable Elimination\n    - Interleave joining and marginalizing\n    - Still NP_hard, but usually much faster than inference by enumeration\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\n\n- **Machine Learning**- acquire a model from data/experience\n  - **Learning parameters** (ex. probabilities)\n  - **Learning structure** (ex. BN graphs)\n  - **Learning hidden concepts** (ex. clustering)\n- **Classification**- given inputs x, predict labels y\n  - Examples:\n    - Spam detection (input: document, output: spam)\n    - Automatic essay grading (input: document, output: grade)\n- **Model-Based Classification**\n  - Build a model (ex. Bayes' net) where both label and features are random variables\n  - Instantiate any observed features\n  - Query for th distribution of the label conditioned on the features\n  - Challenges: Structure of BN? How to learn paremeters?\n- **Naive Bayes**- assume all features are independent effects of the label\n  - Only need to specify how each featur depends on the class\n  - n x |F| x |Y| \n    - Linear number of features\n  - Cons: Model is simplistic\n- **Inference for Naive Bayes**\n  - Goal: compute posterior distribution over label variable Y\n    1. get joint probability of label and evidence for each label\n    2. Sum to get probability of evidence\n    3. Normalize by dividing Step 1 by Step 2\n- Needed for Naive Bayes\n  - Inference method\n    - start with a bunch of probabilities: P(Y) and the P(F_1 | Y) tables\n    - Use standard inference to compute P(Y|F_1...F_n)\n  - Estimates of local condition probability tabels\n    - **Parameters** (theta): P(Y) and P(F_i | Y) \n- Data- labeled instance\n  - Training set- examples with labels\n  - Held out set- if there are hyper parameters, optomize using this\n  - Test set- examples no labels\n- Features- attribute-value pairs which characterise eachx\n- Experimentation cycle:\n  - Learn paramters (ex. model probabilites) using training set\n  - Tune hyperparameters on held out set\n  - Compute accuracy using test set\n  - Never \"peek\" at test set- no overlaps between training and test data\n- Evaluation\n  - accuracy- fraction of instance predicted correctly\n- **Overfitting**- too closely model training data and don't generalize\n  - Can't give unseen events zero probability\n  - In order to generalize must **smooth** or **regularize** estimates\n- **Relative probabilites**- odds ratios \n  - ex. P(W|spam)/P(W|ham)\n- **Parameter Estimation**\n  - **Elicitation**- ask a human (expert)\n  - **Empirically**- use training data (learning)\n  P_ML(x) = count(x)/total samples\n    - Maximize the likelihood of data\n- **Maximum Likelihood**\n  - probem- unseen events (give likelihood of 0)\n- **Laplace smoothing**- pretend you saw every outcome once more than you actually did\n  - can change laplace strength, k\n  - Performs poorly for P(X|Y) when:\n    - |X| is very large\n    - |Y| is very large\n- **Interpolation**\n  - P_lin(x|y) = allpha*P(x|y) = (1.0 - alpha)*P(x)\n    - alpha is hyperparameter\n- Must tune hyperparameters on different data set because otherwise they will not help generalize\n- What to about errors\n  - Add more features\n    - ex. For spam emails maybe words aren't enough- have you emailed the sender? Is it in all caps?\n- **Baseline**- help determine how good task is\n  - Ex. assume all emails are not spam- get 66% accuracy. Classifier that gets 70% correct isn't that good then.\n  - For research, compare to previous work\nSummary:\n  - Bayes rule lets us do diagnostic quieries with causal probabilities\n  - We build classifiers out of a naive Bayes model using training data\n- **Perceptron**- learns through error driven learning\n  - Inputs, multiplied by a weight and summed, if past a threshold take action\n  - ex. weather good? have a friend with you? Festival near you? Take bus\n  - changing weights, changes model\n- **Bias**- how easy it is very a perceptron to fire\n  - equal to -1*threshold\n- Inputs- features (ex. emails- your name, quantity of words)\n  - **Hyperplane** - orthogonal to weight vector, decision plane\n    - Bias changes hyperplane\n- Learn weights through **error driven learning**\n  1. Start with weights = 0\n  2. Classify with current weights\n  3. If correct- no change\n  4. If wrong- adjust weight\n- **Multiclass Decision Rule**\n  - If we have multiple classes\n    - calculate activation score of each class\n    - Which every has the highest prediction score, it is in that class\n  - Learning- if wrong, lower score of wrong asnwer, raise score of right answe\n- Properties of Perceptrons\n  - **Separability**- true if some parameters the training set perfectly correct\n  - **Convergence**- if training is seperable, perceptron will eventually converge\n  - **Mistake Bound**- mac number of mustakes relating to the margin or degree of separability\n    - mistakes < k/delta^2 (delat is margin)\n- Problems with Peceptrons\n  - If data isn't seperable, weight verctors will constantly change\n  - Mediocre generalization finds a \"barely\" seperating solution\n  - **Overtraining**- test/held-out accuracy rises then falls\n  - Fixing:\n    - MIRA- Margin Infused Relaxed Algorithm\n      - Choose an updated size that fixes the current mistake but minimizes change to w\n      - Bad to make updates too large, cap max possible value\n- **Support Vector Machines**- find seperator with max margin\n  - Maximize margin\n  - Onlysupport vectors matter\n- Non-linear seperators- mapping to higher dimensions allows data to become linear seperable\n  - original feature space can always be mapped to some high-dimensional feature space where the training set is seperable\n- Naive Bays vs Perceptrons/MIRA:\n  - NB:\n    - Builds a model using training data\n    - gives prediction proabbilities\n    - Strong assumptions about feature independence\n  - Perceptrons/MIRA:\n    - makes less assumptions about data\n    - mistake-driven learning\n    - Multiple passes through data\n    - Often more accurate\n- **activation value**, a\n  - nueron units apply a non-linear fucntion f to z\n  - y, output of nueral network so if if activation of a nod is the final output of a netowkr then\n  y = a = f(z)\n\n\n## Module 12 Definitions\n* **Concept** - definition\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\n- **Logistic Regression**\n- **Classifier Components**- machine learning classifiers require a training corpus of M observations input/output pairs (x,y)\n  1. **feature representation**- a vectir if features [x1, x2,...,xn]\n  2. **classification function**- computes estamted class, y, via p(y|x)\n  3. **objective function**- for learning, involves minimizing error on training examples\n  4. An algorithm for **optimizing** the objective function\n- **sentiment classifier**- take in text, decide whether there is positive or negative sentiment\n- **Sigmoid funciton**- bounds output range from 0-1\n- **Decision Boundary**- the probability needed to take a certain action\n- Extract features and associate weight to them\n- Learning in logistic regression\n  - **loss function** (objective function)- distance between the system output and the gold output, reward model for being more certain\n    - **cross-entropy loss**\n  - An algorithm for optomizing the objective function- use stochastic gradient descent to minimize the loss function\n- **Loss Function** L(y-hat, y)\n  - **mean squared error**- hard to optomize\n  - **Cross Entropy Loss** (negatiev log likelihood loss)- maximize probability of true gold labels\n- p(y|x) = yhat^y * (1 - yhat)^(1-y)\n- Finding good parameters\n  - theta represents all parameters (weight vector, bias term)\n  - good theta minimizes cross-entropy loss\n- **Gradient Descent**- method that finds a minimum of a function by figuring out in which direction the functions slop is rising the most steeply, and moving in the opposite direction\n  - Loss function is **convex**- one minimum \n  - Guarenteed to find minimum\n- **Gradient**- the difference between the true y and our estimate for x, multiplied by the corresponding input value x_j\n- Mini-batch training\n  - **Stochastic Gradient Descent**- chooses single random example at a time and updates its on that example\n    - Updates fluctuate\n  - **Batch training**- computes gradient over entire dataset.\n    - Gives better estimate of which direction to move the weights but takes a long time to compute\n  - **Mini-batch training**- train on small batch (512 or 1024 depending on computation resources)\n    - Loss is accumulated\n- Regularization\n  - **Overfitting** - poro generalization and poor performance on unseen test set\n  - In logistic regression, if feature occurs in only one class it will get hight weight \n  - **Regularization**- penalizes large weights\n- **Softmax Function**- generalization of the sigmoid function\n  - Input: vector z = [z1,z2,...,zn]\n  - Output: Vector of values normalized in probabilities\n- **Nueral Networks**\n  - Building blockis a single computation unit\n  - Unit takes a set of real valued numbers as input, performs some computation\n  - Input -> Perceptron -> Output\n  - aka multi-layer perceptron\n- Logistiv regression uses a vector of **weights** and a **bias term**\n- **Sigmoid Nuerons**\n  - Solve problem of a small change in weights or bias in any single perceptron can cause output to flip from 0 to 1\n  - Smoothness is crucial- small changes in weight or bias will produce small change in output\n- **Activation function**- takes in input and decides what to do \n  - Nueron units apply a non-linear function f to z\n  - output is **activation value**, a\n  - output of nueral network is y\n  - y = a = f(z)\n  - 3 Non-linear functions\n    1. sigmoid func\n    2. tanh func\n    3. rectified linear unit ReLU\n- **Feed-Forward Nueral Network**\n  - **Multilayer**\n  - Each computation unit is **fully-connected**\n  - **no cycles**\n- **Equations for feedforward network**\n  -  **w**- weight vector\n  - **b**- the bias scalar\n  - combine into single weight matrix **W**- more efficeint\n  1. multiply weight matrix by input vector, x\n  2. Add the bias vector b\n  3. Apply activation function g(ex. Sigmoid)\n  4. Output h\n  h = sigma(Wx + b)\n  - Output layer has a weight matrix **U**\n    - This weight matrix is multiplied by input vector **h** to produce intermediate output, **Z**\n    - z = Uh\n  - y = softmax(z)\n- **Training Nueral Nets**\n  - Needed:\n    - **Loss Function**- cross-entropy loss\n    - **Optomization Algorithm**- gradient descent\n    - **Way of computing gradient of loss function**- error propagation\n- **Computation graphs**- represtn process of computing a mathematical expression. Computation is broken down into seperate operations. Each operation is a node in a graph.\n- **Backward differentiation**\n  - uses **chain rule**\n- Summary\n  - Learn best parameters for the neural net to make its predictions yhat as close to possible as the gold standard labels in our training data y.\n  - Use:\n    - Cross-entrop loss function\n    - Gradient descent for optimization\n    - Error back propagation to compute the gradient of the loss function\n  - More parameters allws us to train systems to perform even more sophisticated tasks\n\n\n\n## Module 13 Definitions\n* **Concept** - definition\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n\n- **Logistic Regression**\n- **Classifier Components**- machine learning classifiers require a training corpus of M observations input/output pairs (x,y)\n  1. **feature representation**- a vectir if features [x1, x2,...,xn]\n  2. **classification function**- computes estamted class, y, via p(y|x)\n  3. **objective function**- for learning, involves minimizing error on training examples\n  4. An algorithm for **optimizing** the objective function\n- **sentiment classifier**- take in text, decide whether there is positive or negative sentiment\n- **Sigmoid funciton**- bounds output range from 0-1\n- **Decision Boundary**- the probability needed to take a certain action\n- Extract features and associate weight to them\n- Learning in logistic regression\n  - **loss function** (objective function)- distance between the system output and the gold output, reward model for being more certain\n    - **cross-entropy loss**\n  - An algorithm for optomizing the objective function- use stochastic gradient descent to minimize the loss function\n- **Loss Function** L(y-hat, y)\n  - **mean squared error**- hard to optomize\n  - **Cross Entropy Loss** (negatiev log likelihood loss)- maximize probability of true gold labels\n- p(y|x) = yhat^y * (1 - yhat)^(1-y)\n- Finding good parameters\n  - theta represents all parameters (weight vector, bias term)\n  - good theta minimizes cross-entropy loss\n- **Gradient Descent**- method that finds a minimum of a function by figuring out in which direction the functions slop is rising the most steeply, and moving in the opposite direction\n  - Loss function is **convex**- one minimum \n  - Guarenteed to find minimum\n- **Gradient**- the difference between the true y and our estimate for x, multiplied by the corresponding input value x_j\n- Mini-batch training\n  - **Stochastic Gradient Descent**- chooses single random example at a time and updates its on that example\n    - Updates fluctuate\n  - **Batch training**- computes gradient over entire dataset.\n    - Gives better estimate of which direction to move the weights but takes a long time to compute\n  - **Mini-batch training**- train on small batch (512 or 1024 depending on computation resources)\n    - Loss is accumulated\n- Regularization\n  - **Overfitting** - poro generalization and poor performance on unseen test set\n  - In logistic regression, if feature occurs in only one class it will get hight weight \n  - **Regularization**- penalizes large weights\n- **Softmax Function**- generalization of the sigmoid function\n  - Input: vector z = [z1,z2,...,zn]\n  - Output: Vector of values normalized in probabilities\n- **Nueral Networks**\n  - Building blockis a single computation unit\n  - Unit takes a set of real valued numbers as input, performs some computation\n  - Input -> Perceptron -> Output\n  - aka multi-layer perceptron\n- Logistiv regression uses a vector of **weights** and a **bias term**\n- **Sigmoid Nuerons**\n  - Solve problem of a small change in weights or bias in any single perceptron can cause output to flip from 0 to 1\n  - Smoothness is crucial- small changes in weight or bias will produce small change in output\n- **Activation function**- takes in input and decides what to do \n  - Nueron units apply a non-linear function f to z\n  - output is **activation value**, a\n  - output of nueral network is y\n  - y = a = f(z)\n  - 3 Non-linear functions\n    1. sigmoid func\n    2. tanh func\n    3. rectified linear unit ReLU\n- **Feed-Forward Nueral Network**\n  - **Multilayer**\n  - Each computation unit is **fully-connected**\n  - **no cycles**\n- **Equations for feedforward network**\n  -  **w**- weight vector\n  - **b**- the bias scalar\n  - combine into single weight matrix **W**- more efficeint\n  1. multiply weight matrix by input vector, x\n  2. Add the bias vector b\n  3. Apply activation function g(ex. Sigmoid)\n  4. Output h\n  h = sigma(Wx + b)\n  - Output layer has a weight matrix **U**\n    - This weight matrix is multiplied by input vector **h** to produce intermediate output, **Z**\n    - z = Uh\n  - y = softmax(z)\n- **Training Nueral Nets**\n  - Needed:\n    - **Loss Function**- cross-entropy loss\n    - **Optomization Algorithm**- gradient descent\n    - **Way of computing gradient of loss function**- error propagation\n- **Computation graphs**- represtn process of computing a mathematical expression. Computation is broken down into seperate operations. Each operation is a node in a graph.\n- **Backward differentiation**\n  - uses **chain rule**\n- Summary\n  - Learn best parameters for the neural net to make its predictions yhat as close to possible as the gold standard labels in our training data y.\n  - Use:\n    - Cross-entrop loss function\n    - Gradient descent for optimization\n    - Error back propagation to compute the gradient of the loss function\n  - More parameters allws us to train systems to perform even more sophisticated tasks\n\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}