{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of Template_for CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f764f04c-dcf4-4f16-a1d7-92d51bfc1c9f"
      },
      "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": 2,
      "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": "fcf3475e-f0eb-442b-e1d2-63f9db151ba3"
      },
      "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": 3,
      "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": 4,
      "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",
        "Reward Function \"\"\" + r\"\"\"$R(s,a,s')$\"\"\" + \"\"\" defined for each state, action, state pair not just goal \n",
        "\n",
        "<b>Markov Decision Process (MDP)</b> - sequential, fully observable, stochastic, additive rewards\n",
        "  * also non-deterministic, can be solved with Expectimax\n",
        "\n",
        "To solve MDP, need:\n",
        "  * <b>set of states</b> \"\"\" + r\"\"\"$s \\in S$\"\"\" + \"\"\"\n",
        "  * <b>set of actions</b> \"\"\" + r\"\"\"$a \\in A$\"\"\" + \"\"\"\n",
        "  * <b>Transition Function</b> \"\"\" + r\"\"\"$T(s, a, s')$\"\"\" + \"\"\"\n",
        "  * <b>Reward Function</b> \"\"\" + r\"\"\"$R(s,a,s')$\"\"\" + \"\"\"\n",
        "  * <b>initial state</b> \"\"\" + r\"\"\"$s_{0}$\"\"\" + \"\"\"\n",
        "  * <b>1+ terminal states</b>\n",
        "\n",
        "<b>Solution = Policy</b>, given state s, outputs action to take, a\n",
        "\n",
        "<b>Sample-based Policy Evaluation</b> averages all sample values, doesn't work because of non-determinism\n",
        "\n",
        "\"\"\" + r\"\"\"$V^{*}(s)=max_a(Q^{*}(s,a))$\"\"\" + \"\"\"\n",
        "\"\"\" + r\"\"\"$Q^{*}(s,a)=\\sum_{s'}T(s, a, s')[R(s, a, s')+\\gamma V^{*}(s')]$\"\"\" + \"\"\"\n",
        "\"\"\" + r\"\"\"$V^{*}(s)=max_a(\\sum_{s'}T(s, a, s')[R(s, a, s')+\\gamma V^{*}(s')])$\"\"\" + \"\"\"\n",
        "\n",
        "Convergence:\n",
        "* Case 1: tree has max depth\n",
        "* Case 2: if the discount is less than 1\n",
        "\n",
        "Problems w/ Value Iteration:\n",
        "* It's slow, O(S^{2}A)\n",
        "* the max at each state rarely changes\n",
        "* the policy converges long before values\n",
        "\n",
        "<b>Policy Iteration:</b>\n",
        "1. Policy Evaluation: calculate utilities for non-optimal policy\n",
        "2. Policy Improvement: update policy using 1-step lookahead\n",
        "- Repeat until policy converges\n",
        "- still optimal\n",
        "- O(S^3), slow but usually converges faster then Value Iteration\n",
        "\n",
        "Rational Preferences:\n",
        "* <b>Orderability</b> - either you prefer A to B, or you're indifferent\n",
        "* <b>Transitivity</b> - \n",
        "* <b>Continuity</b> - I prefer a to C so there exists some lottery of not C (1-C) such that I'm indifferent to both\n",
        "* <b>Substitutability</b> - if I'm indifferent from A to B, then for some p between A, C I must be indifferent to p, B, C\n",
        "\n",
        "----\n",
        "For an MDP:\n",
        "* defined for a fully observable, stochastic environment\n",
        "* policy must define what it should do for all reachable states\n",
        "* proper policy does not always exist\n",
        "* does not always have to have reward function w/ discounted rewards\n",
        "\n",
        "Policy Iteration Considers:\n",
        "* probability of entering s' given s and action a\n",
        "* NOT the max reward obtained from state s\n",
        "* utility associated with s\n",
        "* all of the actions an agent can take from state s\n",
        "\n",
        "The policy is implicitly (not explicitly) udated in value iteration\n",
        "\n",
        "Policy iteratioin often converges faster than Value iteration, but is more costly\n",
        "\n",
        "The utility function must be completely accurate in order to acheive an optimal policy\n",
        "\n",
        "Principle of MEU - agent should maximize the weighted avg. of their utilities\n",
        "\n",
        "\"\"\" \n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"Markovian\": r\"\"\"$P(s'|s,a)$\"\"\" + \" probability only dependent on s, not history\",\n",
        "\"finite horizon\": \"limited time/turns, policy dependent on time\",\n",
        "\"infinite horizon\": \"unlimited time, optimal policy is stationary (no change w/ time)\",\n",
        "\"Policy\": \"choice of action given a state\",\n",
        "\"Utility\": \"sum of discounted rewards\",\n",
        "\"utility function\" : \"theorum of rational preferences\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 5,
      "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": "ddc18fa8-9ae0-443c-f36d-ad54841f6353"
      },
      "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": 6,
      "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 \nReward Function $R(s,a,s')$ defined for each state, action, state pair not just goal \n\n<b>Markov Decision Process (MDP)</b> - sequential, fully observable, stochastic, additive rewards\n  * also non-deterministic, can be solved with Expectimax\n\nTo solve MDP, need:\n  * <b>set of states</b> $s \\in S$\n  * <b>set of actions</b> $a \\in A$\n  * <b>Transition Function</b> $T(s, a, s')$\n  * <b>Reward Function</b> $R(s,a,s')$\n  * <b>initial state</b> $s_{0}$\n  * <b>1+ terminal states</b>\n\n<b>Solution = Policy</b>, given state s, outputs action to take, a\n\n<b>Sample-based Policy Evaluation</b> averages all sample values, doesn't work because of non-determinism\n\n$V^{*}(s)=max_a(Q^{*}(s,a))$\n$Q^{*}(s,a)=\\sum_{s'}T(s, a, s')[R(s, a, s')+\\gamma V^{*}(s')]$\n$V^{*}(s)=max_a(\\sum_{s'}T(s, a, s')[R(s, a, s')+\\gamma V^{*}(s')])$\n\nConvergence:\n* Case 1: tree has max depth\n* Case 2: if the discount is less than 1\n\nProblems w/ Value Iteration:\n* It's slow, O(S^{2}A)\n* the max at each state rarely changes\n* the policy converges long before values\n\n<b>Policy Iteration:</b>\n1. Policy Evaluation: calculate utilities for non-optimal policy\n2. Policy Improvement: update policy using 1-step lookahead\n- Repeat until policy converges\n- still optimal\n- O(S^3), slow but usually converges faster then Value Iteration\n\nRational Preferences:\n* <b>Orderability</b> - either you prefer A to B, or you're indifferent\n* <b>Transitivity</b> - \n* <b>Continuity</b> - I prefer a to C so there exists some lottery of not C (1-C) such that I'm indifferent to both\n* <b>Substitutability</b> - if I'm indifferent from A to B, then for some p between A, C I must be indifferent to p, B, C\n\n----\nFor an MDP:\n* defined for a fully observable, stochastic environment\n* policy must define what it should do for all reachable states\n* proper policy does not always exist\n* does not always have to have reward function w/ discounted rewards\n\nPolicy Iteration Considers:\n* probability of entering s' given s and action a\n* NOT the max reward obtained from state s\n* utility associated with s\n* all of the actions an agent can take from state s\n\nThe policy is implicitly (not explicitly) udated in value iteration\n\nPolicy iteratioin often converges faster than Value iteration, but is more costly\n\nThe utility function must be completely accurate in order to acheive an optimal policy\n\nPrinciple of MEU - agent should maximize the weighted avg. of their utilities\n\n\n\n## Module 8 Definitions\n* **Markovian** - $P(s'|s,a)$ probability only dependent on s, not history\n* **Finite horizon** - limited time/turns, policy dependent on time\n* **Infinite horizon** - unlimited time, optimal policy is stationary (no change w/ time)\n* **Policy** - choice of action given a state\n* **Utility** - sum of discounted rewards\n* **Utility function** - theorum of rational preferences\n* **Expected utility** - 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",
        "Still assume MDP, however\n",
        "* Don't know T (transition function) or R (reward function) \n",
        "\n",
        "<b>Model Based Learning</b>: learn an approx. model based on experiences\n",
        "1. Learn MDP from experiments\n",
        "  * keep track of outcomes s' for each (s,a)\n",
        "  * avg. to estimate T(s',s,a)\n",
        "2. Solve the MDP\n",
        "\n",
        "Direct Evaluation: type of model-based learning, trial & error\n",
        "* not good because wastest info. about state transitions\n",
        "\n",
        "Temporal Difference Learning: a smarter model-based approach\n",
        "* Sample of V(s) \"\"\" + r\"\"\"$sample=R(s,\\pi (s),s') + \\gamma V^{\\pi}(s')$\"\"\" + \"\"\"\n",
        "* Update to V(s) \"\"\" + r\"\"\"$V^{\\pi}(s)=(1-\\alpha)V^{\\pi}(s)+\\alpha sample$\"\"\" + \"\"\"\n",
        "* Same Update \"\"\" + r\"\"\"$V^{\\pi}(s)=V^{\\pi}(s)+\\alpha (sample - V^{\\pi}(s))$\"\"\" + \"\"\"\n",
        "\n",
        "Decreasing the learning rate (alpha) causes converging avgs. & exponential weighting forgets about the past.\n",
        "* think about alpha = 0 and alpha = 1\n",
        "* does not allow us to form new policies though!\n",
        "\n",
        "Q-Learning: allows us to learn transition model & build new policies\n",
        "* \"\"\" + r\"\"\"$Q_{k+1}(s,a)=\\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma max_{a'}Q_{k}(s',a')]$\"\"\" + \"\"\"\n",
        "* \"\"\" + r\"\"\"$sample = R(s,a,s')+\\gamma max_{a'}Q(s',a')$\"\"\" + \"\"\"\n",
        "* \"\"\" + r\"\"\"$Q(s,a) = (1-\\alpha)Q(s,a) + \\alpha (sample)$\"\"\" + \"\"\"\n",
        "\n",
        "Q-Learning converges to optimal policy! But you need to decrease alpha\n",
        "\n",
        "Exploration Techniques:\n",
        "* <b>e-greedy</b>, every step flip a coin & w/ P(e) take a random action\n",
        "* <b>exploration func.</b>, use function to determine when to explore\n",
        "  - \"\"\" + r\"\"\"$Q(s,a) = R(s,a,s')+\\gamma max_{a'}f(Q(s',a'),N(s',a')) \\text{where } f(u,n)=u+k/n$\"\"\" + \"\"\"\n",
        "\n",
        "Approximate Q-Learning: used when there are many states & info!\n",
        "* \"\"\" + r\"\"\"$Q(s,a)=w_{1}f_{1}(s,a) + w_{2}f_{2}(s,a) +w_{3}f_{3}(s,a)$\"\"\" + \"\"\"\n",
        "  - weights and features represent the experience\n",
        "  - Good: reduces the complexity, Bad: states may share features and have conflicting outcomes\n",
        "\n",
        "----\n",
        "Passive RL:\n",
        "* given policy\n",
        "* given all of the states\n",
        "\n",
        "Direct Utility estimation only uses sample transitions\n",
        "* does not compute utility based on connection of state with is successor\n",
        "\n",
        "For ADP, utility of a state is adjusted locally to agree with the utility of at least one successor state\n",
        "\n",
        "Q-Learning with linear function approx. does not gaurantee converge to optimal policy, ex: quadratic function and linear approx. \n",
        "\n",
        "A deterministic policy maps States to Actions\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "e474c510-a567-4fc6-ef77-b48c2382c6e0"
      },
      "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": 8,
      "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 \nStill assume MDP, however\n* Don't know T (transition function) or R (reward function) \n\n<b>Model Based Learning</b>: learn an approx. model based on experiences\n1. Learn MDP from experiments\n  * keep track of outcomes s' for each (s,a)\n  * avg. to estimate T(s',s,a)\n2. Solve the MDP\n\nDirect Evaluation: type of model-based learning, trial & error\n* not good because wastest info. about state transitions\n\nTemporal Difference Learning: a smarter model-based approach\n* Sample of V(s) $sample=R(s,\\pi (s),s') + \\gamma V^{\\pi}(s')$\n* Update to V(s) $V^{\\pi}(s)=(1-\\alpha)V^{\\pi}(s)+\\alpha sample$\n* Same Update $V^{\\pi}(s)=V^{\\pi}(s)+\\alpha (sample - V^{\\pi}(s))$\n\nDecreasing the learning rate (alpha) causes converging avgs. & exponential weighting forgets about the past.\n* think about alpha = 0 and alpha = 1\n* does not allow us to form new policies though!\n\nQ-Learning: allows us to learn transition model & build new policies\n* $Q_{k+1}(s,a)=\\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma max_{a'}Q_{k}(s',a')]$\n* $sample = R(s,a,s')+\\gamma max_{a'}Q(s',a')$\n* $Q(s,a) = (1-\\alpha)Q(s,a) + \\alpha (sample)$\n\nQ-Learning converges to optimal policy! But you need to decrease alpha\n\nExploration Techniques:\n* <b>e-greedy</b>, every step flip a coin & w/ P(e) take a random action\n* <b>exploration func.</b>, use function to determine when to explore\n  - $Q(s,a) = R(s,a,s')+\\gamma max_{a'}f(Q(s',a'),N(s',a')) \\text{where } f(u,n)=u+k/n$\n\nApproximate Q-Learning: used when there are many states & info!\n* $Q(s,a)=w_{1}f_{1}(s,a) + w_{2}f_{2}(s,a) +w_{3}f_{3}(s,a)$\n  - weights and features represent the experience\n  - Good: reduces the complexity, Bad: states may share features and have conflicting outcomes\n\n----\nPassive RL:\n* given policy\n* given all of the states\n\nDirect Utility estimation only uses sample transitions\n* does not compute utility based on connection of state with is successor\n\nFor ADP, utility of a state is adjusted locally to agree with the utility of at least one successor state\n\nQ-Learning with linear function approx. does not gaurantee converge to optimal policy, ex: quadratic function and linear approx. \n\nA deterministic policy maps States to Actions\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",
        "Random Variables are denoted by capitol letters (ex: X) \n",
        "\n",
        "Probability Distributions are tables \n",
        "\n",
        "P(T) \n",
        "|  T  |  P   |\n",
        "--------------\n",
        "| hot | 0.5  |\n",
        "| cold| 0.5  |\n",
        "\n",
        "Joint Distributions, are events for a handful of different Random Variables\n",
        "\n",
        "Event: a set E of outcomes\n",
        "* \"\"\" + r\"\"\"$P(E)=\\sum_{x_1...x_n}P(x_1,...,x_n)$\"\"\" + \"\"\"\n",
        "  - ex: probability it is hot and raining\n",
        "\n",
        "Marginal Distributions: tables where a variable is eliminated by summing all it's outcomes\n",
        "\n",
        "Conditional Probability: \n",
        "* \"\"\" + r\"\"\"$P(a \\mid b) = \\frac{P(a,b)}{P(b)}$\"\"\" + \"\"\"\n",
        "\n",
        "Inference by Enumeration:\n",
        "1. Gather Evidence Variables\n",
        "2. Sum out hidden variables\n",
        "3. Normalize result\n",
        "\n",
        "Product Rule: \"\"\" + r\"\"\"$P(y)P(x \\mid y) = P(x,y)$\"\"\" + \"\"\"\n",
        "\n",
        "The Chain Rule: \"\"\" + r\"\"\"$P(x_1,x_2,x_3)=P(x1)P(x_2 \\mid x_1)P(x_3 \\mid x_1,x_2)$\"\"\" + \"\"\"\n",
        "\n",
        "Bayes Rule: \"\"\" + r\"\"\"$P(x,y)=P(x \\mid y)P(y)=P(y \\mid x)P(x) \\rightarrow P(x\\mid y) = \\frac{P(y\\mid x)}{P(y)}P(x)$\"\"\" + \"\"\"\n",
        "\n",
        "The Markov Assumption allows us to say that the probability of the next word is only dependent on a few previous words, not whole history\n",
        "\n",
        "unigram  - no history\n",
        "bi-gram  - one word history\n",
        "tri-gram - two words history\n",
        "\n",
        "------\n",
        "\n",
        "Independent Events:\n",
        "* \"\"\" + r\"\"\"$P(A \\cup B)=P(A)+P(B)-P(A cap B)$\"\"\" + \"\"\"\n",
        "* \"\"\" + r\"\"\"$P(B \\mid A) = P(B)$\"\"\" + \"\"\"\n",
        "* \"\"\" + r\"\"\"$P(A\\cap B)=P(A)P(B)$\"\"\" + \"\"\"\n",
        "* \"\"\" + r\"\"\"$P(A\\mid B) = P(A)$\"\"\" + \"\"\"\n",
        "\n",
        "Chain Rule: \"\"\" + r\"\"\"$P(X_1, X_2, X_3, X_4)$\"\"\" + \"\"\"\n",
        "* \"\"\" + r\"\"\"$P(X_1\\mid X_2, X_3, X_4)P(X_4)P(X_3\\mid X_4)P(X_2\\mid X_3, X_4)$\"\"\" + \"\"\"\n",
        "* \"\"\" + r\"\"\"$P(X_1, X_2)P(X_3\\mid X_1, X_2)P(X_4\\mid X_1, X_2, X_3)$\"\"\" + \"\"\"\n",
        "\n",
        "For a set of N random variables, there are N! ways of applying the chain rule\n",
        "\n",
        "When computing a tri-gram, normalize the probability of word w given w(i-1) and w(i-2) to add up to 1\n",
        "\n",
        "Markov assumption allows us to estimate probabilities given data\n",
        "* given the present state, the future and the past are independent\n",
        "\n",
        "Regret let's us capture the relative goodness of an exploration procedure\n",
        "\n",
        "For MDP's, the transition function is captured in advance via the probabilities, whereas Reinforcement Learning does not\n",
        "know the transition function\n",
        "* actions are not deterministic, but probabilistic\n",
        "\n",
        "Given n-gram language model, we are interested on the perplexity on a test set\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": 9,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "a314b8a6-a29d-4043-8962-7a03ab6b7ba0"
      },
      "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": 10,
      "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 \nRandom Variables are denoted by capitol letters (ex: X) \n\nProbability Distributions are tables \n\nP(T) \n|  T  |  P   |\n--------------\n| hot | 0.5  |\n| cold| 0.5  |\n\nJoint Distributions, are events for a handful of different Random Variables\n\nEvent: a set E of outcomes\n* $P(E)=\\sum_{x_1...x_n}P(x_1,...,x_n)$\n  - ex: probability it is hot and raining\n\nMarginal Distributions: tables where a variable is eliminated by summing all it's outcomes\n\nConditional Probability: \n* $P(a \\mid b) = \\frac{P(a,b)}{P(b)}$\n\nInference by Enumeration:\n1. Gather Evidence Variables\n2. Sum out hidden variables\n3. Normalize result\n\nProduct Rule: $P(y)P(x \\mid y) = P(x,y)$\n\nThe Chain Rule: $P(x_1,x_2,x_3)=P(x1)P(x_2 \\mid x_1)P(x_3 \\mid x_1,x_2)$\n\nBayes Rule: $P(x,y)=P(x \\mid y)P(y)=P(y \\mid x)P(x) \\rightarrow P(x\\mid y) = \\frac{P(y\\mid x)}{P(y)}P(x)$\n\nThe Markov Assumption allows us to say that the probability of the next word is only dependent on a few previous words, not whole history\n\nunigram  - no history\nbi-gram  - one word history\ntri-gram - two words history\n\n------\n\nIndependent Events:\n* $P(A \\cup B)=P(A)+P(B)-P(A cap B)$\n* $P(B \\mid A) = P(B)$\n* $P(A\\cap B)=P(A)P(B)$\n* $P(A\\mid B) = P(A)$\n\nChain Rule: $P(X_1, X_2, X_3, X_4)$\n* $P(X_1\\mid X_2, X_3, X_4)P(X_4)P(X_3\\mid X_4)P(X_2\\mid X_3, X_4)$\n* $P(X_1, X_2)P(X_3\\mid X_1, X_2)P(X_4\\mid X_1, X_2, X_3)$\n\nFor a set of N random variables, there are N! ways of applying the chain rule\n\nWhen computing a tri-gram, normalize the probability of word w given w(i-1) and w(i-2) to add up to 1\n\nMarkov assumption allows us to estimate probabilities given data\n* given the present state, the future and the past are independent\n\nRegret let's us capture the relative goodness of an exploration procedure\n\nFor MDP's, the transition function is captured in advance via the probabilities, whereas Reinforcement Learning does not\nknow the transition function\n* actions are not deterministic, but probabilistic\n\nGiven n-gram language model, we are interested on the perplexity on a test set\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": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" \n",
        "Bayesian Network\n",
        "1. Each node represents random variables, either discrete/cont.\n",
        "2. Arcs represent child/parent relationship, directed & acyclic\n",
        "3. Each node has prob. information which relates it to it's parents\n",
        "\n",
        "Conditional Prob. Table\n",
        "* only for discrete RVs\n",
        "* each row must sum to 1\n",
        "* 1 table per RV, if k parents & boolean tree then 2^k entries \"\"\"\n",
        "\n",
        "chapter13_2 = \"\"\" \n",
        "syntax - the cond. probs the nodes & the graph\n",
        "semantics - how the syntax translate to a joint prob. distribution\n",
        "\n",
        "Bayes Net is complete & non-redundant representation of the domain\n",
        "* can be more compact than the full join distribution\n",
        "* locally structured, meaning sub comp. only interact w/ bounded number of others, GROWS LINEARLY\n",
        "* compactness is dependent on ordering!\n",
        "\"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" \n",
        "\n",
        "Independence: \"\"\" + r\"\"\"$P(x,y) = P(x)P(y)$\"\"\" + \"\"\"\n",
        "\n",
        "Conditionally Independent given z: \"\"\" + r\"\"\"$P(x,y\\mid z) = P(x\\mid z)P(y\\mid z)$\"\"\" + \"\"\"\n",
        "\n",
        "A Baye's Net Graph is used to help model the environment and capture assumptions about relationship of variables\n",
        "\n",
        "D-Separation: an algorithm for answering queries about relationships\n",
        "\n",
        "----\n",
        "The conditional probability of a variable in a Bayes Net should be specified according to all other nodes in the graph\n",
        "\n",
        "Every variable in a Bayes net is independent of all of its descendants given its children\n",
        "\n",
        "For Locally Structured systems, they grow linearly\n",
        "\n",
        "The same joint distribution can be represented by multiple bayes nets, depending on the ordering\n",
        "\n",
        "If two nodes in a bayes net do not share a path, then they are conditionally independent\n",
        "\n",
        "The conditional probability for a variable only need be specified in terms of it's parents, not all other nodes\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 886
        },
        "cellView": "form",
        "outputId": "ff10dfab-c5e3-48d0-ad6a-43262b6bbff7"
      },
      "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": 12,
      "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 \nBayesian Network\n1. Each node represents random variables, either discrete/cont.\n2. Arcs represent child/parent relationship, directed & acyclic\n3. Each node has prob. information which relates it to it's parents\n\nConditional Prob. Table\n* only for discrete RVs\n* each row must sum to 1\n* 1 table per RV, if k parents & boolean tree then 2^k entries \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n \nsyntax - the cond. probs the nodes & the graph\nsemantics - how the syntax translate to a joint prob. distribution\n\nBayes Net is complete & non-redundant representation of the domain\n* can be more compact than the full join distribution\n* locally structured, meaning sub comp. only interact w/ bounded number of others, GROWS LINEARLY\n* compactness is dependent on ordering!\n\n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n \n\nIndependence: $P(x,y) = P(x)P(y)$\n\nConditionally Independent given z: $P(x,y\\mid z) = P(x\\mid z)P(y\\mid z)$\n\nA Baye's Net Graph is used to help model the environment and capture assumptions about relationship of variables\n\nD-Separation: an algorithm for answering queries about relationships\n\n----\nThe conditional probability of a variable in a Bayes Net should be specified according to all other nodes in the graph\n\nEvery variable in a Bayes net is independent of all of its descendants given its children\n\nFor Locally Structured systems, they grow linearly\n\nThe same joint distribution can be represented by multiple bayes nets, depending on the ordering\n\nIf two nodes in a bayes net do not share a path, then they are conditionally independent\n\nThe conditional probability for a variable only need be specified in terms of it's parents, not all other nodes\n\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",
        " \"\"\" + r\"\"\"$\\sum w_j x_j = w\\cdot x$\"\"\" + \"\"\"\n",
        " moving the threshold to the other side of the equation...\n",
        " \"\"\" + r\"\"\"$b = -threshold$\"\"\" + \"\"\"\n",
        " where \"\"\" + r\"\"\"$\n",
        " f_n = \n",
        " \\begin{cases}\n",
        " 0    &\\text{if } w\\cdot x + b \\leq 0 \\\\\n",
        " 1    &\\text{if } w\\cdot x + b > 0\n",
        " \\end{cases}\n",
        " $\"\"\" + \"\"\"\n",
        "\n",
        " Weights are only updated on incorrect classification\n",
        " * \"\"\" + r\"\"\"$w = w+y^{*}\\cdot f$\"\"\" + \"\"\"\n",
        " \n",
        " Properties of Perceptrons:\n",
        " * <b>Separability</b> true if some parameters get the training set perfectly correct\n",
        " * <b>Convergence</b> will converge eventually (binary case) if the data is separable\n",
        " * <b>Mistake Bound</b> maximum number of mistakes (binary case) related to the degree of separability\n",
        "\n",
        " Problems w/ Perceptrons:\n",
        " * Noise, if the data isn't separable -> thrashing\n",
        " * Mediocre Generalization: may only find a \"barely\" separable solution\n",
        " * Overtraining: May learn idiosyncrasies of training data not applicable to other sets\n",
        "\n",
        " MIRA: technique for choosing update just enough to fix the current missed prediction\n",
        " * \"\"\" + r\"\"\"$\\tau = \\frac{(w'_{y}-w'+{y^*})\\cdot f +1}{2f\\cdot f}$\"\"\" + \"\"\"\n",
        "\n",
        " when guess is incorrect\n",
        " * decrease incorrect weight\"\"\" + r\"\"\"$w_y = w'_y-\\tau f(x)$\"\"\" + \"\"\"\n",
        " * increase correct class weight \"\"\" + r\"\"\"$w_{y^*} = w'_{y^*}-\\tau f(x)$\"\"\" + \"\"\"\n",
        "\n",
        " Non-linear speparators: maps the existing feature space to another one which is linearly separable\n",
        "\n",
        " Perceptrons make less assumptions about the training data (i.e. don't assume independence/condintional independence)\n",
        "\n",
        " ----\n",
        " The Naive Bayes model is “naive” because it assumes that the features are conditionally independent of each other, given the class\n",
        "\n",
        " Given the class Y, \"\"\" + r\"\"\"$P(X_1,X_2,X_3,Y) = P(Y)P(X_1\\mid Y)P(X_2\\mid Y)P(X_3\\mid Y)$\"\"\" + \"\"\"\n",
        "\n",
        " Percepton training weights are not updated every training instance, only when the predicted class is incorrect\n",
        "\n",
        " A Single perceptron is unable to find a separating boundary for the XOR problem, since it is not linearly separable\n",
        "\n",
        " The weight vector for a perceptron is only gauranteed to converge if the training set is separable, it says \n",
        " nothing about a random dataset\n",
        "\n",
        " The inference procedure for a perceptron is defined: compute weighted sum -> then apply a threshold\n",
        "\n",
        " A parametric model has a fixed size on the number of parameters\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 13,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "997ceb33-9902-4145-ed7e-47eb14f052cb"
      },
      "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": 14,
      "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 $\\sum w_j x_j = w\\cdot x$\n moving the threshold to the other side of the equation...\n $b = -threshold$\n where $\n f_n = \n \\begin{cases}\n 0    &\\text{if } w\\cdot x + b \\leq 0 \\\\\n 1    &\\text{if } w\\cdot x + b > 0\n \\end{cases}\n $\n\n Weights are only updated on incorrect classification\n * $w = w+y^{*}\\cdot f$\n \n Properties of Perceptrons:\n * <b>Separability</b> true if some parameters get the training set perfectly correct\n * <b>Convergence</b> will converge eventually (binary case) if the data is separable\n * <b>Mistake Bound</b> maximum number of mistakes (binary case) related to the degree of separability\n\n Problems w/ Perceptrons:\n * Noise, if the data isn't separable -> thrashing\n * Mediocre Generalization: may only find a \"barely\" separable solution\n * Overtraining: May learn idiosyncrasies of training data not applicable to other sets\n\n MIRA: technique for choosing update just enough to fix the current missed prediction\n * $\\tau = \\frac{(w'_{y}-w'+{y^*})\\cdot f +1}{2f\\cdot f}$\n\n when guess is incorrect\n * decrease incorrect weight$w_y = w'_y-\\tau f(x)$\n * increase correct class weight $w_{y^*} = w'_{y^*}-\\tau f(x)$\n\n Non-linear speparators: maps the existing feature space to another one which is linearly separable\n\n Perceptrons make less assumptions about the training data (i.e. don't assume independence/condintional independence)\n\n ----\n The Naive Bayes model is “naive” because it assumes that the features are conditionally independent of each other, given the class\n\n Given the class Y, $P(X_1,X_2,X_3,Y) = P(Y)P(X_1\\mid Y)P(X_2\\mid Y)P(X_3\\mid Y)$\n\n Percepton training weights are not updated every training instance, only when the predicted class is incorrect\n\n A Single perceptron is unable to find a separating boundary for the XOR problem, since it is not linearly separable\n\n The weight vector for a perceptron is only gauranteed to converge if the training set is separable, it says \n nothing about a random dataset\n\n The inference procedure for a perceptron is defined: compute weighted sum -> then apply a threshold\n\n A parametric model has a fixed size on the number of parameters\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",
        "\n",
        "Smoothness is Crucial in Networks for Partial Derivative\n",
        "* Smoothness of σ means that small changes in the weights wj and in the bias b will produce a small change the output from the neuron\n",
        "\n",
        "We use non-linear activation functions because otherwise a linear activation function, the resulting network would be equivalent to a\n",
        "single-layer network \n",
        "\n",
        "Sigmoid = \"\"\" + r\"\"\"$\\frac{1}{1+e^{-z}}$\"\"\" + \"\"\"\n",
        "\n",
        "3 Commonly Used Activation Functions\n",
        "* sigmoid\n",
        "* tanh\n",
        "* ReLU\n",
        "\n",
        "Feed-Forward Neural Netword\n",
        "* basic NN that is fully connected w/ no cycles\n",
        "* no outputs are passed back to previous layes (no memory)\n",
        "h= σ(Wx+b)\n",
        "z = Uh\n",
        "y = softmax(z)\n",
        "\n",
        "A single matrix W is used for the layer weights because it allows for efficient calculation w/ matrix operations\n",
        "\n",
        "Cross-Entropy Loss: \"\"\" + r\"\"\"$L_{CE}(yhat, y)=-logp(y|x)=-[ylog(yhat) + (1-y)log(1-yhat)]=-[ylog(\\sigma (w\\cdot x+b)+(1-y)log(1-\\sigma(w\\cdot x+b)))]$\"\"\" + \"\"\"\n",
        "* \"\"\" + r\"\"\"$p(y\\mid x)=yhat(1-yhat)^{1-y}$\"\"\" + \"\"\"\n",
        "\n",
        "Multinomial Classification: \"\"\" + r\"\"\"$L_{CE}(yhat, y)=-\\sum_{i=1}^{C}y_{i}log(yhat_i)$\"\"\" + \"\"\"\n",
        "\n",
        "Logistic regression is equivalent to a neural network with just one weight layer and a sigmoid output\n",
        "\n",
        "chain rule: \"\"\" + r\"\"\"$f(x)=u(v(x)) \\rightarrow \\frac{df}{dx}=\\frac{du}{dv}\\cdot \\frac{dv}{dx}$\"\"\" + \"\"\"\n",
        "\n",
        "Stochastic Gradient Descent: used to optimize the objective function, minimize the loss function\n",
        "\n",
        "For logistic regression the loss function is typically Convex\n",
        "* convex -> means that gradient descent starting from any point is guaranteed to find the minimum\n",
        "\n",
        "Learning Rate: \"\"\" + r\"\"\"$w^{t+1}=w^{t}-\\eta \\frac{d}{dw}f(x;w)$\"\"\" + \"\"\"\n",
        "* learning rate controls how much we adjust the weights\n",
        "\n",
        "Regularization: a technique used to penalize large weights, help the function generalize better to held-out datasets\n",
        "\n",
        "softmax: a generalization of the sigmoid function used to convert outputs to probabilities\n",
        "* often used in multinomial problems\n",
        "* \"\"\" + r\"\"\"$softmax(z_i)=\\frac{e^{z_j}{\\sum_{j=1}^{k}e^{z_j}}$\"\"\" + \"\"\"\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 15,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "0556d4a1-1066-4fcb-b754-931a791647b0"
      },
      "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": 16,
      "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\nSmoothness is Crucial in Networks for Partial Derivative\n* Smoothness of σ means that small changes in the weights wj and in the bias b will produce a small change the output from the neuron\n\nWe use non-linear activation functions because otherwise a linear activation function, the resulting network would be equivalent to a\nsingle-layer network \n\nSigmoid = $\\frac{1}{1+e^{-z}}$\n\n3 Commonly Used Activation Functions\n* sigmoid\n* tanh\n* ReLU\n\nFeed-Forward Neural Netword\n* basic NN that is fully connected w/ no cycles\n* no outputs are passed back to previous layes (no memory)\nh= σ(Wx+b)\nz = Uh\ny = softmax(z)\n\nA single matrix W is used for the layer weights because it allows for efficient calculation w/ matrix operations\n\nCross-Entropy Loss: $L_{CE}(yhat, y)=-logp(y|x)=-[ylog(yhat) + (1-y)log(1-yhat)]=-[ylog(\\sigma (w\\cdot x+b)+(1-y)log(1-\\sigma(w\\cdot x+b)))]$\n* $p(y\\mid x)=yhat(1-yhat)^{1-y}$\n\nMultinomial Classification: $L_{CE}(yhat, y)=-\\sum_{i=1}^{C}y_{i}log(yhat_i)$\n\nLogistic regression is equivalent to a neural network with just one weight layer and a sigmoid output\n\nchain rule: $f(x)=u(v(x)) \\rightarrow \\frac{df}{dx}=\\frac{du}{dv}\\cdot \\frac{dv}{dx}$\n\nStochastic Gradient Descent: used to optimize the objective function, minimize the loss function\n\nFor logistic regression the loss function is typically Convex\n* convex -> means that gradient descent starting from any point is guaranteed to find the minimum\n\nLearning Rate: $w^{t+1}=w^{t}-\\eta \\frac{d}{dw}f(x;w)$\n* learning rate controls how much we adjust the weights\n\nRegularization: a technique used to penalize large weights, help the function generalize better to held-out datasets\n\nsoftmax: a generalization of the sigmoid function used to convert outputs to probabilities\n* often used in multinomial problems\n* $softmax(z_i)=\\frac{e^{z_j}{\\sum_{j=1}^{k}e^{z_j}}$\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 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 17,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "432a501d-d2e1-4126-d37e-bc0e054a185f"
      },
      "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": 18,
      "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\nSmoothness is Crucial in Networks for Partial Derivative\n* Smoothness of σ means that small changes in the weights wj and in the bias b will produce a small change the output from the neuron\n\nWe use non-linear activation functions because otherwise a linear activation function, the resulting network would be equivalent to a\nsingle-layer network \n\nSigmoid = $\\frac{1}{1+e^{-z}}$\n\n3 Commonly Used Activation Functions\n* sigmoid\n* tanh\n* ReLU\n\nFeed-Forward Neural Netword\n* basic NN that is fully connected w/ no cycles\n* no outputs are passed back to previous layes (no memory)\nh= σ(Wx+b)\nz = Uh\ny = softmax(z)\n\nA single matrix W is used for the layer weights because it allows for efficient calculation w/ matrix operations\n\nCross-Entropy Loss: $L_{CE}(yhat, y)=-logp(y|x)=-[ylog(yhat) + (1-y)log(1-yhat)]=-[ylog(\\sigma (w\\cdot x+b)+(1-y)log(1-\\sigma(w\\cdot x+b)))]$\n* $p(y\\mid x)=yhat(1-yhat)^{1-y}$\n\nMultinomial Classification: $L_{CE}(yhat, y)=-\\sum_{i=1}^{C}y_{i}log(yhat_i)$\n\nLogistic regression is equivalent to a neural network with just one weight layer and a sigmoid output\n\nchain rule: $f(x)=u(v(x)) \\rightarrow \\frac{df}{dx}=\\frac{du}{dv}\\cdot \\frac{dv}{dx}$\n\nStochastic Gradient Descent: used to optimize the objective function, minimize the loss function\n\nFor logistic regression the loss function is typically Convex\n* convex -> means that gradient descent starting from any point is guaranteed to find the minimum\n\nLearning Rate: $w^{t+1}=w^{t}-\\eta \\frac{d}{dw}f(x;w)$\n* learning rate controls how much we adjust the weights\n\nRegularization: a technique used to penalize large weights, help the function generalize better to held-out datasets\n\nsoftmax: a generalization of the sigmoid function used to convert outputs to probabilities\n* often used in multinomial problems\n* $softmax(z_i)=\\frac{e^{z_j}{\\sum_{j=1}^{k}e^{z_j}}$\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": "0ad3c95f-9478-4917-d563-890b15b70f03"
      },
      "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": 19,
      "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 \nReward Function $R(s,a,s')$ defined for each state, action, state pair not just goal \n\n<b>Markov Decision Process (MDP)</b> - sequential, fully observable, stochastic, additive rewards\n  * also non-deterministic, can be solved with Expectimax\n\nTo solve MDP, need:\n  * <b>set of states</b> $s \\in S$\n  * <b>set of actions</b> $a \\in A$\n  * <b>Transition Function</b> $T(s, a, s')$\n  * <b>Reward Function</b> $R(s,a,s')$\n  * <b>initial state</b> $s_{0}$\n  * <b>1+ terminal states</b>\n\n<b>Solution = Policy</b>, given state s, outputs action to take, a\n\n<b>Sample-based Policy Evaluation</b> averages all sample values, doesn't work because of non-determinism\n\n$V^{*}(s)=max_a(Q^{*}(s,a))$\n$Q^{*}(s,a)=\\sum_{s'}T(s, a, s')[R(s, a, s')+\\gamma V^{*}(s')]$\n$V^{*}(s)=max_a(\\sum_{s'}T(s, a, s')[R(s, a, s')+\\gamma V^{*}(s')])$\n\nConvergence:\n* Case 1: tree has max depth\n* Case 2: if the discount is less than 1\n\nProblems w/ Value Iteration:\n* It's slow, O(S^{2}A)\n* the max at each state rarely changes\n* the policy converges long before values\n\n<b>Policy Iteration:</b>\n1. Policy Evaluation: calculate utilities for non-optimal policy\n2. Policy Improvement: update policy using 1-step lookahead\n- Repeat until policy converges\n- still optimal\n- O(S^3), slow but usually converges faster then Value Iteration\n\nRational Preferences:\n* <b>Orderability</b> - either you prefer A to B, or you're indifferent\n* <b>Transitivity</b> - \n* <b>Continuity</b> - I prefer a to C so there exists some lottery of not C (1-C) such that I'm indifferent to both\n* <b>Substitutability</b> - if I'm indifferent from A to B, then for some p between A, C I must be indifferent to p, B, C\n\n----\nFor an MDP:\n* defined for a fully observable, stochastic environment\n* policy must define what it should do for all reachable states\n* proper policy does not always exist\n* does not always have to have reward function w/ discounted rewards\n\nPolicy Iteration Considers:\n* probability of entering s' given s and action a\n* NOT the max reward obtained from state s\n* utility associated with s\n* all of the actions an agent can take from state s\n\nThe policy is implicitly (not explicitly) udated in value iteration\n\nPolicy iteratioin often converges faster than Value iteration, but is more costly\n\nThe utility function must be completely accurate in order to acheive an optimal policy\n\nPrinciple of MEU - agent should maximize the weighted avg. of their utilities\n\n\n\n## Module 8 Definitions\n* **Markovian** - $P(s'|s,a)$ probability only dependent on s, not history\n* **Finite horizon** - limited time/turns, policy dependent on time\n* **Infinite horizon** - unlimited time, optimal policy is stationary (no change w/ time)\n* **Policy** - choice of action given a state\n* **Utility** - sum of discounted rewards\n* **Utility function** - theorum of rational preferences\n* **Expected utility** - 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 \nStill assume MDP, however\n* Don't know T (transition function) or R (reward function) \n\n<b>Model Based Learning</b>: learn an approx. model based on experiences\n1. Learn MDP from experiments\n  * keep track of outcomes s' for each (s,a)\n  * avg. to estimate T(s',s,a)\n2. Solve the MDP\n\nDirect Evaluation: type of model-based learning, trial & error\n* not good because wastest info. about state transitions\n\nTemporal Difference Learning: a smarter model-based approach\n* Sample of V(s) $sample=R(s,\\pi (s),s') + \\gamma V^{\\pi}(s')$\n* Update to V(s) $V^{\\pi}(s)=(1-\\alpha)V^{\\pi}(s)+\\alpha sample$\n* Same Update $V^{\\pi}(s)=V^{\\pi}(s)+\\alpha (sample - V^{\\pi}(s))$\n\nDecreasing the learning rate (alpha) causes converging avgs. & exponential weighting forgets about the past.\n* think about alpha = 0 and alpha = 1\n* does not allow us to form new policies though!\n\nQ-Learning: allows us to learn transition model & build new policies\n* $Q_{k+1}(s,a)=\\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma max_{a'}Q_{k}(s',a')]$\n* $sample = R(s,a,s')+\\gamma max_{a'}Q(s',a')$\n* $Q(s,a) = (1-\\alpha)Q(s,a) + \\alpha (sample)$\n\nQ-Learning converges to optimal policy! But you need to decrease alpha\n\nExploration Techniques:\n* <b>e-greedy</b>, every step flip a coin & w/ P(e) take a random action\n* <b>exploration func.</b>, use function to determine when to explore\n  - $Q(s,a) = R(s,a,s')+\\gamma max_{a'}f(Q(s',a'),N(s',a')) \\text{where } f(u,n)=u+k/n$\n\nApproximate Q-Learning: used when there are many states & info!\n* $Q(s,a)=w_{1}f_{1}(s,a) + w_{2}f_{2}(s,a) +w_{3}f_{3}(s,a)$\n  - weights and features represent the experience\n  - Good: reduces the complexity, Bad: states may share features and have conflicting outcomes\n\n----\nPassive RL:\n* given policy\n* given all of the states\n\nDirect Utility estimation only uses sample transitions\n* does not compute utility based on connection of state with is successor\n\nFor ADP, utility of a state is adjusted locally to agree with the utility of at least one successor state\n\nQ-Learning with linear function approx. does not gaurantee converge to optimal policy, ex: quadratic function and linear approx. \n\nA deterministic policy maps States to Actions\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 \nRandom Variables are denoted by capitol letters (ex: X) \n\nProbability Distributions are tables \n\nP(T) \n|  T  |  P   |\n--------------\n| hot | 0.5  |\n| cold| 0.5  |\n\nJoint Distributions, are events for a handful of different Random Variables\n\nEvent: a set E of outcomes\n* $P(E)=\\sum_{x_1...x_n}P(x_1,...,x_n)$\n  - ex: probability it is hot and raining\n\nMarginal Distributions: tables where a variable is eliminated by summing all it's outcomes\n\nConditional Probability: \n* $P(a \\mid b) = \\frac{P(a,b)}{P(b)}$\n\nInference by Enumeration:\n1. Gather Evidence Variables\n2. Sum out hidden variables\n3. Normalize result\n\nProduct Rule: $P(y)P(x \\mid y) = P(x,y)$\n\nThe Chain Rule: $P(x_1,x_2,x_3)=P(x1)P(x_2 \\mid x_1)P(x_3 \\mid x_1,x_2)$\n\nBayes Rule: $P(x,y)=P(x \\mid y)P(y)=P(y \\mid x)P(x) \\rightarrow P(x\\mid y) = \\frac{P(y\\mid x)}{P(y)}P(x)$\n\nThe Markov Assumption allows us to say that the probability of the next word is only dependent on a few previous words, not whole history\n\nunigram  - no history\nbi-gram  - one word history\ntri-gram - two words history\n\n------\n\nIndependent Events:\n* $P(A \\cup B)=P(A)+P(B)-P(A cap B)$\n* $P(B \\mid A) = P(B)$\n* $P(A\\cap B)=P(A)P(B)$\n* $P(A\\mid B) = P(A)$\n\nChain Rule: $P(X_1, X_2, X_3, X_4)$\n* $P(X_1\\mid X_2, X_3, X_4)P(X_4)P(X_3\\mid X_4)P(X_2\\mid X_3, X_4)$\n* $P(X_1, X_2)P(X_3\\mid X_1, X_2)P(X_4\\mid X_1, X_2, X_3)$\n\nFor a set of N random variables, there are N! ways of applying the chain rule\n\nWhen computing a tri-gram, normalize the probability of word w given w(i-1) and w(i-2) to add up to 1\n\nMarkov assumption allows us to estimate probabilities given data\n* given the present state, the future and the past are independent\n\nRegret let's us capture the relative goodness of an exploration procedure\n\nFor MDP's, the transition function is captured in advance via the probabilities, whereas Reinforcement Learning does not\nknow the transition function\n* actions are not deterministic, but probabilistic\n\nGiven n-gram language model, we are interested on the perplexity on a test set\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 \nBayesian Network\n1. Each node represents random variables, either discrete/cont.\n2. Arcs represent child/parent relationship, directed & acyclic\n3. Each node has prob. information which relates it to it's parents\n\nConditional Prob. Table\n* only for discrete RVs\n* each row must sum to 1\n* 1 table per RV, if k parents & boolean tree then 2^k entries \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n \nsyntax - the cond. probs the nodes & the graph\nsemantics - how the syntax translate to a joint prob. distribution\n\nBayes Net is complete & non-redundant representation of the domain\n* can be more compact than the full join distribution\n* locally structured, meaning sub comp. only interact w/ bounded number of others, GROWS LINEARLY\n* compactness is dependent on ordering!\n\n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n \n\nIndependence: $P(x,y) = P(x)P(y)$\n\nConditionally Independent given z: $P(x,y\\mid z) = P(x\\mid z)P(y\\mid z)$\n\nA Baye's Net Graph is used to help model the environment and capture assumptions about relationship of variables\n\nD-Separation: an algorithm for answering queries about relationships\n\n----\nThe conditional probability of a variable in a Bayes Net should be specified according to all other nodes in the graph\n\nEvery variable in a Bayes net is independent of all of its descendants given its children\n\nFor Locally Structured systems, they grow linearly\n\nThe same joint distribution can be represented by multiple bayes nets, depending on the ordering\n\nIf two nodes in a bayes net do not share a path, then they are conditionally independent\n\nThe conditional probability for a variable only need be specified in terms of it's parents, not all other nodes\n\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 $\\sum w_j x_j = w\\cdot x$\n moving the threshold to the other side of the equation...\n $b = -threshold$\n where $\n f_n = \n \\begin{cases}\n 0    &\\text{if } w\\cdot x + b \\leq 0 \\\\\n 1    &\\text{if } w\\cdot x + b > 0\n \\end{cases}\n $\n\n Weights are only updated on incorrect classification\n * $w = w+y^{*}\\cdot f$\n \n Properties of Perceptrons:\n * <b>Separability</b> true if some parameters get the training set perfectly correct\n * <b>Convergence</b> will converge eventually (binary case) if the data is separable\n * <b>Mistake Bound</b> maximum number of mistakes (binary case) related to the degree of separability\n\n Problems w/ Perceptrons:\n * Noise, if the data isn't separable -> thrashing\n * Mediocre Generalization: may only find a \"barely\" separable solution\n * Overtraining: May learn idiosyncrasies of training data not applicable to other sets\n\n MIRA: technique for choosing update just enough to fix the current missed prediction\n * $\\tau = \\frac{(w'_{y}-w'+{y^*})\\cdot f +1}{2f\\cdot f}$\n\n when guess is incorrect\n * decrease incorrect weight$w_y = w'_y-\\tau f(x)$\n * increase correct class weight $w_{y^*} = w'_{y^*}-\\tau f(x)$\n\n Non-linear speparators: maps the existing feature space to another one which is linearly separable\n\n Perceptrons make less assumptions about the training data (i.e. don't assume independence/condintional independence)\n\n ----\n The Naive Bayes model is “naive” because it assumes that the features are conditionally independent of each other, given the class\n\n Given the class Y, $P(X_1,X_2,X_3,Y) = P(Y)P(X_1\\mid Y)P(X_2\\mid Y)P(X_3\\mid Y)$\n\n Percepton training weights are not updated every training instance, only when the predicted class is incorrect\n\n A Single perceptron is unable to find a separating boundary for the XOR problem, since it is not linearly separable\n\n The weight vector for a perceptron is only gauranteed to converge if the training set is separable, it says \n nothing about a random dataset\n\n The inference procedure for a perceptron is defined: compute weighted sum -> then apply a threshold\n\n A parametric model has a fixed size on the number of parameters\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\nSmoothness is Crucial in Networks for Partial Derivative\n* Smoothness of σ means that small changes in the weights wj and in the bias b will produce a small change the output from the neuron\n\nWe use non-linear activation functions because otherwise a linear activation function, the resulting network would be equivalent to a\nsingle-layer network \n\nSigmoid = $\\frac{1}{1+e^{-z}}$\n\n3 Commonly Used Activation Functions\n* sigmoid\n* tanh\n* ReLU\n\nFeed-Forward Neural Netword\n* basic NN that is fully connected w/ no cycles\n* no outputs are passed back to previous layes (no memory)\nh= σ(Wx+b)\nz = Uh\ny = softmax(z)\n\nA single matrix W is used for the layer weights because it allows for efficient calculation w/ matrix operations\n\nCross-Entropy Loss: $L_{CE}(yhat, y)=-logp(y|x)=-[ylog(yhat) + (1-y)log(1-yhat)]=-[ylog(\\sigma (w\\cdot x+b)+(1-y)log(1-\\sigma(w\\cdot x+b)))]$\n* $p(y\\mid x)=yhat(1-yhat)^{1-y}$\n\nMultinomial Classification: $L_{CE}(yhat, y)=-\\sum_{i=1}^{C}y_{i}log(yhat_i)$\n\nLogistic regression is equivalent to a neural network with just one weight layer and a sigmoid output\n\nchain rule: $f(x)=u(v(x)) \\rightarrow \\frac{df}{dx}=\\frac{du}{dv}\\cdot \\frac{dv}{dx}$\n\nStochastic Gradient Descent: used to optimize the objective function, minimize the loss function\n\nFor logistic regression the loss function is typically Convex\n* convex -> means that gradient descent starting from any point is guaranteed to find the minimum\n\nLearning Rate: $w^{t+1}=w^{t}-\\eta \\frac{d}{dw}f(x;w)$\n* learning rate controls how much we adjust the weights\n\nRegularization: a technique used to penalize large weights, help the function generalize better to held-out datasets\n\nsoftmax: a generalization of the sigmoid function used to convert outputs to probabilities\n* often used in multinomial problems\n* $softmax(z_i)=\\frac{e^{z_j}{\\sum_{j=1}^{k}e^{z_j}}$\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\nSmoothness is Crucial in Networks for Partial Derivative\n* Smoothness of σ means that small changes in the weights wj and in the bias b will produce a small change the output from the neuron\n\nWe use non-linear activation functions because otherwise a linear activation function, the resulting network would be equivalent to a\nsingle-layer network \n\nSigmoid = $\\frac{1}{1+e^{-z}}$\n\n3 Commonly Used Activation Functions\n* sigmoid\n* tanh\n* ReLU\n\nFeed-Forward Neural Netword\n* basic NN that is fully connected w/ no cycles\n* no outputs are passed back to previous layes (no memory)\nh= σ(Wx+b)\nz = Uh\ny = softmax(z)\n\nA single matrix W is used for the layer weights because it allows for efficient calculation w/ matrix operations\n\nCross-Entropy Loss: $L_{CE}(yhat, y)=-logp(y|x)=-[ylog(yhat) + (1-y)log(1-yhat)]=-[ylog(\\sigma (w\\cdot x+b)+(1-y)log(1-\\sigma(w\\cdot x+b)))]$\n* $p(y\\mid x)=yhat(1-yhat)^{1-y}$\n\nMultinomial Classification: $L_{CE}(yhat, y)=-\\sum_{i=1}^{C}y_{i}log(yhat_i)$\n\nLogistic regression is equivalent to a neural network with just one weight layer and a sigmoid output\n\nchain rule: $f(x)=u(v(x)) \\rightarrow \\frac{df}{dx}=\\frac{du}{dv}\\cdot \\frac{dv}{dx}$\n\nStochastic Gradient Descent: used to optimize the objective function, minimize the loss function\n\nFor logistic regression the loss function is typically Convex\n* convex -> means that gradient descent starting from any point is guaranteed to find the minimum\n\nLearning Rate: $w^{t+1}=w^{t}-\\eta \\frac{d}{dw}f(x;w)$\n* learning rate controls how much we adjust the weights\n\nRegularization: a technique used to penalize large weights, help the function generalize better to held-out datasets\n\nsoftmax: a generalization of the sigmoid function used to convert outputs to probabilities\n* often used in multinomial problems\n* $softmax(z_i)=\\frac{e^{z_j}{\\sum_{j=1}^{k}e^{z_j}}$\n\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}