{
  "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/",
          "height": 0
        },
        "outputId": "8cf3b9eb-a74f-4aab-ab76-4a9204d8ff91"
      },
      "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": 6,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "7c90bb97-86b9-47e9-da7a-8a5a23e9e6fe"
      },
      "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": 7,
      "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": 8,
      "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 = \"\"\" Decision-theoretic agent makes rational decisions based on \n",
        "what it believes and what it wants. Probability of reachign s' by doing a \n",
        "in the current state = P(result(a) = s') = sum(over all s) of P(s)P(s' | s,a).\n",
        "Decision theory chooses among actions based on the desirability of their \n",
        "immediate outcomes - environment assumed to be episodic. \"\"\"\n",
        "chapter16_2 = \"\"\" Set of outcomes for each action is a lottery of outcomes \n",
        "with probabilities. Each outcome is either an atomic state or another lottery. \n",
        "Utility theory understands how preferences between complex lotteries\n",
        "are related to preferences between underlying states in those lotteries. \n",
        "Axioms: orderability, transitivity, continuity, suitability, monotonicity, \n",
        "decomposability. From axioms: existence of utility function (U(A) > U(B) ⇔ A ≻ B and U(A) = U(B) ⇔ A ∼ B) \n",
        "and expected utility of a lottery is the sum of the probability of each outcome * \n",
        "utility of that outcome.  \"\"\"\n",
        "chapter16_3 = \"\"\" Utility functions map from lotteries to real numbers. For\n",
        "the utility of money, utility is not proportional to monetary value. \n",
        "Risk-averse vs. risk-seeking behavior. Certainty equivalent is the value\n",
        "that an agent will accept in lieu of a lottery; insurance premium is \n",
        "the difference between an expected monetary value of a lottery and its\n",
        "certainty equivalent. Real outcomes are usually worse than expected, due to \n",
        "selecting actions with highest utility estimate, favoring overly optimistic\n",
        "estimates. More choices, more optimistic estimates. Descriptive theory (describes\n",
        " how actual agents act) are affected by certainty effect, ambiguity \n",
        " evasion, framing effect, anchoring effect.  \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" MDPs are sequential dcision problems for fully observable, \\\n",
        "stochastic environments with a Markovian transition model and additive rewards. \\\n",
        "Reward is bound by +/- Rmax, utility function depends on environment history. \\\n",
        "Additive discounted rewards: $U = R(s_0,a_0,s_1) + \\gamma R(s_1,a_1,s_2) + \\gamma^2 R(s_2,a_2,s_3) + ...$ \\\n",
        "$\\gamma$: 0 if rewards in distant future are insignificant. Comparing policies: compare \\\n",
        "expected policies, $U^{\\pi}(s) = E[\\sum_{t=0}^{\\inf}\\gamma^t R(S_t,\\pi (S_t),S_{t+1})]$ \\\n",
        "Optimal policy: $\\pi^*(s) = argmax \\sum_{s'}P(s'|s,a)[R(s,a,s') + \\gamma U(s')]$ \\\n",
        "Utility of a state is same, but find is the max action (Bellman equation). \\\n",
        "Q-function: $\\sum_{s'}P(s'|s,a)[R(s,a,s')+ \\gamma max_{a'}Q(s',a')]$.\"\"\"\n",
        "chapter17_2 =  \"\"\" Value iteration: n possible states, n Bellman equation with \\\n",
        "n unknowns (utilities of the states). Solve simultaneously for utilities. Iterative \\\n",
        "step: Bellman update, for all states at each iteration. Will reach an equilibrium \\\n",
        "with unique solutions to the Bellman equations due to the update being a contraction \\\n",
        "by a factor of $\\gamma$; converges when $\\gamma < 1$. Stop iteration when update \\\n",
        "is small. Policy iteration.. policy evaluation: given a policy, calculate utility \\\n",
        "of each state if the policy is executed. Simplified Bellman equation. policy improvement: \\\n",
        "calculate a new MEU policy using one-step look-ahead based on new utilities. Terminate \\\n",
        "when policy improvement yields no change in utilities. Linear programming: \\\n",
        "consider as variables in the LP the utilities U(s) for each state s; minimize \\\n",
        "utilities for all states. Online algorithms: use expectimax with rewards on \\\n",
        "nonterminal nodes and terminal transitions. Decision extracted from search tree \\\n",
        "by backing up utility values from leaves. $\\epsilon$ horizon: tree depth H \\\n",
        "such that sum of rewards beyond any leaf at that depth is less than $\\epsilon$. \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function U(s)\" : \"agent's preferences, assigns a single number to a state\", \n",
        "\"expected utility EU(a)\" : \"average utility value of the outcomes, weighted by prob that outcome occurs\", \n",
        "\"maximum expected utility (MEU)\" : \"rational agent should choose action that maximizes agent's EU\", \n",
        "\"orderability\" : \"Exactly one of (A ≻ B), (B ≻ A), or (A ∼ B) holds\", \n",
        "\"transitivity\" : \"(A ≻ B)∧(B ≻ C) ⇒ (A ≻ C)\", \n",
        "\"continuity\" : \"A ≻ B ≻ C ⇒ ∃ p [p,A; 1− p,C] ∼ B\",\n",
        "\"suitability\" : \"A ∼ B ⇒ [p,A; 1− p,C] ∼ [p,B; 1− p,C]\", \n",
        "\"monotonicity\" : \"A ≻ B ⇒ (p > q ⇔ [p,A; 1− p,B] ≻ [q,A; 1−q,B])\", \n",
        "\"decomposability\" : \"[p,A; 1− p,[q,B; 1−q,C]] ∼ [p,A; (1− p)q,B; (1− p)(1−q),C]\", \n",
        "\"preference elicitation\" : \"understanding a human's utility function\",\n",
        "\"Markovian\": \"probability of reaching the next state from the current state only \\\n",
        "depends on the current state\", \n",
        "\"policy\" : \"solution to an MDP; description of a simple reflex agent\",\n",
        "\"optimal policy\" : \"yields the highest expected utility for an agent\", \n",
        "\"nonstationary policy\" : \"policy that depends on time; finite horizon\", \n",
        "\"stationary policy\" : \"no time limit; infinite horizon\", \n",
        "\"discount factor\" : \"$\\gamma$, between 0 and 1. preference for current over future rewards\",\n",
        "\"action-utility function\" : \"Q-function, the expected utility of taking an action in a state\", \n",
        "\"shaping theorem\" : \"This leaves optimal policy unchanged. $R'(s,a,s') = R(s,a,s') + \\gamma \\Phi(s') - \\Phi(s)$\",\n",
        "\"Dynamic Decision Networks\" : \"factored representations\", \n",
        "\"value iteration\" : \"solve n Bellman equations for utilities\", \n",
        "\"policy iteration\" : \"policy evaluation + policy improvement\", \n",
        "\"policy evaluation\" : \"given a policy $\\pi$, calcualte the utility of each state under $\\pi$\", \n",
        "\"policy improvement\" : \"calculate new MEU policy based on new utilities\",\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 31,
      "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": 1145
        },
        "outputId": "768583d8-f2da-48a3-88f2-e0e341266933"
      },
      "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": 32,
      "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 Decision-theoretic agent makes rational decisions based on \nwhat it believes and what it wants. Probability of reachign s' by doing a \nin the current state = P(result(a) = s') = sum(over all s) of P(s)P(s' | s,a).\nDecision theory chooses among actions based on the desirability of their \nimmediate outcomes - environment assumed to be episodic. \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Set of outcomes for each action is a lottery of outcomes \nwith probabilities. Each outcome is either an atomic state or another lottery. \nUtility theory understands how preferences between complex lotteries\nare related to preferences between underlying states in those lotteries. \nAxioms: orderability, transitivity, continuity, suitability, monotonicity, \ndecomposability. From axioms: existence of utility function (U(A) > U(B) ⇔ A ≻ B and U(A) = U(B) ⇔ A ∼ B) \nand expected utility of a lottery is the sum of the probability of each outcome * \nutility of that outcome.  \n\n## AIMA Chapter 16.3 Utility Functions\n Utility functions map from lotteries to real numbers. For\nthe utility of money, utility is not proportional to monetary value. \nRisk-averse vs. risk-seeking behavior. Certainty equivalent is the value\nthat an agent will accept in lieu of a lottery; insurance premium is \nthe difference between an expected monetary value of a lottery and its\ncertainty equivalent. Real outcomes are usually worse than expected, due to \nselecting actions with highest utility estimate, favoring overly optimistic\nestimates. More choices, more optimistic estimates. Descriptive theory (describes\n how actual agents act) are affected by certainty effect, ambiguity \n evasion, framing effect, anchoring effect.  \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n MDPs are sequential dcision problems for fully observable, stochastic environments with a Markovian transition model and additive rewards. Reward is bound by +/- Rmax, utility function depends on environment history. Additive discounted rewards: $U = R(s_0,a_0,s_1) + \\gamma R(s_1,a_1,s_2) + \\gamma^2 R(s_2,a_2,s_3) + ...$ $\\gamma$: 0 if rewards in distant future are insignificant. Comparing policies: compare expected policies, $U^{\\pi}(s) = E[\\sum_{t=0}^{\\inf}\\gamma^t R(S_t,\\pi (S_t),S_{t+1})]$ Optimal policy: $\\pi^*(s) = argmax \\sum_{s'}P(s'|s,a)[R(s,a,s') + \\gamma U(s')]$ Utility of a state is same, but find is the max action (Bellman equation). Q-function: $\\sum_{s'}P(s'|s,a)[R(s,a,s')+ \\gamma max_{a'}Q(s',a')]$.\n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Value iteration: n possible states, n Bellman equation with n unknowns (utilities of the states). Solve simultaneously for utilities. Iterative step: Bellman update, for all states at each iteration. Will reach an equilibrium with unique solutions to the Bellman equations due to the update being a contraction by a factor of $\\gamma$; converges when $\\gamma < 1$. Stop iteration when update is small. Policy iteration.. policy evaluation: given a policy, calculate utility of each state if the policy is executed. Simplified Bellman equation. policy improvement: calculate a new MEU policy using one-step look-ahead based on new utilities. Terminate when policy improvement yields no change in utilities. Linear programming: consider as variables in the LP the utilities U(s) for each state s; minimize utilities for all states. Online algorithms: use expectimax with rewards on nonterminal nodes and terminal transitions. Decision extracted from search tree by backing up utility values from leaves. $\\epsilon$ horizon: tree depth H such that sum of rewards beyond any leaf at that depth is less than $\\epsilon$. \n\n## Module 8 Lecture Notes\n Your summary here \n\n## Module 8 Definitions\n* **Markovian** - probability of reaching the next state from the current state only depends on the current state\n* **Policy** - solution to an MDP; description of a simple reflex agent\n* **Optimal policy** - yields the highest expected utility for an agent\n* **Nonstationary policy** - policy that depends on time; finite horizon\n* **Stationary policy** - no time limit; infinite horizon\n* **Discount factor** - $\\gamma$, between 0 and 1. preference for current over future rewards\n* **Action-utility function** - Q-function, the expected utility of taking an action in a state\n* **Shaping theorem** - This leaves optimal policy unchanged. $R'(s,a,s') = R(s,a,s') + \\gamma \\Phi(s') - \\Phi(s)$\n* **Dynamic decision networks** - factored representations\n* **Value iteration** - solve n Bellman equations for utilities\n* **Policy iteration** - policy evaluation + policy improvement\n* **Policy evaluation** - given a policy $\\pi$, calcualte the utility of each state under $\\pi$\n* **Policy improvement** - calculate new MEU policy based on new utilities\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 =  \"\"\" n-armed bandit arms are each MRPs. Overall problem is an MDP. \\\n",
        "Arms are independent and agent can only work one arm at a time. One-armed bandit: \\\n",
        "pull for arbitrary sequence, or not pull to lose reward of $\\lambda$ each time. \\\n",
        "Optimal strategy: run arm M up to tim T, then switch to no pull for the rest of \\\n",
        "the time. $\\lambda$ for optimal strategy indifferent from above and choosing \\\n",
        "no pull immediately: Gittins index, $\\lambda = max_{T>0} (E(\\sum_{t=0}^{T-1} \\gamma^t R_t))/(E(\\sum_{t=0}^{T-1} \\gamma^t)$ \\\n",
        "Optimal policy: pull arm with highest Gittins index, then update Gittins indices. \\\n",
        "O(n) first iteration, each decision after is O(1) time. Bernoulli bandit: transition \\\n",
        "probability predicts next outcome to be 1 with probability $s_i / (s_i + f_i)$, \\\n",
        "$s$ is number of successes and $f$ is number of failures. Counts initialized to 1, \\\n",
        "no Gittins index bc infinitely many states. Solve truncated MDP with states up to \\\n",
        "total of 100 tries and $\\gamma$ = 0.9. Approximately optimal bandit policies: \\\n",
        "use upper confidence bound heuristic, $UCB(M_i) = \\hat{\\mu}_i + g(N)/\\sqrt(N_i)$, \\\n",
        "mean + function of total number of samples drawn from all arms * stdev. g(N) determines \\\n",
        "regret. Or use Thompson sampling: chooses an arm randomly according to the probability \\\n",
        "that the arm is optimal, given the samples so far. For BSPs, use opportunity cost \\\n",
        "(how much utility is given up per time step by not devoting that time step to another arm). \\\n",
        "Higher oc, more necessary to generate early rewards. \"\"\"\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 = \"\"\" MDPs is offline planning, where you need to know all the \\\n",
        "details. Reinforcement learning: MDP without transition or reward functions. \\\n",
        "Must learn to maximize expected rewards based on observed samples of outcomes. \\\n",
        "Still looking for policy. Model-based learning: based on experiences. Step 1: learn \\\n",
        "empirical MDP model by counting outcomes s' for each s,a; normalize for an estimate \\\n",
        "for T(s,a,s'), and discover each R(s,a,s') when we experience (s,a,s'). Step 2: \\\n",
        "solve the learned MDP. Passive reinforcement learning: input a fixed policy. \\\n",
        "Don't know T or R, so the goal is to learn the state values. To do so, try: direct \\\n",
        "evaluation (Every time you visit a state, write down what the sum of discounted rewards \\\n",
        "(from that state to the end) turned out to be. Avg those samples...bad bc wastes \\\n",
        "information about state connections.) or sample-based policy evaluation: improve \\\n",
        "estimate of utility function by taking samples of outcomes s' (by doing the action from \\\n",
        "the current state) and average. Temporal difference learning: update utility function \\\n",
        "estimate for s each time you experience transition (s,a,s',r) - likely outcomes s' \\\n",
        "will contribute updates more often. This moves values toward value of whatever \\\n",
        "successor occurs using a running average. $sample = R(s,\\pi(s),s') + \\gamma V^{\\pi}(s')$, \\\n",
        "update: $V^{\\pi}(s) = (1 - a)V(s) + a(sample)$. Note: V(s') is not \\\n",
        "looking forward all the way, it's just what V gives for s'. Problem: can't turn values \\\n",
        "into a new policy. Try learning Q-values, not values. Active reinforcement learning: \\\n",
        "Q-value iteration; start with $Q_0(s,a) = 0$, calculate $Q_{k+1}(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma max_{a'}Q_k(s'a')]$ \\\n",
        "Q-learning: receive sample (s,a,s',r), update $Q(s,a) = (1-alpha)Q(s,a) + (alpha)[R + \\gamma max_{a'}Q(s',a')]$ \\\n",
        "This is off-policy learning; will converge to optimal policy even if you act suboptimally. \\\n",
        "How to explore? random actions ($\\epsilon$-greedy) or exploration functions using \\\n",
        "value estimate and visit count n. Modified Q-update: instead of $Q(s',a')$, use \\\n",
        "$f(Q(s',a'),N(s',a'))$, where $f(u,n) = u + k/n$. If you value curiosity, N should be low. Approximate Q-learning: use feature \\\n",
        "representations to write a q-function for any state using a few weights. let \\\n",
        "difference = $[r + \\gamma max_{a'}Q(s',a') - Q(s,a)]$, $Q(s,a) = Q(s,a) + alpha(difference)$ \\\n",
        "and $w_i = w_i + alpha(difference)f_i(s,a)$\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"n-armed bandit\" : \"n levers with unknown prob distributions of winnings\",\n",
        "\"Markov Reward Process\" : \"MRP, a MDP with one action\",\n",
        "\"Gittins index\" : \"max possible utility per discounted time\", \n",
        "\"Bernoulli bandit\" : \"possible rewards are 0 or 1 with fixed and unknown prob\",\n",
        "\"selection problems\" : \"don't need to minimize test failures, just make good decision fast\",\n",
        "\"bandit superprocess\" : \"each arm full MDP rather than MRP\",\n",
        "\"regret\" : \"quantification of how many mistakes you made in the process of learning\",\n",
        "\"learning rate\" : \"for TDL and ARL, alpha (represented as a). Decreasing gives converging averages\",\n",
        "}"
      ],
      "execution_count": 33,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1161
        },
        "cellView": "form",
        "outputId": "4eb1f58d-bfb7-44f9-8d03-1d7a67904617"
      },
      "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": 34,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n n-armed bandit arms are each MRPs. Overall problem is an MDP. Arms are independent and agent can only work one arm at a time. One-armed bandit: pull for arbitrary sequence, or not pull to lose reward of $\\lambda$ each time. Optimal strategy: run arm M up to tim T, then switch to no pull for the rest of the time. $\\lambda$ for optimal strategy indifferent from above and choosing no pull immediately: Gittins index, $\\lambda = max_{T>0} (E(\\sum_{t=0}^{T-1} \\gamma^t R_t))/(E(\\sum_{t=0}^{T-1} \\gamma^t)$ Optimal policy: pull arm with highest Gittins index, then update Gittins indices. O(n) first iteration, each decision after is O(1) time. Bernoulli bandit: transition probability predicts next outcome to be 1 with probability $s_i / (s_i + f_i)$, $s$ is number of successes and $f$ is number of failures. Counts initialized to 1, no Gittins index bc infinitely many states. Solve truncated MDP with states up to total of 100 tries and $\\gamma$ = 0.9. Approximately optimal bandit policies: use upper confidence bound heuristic, $UCB(M_i) = \\hat{\\mu}_i + g(N)/\\sqrt(N_i)$, mean + function of total number of samples drawn from all arms * stdev. g(N) determines regret. Or use Thompson sampling: chooses an arm randomly according to the probability that the arm is optimal, given the samples so far. For BSPs, use opportunity cost (how much utility is given up per time step by not devoting that time step to another arm). Higher oc, more necessary to generate early rewards. \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 MDPs is offline planning, where you need to know all the details. Reinforcement learning: MDP without transition or reward functions. Must learn to maximize expected rewards based on observed samples of outcomes. Still looking for policy. Model-based learning: based on experiences. Step 1: learn empirical MDP model by counting outcomes s' for each s,a; normalize for an estimate for T(s,a,s'), and discover each R(s,a,s') when we experience (s,a,s'). Step 2: solve the learned MDP. Passive reinforcement learning: input a fixed policy. Don't know T or R, so the goal is to learn the state values. To do so, try: direct evaluation (Every time you visit a state, write down what the sum of discounted rewards (from that state to the end) turned out to be. Avg those samples...bad bc wastes information about state connections.) or sample-based policy evaluation: improve estimate of utility function by taking samples of outcomes s' (by doing the action from the current state) and average. Temporal difference learning: update utility function estimate for s each time you experience transition (s,a,s',r) - likely outcomes s' will contribute updates more often. This moves values toward value of whatever successor occurs using a running average. $sample = R(s,\\pi(s),s') + \\gamma V^{\\pi}(s')$, update: $V^{\\pi}(s) = (1 - a)V(s) + a(sample)$. Note: V(s') is not looking forward all the way, it's just what V gives for s'. Problem: can't turn values into a new policy. Try learning Q-values, not values. Active reinforcement learning: Q-value iteration; start with $Q_0(s,a) = 0$, calculate $Q_{k+1}(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma max_{a'}Q_k(s'a')]$ Q-learning: receive sample (s,a,s',r), update $Q(s,a) = (1-alpha)Q(s,a) + (alpha)[R + \\gamma max_{a'}Q(s',a')]$ This is off-policy learning; will converge to optimal policy even if you act suboptimally. How to explore? random actions ($\\epsilon$-greedy) or exploration functions using value estimate and visit count n. Modified Q-update: instead of $Q(s',a')$, use $f(Q(s',a'),N(s',a'))$, where $f(u,n) = u + k/n$. Approximate Q-learning: use feature representations to write a q-function for any state using a few weights. let difference = $[r + \\gamma max_{a'}Q(s',a') - Q(s,a)]$, $Q(s,a) = Q(s,a) + alpha(difference)$ and $w_i = w_i + alpha(difference)f_i(s,a)$\n\n## Module 9 Definitions\n* **N-armed bandit** - n levers with unknown prob distributions of winnings\n* **Markov reward process** - MRP, a MDP with one action\n* **Gittins index** - max possible utility per discounted time\n* **Bernoulli bandit** - possible rewards are 0 or 1 with fixed and unknown prob\n* **Selection problems** - don't need to minimize test failures, just make good decision fast\n* **Bandit superprocess** - each arm full MDP rather than MRP\n* **Regret** - quantification of how many mistakes you made in the process of learning\n* **Learning rate** - for TDL and ARL, alpha (represented as a). Decreasing gives converging averages\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 = \"\"\" A fully specified probability model associates P(w) \\\n",
        "with every possible world w. Inference by enumeration: select entries consistent \\\n",
        "with evidence, sum out hidden variables, normalize. Probabilistic LMs: use chain \\\n",
        "rule to estimate probabilities of upcoming words. Maximum likelihood estimation: \\\n",
        "(count of whole phrase incl upcoming word) / (count of given phrase). Need to know \\\n",
        "how much history to use: unigram, no history; $P(w_1w_2...w_n) = \\prod_i P(w_i)$. \\\n",
        "Bigram: 1 word as history, $P(w_i|w_1w_2...w_{i-1} = P(w|w_{i-1})$. MLE problems: \\\n",
        "out of vocabulary terms. Avoid zeros using smoothing. Also, do everything \\\n",
        "in log space for adding, and to avoid underflow. \"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"observed variables\" : \"evidence\",\n",
        "\"unobserved variables\" : \"states\", \n",
        "\"possible worlds\" : \"sample space, mutually exclusive and exhaustive\",\n",
        "\"probability distribution\" : \"table of probabilities of values\", \n",
        "\"joint distribution\" : \"real number fo an assignment of rvs; determine whether assignment is likely\",\n",
        "\"probabilistic model\" : \"joint distribution over a set of rvs\",\n",
        "\"marginal distribution\" : \"sub-tables that eliminate variables through summing\",\n",
        "\"conditional probability\" : \"$P(a|b) = P(a,b) / P(b)$\", \n",
        "\"probabilistic inference\" : \"get a desired probability from known probabilities\",\n",
        "\"chain rule\" : \"P(x,y,z) = P(x)P(y|x)P(z|x,y)\",\n",
        "\"Bayes' rule\" : \"P(x,y) + P(x|y)P(y) = P(y|x)P(x)\", \n",
        "}"
      ],
      "execution_count": 13,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1328
        },
        "cellView": "form",
        "outputId": "f22ade02-c7b1-4268-9148-8f8baee6feca"
      },
      "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": 14,
      "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 A fully specified probability model associates P(w) with every possible world w. Inference by enumeration: select entries consistent with evidence, sum out hidden variables, normalize. Probabilistic LMs: use chain rule to estimate probabilities of upcoming words. Maximum likelihood estimation: (count of whole phrase incl upcoming word) / (count of given phrase). Need to know how much history to use: unigram, no history; $P(w_1w_2...w_n) = \\prod_i P(w_i)$. Bigram: 1 word as history, $P(w_i|w_1w_2...w_{i-1} = P(w|w_{i-1})$. MLE problems: out of vocabulary terms. Avoid zeros using smoothing. Also, do everything in log space for adding, and to avoid underflow. \n\n## Module 10 Definitions\n* **Observed variables** - evidence\n* **Unobserved variables** - states\n* **Possible worlds** - sample space, mutually exclusive and exhaustive\n* **Probability distribution** - table of probabilities of values\n* **Joint distribution** - real number fo an assignment of rvs; determine whether assignment is likely\n* **Probabilistic model** - joint distribution over a set of rvs\n* **Marginal distribution** - sub-tables that eliminate variables through summing\n* **Conditional probability** - $P(a|b) = P(a,b) / P(b)$\n* **Probabilistic inference** - get a desired probability from known probabilities\n* **Chain rule** - P(x,y,z) = P(x)P(y|x)P(z|x,y)\n* **Bayes' rule** - P(x,y) + P(x|y)P(y) = P(y|x)P(x)\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" Use conditional independence to simplify chain rules. \\\n",
        "Bayes' Nets are a technique for describing complex joint distributions using local \\\n",
        "distributions (conditional probabilities). Notation: node is variables, can be assigned \\\n",
        "or unassigned. Arc is interactions; encode conditional independence. Semantics: set \\\n",
        "of nodes, one per variable x; BN is a directed, acyclic graph; there are conditional \\\n",
        "distributions for each node, one for each combination of parents' values. Sparse systems grow linearly in complexity! Probabilities \\\n",
        "in BNs: $P(x_1,x_2,...x_n) = \\prod_{i=1}^{n} P(x_i|parents(X_i))$; is a product \\\n",
        "of each $x_i$!! Note that BNs are not actually causal. BN size: (joint distribution \\\n",
        "over N boolean variables: $2^N$) N-node net if nodes have up to k parents: $O(N*2^{k+1})$. \\\n",
        "D-separation: look at ALL undirected paths between a and b. If one or more paths \\\n",
        "is active, then independence is not guaranteed; if all paths are inactive, then \\\n",
        "independence is guaranteed; a path is active if each triple is active. Use to \\\n",
        "build a complete list of conditional independencies that are necessarily true. \\\n",
        "Inference: calculate useful quantities from a joint probability distrubution. \\\n",
        "Inference by enumeration in a BN: conditional probabilities are replaced by \\\n",
        "those in a BN. See example on paper. This is slow bc have to join up the whole \\\n",
        "joint distribution before you sum out the hidden variables.\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"independence\" : \"x and y, if $P(x,y) = P(x)P(y)$ or $P(x|y) = P(x)$\",    \n",
        "\"conditional independence\" : \"x of y given z (X $\\perp$ Y | Z), if $P(x,y|z) = P(x|z)P(y|z)$ or P(x|z,y) = P(x|z)\",\n",
        "\n",
        "}\n"
      ],
      "execution_count": 15,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 606
        },
        "cellView": "form",
        "outputId": "7dd99b75-c480-4710-8a9c-5e39f35ed68a"
      },
      "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": 16,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n Use conditional independence to simplify chain rules. Bayes' Nets are a technique for describing complex joint distributions using local distributions (conditional probabilities). Notation: node is variables, can be assigned or unassigned. Arc is interactions; encode conditional independence. Semantics: set of nodes, one per variable x; BN is a directed, acyclic graph; there are conditional distributions for each node, one for each combination of parents' values. Probabilities in BNs: $P(x_1,x_2,...x_n) = \\prod_{i=1}^{n} P(x_i|parents(X_i))$; is a product of each $x_i$!! Note that BNs are not actually causal. BN size: (joint distribution over N boolean variables: $2^N$) N-node net if nodes have up to k parents: $O(N*2^{k+1})$. D-separation: look at ALL undirected paths between a and b. If one or more paths is active, then independence is not guaranteed; if all paths are inactive, then independence is guaranteed; a path is active if each triple is active. Use to build a complete list of conditional independencies that are necessarily true. Inference: calculate useful quantities from a joint probability distrubution. Inference by enumeration in a BN: conditional probabilities are replaced by those in a BN. See example on paper. This is slow bc have to join up the whole joint distribution before you sum out the hidden variables.\n\n## Module 11 Definitions\n* **Independence** - x and y, if $P(x,y) = P(x)P(y)$ or $P(x|y) = P(x)$\n* **Conditional independence** - x of y given z (X $\\perp$ Y | Z), if $P(x,y|z) = P(x|z)P(y|z)$ or P(x|z,y) = P(x|z)\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 = \"\"\" Model where both label and features are rvs. \\\n",
        "Naive Bayes: assume all features are independent effects of the label, \\\n",
        "$P(Y,F_1,...,F_n) = P(Y) \\prod_{i}P(F_i|Y)$. Inference goal: compute posterior \\\n",
        "distribution over label variable Y; 1. get joint prob of label & evidence. 2. \\\n",
        "sum to get probability of evidence. 3. normalize by dividing step 1 with 2. \\\n",
        "Need: estimates of local conditional tables, with P(Y), $P(F_i|Y)$ for each \\\n",
        "feature. Training: learn parameters on training set, tune hyperparameters on \\\n",
        "held-out set, compute accuracy of test set. Generalization: relative frequency (max likelihood)\\\n",
        "parameters overfit training data...zero probability is a problem. Need to smooth \\\n",
        "or regularize estimates using Laplace Smoothing (pretend you saw every outcome \\\n",
        "one or k more times than you actually did, or smooth each condition independently). \\\n",
        "Or: linear interpolation using alpha, $P_{LIN}(x|y) = a\\hat{P}(x|y) + (1-a)\\hat{P}(x)$ \\\n",
        "If errors: need more features. Baselines: help to know what a good accuracy is. \\\n",
        "Weak baseline: most frequent label classifier to all test instances; strong baseline: \\\n",
        "use previous work. Confidences: posterior over the top label, $confidence(x) = max_y P(y|x)$. \\\n",
        "No guarantee confidence is correct. Weak calibration: higher confidences lead to higher \\\n",
        "accuracy. Perceptrons! Linear classifiers, input is feature values. Each feature \\\n",
        "has a weight, and activation = $\\sum_i w_i (dot prod) f_i(x)$. Weight updates (binary \\\n",
        "perceptron): start with weights = 0, then for each training instance, classify \\\n",
        "with current states. If correct, no change. If wrong, adjust weight vector by \\\n",
        "adding/subtracting (if y* is -1) feature vector: $w = w + y^* (dot prod) f$. (multiclass \\\n",
        "perceptron): start with all weights = 0. for each training example, predict \\\n",
        "with current weights (dot prod). If wrong: $w_y = w_y - f(x)$ and $w_{y^*} = w_{y^*} + f(x)$. \\\n",
        "Properties: separable if some parameters get training set fully correct; converges \\\n",
        "if training is separable. Problems: noise, mediocre generalization, overtraining. \\\n",
        "Adjust weight update to mitigate these effects: MIRA*: choose update size tau \\\n",
        "where $w_y = w'_y - t f(x)$ and $w_{y^*} = w'_{y^*} + t f(x)$. Linear separators: \\\n",
        "support vector machines, find separator that maximizes margin. SVMs = MIRA \\\n",
        "where you optimize over all examples at once. \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"prior over label\" : \"P(Y)\",\n",
        "\"bag-of-words\" : \"Naive Bayes for text. All positions share same conditional probs\", \n",
        "\"overfitting\" : \"when the model fits training data, but can't generalize well\",\n",
        "\"maximum likelihood\" : \"of estimates; relative frequency. $P_{ML}(x) = count(x)/total samples$\",\n",
        "\"Laplace Smoothing\" : \"$P_{LAP}(x) = (c(x) + 1)/(N + |X|)$\", \n",
        "\"confidence\" : \"how sure classifier is of classificaiton\",\n",
        "\"parametric model\" : \"fixed size on the number of parameters\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 17,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1679
        },
        "cellView": "form",
        "outputId": "61eeada6-4230-4101-e40f-b0dab3d26a6f"
      },
      "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": 18,
      "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 Model where both label and features are rvs. Naive Bayes: assume all features are independent effects of the label, $P(Y,F_1,...,F_n) = P(Y) \\prod_{i}P(F_i|Y)$. Inference goal: compute posterior distribution over label variable Y; 1. get joint prob of label & evidence. 2. sum to get probability of evidence. 3. normalize by dividing step 1 with 2. Need: estimates of local conditional tables, with P(Y), $P(F_i|Y)$ for each feature. Training: learn parameters on training set, tune hyperparameters on held-out set, compute accuracy of test set. Generalization: relative frequency (max likelihood)parameters overfit training data...zero probability is a problem. Need to smooth or regularize estimates using Laplace Smoothing (pretend you saw every outcome one or k more times than you actually did, or smooth each condition independently). Or: linear interpolation using alpha, $P_{LIN}(x|y) = a\\hat{P}(x|y) + (1-a)\\hat{P}(x)$ If errors: need more features. Baselines: help to know what a good accuracy is. Weak baseline: most frequent label classifier to all test instances; strong baseline: use previous work. Confidences: posterior over the top label, $confidence(x) = max_y P(y|x)$. No guarantee confidence is correct. Weak calibration: higher confidences lead to higher accuracy. Perceptrons! Linear classifiers, input is feature values. Each feature has a weight, and activation = $\\sum_i w_i (dot prod) f_i(x)$. Weight updates (binary perceptron): start with weights = 0, then for each training instance, classify with current states. If correct, no change. If wrong, adjust weight vector by adding/subtracting (if y* is -1) feature vector: $w = w + y^* (dot prod) f$. (multiclass perceptron): start with all weights = 0. for each training example, predict with current weights (dot prod). If wrong: $w_y = w_y - f(x)$ and $w_{y^*} = w_{y^*} + f(x)$. Properties: separable if some parameters get training set fully correct; converges if training is separable. Problems: noise, mediocre generalization, overtraining. Adjust weight update to mitigate these effects: MIRA*: choose update size tau where $w_y = w'_y - t f(x)$ and $w_{y^*} = w'_{y^*} + t f(x)$. Linear separators: support vector machines, find separator that maximizes margin. SVMs = MIRA where you optimize over all examples at once. \n\n## Module 12 Definitions\n* **Prior over label** - P(Y)\n* **Bag-of-words** - Naive Bayes for text. All positions share same conditional probs\n* **Overfitting** - when the model fits training data, but can't generalize well\n* **Maximum likelihood** - of estimates; relative frequency. $P_{ML}(x) = count(x)/total samples$\n* **Laplace smoothing** - $P_{LAP}(x) = (c(x) + 1)/(N + |X|)$\n* **Confidence** - how sure classifier is of classificaiton\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 = \"\"\" ML classifiers require a training corpus of observations. \\\n",
        "Classification function: logistic regression learns a vector of weights and bias, \\\n",
        "$z = w (dot) x + b$. Use sigmoid function to normalize output. Getting weights: \\\n",
        "loss function tells distance between system output and gold output. Use stochastic gradient \\\n",
        "descent algorithm for optimizing (minimizing) loss function. Cross entropy loss: \\\n",
        "$L_{CE}(\\hat{y},y) = -\\log P(y|x) = -[y\\log \\hat{y} + (1-y)\\log (1-\\hat{y})]$. \\\n",
        "Loss on all training examples: negative sum of all $L_{CE}(\\hat{y}^{(i)}|y^{(i)})$. \\\n",
        "Use gradient descent to find good parameters; update each parameter by old weight - \\\n",
        "$\\eta$ * value of slope. For many dimensions, update each dimension $w_i$. \\\n",
        "Derivative of $L_{CE}(w,b)$ wrt $w_i$ is $[\\sigma (w (dot) x + b) - y]x_j$, or \\\n",
        "(prediction - truth)*value of feature. We want to minimize average loss: sum of \\\n",
        "all $m$ $L_{CE}$ divided by $m$. Gradient for multiple data points is sum of \\\n",
        "individual gradients. Use regularization for overfitting - low-occurring features \\\n",
        "result in high weights that are penalized by regularization. For multinominal \\\n",
        "logistic regression, use softmax function instead of sigmoid. Neural Networks! \\\n",
        "Use sigmoid neurons for smoothness. FF NN: weight matrix & single bias vector for \\\n",
        "each hidden layer. hidden layer output = $h = \\sigma(Wx + b)$; intermediate output \\\n",
        "$z = Uh$ (weight matrix U). $y = softmax(z)$. Training neural nets: use cross-entropy \\\n",
        "loss and gradient descent. For gradient of loss function, use error propagation \\\n",
        "and computation graphs. \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"feature representation\" : \"vector of features for an input\",\n",
        "\"classification function\" : \"computes estimated class for an input\",\n",
        "\"objective function\" : \"loss function; for learning\",\n",
        "\"sigmoid function\" : \"$y = 1/(q+e^{-z})$\", \n",
        "\"learning rate\" : \"$\\eta$\", \n",
        "\"batch training\" : \"gradient descent over the entire dataset at once\", \n",
        "\"mini-batch training\" : \"train on small batches in parallel, loss accumulated\",\n",
        "\"softmax function\" : \"$ = e^{z_j}/(\\sum_{j=1}^{k} e^{z_j})$\", \n",
        "\"feed-foward neural network\" : \"multilayer, fully-connected, no cycles. outputs passed to units in next layer\",\n",
        "\n",
        "}\n"
      ],
      "execution_count": 26,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1428
        },
        "cellView": "form",
        "outputId": "766f7322-4d31-47a4-d9e6-cd029d9639fa"
      },
      "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": 27,
      "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 ML classifiers require a training corpus of observations. Classification function: logistic regression learns a vector of weights and bias, $z = w (dot) x + b$. Use sigmoid function to normalize output. Getting weights: loss function tells distance between system output and gold output. Use stochastic gradient descent algorithm for optimizing (minimizing) loss function. Cross entropy loss: $L_{CE}(\\hat{y},y) = -\\log P(y|x) = -[y\\log \\hat{y} + (1-y)\\log (1-\\hat{y})]$. Loss on all training examples: negative sum of all $L_{CE}(\\hat{y}^{(i)}|y^{(i)})$. Use gradient descent to find good parameters; update each parameter by old weight - $\\eta$ * value of slope. For many dimensions, update each dimension $w_i$. Derivative of $L_{CE}(w,b)$ wrt $w_i$ is $[\\sigma (w (dot) x + b) - y]x_j$, or (prediction - truth)*value of feature. We want to minimize average loss: sum of all $m$ $L_{CE}$ divided by $m$. Gradient for multiple data points is sum of individual gradients. Use regularization for overfitting - low-occurring features result in high weights that are penalized by regularization. For multinominal logistic regression, use softmax function instead of sigmoid. Neural Networks! Use sigmoid neurons for smoothness. FF NN: weight matrix & single bias vector for each hidden layer. hidden layer output = $h = \\sigma(Wx + b)$; intermediate output $z = Uh$ (weight matrix U). $y = softmax(z)$. Training neural nets: use cross-entropy loss and gradient descent. For gradient of loss function, use error propagation and computation graphs. \n\n## Module 13 Definitions\n* **Feature representation** - vector of features for an input\n* **Classification function** - computes estimated class for an input\n* **Objective function** - loss function; for learning\n* **Sigmoid function** - $y = 1/(q+e^{-z})$\n* **Learning rate** - $\\eta$\n* **Batch training** - gradient descent over the entire dataset at once\n* **Mini-batch training** - train on small batches in parallel, loss accumulated\n* **Softmax function** - $ = e^{z_j}/(\\sum_{j=1}^{k} e^{z_j})$\n* **Feed-foward neural network** - multilayer, fully-connected, no cycles. outputs passed to units in next layer\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 = \"\"\" Neural LMs: Associate each word in the vocab with a \\\n",
        "vector representation; express joint probability function of a word sequence in \\\n",
        "terms of the word vectors for the words in that sequences; simultaneously learn \\\n",
        "the word vectors and the parameters of the function. Probability function: product \\\n",
        "of conditional probabilities of the next word given the previous word using \\\n",
        "a FFNN. Training: using cross-entropy loss. Create mapping function C from any word \\\n",
        "in V onto $R^M$ (vector representing word). Store in a V-by-M matrix, initialize \\\n",
        "with singular value decomposition (SVD). Difficulties: too many parameters. \\\n",
        "Try generalizing. Vector semantics: vector space models. Term-document matrix \\\n",
        "value: how often that term occurred in that document. Vector L2 normalization: \\\n",
        "plot each normalized word by doc_x vs. doc_y plot, normalize by dividing by \\\n",
        "$||u||=\\sqrt{\\sum_{i=1}^n u_i^2}$. Term-term matrix value: how often a column \\\n",
        "term appears in a context window surrounding a row term. Defining a word's context: \\\n",
        "try using syntax. Or transform vectors using TF-IDF. Can get dense vectors by \\\n",
        "training a classifier: 1. treat target word and context as positive examples, \\\n",
        "2. randomly sample other words in the lexicon to get negative samples, 3. \\\n",
        "use logistic regression to train a classifier to distinguish these cases, \\\n",
        "4. use weights as embeddings. Word2Vec: uses skip-gram with negative sampling \\\n",
        "for training positive or negative samples. Want to use to maximize similarity of \\\n",
        "target word, context word (t,c) pairs from positive data and minimize similarity \\\n",
        "of (t,c) pairs from negative data. Objective criteria: to maximize \\\n",
        "$\\sum_{(t,c) \\in +} \\log P(+|t,c) + \\sum_{(t,c) \\in -} \\log P(-|t,c)$ \\\n",
        "To compute P(+|t,c): \\\n",
        "similarity(t,c) approximately t (dot) c, then squash with sigmoid. \\\n",
        "Do for all context words and multiply them together (assume context words are \\\n",
        "independent); can use logs to sum. Noise words are chosen using a weighted \\\n",
        "unigram frequency, alpha = 3/4 (P(w) = count(w)^(alpha) / sum of count(w)^(alpha)). \\\n",
        "Evaluating embeddings: intrinsic evaluation, Kentall's tau = (number of concordant pairs – \\\n",
        "number of discordant pairs)/ (total pairs = N(N-1)/2). \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"TF-IDF\" : \"term frequency * inverse document frequency\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 28,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1170
        },
        "outputId": "fc5b317e-6889-4b59-8583-d67069ba290b"
      },
      "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": 29,
      "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 ML classifiers require a training corpus of observations. Classification function: logistic regression learns a vector of weights and bias, $z = w (dot) x + b$. Use sigmoid function to normalize output. Getting weights: loss function tells distance between system output and gold output. Use stochastic gradient descent algorithm for optimizing (minimizing) loss function. Cross entropy loss: $L_{CE}(\\hat{y},y) = -\\log P(y|x) = -[y\\log \\hat{y} + (1-y)\\log (1-\\hat{y})]$. Loss on all training examples: negative sum of all $L_{CE}(\\hat{y}^{(i)}|y^{(i)})$. Use gradient descent to find good parameters; update each parameter by old weight - $\\eta$ * value of slope. For many dimensions, update each dimension $w_i$. Derivative of $L_{CE}(w,b)$ wrt $w_i$ is $[\\sigma (w (dot) x + b) - y]x_j$, or (prediction - truth)*value of feature. We want to minimize average loss: sum of all $m$ $L_{CE}$ divided by $m$. Gradient for multiple data points is sum of individual gradients. Use regularization for overfitting - low-occurring features result in high weights that are penalized by regularization. For multinominal logistic regression, use softmax function instead of sigmoid. Neural Networks! Use sigmoid neurons for smoothness. FF NN: weight matrix & single bias vector for each hidden layer. hidden layer output = $h = \\sigma(Wx + b)$; intermediate output $z = Uh$ (weight matrix U). $y = softmax(z)$. Training neural nets: use cross-entropy loss and gradient descent. For gradient of loss function, use error propagation and computation graphs. \n\n## Module 14 Definitions\n* **Tf-idf** - term frequency * inverse document frequency\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": 8167
        },
        "id": "T3cm1WV542_a",
        "outputId": "657ee89d-efd5-4556-eb7b-0b615b7dc6bd"
      },
      "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": 30,
      "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 MDPs are sequential dcision problems for fully observable, stochastic environments with a Markovian transition model and additive rewards. Reward is bound by +/- Rmax, utility function depends on environment history. Additive discounted rewards: $U = R(s_0,a_0,s_1) + \\gamma R(s_1,a_1,s_2) + \\gamma^2 R(s_2,a_2,s_3) + ...$ $\\gamma$: 0 if rewards in distant future are insignificant. Comparing policies: compare expected policies, $U^{\\pi}(s) = E[\\sum_{t=0}^{\\inf}\\gamma^t R(S_t,\\pi (S_t),S_{t+1})]$ Optimal policy: $\\pi^*(s) = argmax \\sum_{s'}P(s'|s,a)[R(s,a,s') + \\gamma U(s')]$ Utility of a state is same, but find is the max action (Bellman equation). Q-function: $\\sum_{s'}P(s'|s,a)[R(s,a,s')+ \\gamma max_{a'}Q(s',a')]$.\n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Value iteration: n possible states, n Bellman equation with n unknowns (utilities of the states). Solve simultaneously for utilities. Iterative step: Bellman update, for all states at each iteration. Will reach an equilibrium with unique solutions to the Bellman equations due to the update being a contraction by a factor of $\\gamma$; converges when $\\gamma < 1$. Stop iteration when update is small. Policy iteration.. policy evaluation: given a policy, calculate utility of each state if the policy is executed. Simplified Bellman equation. policy improvement: calculate a new MEU policy using one-step look-ahead based on new utilities. Terminate when policy improvement yields no change in utilities. Linear programming: consider as variables in the LP the utilities U(s) for each state s; minimize utilities for all states. Online algorithms: use expectimax with rewards on nonterminal nodes and terminal transitions. Decision extracted from search tree by backing up utility values from leaves. $\\epsilon$ horizon: tree depth H such that sum of rewards beyond any leaf at that depth is less than $\\epsilon$. \n\n## Module 8 Lecture Notes\n Your summary here \n\n## Module 8 Definitions\n* **Markovian** - probability of reaching the next state from the current state only depends on the current state\n* **Policy** - solution to an MDP; description of a simple reflex agent\n* **Optimal policy** - yields the highest expected utility for an agent\n* **Nonstationary policy** - policy that depends on time; finite horizon\n* **Stationary policy** - no time limit; infinite horizon\n* **Discount factor** - $\\gamma$, between 0 and 1. preference for current over future rewards\n* **Action-utility function** - Q-function, the expected utility of taking an action in a state\n* **Shaping theorem** - This leaves optimal policy unchanged. $R'(s,a,s') = R(s,a,s') + \\gamma \\Phi(s') - \\Phi(s)$\n* **Dynamic decision networks** - factored representations\n* **Value iteration** - solve n Bellman equations for utilities\n* **Policy iteration** - policy evaluation + policy improvement\n* **Policy evaluation** - given a policy $\\pi$, calcualte the utility of each state under $\\pi$\n* **Policy improvement** - calculate new MEU policy based on new utilities\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n n-armed bandit arms are each MRPs. Overall problem is an MDP. Arms are independent and agent can only work one arm at a time. One-armed bandit: pull for arbitrary sequence, or not pull to lose reward of $\\lambda$ each time. Optimal strategy: run arm M up to tim T, then switch to no pull for the rest of the time. $\\lambda$ for optimal strategy indifferent from above and choosing no pull immediately: Gittins index, $\\lambda = max_{T>0} \frac{E(\\sum_{t=0}^{T-1} \\gamma^t R_t)}{E(\\sum_{t=0}^{T-1} \\gamma^t}$ Optimal policy: pull arm with highest Gittins index, then update Gittins indices. O(n) first iteration, each decision after is O(1) time. Bernoulli bandit: transition probability predicts next outcome to be 1 with probability $s_i / (s_i + f_i)$, $s$ is number of successes and $f$ is number of failures. Counts initialized to 1, no Gittins index bc infinitely many states. Solve truncated MDP with states up to total of 100 tries and $\\gamma$ = 0.9. Approximately optimal bandit policies: use upper confidence bound heuristic, $UCB(M_i) = \\hat{\\mu}_i + g(N)/\\sqrt(N_i)$, mean + function of total number of samples drawn from all arms * stdev. g(N) determines regret. Or use Thompson sampling: chooses an arm randomly according to the probability that the arm is optimal, given the samples so far. For BSPs, use opportunity cost (how much utility is given up per time step by not devoting that time step to another arm). Higher oc, more necessary to generate early rewards. \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 MDPs is offline planning, where you need to know all the details. Reinforcement learning: MDP without transition or reward functions. Must learn to maximize expected rewards based on observed samples of outcomes. Still looking for policy. Model-based learning: based on experiences. Step 1: learn empirical MDP model by counting outcomes s' for each s,a; normalize for an estimate for T(s,a,s'), and discover each R(s,a,s') when we experience (s,a,s'). Step 2: solve the learned MDP. Passive reinforcement learning: input a fixed policy. Don't know T or R, so the goal is to learn the state values. To do so, try: direct evaluation (Every time you visit a state, write down what the sum of discounted rewards (from that state to the end) turned out to be. Avg those samples...bad bc wastes information about state connections.) or sample-based policy evaluation: improve estimate of utility function by taking samples of outcomes s' (by doing the action from the current state) and average. Temporal difference learning: update utility function estimate for s each time you experience transition (s,a,s',r) - likely outcomes s' will contribute updates more often. This moves values toward value of whatever successor occurs using a running average. $sample = R(s,\\pi(s),s') + \\gamma V^{\\pi}(s')$, update: $V^{\\pi}(s) = (1 - a)V(s) + a(sample)$. Note: V(s') is not looking forward all the way, it's just what V gives for s'. Problem: can't turn values into a new policy. Try learning Q-values, not values. Active reinforcement learning: Q-value iteration; start with $Q_0(s,a) = 0$, calculate $Q_{k+1}(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma max_{a'}Q_k(s'a')]$ Q-learning: receive sample (s,a,s',r), update $Q(s,a) = (1-alpha)Q(s,a) + (alpha)[R + \\gamma max_{a'}Q(s',a')]$ This is off-policy learning; will converge to optimal policy even if you act suboptimally. How to explore? random actions ($\\epsilon$-greedy) or exploration functions using value estimate and visit count n. Modified Q-update: instead of $Q(s',a')$, use $f(Q(s',a'),N(s',a'))$, where $f(u,n) = u + k/n$. Approximate Q-learning: use feature representations to write a q-function for any state using a few weights. let difference = $[r + \\gamma max_{a'}Q(s',a') - Q(s,a)]$, $Q(s,a) = Q(s,a) + alpha(difference)$ and $w_i = w_i + alpha(difference)f_i(s,a)$\n\n## Module 9 Definitions\n* **N-armed bandit** - n levers with unknown prob distributions of winnings\n* **Markov reward process** - MRP, a MDP with one action\n* **Gittins index** - max possible utility per discounted time\n* **Bernoulli bandit** - possible rewards are 0 or 1 with fixed and unknown prob\n* **Selection problems** - don't need to minimize test failures, just make good decision fast\n* **Bandit superprocess** - each arm full MDP rather than MRP\n* **Regret** - quantification of how many mistakes you made in the process of learning\n* **Learning rate** - for TDL and ARL, alpha (represented as a). Decreasing gives converging averages\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 A fully specified probability model associates P(w) with every possible world w. Inference by enumeration: select entries consistent with evidence, sum out hidden variables, normalize. Probabilistic LMs: use chain rule to estimate probabilities of upcoming words. Maximum likelihood estimation: (count of whole phrase incl upcoming word) / (count of given phrase). Need to know how much history to use: unigram, no history; $P(w_1w_2...w_n) = \\prod_i P(w_i)$. Bigram: 1 word as history, $P(w_i|w_1w_2...w_{i-1} = P(w|w_{i-1})$. MLE problems: out of vocabulary terms. Avoid zeros using smoothing. Also, do everything in log space for adding, and to avoid underflow. \n\n## Module 10 Definitions\n* **Observed variables** - evidence\n* **Unobserved variables** - states\n* **Possible worlds** - sample space, mutually exclusive and exhaustive\n* **Probability distribution** - table of probabilities of values\n* **Joint distribution** - real number fo an assignment of rvs; determine whether assignment is likely\n* **Probabilistic model** - joint distribution over a set of rvs\n* **Marginal distribution** - sub-tables that eliminate variables through summing\n* **Conditional probability** - $P(a|b) = P(a,b) / P(b)$\n* **Probabilistic inference** - get a desired probability from known probabilities\n* **Chain rule** - P(x,y,z) = P(x)P(y|x)P(z|x,y)\n* **Bayes' rule** - P(x,y) + P(x|y)P(y) = P(y|x)P(x)\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n Use conditional independence to simplify chain rules. Bayes' Nets are a technique for describing complex joint distributions using local distributions (conditional probabilities). Notation: node is variables, can be assigned or unassigned. Arc is interactions; encode conditional independence. Semantics: set of nodes, one per variable x; BN is a directed, acyclic graph; there are conditional distributions for each node, one for each combination of parents' values. Probabilities in BNs: $P(x_1,x_2,...x_n) = \\prod_{i=1}^{n} P(x_i|parents(X_i))$; is a product of each $x_i$!! Note that BNs are not actually causal. BN size: (joint distribution over N boolean variables: $2^N$) N-node net if nodes have up to k parents: $O(N*2^{k+1})$. D-separation: look at ALL undirected paths between a and b. If one or more paths is active, then independence is not guaranteed; if all paths are inactive, then independence is guaranteed; a path is active if each triple is active. Use to build a complete list of conditional independencies that are necessarily true. Inference: calculate useful quantities from a joint probability distrubution. Inference by enumeration in a BN: conditional probabilities are replaced by those in a BN. See example on paper. This is slow bc have to join up the whole joint distribution before you sum out the hidden variables.\n\n## Module 11 Definitions\n* **Independence** - x and y, if $P(x,y) = P(x)P(y)$ or $P(x|y) = P(x)$\n* **Conditional independence** - x of y given z (X $\\perp$ Y | Z), if $P(x,y|z) = P(x|z)P(y|z)$ or P(x|z,y) = P(x|z)\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 Model where both label and features are rvs. Naive Bayes: assume all features are independent effects of the label, $P(Y,F_1,...,F_n) = P(Y) \\prod_{i}P(F_i|Y)$. Inference goal: compute posterior distribution over label variable Y; 1. get joint prob of label & evidence. 2. sum to get probability of evidence. 3. normalize by dividing step 1 with 2. Need: estimates of local conditional tables, with P(Y), $P(F_i|Y)$ for each feature. Training: learn parameters on training set, tune hyperparameters on held-out set, compute accuracy of test set. Generalization: relative frequency (max likelihood)parameters overfit training data...zero probability is a problem. Need to smooth or regularize estimates using Laplace Smoothing (pretend you saw every outcome one or k more times than you actually did, or smooth each condition independently). Or: linear interpolation using alpha, $P_{LIN}(x|y) = a\\hat{P}(x|y) + (1-a)\\hat{P}(x)$ If errors: need more features. Baselines: help to know what a good accuracy is. Weak baseline: most frequent label classifier to all test instances; strong baseline: use previous work. Confidences: posterior over the top label, $confidence(x) = max_y P(y|x)$. No guarantee confidence is correct. Weak calibration: higher confidences lead to higher accuracy. Perceptrons! Linear classifiers, input is feature values. Each feature has a weight, and activation = $\\sum_i w_i (dot prod) f_i(x)$. Weight updates (binary perceptron): start with weights = 0, then for each training instance, classify with current states. If correct, no change. If wrong, adjust weight vector by adding/subtracting (if y* is -1) feature vector: $w = w + y^* (dot prod) f$. (multiclass perceptron): start with all weights = 0. for each training example, predict with current weights (dot prod). If wrong: $w_y = w_y - f(x)$ and $w_{y^*} = w_{y^*} + f(x)$. Properties: separable if some parameters get training set fully correct; converges if training is separable. Problems: noise, mediocre generalization, overtraining. Adjust weight update to mitigate these effects: MIRA*: choose update size tau where $w_y = w'_y - t f(x)$ and $w_{y^*} = w'_{y^*} + t f(x)$. Linear separators: support vector machines, find separator that maximizes margin. SVMs = MIRA where you optimize over all examples at once. \n\n## Module 12 Definitions\n* **Prior over label** - P(Y)\n* **Bag-of-words** - Naive Bayes for text. All positions share same conditional probs\n* **Overfitting** - when the model fits training data, but can't generalize well\n* **Maximum likelihood** - of estimates; relative frequency. $P_{ML}(x) = count(x)/total samples$\n* **Laplace smoothing** - $P_{LAP}(x) = (c(x) + 1)/(N + |X|)$\n* **Confidence** - how sure classifier is of classificaiton\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 ML classifiers require a training corpus of observations. Classification function: logistic regression learns a vector of weights and bias, $z = w (dot) x + b$. Use sigmoid function to normalize output. Getting weights: loss function tells distance between system output and gold output. Use stochastic gradient descent algorithm for optimizing (minimizing) loss function. Cross entropy loss: $L_{CE}(\\hat{y},y) = -\\log P(y|x) = -[y\\log \\hat{y} + (1-y)\\log (1-\\hat{y})]$. Loss on all training examples: negative sum of all $L_{CE}(\\hat{y}^{(i)}|y^{(i)})$. Use gradient descent to find good parameters; update each parameter by old weight - $\\eta$ * value of slope. For many dimensions, update each dimension $w_i$. Derivative of $L_{CE}(w,b)$ wrt $w_i$ is $[\\sigma (w (dot) x + b) - y]x_j$, or (prediction - truth)*value of feature. We want to minimize average loss: sum of all $m$ $L_{CE}$ divided by $m$. Gradient for multiple data points is sum of individual gradients. Use regularization for overfitting - low-occurring features result in high weights that are penalized by regularization. For multinominal logistic regression, use softmax function instead of sigmoid. Neural Networks! Use sigmoid neurons for smoothness. FF NN: weight matrix & single bias vector for each hidden layer. hidden layer output = $h = \\sigma(Wx + b)$; intermediate output $z = Uh$ (weight matrix U). $y = softmax(z)$. Training neural nets: use cross-entropy loss and gradient descent. For gradient of loss function, use error propagation and computation graphs. \n\n## Module 13 Definitions\n* **Feature representation** - vector of features for an input\n* **Classification function** - computes estimated class for an input\n* **Objective function** - loss function; for learning\n* **Sigmoid function** - $y = 1/(q+e^{-z})$\n* **Learning rate** - $\\eta$\n* **Batch training** - gradient descent over the entire dataset at once\n* **Mini-batch training** - train on small batches in parallel, loss accumulated\n* **Softmax function** - $ = e^{z_j}/(\\sum_{j=1}^{k} e^{z_j})$\n* **Feed-foward neural network** - multilayer, fully-connected, no cycles. outputs passed to units in next layer\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 ML classifiers require a training corpus of observations. Classification function: logistic regression learns a vector of weights and bias, $z = w (dot) x + b$. Use sigmoid function to normalize output. Getting weights: loss function tells distance between system output and gold output. Use stochastic gradient descent algorithm for optimizing (minimizing) loss function. Cross entropy loss: $L_{CE}(\\hat{y},y) = -\\log P(y|x) = -[y\\log \\hat{y} + (1-y)\\log (1-\\hat{y})]$. Loss on all training examples: negative sum of all $L_{CE}(\\hat{y}^{(i)}|y^{(i)})$. Use gradient descent to find good parameters; update each parameter by old weight - $\\eta$ * value of slope. For many dimensions, update each dimension $w_i$. Derivative of $L_{CE}(w,b)$ wrt $w_i$ is $[\\sigma (w (dot) x + b) - y]x_j$, or (prediction - truth)*value of feature. We want to minimize average loss: sum of all $m$ $L_{CE}$ divided by $m$. Gradient for multiple data points is sum of individual gradients. Use regularization for overfitting - low-occurring features result in high weights that are penalized by regularization. For multinominal logistic regression, use softmax function instead of sigmoid. Neural Networks! Use sigmoid neurons for smoothness. FF NN: weight matrix & single bias vector for each hidden layer. hidden layer output = $h = \\sigma(Wx + b)$; intermediate output $z = Uh$ (weight matrix U). $y = softmax(z)$. Training neural nets: use cross-entropy loss and gradient descent. For gradient of loss function, use error propagation and computation graphs. \n\n## Module 14 Definitions\n* **Tf-idf** - term frequency * inverse document frequency\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}