{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of Template_for CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b75752bd-fffa-4cb3-e7ab-796d78510b5e"
      },
      "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": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "8f1ec18d-126a-4398-8559-fce080da84dd"
      },
      "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": 2,
      "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": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" Chapter 16.1 summary. \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\"\n",
        "10/12/21: MDP (part1 1) \n",
        "-up until now… deterministic (you know the exact result of your actions)  now.. Stochastic\n",
        "\n",
        "-Stochastic Transition Model are Markovian: prob of arriving at s’ ONLY depends on s and not history of earlier states\n",
        "\t-P(s’|s,a)\n",
        "\n",
        "-Utility/Reward Function\n",
        "\t-R(s,a,s’)\t\n",
        "\t-apply reward function to sequence of states and actions\n",
        "\t-agent receives reward at each time step \n",
        "\t-rewards are additive\n",
        "\n",
        "-Markov Decision Process (non-deterministic search problems)\n",
        "\t-a sequential decision problem\n",
        "\t-for fully obervable environment\n",
        "\t-w/ stochastic transition model\n",
        "\t-has additive rewards\n",
        "\n",
        "\t-DEFINE the following:\t\t\n",
        "\t\t1) set of states: s ∈ S\n",
        "\t\t2) set of actions: a ∈ A\n",
        "\t\t3) transition function: T(s,a,s’)\n",
        "\t\t\t-prob that executing action a in s will lead to s’: P(s’ | s,a)\n",
        "\t\t\t-prob is called the model\n",
        "\t\t4) reward function: R(s,a,s’)\n",
        "\t\t\t-sometimes just R(s) or R(s’)\n",
        "\t\t5) initial state: s0\n",
        "\t\t6) OPTIONAL: one or more terminal states\n",
        "\n",
        "-Solution == Policy  b/c non-determinisim of MDP\n",
        "\t-policy: maps from state onto action to take if the agent is in that state\n",
        "\t-tells agent what action to take at a given state\n",
        "\t- π(s) = a\n",
        "\t- π* = optimal policy\t\n",
        "\t-expected utility: of all possible paths generated by policy (b/c stochastic)\n",
        "\n",
        "\n",
        "-Sequences of Rewards: performance of an agent - sum of the rewards for the transitions it takes\n",
        "\t-Uh([s0,a0, s1,a1,…,  sn]) = R(s0,a0,s1) + R(ss,as,s2) + .. + R(sn-1,an-1,sn)\n",
        "\t-more or less?\n",
        "\t-now or later?\n",
        "\n",
        "\t-Discounting: value of rewards decay in the future (TIME VALUE)  each step, multiply by discount once\n",
        "-sooner reward > later reward\n",
        "\t\t-helps algorithms converge\n",
        "\n",
        "-Stationary Preferences: assuming stationary preferences, additive and discounted utility definitions the same\n",
        "\n",
        "-Additive Utilies & Discounted Utilieies\n",
        "-Problem: Infinite Utilities: what if game lasts forever  infinite rewards? NO\n",
        "-Solutions:\n",
        "\t1) (BAD) Finite horizon (like depth limited search): terminate episodes after fixed # of steps\n",
        "\t\t-gives nonstationary policies (pi depends on time left)\n",
        "2) (GOOD) Discounting using 0 < λ< 1 \n",
        "3) Absorbing state: guarantee that for every policy, a terminal state will eventually be reached\n",
        "\n",
        "-RECAP: \n",
        "-Defining MDP\n",
        "\t1) set of states S\n",
        "\t2) start state s0\n",
        "\t3) set of actions A\n",
        "\t4) transitions P(s’ | a,a) or T(s,a,s’)\n",
        "\t5) rewards  R(s,a,s’) and discount λ\n",
        "\t\n",
        "\t-MDP quantities:\t\n",
        "\t\t-Policy = choice of actions fo reach state\n",
        "\t\t-Utility = sum of (discounted) rewards\n",
        "\t\t-Solution is policy = π(S) = a\n",
        "\n",
        "\n",
        "\n",
        "10/19/21: MDP (part 2), Bellman Equations\n",
        "-Bellman Equations:\n",
        "\t1) take correct first action (V*)\n",
        "\t2) keep being optimal (Q*)\n",
        "1) Value Iteration (hyperdrive example)  compute value of every state based on optimal action to find best policy \n",
        "\t-One Step Lookahead: start at bottom, calculate UP the tree\n",
        "\t-Efficiency: O(S^2 * A) per iteration\n",
        "-Convergence*: how do we know values will converge after finite # of steps?\n",
        "\t1) case1: tree has maximum depth M  it’ll just terminated after depth\n",
        "\t2) case2:  discount is less than 1  discount gives smaller values as you go up more plys\n",
        "\n",
        "2) Policy Evaluation: compare 2 policies, given a policy how good is it?  do what π says\n",
        "\t-One Step Lookahead with π instead of *\n",
        "-compute utility of state s under fixed policy (generally non-optimal)\n",
        "-Efficiency: O(S^2) per iteration\n",
        "\n",
        "3) Policy Extraction: given optimal values V*(s), how should we act?  do ONE STEP mini-expectimax\n",
        "\t-policy extraction = policy is implied by values\n",
        "-Compute Actions from Value  Mini-Expectivema\n",
        "-Compute Actions from Q-VALUES NOT VALUES\n",
        "\n",
        "4) Policy Iteration: \n",
        "\tStep 1: Policy evaluation: calculate utilities for some fixed policy (non-opimal utilities) until convergence \n",
        "\tStep 2: Policy improvement: update policy using one-step look-ahead with resulting converged utilities (still \t\t\tnon optimal) as future values\n",
        "\t-repeat until policy coverge\n",
        "\n",
        "\t-optimal\n",
        "\n",
        "-Comparison of Value Iteration and Policy Iteration: compute the same thing (optimal values)\n",
        "\t-value iteration:\n",
        "\t\t-each iteration updates both values (and implicitly) the policy\n",
        "\t\t-don’t track policy  taking max over actions implicitly recomputes it\t\t\n",
        "\n",
        "\t-policy iteration:\n",
        "\t\t-several passes that updates utilities with fixed policy (fast b/c consider only one action, not all of them)\n",
        "\t\t-after policy evaluted, new policy chosen (slow like value-iteratio pass)\n",
        "\t\t-newpolicy better (or we’re done) \t\n",
        "\n",
        "-SUMMARY: MDP Algorithms (they’re all basically the same)\n",
        "\t1) compute optimal values  value iteration OR policy iteration\n",
        "\t2) compute values for particular policy  policy evaluation\n",
        "\t3) turn values into a policy  policy extraction (one-step lookahead)\n",
        "\t-they’re all basically the same\n",
        "\t-all use onestep lookahead\n",
        "\t-differ only in whether er plug in a fixed policy or max over action\n",
        "\n",
        "\n",
        "10/21/21: Maximum Expected Utility \n",
        "-Maximum Expected Utility (MEU): why average utilities and not minimax?\n",
        "-principle of maximum expected utility: rational agent should choose action that maximizes expected utility, given its knowledge\n",
        "-Minimax (insenstive to monotonic transformations) vs Expectimax (magnitude matters in expectimax)\n",
        "\t-magnitude affects which branch you go down in expectimax (vs doesn’t amtter in minimax)\n",
        "\n",
        "-Utilities: functions from outcomes (states of the world) to real numbers (agent’s preferences)\n",
        "\t-in game, may be simple (+1/-1)\n",
        "\t-summarize the agent’s goals\n",
        "\t-Theorem: any “rational” preferneces can be summarized as a utility function\n",
        "\t-we hard-wire utilities and let behaviors emerge  “this is outcome you want, certain behavior emerges”\n",
        "\t\t-(ice cream)\n",
        "\n",
        "-Preferences:\n",
        "\t-agent has preferences among:\n",
        "\t\t1) Prizes: A,B,\n",
        "\t\t2) Lotteries: situations with uncertain prizes; L = [p,A ; (1-p), B]\n",
        "\t\t\t\t\t\t**agent prefers outcome A to outcome B\n",
        "\n",
        "\t-Rational Preferences\n",
        "\t\t-Theorem: rational preferences imply behavior describable as maximization of Expected Utility\n",
        "\n",
        "-Maximum Expected Utility (MEU) Principle: \n",
        "-Theorem: there exists a real-valued function, U, that maps some ourcome A, to a real number\n",
        "-choose action that maximizes expected utility\n",
        "-Note: an agent can be entirely rational (aka consistent with MEU) without ever representing or manipulating utilities and probabilites\n",
        "-e.g. a lookup table for perfect tic-tac-toe, a reflex vacuum cleaner\n",
        "\t-Utility Scales:\n",
        "\t\t-Normal utilities: u+ = 1.0, u- = 0.0\n",
        "-Micromorts: one-millionth chance of death, useful for aying to reduce product risks\n",
        "-QALYs: quality-adjusted life years, useful for medical decisions with big risk\n",
        "\n",
        "-Human Utilities:\n",
        "\t-Utilities map states to real numbers. Which numbers?  how much somone is WILLING TO PAY\n",
        "\t\t-Standard aproach:\n",
        "\t\t1) Compare prize A to standard lottery Lp b/t\n",
        "\t\t\t-best possible prize, u+ with prob p\n",
        "\t\t\t-worst possible catastrophe, u- with prob 1-p\n",
        "\t\t2) adjust lottery prop p until indifference: A ~ Lp\n",
        "\t\t3) resulting p is a utility in [0,1]\n",
        "\n",
        "\t\t*money is NOT a utility scale  people are risk averse to money *closer to debt are actually more risk prone\n",
        "\t\t\t-ex) Insurance industry\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"Your definition here\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "\"etc.\": \"your definition here\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "7b96dd78-6029-447e-aad2-9dd37278d545"
      },
      "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": 5,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n\n10/12/21: MDP (part1 1) \n-up until now… deterministic (you know the exact result of your actions)  now.. Stochastic\n\n-Stochastic Transition Model are Markovian: prob of arriving at s’ ONLY depends on s and not history of earlier states\n\t-P(s’|s,a)\n\n-Utility/Reward Function\n\t-R(s,a,s’)\t\n\t-apply reward function to sequence of states and actions\n\t-agent receives reward at each time step \n\t-rewards are additive\n\n-Markov Decision Process (non-deterministic search problems)\n\t-a sequential decision problem\n\t-for fully obervable environment\n\t-w/ stochastic transition model\n\t-has additive rewards\n\n\t-DEFINE the following:\t\t\n\t\t1) set of states: s ∈ S\n\t\t2) set of actions: a ∈ A\n\t\t3) transition function: T(s,a,s’)\n\t\t\t-prob that executing action a in s will lead to s’: P(s’ | s,a)\n\t\t\t-prob is called the model\n\t\t4) reward function: R(s,a,s’)\n\t\t\t-sometimes just R(s) or R(s’)\n\t\t5) initial state: s0\n\t\t6) OPTIONAL: one or more terminal states\n\n-Solution == Policy  b/c non-determinisim of MDP\n\t-policy: maps from state onto action to take if the agent is in that state\n\t-tells agent what action to take at a given state\n\t- π(s) = a\n\t- π* = optimal policy\t\n\t-expected utility: of all possible paths generated by policy (b/c stochastic)\n\n\n-Sequences of Rewards: performance of an agent - sum of the rewards for the transitions it takes\n\t-Uh([s0,a0, s1,a1,…,  sn]) = R(s0,a0,s1) + R(ss,as,s2) + .. + R(sn-1,an-1,sn)\n\t-more or less?\n\t-now or later?\n\n\t-Discounting: value of rewards decay in the future (TIME VALUE)  each step, multiply by discount once\n-sooner reward > later reward\n\t\t-helps algorithms converge\n\n-Stationary Preferences: assuming stationary preferences, additive and discounted utility definitions the same\n\n-Additive Utilies & Discounted Utilieies\n-Problem: Infinite Utilities: what if game lasts forever  infinite rewards? NO\n-Solutions:\n\t1) (BAD) Finite horizon (like depth limited search): terminate episodes after fixed # of steps\n\t\t-gives nonstationary policies (pi depends on time left)\n2) (GOOD) Discounting using 0 < λ< 1 \n3) Absorbing state: guarantee that for every policy, a terminal state will eventually be reached\n\n-RECAP: \n-Defining MDP\n\t1) set of states S\n\t2) start state s0\n\t3) set of actions A\n\t4) transitions P(s’ | a,a) or T(s,a,s’)\n\t5) rewards  R(s,a,s’) and discount λ\n\t\n\t-MDP quantities:\t\n\t\t-Policy = choice of actions fo reach state\n\t\t-Utility = sum of (discounted) rewards\n\t\t-Solution is policy = π(S) = a\n\n\n\n10/19/21: MDP (part 2), Bellman Equations\n-Bellman Equations:\n\t1) take correct first action (V*)\n\t2) keep being optimal (Q*)\n1) Value Iteration (hyperdrive example)  compute value of every state based on optimal action to find best policy \n\t-One Step Lookahead: start at bottom, calculate UP the tree\n\t-Efficiency: O(S^2 * A) per iteration\n-Convergence*: how do we know values will converge after finite # of steps?\n\t1) case1: tree has maximum depth M  it’ll just terminated after depth\n\t2) case2:  discount is less than 1  discount gives smaller values as you go up more plys\n\n2) Policy Evaluation: compare 2 policies, given a policy how good is it?  do what π says\n\t-One Step Lookahead with π instead of *\n-compute utility of state s under fixed policy (generally non-optimal)\n-Efficiency: O(S^2) per iteration\n\n3) Policy Extraction: given optimal values V*(s), how should we act?  do ONE STEP mini-expectimax\n\t-policy extraction = policy is implied by values\n-Compute Actions from Value  Mini-Expectivema\n-Compute Actions from Q-VALUES NOT VALUES\n\n4) Policy Iteration: \n\tStep 1: Policy evaluation: calculate utilities for some fixed policy (non-opimal utilities) until convergence \n\tStep 2: Policy improvement: update policy using one-step look-ahead with resulting converged utilities (still \t\t\tnon optimal) as future values\n\t-repeat until policy coverge\n\n\t-optimal\n\n-Comparison of Value Iteration and Policy Iteration: compute the same thing (optimal values)\n\t-value iteration:\n\t\t-each iteration updates both values (and implicitly) the policy\n\t\t-don’t track policy  taking max over actions implicitly recomputes it\t\t\n\n\t-policy iteration:\n\t\t-several passes that updates utilities with fixed policy (fast b/c consider only one action, not all of them)\n\t\t-after policy evaluted, new policy chosen (slow like value-iteratio pass)\n\t\t-newpolicy better (or we’re done) \t\n\n-SUMMARY: MDP Algorithms (they’re all basically the same)\n\t1) compute optimal values  value iteration OR policy iteration\n\t2) compute values for particular policy  policy evaluation\n\t3) turn values into a policy  policy extraction (one-step lookahead)\n\t-they’re all basically the same\n\t-all use onestep lookahead\n\t-differ only in whether er plug in a fixed policy or max over action\n\n\n10/21/21: Maximum Expected Utility \n-Maximum Expected Utility (MEU): why average utilities and not minimax?\n-principle of maximum expected utility: rational agent should choose action that maximizes expected utility, given its knowledge\n-Minimax (insenstive to monotonic transformations) vs Expectimax (magnitude matters in expectimax)\n\t-magnitude affects which branch you go down in expectimax (vs doesn’t amtter in minimax)\n\n-Utilities: functions from outcomes (states of the world) to real numbers (agent’s preferences)\n\t-in game, may be simple (+1/-1)\n\t-summarize the agent’s goals\n\t-Theorem: any “rational” preferneces can be summarized as a utility function\n\t-we hard-wire utilities and let behaviors emerge  “this is outcome you want, certain behavior emerges”\n\t\t-(ice cream)\n\n-Preferences:\n\t-agent has preferences among:\n\t\t1) Prizes: A,B,\n\t\t2) Lotteries: situations with uncertain prizes; L = [p,A ; (1-p), B]\n\t\t\t\t\t\t**agent prefers outcome A to outcome B\n\n\t-Rational Preferences\n\t\t-Theorem: rational preferences imply behavior describable as maximization of Expected Utility\n\n-Maximum Expected Utility (MEU) Principle: \n-Theorem: there exists a real-valued function, U, that maps some ourcome A, to a real number\n-choose action that maximizes expected utility\n-Note: an agent can be entirely rational (aka consistent with MEU) without ever representing or manipulating utilities and probabilites\n-e.g. a lookup table for perfect tic-tac-toe, a reflex vacuum cleaner\n\t-Utility Scales:\n\t\t-Normal utilities: u+ = 1.0, u- = 0.0\n-Micromorts: one-millionth chance of death, useful for aying to reduce product risks\n-QALYs: quality-adjusted life years, useful for medical decisions with big risk\n\n-Human Utilities:\n\t-Utilities map states to real numbers. Which numbers?  how much somone is WILLING TO PAY\n\t\t-Standard aproach:\n\t\t1) Compare prize A to standard lottery Lp b/t\n\t\t\t-best possible prize, u+ with prob p\n\t\t\t-worst possible catastrophe, u- with prob 1-p\n\t\t2) adjust lottery prop p until indifference: A ~ Lp\n\t\t3) resulting p is a utility in [0,1]\n\n\t\t*money is NOT a utility scale  people are risk averse to money *closer to debt are actually more risk prone\n\t\t\t-ex) Insurance industry\n\n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "chapter17_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_3 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_4 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_5 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\"\n",
        "10/12/21: Reinforcement Learning \n",
        "-Double Bandits (transition from MDP to Reinforcement Learning)\n",
        "\t-Offline Planning:  SOLVING MDP IS PLANNING\n",
        "\t\t-don’t have to actually play, just need to know details of the MDP\n",
        "\n",
        "OFFLINE PLANNING\n",
        "\n",
        "\t-RULES CHANGED: When you don’t know probabbiltiy of RED  find the prob function of Red\n",
        "\t\t-this is Reinforcement Learning  learning, not planning\n",
        "\t\t-must act it out to actually learn (vs in MDP wher eyou can just calculate)\n",
        "\n",
        "-Reinforcement Learning\n",
        "-Exploration: you have to try unknown actions to get information\n",
        "-Exploitation: eventually you use what you know\n",
        "-Regret: even if you learn intelligently, you make mistakes\n",
        "-Sampling: because of chance, you have to try things repeatedlyt\n",
        "-Difficulty: learning can be much ahrder than solving a known MDP\n",
        "\n",
        "Basic Idea:\n",
        "-REceive feedback in the form or rewards\n",
        "-Agent's utilityis defined by the rewards fiunctions\n",
        "-Must learn to act so as tro maximize expected rewards\n",
        "-All learning based on observe dsamples of outcomes\n",
        "\n",
        "-Still assume MDP:\n",
        "\t1) set of states: s ∈ S\n",
        "\t2) set of actions (per state): a ∈ A\n",
        "\t3) model: T(s,a,s’)\n",
        "\t4) reward function: R(s,a,s’)\n",
        "\t-still looking for policy π(s)\n",
        "\n",
        "\t*NEW TWIST: don’t know T or R so don’t know which states are good or what actions do so must TRY them\n",
        "\n",
        "-Offline (MDP) vs Online (RL)\tMDP) vs Online (RL)\n",
        "\n",
        "1) Model Based Learning\n",
        "2) Model Free Learning\n",
        "-Model-Based Learning: explicitly model transition function\n",
        "\n",
        "-Model Free Learning: not explicitly construct transition function\n",
        "\t-every time you take action: compare result of action to what you thoguht would happen \n",
        "\t-update beliefs on what ought to happen based on the outcome that really occurred  or whether it was better or worse\n",
        "\t tracking the values of the utility of being in a state (not T or R)\n",
        "\t2: types:\n",
        "\t1) Passive Reinforcement Learning: someone picks policy and we act on it  see value of different states\n",
        "\t2) \n",
        "\n",
        "\t-Passive Reinforcement Learning: \n",
        "\t\t-input: fixed policy π(s)\n",
        "\t\t-don’t know model: T(s,a,s’)\n",
        "\t\t-don’t know reward function: R(s,a,s’)\n",
        "\t\t-Goal: learn the state values\n",
        "\n",
        "1) Direct Evalution (sample based approach): average together observed sample values\n",
        "\t\t\t(LIKE VALUE ITERATION)\n",
        "-goal: compute values for each state under π\n",
        "\t\t\t\t-act according to π\n",
        "\t\t\t\t-every time you visit state, write down what sum of discounted rewards is\n",
        "\t\t\t\t-average those samples\n",
        "\t\t\t-Good vs Bad:\n",
        "\t\t\t\tGood: easy to undesrtand, doesn’t require knoledge of T or R, eventually computes \t\t\t\t\tcorrect avg values using just sample transations\n",
        "\t\t\t\t-Bad: wastes information about state connections, each state must be learned \t\t\t\t\t\tseparately  takes long time to learn\n",
        "\n",
        "10/28 /21: Reinforcement Learning \n",
        "-Passive Reinforcement Learning\n",
        "\t-can we find state values with policy evaluation? Sample-based policy evalution?  no guarantee to return to state s\n",
        "\n",
        "2) Temperal Difference Learning (algorithm): have a moving average that learns from every experience\n",
        "(LIKE POLICY EVALUTION)\n",
        "\t-update V(s) each time we experience a transition (s, a, s’, r)\n",
        "\t-likely outcomes s’ contribute to updates more often\n",
        "\n",
        "\t-temporal difference learning of values:\n",
        "\t\t-policy still fixed, still doing evaluation\n",
        "\t\t-move values toward value of whatever successor occurs: running average\n",
        "\t\t\t-a.k.a. update value of state s with current value and the reward of the one sample\n",
        "\n",
        "\t\t-Q-Learning (same calc moving average)\n",
        "\t\t\t-converges to optimal policy EVEN IF acting suboptimally  off-policy learning\n",
        "\t\t\t\t-have to explore enough\n",
        "\t\t\t\t-eventually make learning rate small enough, BUT not decrease too quickly\n",
        "Exploration vs Exploitation\n",
        "-Exploitation (use current knowledge about best state, take that actions\n",
        "-Exploration: explore new things, see if it’s better or worse than current estimate\n",
        "\n",
        "-How to explore?\t\n",
        "1) Random Actions (epsilon-greedy): with small prob. Epsilon, take random action  keep doing bad stuff\n",
        "\t2) Exploration Functions: explore areas whose badness is not yet established, eventually stop exploring\n",
        "\t\t-take value estimate u and a visit count n, return optimistic utility \n",
        "-Regret: measure of total mistake cost: difference b/t expected rewards and optimal rewards\n",
        "\t-how to learn optimal policy optmally  less regret\n",
        "\n",
        "-Approximate Q-Learning: generalizing across states\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "414e2eea-1058-4482-c00f-bb7fc16cab35"
      },
      "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": 7,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\n10/12/21: Reinforcement Learning \n-Double Bandits (transition from MDP to Reinforcement Learning)\n\t-Offline Planning:  SOLVING MDP IS PLANNING\n\t\t-don’t have to actually play, just need to know details of the MDP\n\nOFFLINE PLANNING\n\n\t-RULES CHANGED: When you don’t know probabbiltiy of RED  find the prob function of Red\n\t\t-this is Reinforcement Learning  learning, not planning\n\t\t-must act it out to actually learn (vs in MDP wher eyou can just calculate)\n\n-Reinforcement Learning\n-Exploration: you have to try unknown actions to get information\n-Exploitation: eventually you use what you know\n-Regret: even if you learn intelligently, you make mistakes\n-Sampling: because of chance, you have to try things repeatedlyt\n-Difficulty: learning can be much ahrder than solving a known MDP\n\nBasic Idea:\n-REceive feedback in the form or rewards\n-Agent's utilityis defined by the rewards fiunctions\n-Must learn to act so as tro maximize expected rewards\n-All learning based on observe dsamples of outcomes\n\n-Still assume MDP:\n\t1) set of states: s ∈ S\n\t2) set of actions (per state): a ∈ A\n\t3) model: T(s,a,s’)\n\t4) reward function: R(s,a,s’)\n\t-still looking for policy π(s)\n\n\t*NEW TWIST: don’t know T or R so don’t know which states are good or what actions do so must TRY them\n\n-Offline (MDP) vs Online (RL)\tMDP) vs Online (RL)\n\n1) Model Based Learning\n2) Model Free Learning\n-Model-Based Learning: explicitly model transition function\n\n-Model Free Learning: not explicitly construct transition function\n\t-every time you take action: compare result of action to what you thoguht would happen \n\t-update beliefs on what ought to happen based on the outcome that really occurred  or whether it was better or worse\n\t tracking the values of the utility of being in a state (not T or R)\n\t2: types:\n\t1) Passive Reinforcement Learning: someone picks policy and we act on it  see value of different states\n\t2) \n\n\t-Passive Reinforcement Learning: \n\t\t-input: fixed policy π(s)\n\t\t-don’t know model: T(s,a,s’)\n\t\t-don’t know reward function: R(s,a,s’)\n\t\t-Goal: learn the state values\n\n1) Direct Evalution (sample based approach): average together observed sample values\n\t\t\t(LIKE VALUE ITERATION)\n-goal: compute values for each state under π\n\t\t\t\t-act according to π\n\t\t\t\t-every time you visit state, write down what sum of discounted rewards is\n\t\t\t\t-average those samples\n\t\t\t-Good vs Bad:\n\t\t\t\tGood: easy to undesrtand, doesn’t require knoledge of T or R, eventually computes \t\t\t\t\tcorrect avg values using just sample transations\n\t\t\t\t-Bad: wastes information about state connections, each state must be learned \t\t\t\t\t\tseparately  takes long time to learn\n\n10/28 /21: Reinforcement Learning \n-Passive Reinforcement Learning\n\t-can we find state values with policy evaluation? Sample-based policy evalution?  no guarantee to return to state s\n\n2) Temperal Difference Learning (algorithm): have a moving average that learns from every experience\n(LIKE POLICY EVALUTION)\n\t-update V(s) each time we experience a transition (s, a, s’, r)\n\t-likely outcomes s’ contribute to updates more often\n\n\t-temporal difference learning of values:\n\t\t-policy still fixed, still doing evaluation\n\t\t-move values toward value of whatever successor occurs: running average\n\t\t\t-a.k.a. update value of state s with current value and the reward of the one sample\n\n\t\t-Q-Learning (same calc moving average)\n\t\t\t-converges to optimal policy EVEN IF acting suboptimally  off-policy learning\n\t\t\t\t-have to explore enough\n\t\t\t\t-eventually make learning rate small enough, BUT not decrease too quickly\nExploration vs Exploitation\n-Exploitation (use current knowledge about best state, take that actions\n-Exploration: explore new things, see if it’s better or worse than current estimate\n\n-How to explore?\t\n1) Random Actions (epsilon-greedy): with small prob. Epsilon, take random action  keep doing bad stuff\n\t2) Exploration Functions: explore areas whose badness is not yet established, eventually stop exploring\n\t\t-take value estimate u and a visit count n, return optimistic utility \n-Regret: measure of total mistake cost: difference b/t expected rewards and optimal rewards\n\t-how to learn optimal policy optmally  less regret\n\n-Approximate Q-Learning: generalizing across states\n\n\n\n\n\n\n## Module 9 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\"\n",
        "Module 10: Probabilities and Language Models \n",
        "-Review basics of probability theory:\n",
        "\t-Axioms of probability\n",
        "\t-What an event is\n",
        "\t-What a probabilistic model is\n",
        "\t-Interactions between joint probabilities, conditional probabilities, marginal distributions\n",
        "-the chain rule\n",
        "-Bayes rule\n",
        "-performing probabilistic inference\n",
        "-probabilsitic language models\n",
        "\n",
        "Lesson1: Review on Probabilities \n",
        "-Uncertainty\n",
        "\t-observed variables (evidence)\n",
        "\t-unobserved variables (states)\n",
        "\t-model: agent knows something about how the known variables relate to unknown variables’\n",
        "\n",
        "-Sample Space: all possible worlds; mutually exclusive and exhaustive\n",
        "\t-probabilities find out how likely a possible world is \n",
        "\n",
        "-Random Variable: some aspect of the world which we may of uncertainty about\n",
        "\n",
        "-Axioms of Probability: \n",
        "\t1) probability of any possible owrld is between 0 and 1\n",
        "\t2) total probability of all outcomes is 1\n",
        "\n",
        "Lesson2: Distributions \n",
        "-Probablity Distributions: unobserved random variables have distributions\n",
        "\t-Distribution: table of probability of values\n",
        "\tP(X = hot)\n",
        "\n",
        "1) Joint Distributions (beyond single random variables): over a set of random varaibles (X1, X2,.., Xn) specifies a number for each outcome\n",
        "\tP(X1=x1, X2=x2,…,Xn=xn)\n",
        "\tP(T,W) \n",
        "-Probabilistic Model: joint distribution over a set of random variables\n",
        "\t-(random) variables with domains\n",
        "\t-assignments are called outcomes\n",
        "\t-joint distributions: say whether assignemnts are likely\n",
        "\t-normalized: sum to 1.0\n",
        "\t-ideally: only certain variables directly interact\n",
        "\n",
        "-Event: set of possible outcomes \n",
        "\n",
        "2) Marginal Distrubtions: sub tables which eliminate variables (summing out) if you only want 1 variable from joint\n",
        "\n",
        "\n",
        "3) Conditional Probabilities: \n",
        "\n",
        "\n",
        "Lesson3: Probabilistic Inference and RUles \n",
        "-Probability Models:\n",
        "-Probabilistic Inference: compute desired probability from other know probabilities (conditional from joint)\n",
        "\t-conditional probabilities change with new evidence (new conditionals)\n",
        "\t-observe things, make predictions about other things\n",
        "\n",
        "-Inference by Enumeration\n",
        "-Product Rule: \n",
        "\t-P(y)P(x|y) = P(x,y)\n",
        "\n",
        "-Chain Rule (product rule for more than 2 variables)\n",
        "\n",
        "\n",
        "\n",
        "Lesson4: Probabilistic Langauge Models \n",
        "-what’s the likely next word?\n",
        "\n",
        "-Goal: assign probability to a sentence\n",
        "\t-autocomplete for texting\n",
        "\t-machine translation\n",
        "\t-spelling correction\n",
        "\t-speech recognition\n",
        "\t-other natural lanauge generation tasks: summarizaition, question-answering, dialog systems\n",
        "\n",
        "-Language Model (LM): model that computes probability of sentence or sequence of words OR of upcoming word\n",
        "-How to estimate these probabilities  MLE (empirical method)\n",
        "\t-Simplifying Assumption  Markov Assumption: prob moving to next state only depends on current state\n",
        "-don’t use whole context of sentence  use prevoius k words \n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "e39aee52-1c39-4d51-a11f-3092df21327e"
      },
      "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": 9,
      "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\nModule 10: Probabilities and Language Models \n-Review basics of probability theory:\n\t-Axioms of probability\n\t-What an event is\n\t-What a probabilistic model is\n\t-Interactions between joint probabilities, conditional probabilities, marginal distributions\n-the chain rule\n-Bayes rule\n-performing probabilistic inference\n-probabilsitic language models\n\nLesson1: Review on Probabilities \n-Uncertainty\n\t-observed variables (evidence)\n\t-unobserved variables (states)\n\t-model: agent knows something about how the known variables relate to unknown variables’\n\n-Sample Space: all possible worlds; mutually exclusive and exhaustive\n\t-probabilities find out how likely a possible world is \n\n-Random Variable: some aspect of the world which we may of uncertainty about\n\n-Axioms of Probability: \n\t1) probability of any possible owrld is between 0 and 1\n\t2) total probability of all outcomes is 1\n\nLesson2: Distributions \n-Probablity Distributions: unobserved random variables have distributions\n\t-Distribution: table of probability of values\n\tP(X = hot)\n\n1) Joint Distributions (beyond single random variables): over a set of random varaibles (X1, X2,.., Xn) specifies a number for each outcome\n\tP(X1=x1, X2=x2,…,Xn=xn)\n\tP(T,W) \n-Probabilistic Model: joint distribution over a set of random variables\n\t-(random) variables with domains\n\t-assignments are called outcomes\n\t-joint distributions: say whether assignemnts are likely\n\t-normalized: sum to 1.0\n\t-ideally: only certain variables directly interact\n\n-Event: set of possible outcomes \n\n2) Marginal Distrubtions: sub tables which eliminate variables (summing out) if you only want 1 variable from joint\n\n\n3) Conditional Probabilities: \n\n\nLesson3: Probabilistic Inference and RUles \n-Probability Models:\n-Probabilistic Inference: compute desired probability from other know probabilities (conditional from joint)\n\t-conditional probabilities change with new evidence (new conditionals)\n\t-observe things, make predictions about other things\n\n-Inference by Enumeration\n-Product Rule: \n\t-P(y)P(x|y) = P(x,y)\n\n-Chain Rule (product rule for more than 2 variables)\n\n\n\nLesson4: Probabilistic Langauge Models \n-what’s the likely next word?\n\n-Goal: assign probability to a sentence\n\t-autocomplete for texting\n\t-machine translation\n\t-spelling correction\n\t-speech recognition\n\t-other natural lanauge generation tasks: summarizaition, question-answering, dialog systems\n\n-Language Model (LM): model that computes probability of sentence or sequence of words OR of upcoming word\n-How to estimate these probabilities  MLE (empirical method)\n\t-Simplifying Assumption  Markov Assumption: prob moving to next state only depends on current state\n-don’t use whole context of sentence  use prevoius k words \n\n\n\n## Module 10 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\"\n",
        "Module 11: Probabilistic Reasoning and Bayes’ Nets\n",
        "11/9/21 (11/8): Bayes’ Nets (part1) \n",
        "-Probabilistic Models: reason how the world works  given evidence and draw inferences from it  Bayes’ Net is one kind\n",
        "\t-explanation: diagnostic reasoning\n",
        "\t-prediction: causal reasoning\n",
        "\n",
        "-Review: Independence\n",
        "\tP(x,y) = P(x)P(y) OR P(x|y) = P(x)\n",
        "\t-independence lets you store marginal probabilities tables (instead of joint prob tables)  less memory\n",
        "\t-we want partial independence (not full independence, which won’t let us find anyting)  conditional ind.\n",
        "\n",
        "-Review: Conditional Independence: ⫫\n",
        "\t-conditional independence: core of Bayes’ nets (toothache example), how to form inferences about the world\n",
        "\tP(x,y|z) = P(x|z) * P(y|z) OR P(x|y,z) = P(x|z).\n",
        "\n",
        "-Conditional Independence and Chain Rule: independence assumption allows you to make table MUCH SMALLER\n",
        "\t BAYES NETS\n",
        "\n",
        "-Bayes’ Nets: technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities) with graphical models  graphical model & conditional probabilities with parents\n",
        "\t-full joint distribution table is too big, hard to learn  independece asusmptions  learn\n",
        "\t-graphical models: describe how local variables interact  chained together to give global, indirect interations\n",
        "\t\t-use just parents of a node vs all the other nodes and a node for conditional\n",
        "\n",
        "\t-Graphical Model Notation\n",
        "\t\t-Node: variables (with domains); assigned (observed) or unassigned (unobserved)\n",
        "\t\t-Arc: interactions; indicate direct influence between variables (conditional independence)\n",
        "\n",
        "11/11/21: Bayes’ Nets (part 2)\n",
        "-Bayes’ Nets: \n",
        "\t-encode joint distributions\n",
        "\t-(today) answer queries about that distribution \n",
        "\t-(finally) answer numerical queries (inference)\n",
        "\n",
        "-Causality: BN don’t have to actually be causal, but easier  the arrows REALLY encode conditional independence\n",
        "\n",
        "-Bayes’ Nets: Assumptions\n",
        "\t-assumptions: we remove some conditoinal variables and just use parents\n",
        "\t\t\n",
        "-there are other conditional independence assumptoins beyond “chain rule  Bayes’ net”\n",
        "\t\t-can be read off of graph… D-separation \n",
        "\n",
        "-D-Separation: (D stands for descendents); study indepdendece properties of whole Bayes’ net by breaking it down into triples (3 types of triples)\n",
        "\t1) Causal Chain: X causes Y causes Z  X independent of Z? NO;    X cond. independent of Z given Y? YES\n",
        "\t2) Common Cause: X and Z bot caused by Y X independent of Z? NO;    X cond. independent of Z given Y? YES\n",
        "3) Common Effect: two casues of one effect (v-structure);  BACKWARDS FROM PREV 2 CASES\n",
        " X independent of Y? YES;    X cond. independent of Y given Z? NO\n",
        "*) General Case: in a given BN, are two variables independent (given evidence)?  analyze graph \n",
        "\n",
        "\n",
        "-Reachability:\n",
        "\t-Inactive Paths: 3 D separataion cases\n",
        "\t-Active Paths: opposite of those\n",
        "\t-if one or more paths is inactive, then the whole path is inactive  independence guaranteed\n",
        "\n",
        "-Bayes’ Nets Representation Summary:\n",
        "\t-compactly encode joint distributions\n",
        "\t-guaranteed independencies of distributions can be deduced from BN graph structure\n",
        "\t-D-separation gives precise conditional independence guarantees from graph\n",
        "\t-Bayes’ Net’s joint distributoin may have more cond. Independence that’s not detectable under further inspect\n",
        "\n",
        "-Inference: given that we see something, how does that affect beliefs about things we haven’t seen yet?\n",
        "\t1) Posterior Probability: (P(Q| E1 = e1… Ek=ek)\n",
        "\t2) Most Likely Explanation: argmax P(Q=q| E1=e1…Ek=ek)\n",
        "\n",
        "-Inference by Enumeration (Posterior Probability)\n",
        "\t-BUT: still calculating huge join probability\n",
        "\t-Inference by Enumeration vs Variable Elimination\n",
        "\t\t-Inference by Enumeration is slow: join whole join distribution before you sum out hidden vars\n",
        "\t\t-Variable Elimination: interleave joining and marginalizing  (textbook)\n",
        "\n",
        "Next:\n",
        "\t-Bayes’ Nets: given prpobability tables (ask an expert)\n",
        "\t-Next: Naïve Bayes: learn probabilities from data and make predictions based on what we’ve observed\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "a6bc8b26-37ff-4768-f41d-dbf7055c00d4"
      },
      "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": 11,
      "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\nModule 11: Probabilistic Reasoning and Bayes’ Nets\n11/9/21 (11/8): Bayes’ Nets (part1) \n-Probabilistic Models: reason how the world works  given evidence and draw inferences from it  Bayes’ Net is one kind\n\t-explanation: diagnostic reasoning\n\t-prediction: causal reasoning\n\n-Review: Independence\n\tP(x,y) = P(x)P(y) OR P(x|y) = P(x)\n\t-independence lets you store marginal probabilities tables (instead of joint prob tables)  less memory\n\t-we want partial independence (not full independence, which won’t let us find anyting)  conditional ind.\n\n-Review: Conditional Independence: ⫫\n\t-conditional independence: core of Bayes’ nets (toothache example), how to form inferences about the world\n\tP(x,y|z) = P(x|z) * P(y|z) OR P(x|y,z) = P(x|z).\n\n-Conditional Independence and Chain Rule: independence assumption allows you to make table MUCH SMALLER\n\t BAYES NETS\n\n-Bayes’ Nets: technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities) with graphical models  graphical model & conditional probabilities with parents\n\t-full joint distribution table is too big, hard to learn  independece asusmptions  learn\n\t-graphical models: describe how local variables interact  chained together to give global, indirect interations\n\t\t-use just parents of a node vs all the other nodes and a node for conditional\n\n\t-Graphical Model Notation\n\t\t-Node: variables (with domains); assigned (observed) or unassigned (unobserved)\n\t\t-Arc: interactions; indicate direct influence between variables (conditional independence)\n\n11/11/21: Bayes’ Nets (part 2)\n-Bayes’ Nets: \n\t-encode joint distributions\n\t-(today) answer queries about that distribution \n\t-(finally) answer numerical queries (inference)\n\n-Causality: BN don’t have to actually be causal, but easier  the arrows REALLY encode conditional independence\n\n-Bayes’ Nets: Assumptions\n\t-assumptions: we remove some conditoinal variables and just use parents\n\t\t\n-there are other conditional independence assumptoins beyond “chain rule  Bayes’ net”\n\t\t-can be read off of graph… D-separation \n\n-D-Separation: (D stands for descendents); study indepdendece properties of whole Bayes’ net by breaking it down into triples (3 types of triples)\n\t1) Causal Chain: X causes Y causes Z  X independent of Z? NO;    X cond. independent of Z given Y? YES\n\t2) Common Cause: X and Z bot caused by Y X independent of Z? NO;    X cond. independent of Z given Y? YES\n3) Common Effect: two casues of one effect (v-structure);  BACKWARDS FROM PREV 2 CASES\n X independent of Y? YES;    X cond. independent of Y given Z? NO\n*) General Case: in a given BN, are two variables independent (given evidence)?  analyze graph \n\n\n-Reachability:\n\t-Inactive Paths: 3 D separataion cases\n\t-Active Paths: opposite of those\n\t-if one or more paths is inactive, then the whole path is inactive  independence guaranteed\n\n-Bayes’ Nets Representation Summary:\n\t-compactly encode joint distributions\n\t-guaranteed independencies of distributions can be deduced from BN graph structure\n\t-D-separation gives precise conditional independence guarantees from graph\n\t-Bayes’ Net’s joint distributoin may have more cond. Independence that’s not detectable under further inspect\n\n-Inference: given that we see something, how does that affect beliefs about things we haven’t seen yet?\n\t1) Posterior Probability: (P(Q| E1 = e1… Ek=ek)\n\t2) Most Likely Explanation: argmax P(Q=q| E1=e1…Ek=ek)\n\n-Inference by Enumeration (Posterior Probability)\n\t-BUT: still calculating huge join probability\n\t-Inference by Enumeration vs Variable Elimination\n\t\t-Inference by Enumeration is slow: join whole join distribution before you sum out hidden vars\n\t\t-Variable Elimination: interleave joining and marginalizing  (textbook)\n\nNext:\n\t-Bayes’ Nets: given prpobability tables (ask an expert)\n\t-Next: Naïve Bayes: learn probabilities from data and make predictions based on what we’ve observed\n\n\n\n\n## Module 11 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\"\n",
        "ML STUFF\n",
        "\n",
        "Module 12: Probabilistic Reasoning and Bayes’ Nets\n",
        "11/16/21: Machine Learning: Naïve Bayes \n",
        "-Up until now: \n",
        "-AI: how to use a model to make optimal decisions\n",
        "-Machine Learning: how to acquire a model from data/experience\n",
        "\t-learning paramters (e.g. probabilities)\n",
        "\t-learning structure (e.g. BN graphs)\n",
        "\t-learning hidden concepts (e.g. clustering)\n",
        "\n",
        "-Today: model-based classsification with Naïve Bayes and Perceptrons\n",
        "\n",
        "-Machine Learning: \n",
        "\t-Supervised Learning: Classification: given input x, predict labels y\n",
        "\t\t-Binary Classification: email spam or not spam\n",
        "\t\t-Multi-Class Classificaiotn: digit recognition\n",
        "\t\n",
        "-Model-Based Classification\n",
        "\t-build a model (e.g. Bayes Net) where both the label and features are random variables\n",
        "\t-instantiate any obesrved features\n",
        "\t-query for the distribution of the label conditioned on the features\n",
        "\n",
        "\t-Challenges:\n",
        "\t\t-what structure should the BN have?\n",
        "\t\t-how should we learn its parameters?\n",
        "\n",
        "-Naïve Bayes: \n",
        "\t-assume independence between features, works anyway\n",
        "\n",
        "-Generalization and Overfitting:\n",
        "\t-relative freqeuency parameteres will overfit the training data  smooth or regularize the estimates to generalize\n",
        "\n",
        "-Parameter Estimation:\n",
        "\t-to estimate the distribution of a random variable:\n",
        "\t\t-elicitation: ask a human\n",
        "\t\t-empirically: use training data (learning)  use estimate that maximizes the likelihood of the data\n",
        "\n",
        "\t-Maximum Likelihood: relative frequencies are the MLE\n",
        "\t-Laplace Smoothing: (for when event doesn’t occur in training data) reserve small probability for unseen events\n",
        "\t\t-avoid zero probabilities\n",
        "\t\t1) Add One Smoothing\n",
        "\n",
        "-Hyperparameter: the amount/type of smoothing to do; k, alpha\n",
        "\t-learn parameters on training data\n",
        "-tune hyperparamters on held-out data  for each value of the hyperparameters, train and test on held-out data \n",
        "\n",
        "11/18/21: Machine Learning: Perceptrons \n",
        "-Baseline: helps determine how hard a task is & what a “good” accuracy is\n",
        "\n",
        "-Confidence: how sure the classifier is of th-ML Naïve Bayes Summary:\n",
        "\t-Bayes’ Rule: lets us do diagnostic queries with causal probabilities\n",
        "\t-Naïve Bayes Assumptions: takes all features to be independent given the class label\n",
        "\t-we can build classifiers out of a naïve Bayes model using training data\n",
        "\t-Smoothing Estimates: is important in real life\n",
        "\t-Classifier Confidence: are useful, when you can get them\n",
        "\n",
        "-NOW… Perceptrons (like a neuron of a brain)\n",
        "\t-perceptron (sigmoid function) is a device that makes decisions by weighing up evidence\n",
        "e classification\n",
        "-Learning: Binary Perceptron: update weights for every item in training data\n",
        "\t-start with weights = 0\n",
        "\t-for each training instance:\n",
        "\t\t-classifiy with current weights\n",
        "\t\t-if correct: if y label with curent weights is correct (aka same as human label y*) (y = y*)  no change\n",
        "\t\t-if wrong: adjust weight vector\n",
        "-Properties of Perceptrons:\n",
        "\t1) Separability: true of some parameters get the training set perfectly correct\n",
        "\t2) Convergence: if the training is separable, perceptron will eventually converge (binary case)\n",
        "\t3) Mistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\n",
        "\n",
        "-Problems with Perceptron\n",
        "\t1) Noise: if data isn’t separable, weights might thrash  solution: averaging weight vectors over time \n",
        "\t2) Medocre generalization: finds a “barely” separable solution \n",
        "\t3) Overtraining: test/held-out accuracy usually rises, then falls (like overfitting)\n",
        "11/23/21\n",
        "-Fixing the Perceptron: adjust the weight update to mitigate the problems\n",
        "1)\tMIRA = Margin Infused Relaxed Algorithm; choose an update size that fixes the current mistake but minimizes the \tchange to w\n",
        "2)\tSupport Vector Machines (Linear Separator): maximize the margin\n",
        "3)\tMap Data to Higher-Dimensional Space (Non-Linear Separator)\n",
        "-SUMMARY  OF Classification: \n",
        "\t1) Naïve Bayes:\n",
        "\t\t-Builds a model training data\n",
        "\t\t-Gives prediction probabilities\n",
        "\t\t-Strong assumptions about feature independence\n",
        "\t\t-One pass through data (counting)\n",
        "\t2) Perceptrons / MIRA:\n",
        "\t\t-makes less assumptions about data\n",
        "\t\t-Mistake-driven learning\n",
        "\t\t-Multiple passes through data (prediction)\n",
        "\t\t-Often more accurate\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "16cb4cc1-fb12-499e-e9b2-63d3873cd837"
      },
      "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": 13,
      "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\nML STUFF\n\nModule 12: Probabilistic Reasoning and Bayes’ Nets\n11/16/21: Machine Learning: Naïve Bayes \n-Up until now: \n-AI: how to use a model to make optimal decisions\n-Machine Learning: how to acquire a model from data/experience\n\t-learning paramters (e.g. probabilities)\n\t-learning structure (e.g. BN graphs)\n\t-learning hidden concepts (e.g. clustering)\n\n-Today: model-based classsification with Naïve Bayes and Perceptrons\n\n-Machine Learning: \n\t-Supervised Learning: Classification: given input x, predict labels y\n\t\t-Binary Classification: email spam or not spam\n\t\t-Multi-Class Classificaiotn: digit recognition\n\t\n-Model-Based Classification\n\t-build a model (e.g. Bayes Net) where both the label and features are random variables\n\t-instantiate any obesrved features\n\t-query for the distribution of the label conditioned on the features\n\n\t-Challenges:\n\t\t-what structure should the BN have?\n\t\t-how should we learn its parameters?\n\n-Naïve Bayes: \n\t-assume independence between features, works anyway\n\n-Generalization and Overfitting:\n\t-relative freqeuency parameteres will overfit the training data  smooth or regularize the estimates to generalize\n\n-Parameter Estimation:\n\t-to estimate the distribution of a random variable:\n\t\t-elicitation: ask a human\n\t\t-empirically: use training data (learning)  use estimate that maximizes the likelihood of the data\n\n\t-Maximum Likelihood: relative frequencies are the MLE\n\t-Laplace Smoothing: (for when event doesn’t occur in training data) reserve small probability for unseen events\n\t\t-avoid zero probabilities\n\t\t1) Add One Smoothing\n\n-Hyperparameter: the amount/type of smoothing to do; k, alpha\n\t-learn parameters on training data\n-tune hyperparamters on held-out data  for each value of the hyperparameters, train and test on held-out data \n\n11/18/21: Machine Learning: Perceptrons \n-Baseline: helps determine how hard a task is & what a “good” accuracy is\n\n-Confidence: how sure the classifier is of th-ML Naïve Bayes Summary:\n\t-Bayes’ Rule: lets us do diagnostic queries with causal probabilities\n\t-Naïve Bayes Assumptions: takes all features to be independent given the class label\n\t-we can build classifiers out of a naïve Bayes model using training data\n\t-Smoothing Estimates: is important in real life\n\t-Classifier Confidence: are useful, when you can get them\n\n-NOW… Perceptrons (like a neuron of a brain)\n\t-perceptron (sigmoid function) is a device that makes decisions by weighing up evidence\ne classification\n-Learning: Binary Perceptron: update weights for every item in training data\n\t-start with weights = 0\n\t-for each training instance:\n\t\t-classifiy with current weights\n\t\t-if correct: if y label with curent weights is correct (aka same as human label y*) (y = y*)  no change\n\t\t-if wrong: adjust weight vector\n-Properties of Perceptrons:\n\t1) Separability: true of some parameters get the training set perfectly correct\n\t2) Convergence: if the training is separable, perceptron will eventually converge (binary case)\n\t3) Mistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\n\n-Problems with Perceptron\n\t1) Noise: if data isn’t separable, weights might thrash  solution: averaging weight vectors over time \n\t2) Medocre generalization: finds a “barely” separable solution \n\t3) Overtraining: test/held-out accuracy usually rises, then falls (like overfitting)\n11/23/21\n-Fixing the Perceptron: adjust the weight update to mitigate the problems\n1)\tMIRA = Margin Infused Relaxed Algorithm; choose an update size that fixes the current mistake but minimizes the \tchange to w\n2)\tSupport Vector Machines (Linear Separator): maximize the margin\n3)\tMap Data to Higher-Dimensional Space (Non-Linear Separator)\n-SUMMARY  OF Classification: \n\t1) Naïve Bayes:\n\t\t-Builds a model training data\n\t\t-Gives prediction probabilities\n\t\t-Strong assumptions about feature independence\n\t\t-One pass through data (counting)\n\t2) Perceptrons / MIRA:\n\t\t-makes less assumptions about data\n\t\t-Mistake-driven learning\n\t\t-Multiple passes through data (prediction)\n\t\t-Often more accurate\n\n\n\n\n## Module 12 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\"Just ML:NN STUFF\n",
        "Module 13: Neural Networks\n",
        "11/23/21: Neural Networks: Logistic Regression \n",
        "\n",
        "-Logistic Regression:\n",
        "-Sentiment Classifier\n",
        "\t-normalize z (only difference b/t perceptron and logistic regression)\n",
        "-Extract Features:\n",
        "\t-add features for language and give it a value\n",
        "\t-multiply by weights to get z score\n",
        "\t-normalize z with signmoid function\n",
        "\n",
        "-Learning in Logistic Regession (learn WEIGHTS and BIAS)\n",
        "\t1) Objective/Loss Function: gives distance between output and given output  Cross-Entropy Loss\n",
        "\t2) Optimize Loss Function: Stochastic Gradient Descent\n",
        "\n",
        "\t-Cross-Entropy Loss: gives difference between y_hat and y\n",
        "\n",
        "11/30/21-Stochastic Gradient Descent\n",
        "-(worked example 36:00)\n",
        "\n",
        "-Mini-batch training\n",
        "\t-Stochastic  one example at a time, updates weights on that example\n",
        "\t-Batch Training  trains on whole dataset, slow\n",
        "\t-Mini-Batch training  trian on small batch\n",
        "\n",
        "-Regularization: penalize large weights to prevent overfitting\n",
        "\t1) Lasso regression (L1)\n",
        "\t2) Ridge regression (L2)\n",
        "\n",
        "-Multinomal Logistic Regression: positive, negative, neutral\n",
        "\t-softmax function (generalization of sigmoid function)w\n",
        "\n",
        "11/30/21: Machine Learning: Neural Networks \n",
        "\n",
        "-Perceptron  Logistic Regression\n",
        "-Sigmoid  Activation Function\n",
        "\n",
        "-Feed-Forward Neural Network \n",
        "_Equations of Feedforward NN\n",
        "h = sigma(Wx+b)\n",
        "z=Uh\n",
        "y=softmax(z)\n",
        "\n",
        "Summary:\n",
        "Cross Entropy Loss Functoin\n",
        "Gradient Descent to perform optimizatoin\n",
        "Error back Propagation to compute the gradient of the loss function \n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 14,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "54df80f1-55f4-491c-d2f4-616da58f2df8"
      },
      "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": 15,
      "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\nJust ML:NN STUFF\nModule 13: Neural Networks\n11/23/21: Neural Networks: Logistic Regression \n\n-Logistic Regression:\n-Sentiment Classifier\n\t-normalize z (only difference b/t perceptron and logistic regression)\n-Extract Features:\n\t-add features for language and give it a value\n\t-multiply by weights to get z score\n\t-normalize z with signmoid function\n\n-Learning in Logistic Regession (learn WEIGHTS and BIAS)\n\t1) Objective/Loss Function: gives distance between output and given output  Cross-Entropy Loss\n\t2) Optimize Loss Function: Stochastic Gradient Descent\n\n\t-Cross-Entropy Loss: gives difference between y_hat and y\n\n11/30/21-Stochastic Gradient Descent\n-(worked example 36:00)\n\n-Mini-batch training\n\t-Stochastic  one example at a time, updates weights on that example\n\t-Batch Training  trains on whole dataset, slow\n\t-Mini-Batch training  trian on small batch\n\n-Regularization: penalize large weights to prevent overfitting\n\t1) Lasso regression (L1)\n\t2) Ridge regression (L2)\n\n-Multinomal Logistic Regression: positive, negative, neutral\n\t-softmax function (generalization of sigmoid function)w\n\n11/30/21: Machine Learning: Neural Networks \n\n-Perceptron  Logistic Regression\n-Sigmoid  Activation Function\n\n-Feed-Forward Neural Network \n_Equations of Feedforward NN\nh = sigma(Wx+b)\nz=Uh\ny=softmax(z)\n\nSummary:\nCross Entropy Loss Functoin\nGradient Descent to perform optimizatoin\nError back Propagation to compute the gradient of the loss function \n\n\n\n## Module 13 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 16,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "66a70d45-2d43-4305-d567-14e12594e4ff"
      },
      "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": 17,
      "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\nJust ML:NN STUFF\nModule 13: Neural Networks\n11/23/21: Neural Networks: Logistic Regression \n\n-Logistic Regression:\n-Sentiment Classifier\n\t-normalize z (only difference b/t perceptron and logistic regression)\n-Extract Features:\n\t-add features for language and give it a value\n\t-multiply by weights to get z score\n\t-normalize z with signmoid function\n\n-Learning in Logistic Regession (learn WEIGHTS and BIAS)\n\t1) Objective/Loss Function: gives distance between output and given output  Cross-Entropy Loss\n\t2) Optimize Loss Function: Stochastic Gradient Descent\n\n\t-Cross-Entropy Loss: gives difference between y_hat and y\n\n11/30/21-Stochastic Gradient Descent\n-(worked example 36:00)\n\n-Mini-batch training\n\t-Stochastic  one example at a time, updates weights on that example\n\t-Batch Training  trains on whole dataset, slow\n\t-Mini-Batch training  trian on small batch\n\n-Regularization: penalize large weights to prevent overfitting\n\t1) Lasso regression (L1)\n\t2) Ridge regression (L2)\n\n-Multinomal Logistic Regression: positive, negative, neutral\n\t-softmax function (generalization of sigmoid function)w\n\n11/30/21: Machine Learning: Neural Networks \n\n-Perceptron  Logistic Regression\n-Sigmoid  Activation Function\n\n-Feed-Forward Neural Network \n_Equations of Feedforward NN\nh = sigma(Wx+b)\nz=Uh\ny=softmax(z)\n\nSummary:\nCross Entropy Loss Functoin\nGradient Descent to perform optimizatoin\nError back Propagation to compute the gradient of the loss function \n\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "5ba9c76a-be0a-4ee4-f837-3504a486a28c"
      },
      "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": 18,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n\n10/12/21: MDP (part1 1) \n-up until now… deterministic (you know the exact result of your actions)  now.. Stochastic\n\n-Stochastic Transition Model are Markovian: prob of arriving at s’ ONLY depends on s and not history of earlier states\n\t-P(s’|s,a)\n\n-Utility/Reward Function\n\t-R(s,a,s’)\t\n\t-apply reward function to sequence of states and actions\n\t-agent receives reward at each time step \n\t-rewards are additive\n\n-Markov Decision Process (non-deterministic search problems)\n\t-a sequential decision problem\n\t-for fully obervable environment\n\t-w/ stochastic transition model\n\t-has additive rewards\n\n\t-DEFINE the following:\t\t\n\t\t1) set of states: s ∈ S\n\t\t2) set of actions: a ∈ A\n\t\t3) transition function: T(s,a,s’)\n\t\t\t-prob that executing action a in s will lead to s’: P(s’ | s,a)\n\t\t\t-prob is called the model\n\t\t4) reward function: R(s,a,s’)\n\t\t\t-sometimes just R(s) or R(s’)\n\t\t5) initial state: s0\n\t\t6) OPTIONAL: one or more terminal states\n\n-Solution == Policy  b/c non-determinisim of MDP\n\t-policy: maps from state onto action to take if the agent is in that state\n\t-tells agent what action to take at a given state\n\t- π(s) = a\n\t- π* = optimal policy\t\n\t-expected utility: of all possible paths generated by policy (b/c stochastic)\n\n\n-Sequences of Rewards: performance of an agent - sum of the rewards for the transitions it takes\n\t-Uh([s0,a0, s1,a1,…,  sn]) = R(s0,a0,s1) + R(ss,as,s2) + .. + R(sn-1,an-1,sn)\n\t-more or less?\n\t-now or later?\n\n\t-Discounting: value of rewards decay in the future (TIME VALUE)  each step, multiply by discount once\n-sooner reward > later reward\n\t\t-helps algorithms converge\n\n-Stationary Preferences: assuming stationary preferences, additive and discounted utility definitions the same\n\n-Additive Utilies & Discounted Utilieies\n-Problem: Infinite Utilities: what if game lasts forever  infinite rewards? NO\n-Solutions:\n\t1) (BAD) Finite horizon (like depth limited search): terminate episodes after fixed # of steps\n\t\t-gives nonstationary policies (pi depends on time left)\n2) (GOOD) Discounting using 0 < λ< 1 \n3) Absorbing state: guarantee that for every policy, a terminal state will eventually be reached\n\n-RECAP: \n-Defining MDP\n\t1) set of states S\n\t2) start state s0\n\t3) set of actions A\n\t4) transitions P(s’ | a,a) or T(s,a,s’)\n\t5) rewards  R(s,a,s’) and discount λ\n\t\n\t-MDP quantities:\t\n\t\t-Policy = choice of actions fo reach state\n\t\t-Utility = sum of (discounted) rewards\n\t\t-Solution is policy = π(S) = a\n\n\n\n10/19/21: MDP (part 2), Bellman Equations\n-Bellman Equations:\n\t1) take correct first action (V*)\n\t2) keep being optimal (Q*)\n1) Value Iteration (hyperdrive example)  compute value of every state based on optimal action to find best policy \n\t-One Step Lookahead: start at bottom, calculate UP the tree\n\t-Efficiency: O(S^2 * A) per iteration\n-Convergence*: how do we know values will converge after finite # of steps?\n\t1) case1: tree has maximum depth M  it’ll just terminated after depth\n\t2) case2:  discount is less than 1  discount gives smaller values as you go up more plys\n\n2) Policy Evaluation: compare 2 policies, given a policy how good is it?  do what π says\n\t-One Step Lookahead with π instead of *\n-compute utility of state s under fixed policy (generally non-optimal)\n-Efficiency: O(S^2) per iteration\n\n3) Policy Extraction: given optimal values V*(s), how should we act?  do ONE STEP mini-expectimax\n\t-policy extraction = policy is implied by values\n-Compute Actions from Value  Mini-Expectivema\n-Compute Actions from Q-VALUES NOT VALUES\n\n4) Policy Iteration: \n\tStep 1: Policy evaluation: calculate utilities for some fixed policy (non-opimal utilities) until convergence \n\tStep 2: Policy improvement: update policy using one-step look-ahead with resulting converged utilities (still \t\t\tnon optimal) as future values\n\t-repeat until policy coverge\n\n\t-optimal\n\n-Comparison of Value Iteration and Policy Iteration: compute the same thing (optimal values)\n\t-value iteration:\n\t\t-each iteration updates both values (and implicitly) the policy\n\t\t-don’t track policy  taking max over actions implicitly recomputes it\t\t\n\n\t-policy iteration:\n\t\t-several passes that updates utilities with fixed policy (fast b/c consider only one action, not all of them)\n\t\t-after policy evaluted, new policy chosen (slow like value-iteratio pass)\n\t\t-newpolicy better (or we’re done) \t\n\n-SUMMARY: MDP Algorithms (they’re all basically the same)\n\t1) compute optimal values  value iteration OR policy iteration\n\t2) compute values for particular policy  policy evaluation\n\t3) turn values into a policy  policy extraction (one-step lookahead)\n\t-they’re all basically the same\n\t-all use onestep lookahead\n\t-differ only in whether er plug in a fixed policy or max over action\n\n\n10/21/21: Maximum Expected Utility \n-Maximum Expected Utility (MEU): why average utilities and not minimax?\n-principle of maximum expected utility: rational agent should choose action that maximizes expected utility, given its knowledge\n-Minimax (insenstive to monotonic transformations) vs Expectimax (magnitude matters in expectimax)\n\t-magnitude affects which branch you go down in expectimax (vs doesn’t amtter in minimax)\n\n-Utilities: functions from outcomes (states of the world) to real numbers (agent’s preferences)\n\t-in game, may be simple (+1/-1)\n\t-summarize the agent’s goals\n\t-Theorem: any “rational” preferneces can be summarized as a utility function\n\t-we hard-wire utilities and let behaviors emerge  “this is outcome you want, certain behavior emerges”\n\t\t-(ice cream)\n\n-Preferences:\n\t-agent has preferences among:\n\t\t1) Prizes: A,B,\n\t\t2) Lotteries: situations with uncertain prizes; L = [p,A ; (1-p), B]\n\t\t\t\t\t\t**agent prefers outcome A to outcome B\n\n\t-Rational Preferences\n\t\t-Theorem: rational preferences imply behavior describable as maximization of Expected Utility\n\n-Maximum Expected Utility (MEU) Principle: \n-Theorem: there exists a real-valued function, U, that maps some ourcome A, to a real number\n-choose action that maximizes expected utility\n-Note: an agent can be entirely rational (aka consistent with MEU) without ever representing or manipulating utilities and probabilites\n-e.g. a lookup table for perfect tic-tac-toe, a reflex vacuum cleaner\n\t-Utility Scales:\n\t\t-Normal utilities: u+ = 1.0, u- = 0.0\n-Micromorts: one-millionth chance of death, useful for aying to reduce product risks\n-QALYs: quality-adjusted life years, useful for medical decisions with big risk\n\n-Human Utilities:\n\t-Utilities map states to real numbers. Which numbers?  how much somone is WILLING TO PAY\n\t\t-Standard aproach:\n\t\t1) Compare prize A to standard lottery Lp b/t\n\t\t\t-best possible prize, u+ with prob p\n\t\t\t-worst possible catastrophe, u- with prob 1-p\n\t\t2) adjust lottery prop p until indifference: A ~ Lp\n\t\t3) resulting p is a utility in [0,1]\n\n\t\t*money is NOT a utility scale  people are risk averse to money *closer to debt are actually more risk prone\n\t\t\t-ex) Insurance industry\n\n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\n10/12/21: Reinforcement Learning \n-Double Bandits (transition from MDP to Reinforcement Learning)\n\t-Offline Planning:  SOLVING MDP IS PLANNING\n\t\t-don’t have to actually play, just need to know details of the MDP\n\nOFFLINE PLANNING\n\n\t-RULES CHANGED: When you don’t know probabbiltiy of RED  find the prob function of Red\n\t\t-this is Reinforcement Learning  learning, not planning\n\t\t-must act it out to actually learn (vs in MDP wher eyou can just calculate)\n\n-Reinforcement Learning\n-Exploration: you have to try unknown actions to get information\n-Exploitation: eventually you use what you know\n-Regret: even if you learn intelligently, you make mistakes\n-Sampling: because of chance, you have to try things repeatedlyt\n-Difficulty: learning can be much ahrder than solving a known MDP\n\nBasic Idea:\n-REceive feedback in the form or rewards\n-Agent's utilityis defined by the rewards fiunctions\n-Must learn to act so as tro maximize expected rewards\n-All learning based on observe dsamples of outcomes\n\n-Still assume MDP:\n\t1) set of states: s ∈ S\n\t2) set of actions (per state): a ∈ A\n\t3) model: T(s,a,s’)\n\t4) reward function: R(s,a,s’)\n\t-still looking for policy π(s)\n\n\t*NEW TWIST: don’t know T or R so don’t know which states are good or what actions do so must TRY them\n\n-Offline (MDP) vs Online (RL)\tMDP) vs Online (RL)\n\n1) Model Based Learning\n2) Model Free Learning\n-Model-Based Learning: explicitly model transition function\n\n-Model Free Learning: not explicitly construct transition function\n\t-every time you take action: compare result of action to what you thoguht would happen \n\t-update beliefs on what ought to happen based on the outcome that really occurred  or whether it was better or worse\n\t tracking the values of the utility of being in a state (not T or R)\n\t2: types:\n\t1) Passive Reinforcement Learning: someone picks policy and we act on it  see value of different states\n\t2) \n\n\t-Passive Reinforcement Learning: \n\t\t-input: fixed policy π(s)\n\t\t-don’t know model: T(s,a,s’)\n\t\t-don’t know reward function: R(s,a,s’)\n\t\t-Goal: learn the state values\n\n1) Direct Evalution (sample based approach): average together observed sample values\n\t\t\t(LIKE VALUE ITERATION)\n-goal: compute values for each state under π\n\t\t\t\t-act according to π\n\t\t\t\t-every time you visit state, write down what sum of discounted rewards is\n\t\t\t\t-average those samples\n\t\t\t-Good vs Bad:\n\t\t\t\tGood: easy to undesrtand, doesn’t require knoledge of T or R, eventually computes \t\t\t\t\tcorrect avg values using just sample transations\n\t\t\t\t-Bad: wastes information about state connections, each state must be learned \t\t\t\t\t\tseparately  takes long time to learn\n\n10/28 /21: Reinforcement Learning \n-Passive Reinforcement Learning\n\t-can we find state values with policy evaluation? Sample-based policy evalution?  no guarantee to return to state s\n\n2) Temperal Difference Learning (algorithm): have a moving average that learns from every experience\n(LIKE POLICY EVALUTION)\n\t-update V(s) each time we experience a transition (s, a, s’, r)\n\t-likely outcomes s’ contribute to updates more often\n\n\t-temporal difference learning of values:\n\t\t-policy still fixed, still doing evaluation\n\t\t-move values toward value of whatever successor occurs: running average\n\t\t\t-a.k.a. update value of state s with current value and the reward of the one sample\n\n\t\t-Q-Learning (same calc moving average)\n\t\t\t-converges to optimal policy EVEN IF acting suboptimally  off-policy learning\n\t\t\t\t-have to explore enough\n\t\t\t\t-eventually make learning rate small enough, BUT not decrease too quickly\nExploration vs Exploitation\n-Exploitation (use current knowledge about best state, take that actions\n-Exploration: explore new things, see if it’s better or worse than current estimate\n\n-How to explore?\t\n1) Random Actions (epsilon-greedy): with small prob. Epsilon, take random action  keep doing bad stuff\n\t2) Exploration Functions: explore areas whose badness is not yet established, eventually stop exploring\n\t\t-take value estimate u and a visit count n, return optimistic utility \n-Regret: measure of total mistake cost: difference b/t expected rewards and optimal rewards\n\t-how to learn optimal policy optmally  less regret\n\n-Approximate Q-Learning: generalizing across states\n\n\n\n\n\n\n## Module 9 Definitions\n* **Term** - your definition here\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n\nModule 10: Probabilities and Language Models \n-Review basics of probability theory:\n\t-Axioms of probability\n\t-What an event is\n\t-What a probabilistic model is\n\t-Interactions between joint probabilities, conditional probabilities, marginal distributions\n-the chain rule\n-Bayes rule\n-performing probabilistic inference\n-probabilsitic language models\n\nLesson1: Review on Probabilities \n-Uncertainty\n\t-observed variables (evidence)\n\t-unobserved variables (states)\n\t-model: agent knows something about how the known variables relate to unknown variables’\n\n-Sample Space: all possible worlds; mutually exclusive and exhaustive\n\t-probabilities find out how likely a possible world is \n\n-Random Variable: some aspect of the world which we may of uncertainty about\n\n-Axioms of Probability: \n\t1) probability of any possible owrld is between 0 and 1\n\t2) total probability of all outcomes is 1\n\nLesson2: Distributions \n-Probablity Distributions: unobserved random variables have distributions\n\t-Distribution: table of probability of values\n\tP(X = hot)\n\n1) Joint Distributions (beyond single random variables): over a set of random varaibles (X1, X2,.., Xn) specifies a number for each outcome\n\tP(X1=x1, X2=x2,…,Xn=xn)\n\tP(T,W) \n-Probabilistic Model: joint distribution over a set of random variables\n\t-(random) variables with domains\n\t-assignments are called outcomes\n\t-joint distributions: say whether assignemnts are likely\n\t-normalized: sum to 1.0\n\t-ideally: only certain variables directly interact\n\n-Event: set of possible outcomes \n\n2) Marginal Distrubtions: sub tables which eliminate variables (summing out) if you only want 1 variable from joint\n\n\n3) Conditional Probabilities: \n\n\nLesson3: Probabilistic Inference and RUles \n-Probability Models:\n-Probabilistic Inference: compute desired probability from other know probabilities (conditional from joint)\n\t-conditional probabilities change with new evidence (new conditionals)\n\t-observe things, make predictions about other things\n\n-Inference by Enumeration\n-Product Rule: \n\t-P(y)P(x|y) = P(x,y)\n\n-Chain Rule (product rule for more than 2 variables)\n\n\n\nLesson4: Probabilistic Langauge Models \n-what’s the likely next word?\n\n-Goal: assign probability to a sentence\n\t-autocomplete for texting\n\t-machine translation\n\t-spelling correction\n\t-speech recognition\n\t-other natural lanauge generation tasks: summarizaition, question-answering, dialog systems\n\n-Language Model (LM): model that computes probability of sentence or sequence of words OR of upcoming word\n-How to estimate these probabilities  MLE (empirical method)\n\t-Simplifying Assumption  Markov Assumption: prob moving to next state only depends on current state\n-don’t use whole context of sentence  use prevoius k words \n\n\n\n## Module 10 Definitions\n* **Term** - your definition here\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\nModule 11: Probabilistic Reasoning and Bayes’ Nets\n11/9/21 (11/8): Bayes’ Nets (part1) \n-Probabilistic Models: reason how the world works  given evidence and draw inferences from it  Bayes’ Net is one kind\n\t-explanation: diagnostic reasoning\n\t-prediction: causal reasoning\n\n-Review: Independence\n\tP(x,y) = P(x)P(y) OR P(x|y) = P(x)\n\t-independence lets you store marginal probabilities tables (instead of joint prob tables)  less memory\n\t-we want partial independence (not full independence, which won’t let us find anyting)  conditional ind.\n\n-Review: Conditional Independence: ⫫\n\t-conditional independence: core of Bayes’ nets (toothache example), how to form inferences about the world\n\tP(x,y|z) = P(x|z) * P(y|z) OR P(x|y,z) = P(x|z).\n\n-Conditional Independence and Chain Rule: independence assumption allows you to make table MUCH SMALLER\n\t BAYES NETS\n\n-Bayes’ Nets: technique for describing complex joint distributions (models) using simple, local distributions (conditional probabilities) with graphical models  graphical model & conditional probabilities with parents\n\t-full joint distribution table is too big, hard to learn  independece asusmptions  learn\n\t-graphical models: describe how local variables interact  chained together to give global, indirect interations\n\t\t-use just parents of a node vs all the other nodes and a node for conditional\n\n\t-Graphical Model Notation\n\t\t-Node: variables (with domains); assigned (observed) or unassigned (unobserved)\n\t\t-Arc: interactions; indicate direct influence between variables (conditional independence)\n\n11/11/21: Bayes’ Nets (part 2)\n-Bayes’ Nets: \n\t-encode joint distributions\n\t-(today) answer queries about that distribution \n\t-(finally) answer numerical queries (inference)\n\n-Causality: BN don’t have to actually be causal, but easier  the arrows REALLY encode conditional independence\n\n-Bayes’ Nets: Assumptions\n\t-assumptions: we remove some conditoinal variables and just use parents\n\t\t\n-there are other conditional independence assumptoins beyond “chain rule  Bayes’ net”\n\t\t-can be read off of graph… D-separation \n\n-D-Separation: (D stands for descendents); study indepdendece properties of whole Bayes’ net by breaking it down into triples (3 types of triples)\n\t1) Causal Chain: X causes Y causes Z  X independent of Z? NO;    X cond. independent of Z given Y? YES\n\t2) Common Cause: X and Z bot caused by Y X independent of Z? NO;    X cond. independent of Z given Y? YES\n3) Common Effect: two casues of one effect (v-structure);  BACKWARDS FROM PREV 2 CASES\n X independent of Y? YES;    X cond. independent of Y given Z? NO\n*) General Case: in a given BN, are two variables independent (given evidence)?  analyze graph \n\n\n-Reachability:\n\t-Inactive Paths: 3 D separataion cases\n\t-Active Paths: opposite of those\n\t-if one or more paths is inactive, then the whole path is inactive  independence guaranteed\n\n-Bayes’ Nets Representation Summary:\n\t-compactly encode joint distributions\n\t-guaranteed independencies of distributions can be deduced from BN graph structure\n\t-D-separation gives precise conditional independence guarantees from graph\n\t-Bayes’ Net’s joint distributoin may have more cond. Independence that’s not detectable under further inspect\n\n-Inference: given that we see something, how does that affect beliefs about things we haven’t seen yet?\n\t1) Posterior Probability: (P(Q| E1 = e1… Ek=ek)\n\t2) Most Likely Explanation: argmax P(Q=q| E1=e1…Ek=ek)\n\n-Inference by Enumeration (Posterior Probability)\n\t-BUT: still calculating huge join probability\n\t-Inference by Enumeration vs Variable Elimination\n\t\t-Inference by Enumeration is slow: join whole join distribution before you sum out hidden vars\n\t\t-Variable Elimination: interleave joining and marginalizing  (textbook)\n\nNext:\n\t-Bayes’ Nets: given prpobability tables (ask an expert)\n\t-Next: Naïve Bayes: learn probabilities from data and make predictions based on what we’ve observed\n\n\n\n\n## Module 11 Definitions\n* **Concept** - definition\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\nML STUFF\n\nModule 12: Probabilistic Reasoning and Bayes’ Nets\n11/16/21: Machine Learning: Naïve Bayes \n-Up until now: \n-AI: how to use a model to make optimal decisions\n-Machine Learning: how to acquire a model from data/experience\n\t-learning paramters (e.g. probabilities)\n\t-learning structure (e.g. BN graphs)\n\t-learning hidden concepts (e.g. clustering)\n\n-Today: model-based classsification with Naïve Bayes and Perceptrons\n\n-Machine Learning: \n\t-Supervised Learning: Classification: given input x, predict labels y\n\t\t-Binary Classification: email spam or not spam\n\t\t-Multi-Class Classificaiotn: digit recognition\n\t\n-Model-Based Classification\n\t-build a model (e.g. Bayes Net) where both the label and features are random variables\n\t-instantiate any obesrved features\n\t-query for the distribution of the label conditioned on the features\n\n\t-Challenges:\n\t\t-what structure should the BN have?\n\t\t-how should we learn its parameters?\n\n-Naïve Bayes: \n\t-assume independence between features, works anyway\n\n-Generalization and Overfitting:\n\t-relative freqeuency parameteres will overfit the training data  smooth or regularize the estimates to generalize\n\n-Parameter Estimation:\n\t-to estimate the distribution of a random variable:\n\t\t-elicitation: ask a human\n\t\t-empirically: use training data (learning)  use estimate that maximizes the likelihood of the data\n\n\t-Maximum Likelihood: relative frequencies are the MLE\n\t-Laplace Smoothing: (for when event doesn’t occur in training data) reserve small probability for unseen events\n\t\t-avoid zero probabilities\n\t\t1) Add One Smoothing\n\n-Hyperparameter: the amount/type of smoothing to do; k, alpha\n\t-learn parameters on training data\n-tune hyperparamters on held-out data  for each value of the hyperparameters, train and test on held-out data \n\n11/18/21: Machine Learning: Perceptrons \n-Baseline: helps determine how hard a task is & what a “good” accuracy is\n\n-Confidence: how sure the classifier is of th-ML Naïve Bayes Summary:\n\t-Bayes’ Rule: lets us do diagnostic queries with causal probabilities\n\t-Naïve Bayes Assumptions: takes all features to be independent given the class label\n\t-we can build classifiers out of a naïve Bayes model using training data\n\t-Smoothing Estimates: is important in real life\n\t-Classifier Confidence: are useful, when you can get them\n\n-NOW… Perceptrons (like a neuron of a brain)\n\t-perceptron (sigmoid function) is a device that makes decisions by weighing up evidence\ne classification\n-Learning: Binary Perceptron: update weights for every item in training data\n\t-start with weights = 0\n\t-for each training instance:\n\t\t-classifiy with current weights\n\t\t-if correct: if y label with curent weights is correct (aka same as human label y*) (y = y*)  no change\n\t\t-if wrong: adjust weight vector\n-Properties of Perceptrons:\n\t1) Separability: true of some parameters get the training set perfectly correct\n\t2) Convergence: if the training is separable, perceptron will eventually converge (binary case)\n\t3) Mistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\n\n-Problems with Perceptron\n\t1) Noise: if data isn’t separable, weights might thrash  solution: averaging weight vectors over time \n\t2) Medocre generalization: finds a “barely” separable solution \n\t3) Overtraining: test/held-out accuracy usually rises, then falls (like overfitting)\n11/23/21\n-Fixing the Perceptron: adjust the weight update to mitigate the problems\n1)\tMIRA = Margin Infused Relaxed Algorithm; choose an update size that fixes the current mistake but minimizes the \tchange to w\n2)\tSupport Vector Machines (Linear Separator): maximize the margin\n3)\tMap Data to Higher-Dimensional Space (Non-Linear Separator)\n-SUMMARY  OF Classification: \n\t1) Naïve Bayes:\n\t\t-Builds a model training data\n\t\t-Gives prediction probabilities\n\t\t-Strong assumptions about feature independence\n\t\t-One pass through data (counting)\n\t2) Perceptrons / MIRA:\n\t\t-makes less assumptions about data\n\t\t-Mistake-driven learning\n\t\t-Multiple passes through data (prediction)\n\t\t-Often more accurate\n\n\n\n\n## Module 12 Definitions\n* **Concept** - definition\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\nJust ML:NN STUFF\nModule 13: Neural Networks\n11/23/21: Neural Networks: Logistic Regression \n\n-Logistic Regression:\n-Sentiment Classifier\n\t-normalize z (only difference b/t perceptron and logistic regression)\n-Extract Features:\n\t-add features for language and give it a value\n\t-multiply by weights to get z score\n\t-normalize z with signmoid function\n\n-Learning in Logistic Regession (learn WEIGHTS and BIAS)\n\t1) Objective/Loss Function: gives distance between output and given output  Cross-Entropy Loss\n\t2) Optimize Loss Function: Stochastic Gradient Descent\n\n\t-Cross-Entropy Loss: gives difference between y_hat and y\n\n11/30/21-Stochastic Gradient Descent\n-(worked example 36:00)\n\n-Mini-batch training\n\t-Stochastic  one example at a time, updates weights on that example\n\t-Batch Training  trains on whole dataset, slow\n\t-Mini-Batch training  trian on small batch\n\n-Regularization: penalize large weights to prevent overfitting\n\t1) Lasso regression (L1)\n\t2) Ridge regression (L2)\n\n-Multinomal Logistic Regression: positive, negative, neutral\n\t-softmax function (generalization of sigmoid function)w\n\n11/30/21: Machine Learning: Neural Networks \n\n-Perceptron  Logistic Regression\n-Sigmoid  Activation Function\n\n-Feed-Forward Neural Network \n_Equations of Feedforward NN\nh = sigma(Wx+b)\nz=Uh\ny=softmax(z)\n\nSummary:\nCross Entropy Loss Functoin\nGradient Descent to perform optimizatoin\nError back Propagation to compute the gradient of the loss function \n\n\n\n## Module 13 Definitions\n* **Concept** - definition\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\nJust ML:NN STUFF\nModule 13: Neural Networks\n11/23/21: Neural Networks: Logistic Regression \n\n-Logistic Regression:\n-Sentiment Classifier\n\t-normalize z (only difference b/t perceptron and logistic regression)\n-Extract Features:\n\t-add features for language and give it a value\n\t-multiply by weights to get z score\n\t-normalize z with signmoid function\n\n-Learning in Logistic Regession (learn WEIGHTS and BIAS)\n\t1) Objective/Loss Function: gives distance between output and given output  Cross-Entropy Loss\n\t2) Optimize Loss Function: Stochastic Gradient Descent\n\n\t-Cross-Entropy Loss: gives difference between y_hat and y\n\n11/30/21-Stochastic Gradient Descent\n-(worked example 36:00)\n\n-Mini-batch training\n\t-Stochastic  one example at a time, updates weights on that example\n\t-Batch Training  trains on whole dataset, slow\n\t-Mini-Batch training  trian on small batch\n\n-Regularization: penalize large weights to prevent overfitting\n\t1) Lasso regression (L1)\n\t2) Ridge regression (L2)\n\n-Multinomal Logistic Regression: positive, negative, neutral\n\t-softmax function (generalization of sigmoid function)w\n\n11/30/21: Machine Learning: Neural Networks \n\n-Perceptron  Logistic Regression\n-Sigmoid  Activation Function\n\n-Feed-Forward Neural Network \n_Equations of Feedforward NN\nh = sigma(Wx+b)\nz=Uh\ny=softmax(z)\n\nSummary:\nCross Entropy Loss Functoin\nGradient Descent to perform optimizatoin\nError back Propagation to compute the gradient of the loss function \n\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}