{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of Template_for CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": [
        "aPtM8g7R0Pds",
        "5yG3-YncJfTB",
        "GZZXyrV-xuAp",
        "9xRbdqDox2zD",
        "vX7lbnJd4sT5"
      ]
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "dbf52766-6262-485e-e065-b46f8c572ce1"
      },
      "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": 34,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "cdadc06a-9f51-4d50-b5fa-5ed949cdab96"
      },
      "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": 35,
      "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": 36,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "e063a711-214c-4b7b-f8e9-5f20eb6fdb75"
      },
      "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 = \"\"\" Our Problem space is given by a FULLY-OBSERVABLE environments where an agent\n",
        "sequentially picks actions.  The game or episode TERMINATES when the agent reaches a goal-state (failure or success). \n",
        "We also assume our environment to be STOCHASTIC, which means there is some uncertainty with each agent's action.  Thus, the\n",
        "longer the chain of fixed actions we give to our agent, the less likely it is to exactly follow all of the actions.  The\n",
        "Stochastic TRANSITION MODEL is given by $T(s, a, s') = p(s' | s, a)$, which in english tells us that the probability of reaching state s' from state s\n",
        "using action a, is independent of other prior events or states.  We also need to give our agent some REWARD or UTILITY FUNCTION, which is computed\n",
        "using a sequence of states and actions.  The REWARD FUNCTION usually gives positive rewards for success goal states, negative rewards for failure goal states, \n",
        "and small negative rewards for non-terminal states.  Rewards are ADDITIVE.  The solution of an MDP is called the POLICY, denoted as $\\pi^*$, which gives the\n",
        "optimal action at each state.  We must compute the expected utility of all possible paths realized in sampling from our Stochastic world.  The total\n",
        "REWARD or UTILITY is the sum of the rewards from each transition it makes.  Because we care more about the more recent rewards, we often discount rewards\n",
        "from earlier actions.  This is realized with a DISCOUNT FACTOR $\\gamma$.  Each MDP state projects and EXPECTIMAX-LIKE search tree, where there are transitions from\n",
        "the current state to various q-states of state-action pairs (similar to expectimax nodes), and then there are transitions from each q-state to each possible resulting\n",
        "state.  We denote the converged expected VALUE (utility) of a state as $V^*(s)$, and the expected Q-VALUE (utility) of a q-state as $Q^*(s,a)$.  Value Iteration\n",
        "is comprised of two main steps: Perform one-ply expectimax search for values at all states, and update them according to the recursive Optimal Value equation until convergence.\n",
        "The Bellman Update rules tell us that optimality conditions on taking the correct first action and taking optimal actions afterwards.  Policy oftentimes converges\n",
        "faster than values because our agent can perform optimally even with a suboptimal reward function.  Policy iteration leverages this fact and does the following: Fix $pi^i$.\n",
        "Update values until convergence for fixed poicy.  Update policy according to one-ply expectimax.  Repeat until convergence.  Both VALUE ITERATION and POLICY ITERATION are\n",
        "variations and applications of BELLMAN UPDATES. \\n\n",
        "\n",
        "A NOTE ON UTILITIES: We use the principle of maximum expected utility because the environment is stochastic.  Our utility function must therefore have appropriate magnitudes,\n",
        "not just relative preferences preserved.  UTILITIES are mappings from states to real numbers which describe an agent's preferences.  By only enforcing preferences,\n",
        "our agent can learn optimal behavior to achieve it's goal, rather than being constrained to behavior.  There are several axioms of preferences/utility, they are listed in\n",
        "the definitions.  For any preferences meet these constraints, there exists a utility function s.t. $U(A) \\geq U(B) \\Leftrightarrow A \\geq B$ and \n",
        "$U([p_1, S_1;...; [p_n, S_n]]) = \\sum_i p_iU(S_i)$.\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"Your definition here\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "\"Optimal Value\": \"$V^*(s) = max_a Q^*(s,a)$\",\n",
        "\"Optimal Q-Value\": \"$Q^*(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gammaV^*(s')]$\",\n",
        "\"Optimal Value (recursive)\": \"$V^*(s) = max_a \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma V^*(s')]$\",\n",
        "\"Value Iteration\": \"$V_{k+1}(s) \\leftarrow max_a \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma V_k(s')]$\",\n",
        "\"Policy Iteration (Evaluation)\": \"$V^{\\pi_i}_{k+1}(s) \\leftarrow \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s') + \\gamma V^{\\pi_i}_k(s')]$\",\n",
        "\"Policy Iteration (Improvement)\": \"$\\pi_{i+1}(s) = argmax_a \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s') + \\gamma V^{\\pi_i}_k(s')]$\",\n",
        "\"Rational Preferences (Axiom of Transitivity)\": \"$(A>B) \\wedge (B>C) \\Rightarrow (A>C)$\",\n",
        "\"Rational Preferences (Axiom of Orderability)\": \"$(A>B) \\lor (B>A) \\lor (A \\sim B)$\",\n",
        "\"Rational Preferences (Axiom of Continuity)\": \"$A>B>C \\Rightarrow \\exists p, [p,A; 1-p,C] \\sim B$\",\n",
        "\"Rational Preferences (Axiom of Substitutability)\": \"$A \\sim B \\Rightarrow [p,A; 1-p,C] \\sim [p,B; 1-p,C]$\",\n",
        "\"Rational Preferences (Axiom of Monotonicity)\": \"$A>B \\Rightarrow (p \\geq q \\Leftrightarrow [p,A; 1-p,B] \\geq [q,A; 1-q,B])$\"\n",
        "}\n",
        "\n",
        "print(\"The length in words is\", len(module8_lecture_notes.split(' ')))\n",
        "print(\"The length in characters is\", len(module8_lecture_notes))"
      ],
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 516\n",
            "The length in characters is 3296\n"
          ]
        }
      ]
    },
    {
      "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": 0
        },
        "outputId": "49b1394e-2731-41fb-a478-e253f8ee9978"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": 52,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n Our Problem space is given by a FULLY-OBSERVABLE environments where an agent\nsequentially picks actions.  The game or episode TERMINATES when the agent reaches a goal-state (failure or success). \nWe also assume our environment to be STOCHASTIC, which means there is some uncertainty with each agent's action.  Thus, the\nlonger the chain of fixed actions we give to our agent, the less likely it is to exactly follow all of the actions.  The\nStochastic TRANSITION MODEL is given by $T(s, a, s') = p(s' | s, a)$, which in english tells us that the probability of reaching state s' from state s\nusing action a, is independent of other prior events or states.  We also need to give our agent some REWARD or UTILITY FUNCTION, which is computed\nusing a sequence of states and actions.  The REWARD FUNCTION usually gives positive rewards for success goal states, negative rewards for failure goal states, \nand small negative rewards for non-terminal states.  Rewards are ADDITIVE.  The solution of an MDP is called the POLICY, denoted as $\\pi^*$, which gives the\noptimal action at each state.  We must compute the expected utility of all possible paths realized in sampling from our Stochastic world.  The total\nREWARD or UTILITY is the sum of the rewards from each transition it makes.  Because we care more about the more recent rewards, we often discount rewards\nfrom earlier actions.  This is realized with a DISCOUNT FACTOR $\\gamma$.  Each MDP state projects and EXPECTIMAX-LIKE search tree, where there are transitions from\nthe current state to various q-states of state-action pairs (similar to expectimax nodes), and then there are transitions from each q-state to each possible resulting\nstate.  We denote the converged expected VALUE (utility) of a state as $V^*(s)$, and the expected Q-VALUE (utility) of a q-state as $Q^*(s,a)$.  Value Iteration\nis comprised of two main steps: Perform one-ply expectimax search for values at all states, and update them according to the recursive Optimal Value equation until convergence.\nThe Bellman Update rules tell us that optimality conditions on taking the correct first action and taking optimal actions afterwards.  Policy oftentimes converges\nfaster than values because our agent can perform optimally even with a suboptimal reward function.  Policy iteration leverages this fact and does the following: Fix $pi^i$.\nUpdate values until convergence for fixed poicy.  Update policy according to one-ply expectimax.  Repeat until convergence.  Both VALUE ITERATION and POLICY ITERATION are\nvariations and applications of BELLMAN UPDATES. \n\n\nA NOTE ON UTILITIES: We use the principle of maximum expected utility because the environment is stochastic.  Our utility function must therefore have appropriate magnitudes,\nnot just relative preferences preserved.  UTILITIES are mappings from states to real numbers which describe an agent's preferences.  By only enforcing preferences,\nour agent can learn optimal behavior to achieve it's goal, rather than being constrained to behavior.  There are several axioms of preferences/utility, they are listed in\nthe definitions.  For any preferences meet these constraints, there exists a utility function s.t. $U(A) \\geq U(B) \\Leftrightarrow A \\geq B$ and \n$U([p_1, S_1;...; [p_n, S_n]]) = \\sum_i p_iU(S_i)$.\n\n\n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Optimal value** - $V^*(s) = max_a Q^*(s,a)$\n* **Optimal q-value** - $Q^*(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gammaV^*(s')]$\n* **Optimal value (recursive)** - $V^*(s) = max_a \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma V^*(s')]$\n* **Value iteration** - $V_{k+1}(s) \\leftarrow max_a \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma V_k(s')]$\n* **Policy iteration (evaluation)** - $V^{\\pi_i}_{k+1}(s) \\leftarrow \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s') + \\gamma V^{\\pi_i}_k(s')]$\n* **Policy iteration (improvement)** - $\\pi_{i+1}(s) = argmax_a \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s') + \\gamma V^{\\pi_i}_k(s')]$\n* **Rational preferences (axiom of transitivity)** - $(A>B) \\wedge (B>C) \\Rightarrow (A>C)$\n* **Rational preferences (axiom of orderability)** - $(A>B) \\lor (B>A) \\lor (A \\sim B)$\n* **Rational preferences (axiom of continuity)** - $A>B>C \\Rightarrow \\exists p, [p,A; 1-p,C] \\sim B$\n* **Rational preferences (axiom of substitutability)** - $A \\sim B \\Rightarrow [p,A; 1-p,C] \\sim [p,B; 1-p,C]$\n* **Rational preferences (axiom of monotonicity)** - $A>B \\Rightarrow (p \\geq q \\Leftrightarrow [p,A; 1-p,B] \\geq [q,A; 1-q,B])$\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 = \"\"\" Reinforcement Learning differs from an MDP beacause we don't/can't know\n",
        "all of the possible states, and therefore state/action pairs.  As such, our agent needs to take actions\n",
        "to learn it's policy, and find such a policy that maximizes expected rewards.  To formalize our setup,\n",
        "we still have a set of states and a set of actions for each state, but we no longer know the TRANSITION\n",
        "MODEL nor the REWARD FUNCTION.  In MODEL-BASED LEARNING, our agent learns an approximate transition model and\n",
        "reward function based on its experiences.  Our agent then solves the learned MDP using say value or policy iteration.\n",
        "In MODEL-FREE LEARNING, we do not explicitly develop a probabilistic model of transitions and rewards.  Instead, we \n",
        "only keep track of VALUES, so whenever an outcome deviates from our expectation, we only need to update values. \n",
        "In PASSIVE REINFORCEMENT LEARNING, we take actions according to the policy and learn from this experience.  Our goal is\n",
        "thus to compute the values for each state under a particular $\\pi$.  TEMPORAL DIFFERENCE LEARNING essentially updates\n",
        "V(s) each time we experience a particular transition (s,a,s',r).  With fixed policy, we update $V^{\\pi}(s)$ by an exponential\n",
        "moving average with the most recent sample.  This effectively weighs current estimates for a value more than the most recent samples. \n",
        "TD Learning learns values but cannot update policy according to values because Q-values are needed. \\n\n",
        "In ACTIVE REINFORCEMENT LEARNING, the learner makes choices, according to exploration and exploitation, and learns the optimal policy\n",
        "by Q-values and therefore by values.  Q-LEARNING uses the same idea as TD Learning, but uses q-values instead of values.  We still keep\n",
        "an exponential moving average of the samples for the Q-state for a particular state-action pair.  Q-LEARNING converges to optimal policy\n",
        "even if the agent is acting suboptimally.  However, in order to achieve this, the agent must balance EXPLORATION VS. EXPLOITATION, and make\n",
        "sure that the learning rate for incorporating new samples is small enough but won't decrease too quickly.  On the note of EXPLORATION VS. EXPLOITATION,\n",
        "one strategy to balance this tradeoff is with small probability $\\epsilon$, act randomly, and with large probability $(1 - \\epsilon)$, act on policy.  This \n",
        "ensures that new actions are explored sometimes, but in convergence, this probability should decrease.  REGRET is a measure of our agents \n",
        "total mistake cost over the course of learning.  APPROXIMATE Q-LEARNING uses a linear approximation of Q-values via a weighted summation of features. \n",
        "This idea is what generalizes into deep reinforcement learning.  By approximating the Q-values with a weighting function, we only need to update weights of\n",
        "our approximator.  With a neural network, this principle is leveraged by backpropogation.\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"Offline Planning\": \"Solving an MDP with fully-observable states and actions\",\n",
        "\"Online Planning\": \"Taking actions to learn an approximate MDP\",\n",
        "\"Sample-Based Policy Evaluation\": \"$V^{\\pi}_{k+1}(s) \\leftarrow \\\\frac{1}{n} \\sum_i R(s,\\pi(s),s_i') + \\gamma V^{\\pi}_k(s_i')$\",\n",
        "\"Temporal Difference Learning\": \"$V^{\\pi}(s) \\leftarrow (1 - \\\\alpha)V^{\\pi}(s) + \\\\alpha(R(s,\\pi(s),s') + \\gamma V^{\\pi}(s'))$\",\n",
        "\"Q-Value Iteration\": \"$Q_{k+1}(s,a) \\leftarrow \\sum_{s'}T(s,a,s')(R(s,a,s') + \\gamma max_{a'}Q_k(s',a'))$\"\n",
        "}"
      ],
      "execution_count": 53,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "cellView": "form",
        "outputId": "15ce6646-c539-4711-b58e-f5d6137af9f2"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": 54,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n Reinforcement Learning differs from an MDP beacause we don't/can't know\nall of the possible states, and therefore state/action pairs.  As such, our agent needs to take actions\nto learn it's policy, and find such a policy that maximizes expected rewards.  To formalize our setup,\nwe still have a set of states and a set of actions for each state, but we no longer know the TRANSITION\nMODEL nor the REWARD FUNCTION.  In MODEL-BASED LEARNING, our agent learns an approximate transition model and\nreward function based on its experiences.  Our agent then solves the learned MDP using say value or policy iteration.\nIn MODEL-FREE LEARNING, we do not explicitly develop a probabilistic model of transitions and rewards.  Instead, we \nonly keep track of VALUES, so whenever an outcome deviates from our expectation, we only need to update values. \nIn PASSIVE REINFORCEMENT LEARNING, we take actions according to the policy and learn from this experience.  Our goal is\nthus to compute the values for each state under a particular $\\pi$.  TEMPORAL DIFFERENCE LEARNING essentially updates\nV(s) each time we experience a particular transition (s,a,s',r).  With fixed policy, we update $V^{\\pi}(s)$ by an exponential\nmoving average with the most recent sample.  This effectively weighs current estimates for a value more than the most recent samples. \nTD Learning learns values but cannot update policy according to values because Q-values are needed. \n\nIn ACTIVE REINFORCEMENT LEARNING, the learner makes choices, according to exploration and exploitation, and learns the optimal policy\nby Q-values and therefore by values.  Q-LEARNING uses the same idea as TD Learning, but uses q-values instead of values.  We still keep\nan exponential moving average of the samples for the Q-state for a particular state-action pair.  Q-LEARNING converges to optimal policy\neven if the agent is acting suboptimally.  However, in order to achieve this, the agent must balance EXPLORATION VS. EXPLOITATION, and make\nsure that the learning rate for incorporating new samples is small enough but won't decrease too quickly.  On the note of EXPLORATION VS. EXPLOITATION,\none strategy to balance this tradeoff is with small probability $\\epsilon$, act randomly, and with large probability $(1 - \\epsilon)$, act on policy.  This \nensures that new actions are explored sometimes, but in convergence, this probability should decrease.  REGRET is a measure of our agents \ntotal mistake cost over the course of learning.  APPROXIMATE Q-LEARNING uses a linear approximation of Q-values via a weighted summation of features. \nThis idea is what generalizes into deep reinforcement learning.  By approximating the Q-values with a weighting function, we only need to update weights of\nour approximator.  With a neural network, this principle is leveraged by backpropogation.\n\n\n## Module 9 Definitions\n* **Offline planning** - Solving an MDP with fully-observable states and actions\n* **Online planning** - Taking actions to learn an approximate MDP\n* **Sample-based policy evaluation** - $V^{\\pi}_{k+1}(s) \\leftarrow \\frac{1}{n} \\sum_i R(s,\\pi(s),s_i') + \\gamma V^{\\pi}_k(s_i')$\n* **Temporal difference learning** - $V^{\\pi}(s) \\leftarrow (1 - \\alpha)V^{\\pi}(s) + \\alpha(R(s,\\pi(s),s') + \\gamma V^{\\pi}(s'))$\n* **Q-value iteration** - $Q_{k+1}(s,a) \\leftarrow \\sum_{s'}T(s,a,s')(R(s,a,s') + \\gamma max_{a'}Q_k(s',a'))$\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 = \"\"\" We'd now like to move forward with a probabilistic understanding of our world.  RANDOM VARIABLES\n",
        "are aspects of the world which we may have uncertainty about.  Given some set of states for random variables $w$, we way that\n",
        "if the state is possible, then its probability must be between 0 and 1.  PROBABILITY DISTRIBUTIONS are either discrete or \n",
        "continous, but regardless, they describe the probabilities of each possible state/value of a random variable. JOINT DISTRIBUTIONS\n",
        "describe the probabilities of each possible combination of states/values for two or more random variables.  The size of a joint\n",
        "distribution is $O(d^n)$ where d is the largest domain size and n is the number of variables.  A PROBABALISTIC MODEL is a joint\n",
        "distribution over a set of random variables.  The probability of an EVENT is the probability of a particular combination or set of \n",
        "combinations of states/values, are assigned to the variables in a Probabilistic Model.  MARGINAL DISTRIBUTIONS can be subtables of\n",
        "a joint distribution, but intuitively are the probability of one variable's assignment to a particular value or set of values, reagardless\n",
        "of the values of other variables.  CONDITIONAL PROBABILITY is one of our most important rules of probability, and it relates the JOINT DISTRIBUTION,\n",
        "MARGINAL DISTRIBUTION, and CONDITIONAL DISTRIBUTION.  This formulation for conditional probability then gives us BAYES RULE.\n",
        "We use the CHAIN RULE to help us compute joint distributions of more than two variables.  Bayes Rule allows us to compute and use the simplest\n",
        "distributions as inputs and output their joint.  \\n\n",
        "Probabilistic Language Modeling builds on the framework we have laid.  One of the fundamental tasks is to compute the probability of an upcoming word: \n",
        "$P(w_5 | w_1, w_2, w_3, w_4)$.  A LANGUAGE MODEL either computes this, or the probability of a sequence of words.  The joint probability\n",
        "of words in a sentence is given by: $P(w_1, w_2, ..., w_n) = \\Pi_i P(w_i | w_1w_2...w_{i-1})$.  This can be extremely computationally\n",
        "intensive to compute, especially for long sentences, so it pays off to make a Markovian Assumption that the next word depends only on the prior $k$ words.\n",
        "This limits the preceding context of a particular word to improve computation efficiency, while also enriching our model's ability to generalize on\n",
        "new patterns.  These simple models are called N_GRAM MODELS, and are limited by the fact that language has long-distance dependencies that cannot be captured\n",
        "by near neighbor word associations.\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"Marginal Probability Distribution\": \"$P(t) = \\sum_{s}P(t,s)$\",\n",
        "\"Conditional Probability Distribution\": \"$P(a|b) = \\\\frac{P(a,b)}{P(b)}$\",\n",
        "\"Bayes Rule\": \"$P(x|y) = \\\\frac{P(y|x)}{P(y)}P(x)$\"\n",
        "}"
      ],
      "execution_count": 55,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "cellView": "form",
        "outputId": "1342d46a-84df-4cb8-fa04-6a57712bbd1b"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": 56,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n We'd now like to move forward with a probabilistic understanding of our world.  RANDOM VARIABLES\nare aspects of the world which we may have uncertainty about.  Given some set of states for random variables $w$, we way that\nif the state is possible, then its probability must be between 0 and 1.  PROBABILITY DISTRIBUTIONS are either discrete or \ncontinous, but regardless, they describe the probabilities of each possible state/value of a random variable. JOINT DISTRIBUTIONS\ndescribe the probabilities of each possible combination of states/values for two or more random variables.  The size of a joint\ndistribution is $O(d^n)$ where d is the largest domain size and n is the number of variables.  A PROBABALISTIC MODEL is a joint\ndistribution over a set of random variables.  The probability of an EVENT is the probability of a particular combination or set of \ncombinations of states/values, are assigned to the variables in a Probabilistic Model.  MARGINAL DISTRIBUTIONS can be subtables of\na joint distribution, but intuitively are the probability of one variable's assignment to a particular value or set of values, reagardless\nof the values of other variables.  CONDITIONAL PROBABILITY is one of our most important rules of probability, and it relates the JOINT DISTRIBUTION,\nMARGINAL DISTRIBUTION, and CONDITIONAL DISTRIBUTION.  This formulation for conditional probability then gives us BAYES RULE.\nWe use the CHAIN RULE to help us compute joint distributions of more than two variables.  Bayes Rule allows us to compute and use the simplest\ndistributions as inputs and output their joint.  \n\nProbabilistic Language Modeling builds on the framework we have laid.  One of the fundamental tasks is to compute the probability of an upcoming word: \n$P(w_5 | w_1, w_2, w_3, w_4)$.  A LANGUAGE MODEL either computes this, or the probability of a sequence of words.  The joint probability\nof words in a sentence is given by: $P(w_1, w_2, ..., w_n) = \\Pi_i P(w_i | w_1w_2...w_{i-1})$.  This can be extremely computationally\nintensive to compute, especially for long sentences, so it pays off to make a Markovian Assumption that the next word depends only on the prior $k$ words.\nThis limits the preceding context of a particular word to improve computation efficiency, while also enriching our model's ability to generalize on\nnew patterns.  These simple models are called N_GRAM MODELS, and are limited by the fact that language has long-distance dependencies that cannot be captured\nby near neighbor word associations.\n \n\n## Module 10 Definitions\n* **Marginal probability distribution** - $P(t) = \\sum_{s}P(t,s)$\n* **Conditional probability distribution** - $P(a|b) = \\frac{P(a,b)}{P(b)}$\n* **Bayes rule** - $P(x|y) = \\frac{P(y|x)}{P(y)}P(x)$\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" Two variables are INDEPENDENT if for all x,y: P(x, y) = P(x)P(y).  We can\n",
        "write this in terms of conditional probability as: for all x,y: P(x|y) = P(x).  We write this as $X \\\\bot Y$.\n",
        "CONDITIONAL INDEPENDENCE tells us that X is conditionally independent of Y given Z $\\Leftrightarrow \\\\forall$ x,y,z: P(x|z,y) = P(x|z).\n",
        "BAYES NETS are a technique for describing complex joint probability distributions (models) using simple, local distributions (conditional probabilities).\n",
        "Nodes in a Bayes Net are variables with domains which can be assigned if the variable is observed or unassigned if the variable is unobserved.\n",
        "Directed Edges are called Arcs, which indicate direct influence between variables.  An arc from A to B means that A has strong implication on the value of \n",
        "B.  The conditional distribution at each node is conditioned by all of the incoming arcs to the node.  Thus, a Bayes Net is a DAG whose nodes contain \n",
        "a distribution conditioned on all variables with arcs to that node, such that it is a representation of a joint distribution.  In this formulation,\n",
        "we only need to condition on the parents of the current node, which simplifies computation.  Bayes Nets which reflect causal relationships are often\n",
        "simpler and more intuitive.  Not all Bayes Nets need to reflect causality.  Bayes Nets provide a massive space complexity improvement over a joint distribution\n",
        "table.  In fact, an N boolean variable joint distribution requires $2^N$ rows, while an N-node Bayes Net with maximal indegree of k requires $O(N*2^{k+1})$ space. \n",
        "A CAUSAL CHAIN is some chain of variables with arcs in a Bayes Net s.t. $P(x,y,z) = P(x)P(y|x)P(z|y)$.  A COMMON CAUSE is a set of three variables where one variable\n",
        "has an arc to two different variables, but the two different variables are unrelated to each other.  A COMMON EFFECT is the opposite case: for a set of three variables,\n",
        "two variables have arcs to the remaining variable, but not arcs to each other.  REACHABILITY is parameterized by the notion of active and inactive paths in a Bayes Net.\n",
        "A Path is ACTIVE if each triple of nodes with arcs between them is either a CAUSAL CHAIN, COMMON CAUSE, or COMMON EFFECT.  D-SEPARATION is used when we'd like to determine\n",
        "some conditional independence between more than 3 variables, for instance $X_i \\\\bot X_j | {X_{k_1},..., X_{k_n}}$.  This is done by checking all UNDIRECTED PATHS between\n",
        "variables $X_i$ and $X_j$.  If all undirected paths between these two variables are INACTIVE, then the conditional independence statement holds.  INFERENCE BY ENUMERATION\n",
        "is a method of inferencing which uses hidden variables summed out to get a Joint Distribution of a Query Variable and some evidence variables.   \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 57,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "9c3c3cf1-e7c7-4129-9d7f-2d2a3138ad84"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": 58,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n Two variables are INDEPENDENT if for all x,y: P(x, y) = P(x)P(y).  We can\nwrite this in terms of conditional probability as: for all x,y: P(x|y) = P(x).  We write this as $X \\bot Y$.\nCONDITIONAL INDEPENDENCE tells us that X is conditionally independent of Y given Z $\\Leftrightarrow \\forall$ x,y,z: P(x|z,y) = P(x|z).\nBAYES NETS are a technique for describing complex joint probability distributions (models) using simple, local distributions (conditional probabilities).\nNodes in a Bayes Net are variables with domains which can be assigned if the variable is observed or unassigned if the variable is unobserved.\nDirected Edges are called Arcs, which indicate direct influence between variables.  An arc from A to B means that A has strong implication on the value of \nB.  The conditional distribution at each node is conditioned by all of the incoming arcs to the node.  Thus, a Bayes Net is a DAG whose nodes contain \na distribution conditioned on all variables with arcs to that node, such that it is a representation of a joint distribution.  In this formulation,\nwe only need to condition on the parents of the current node, which simplifies computation.  Bayes Nets which reflect causal relationships are often\nsimpler and more intuitive.  Not all Bayes Nets need to reflect causality.  Bayes Nets provide a massive space complexity improvement over a joint distribution\ntable.  In fact, an N boolean variable joint distribution requires $2^N$ rows, while an N-node Bayes Net with maximal indegree of k requires $O(N*2^{k+1})$ space. \nA CAUSAL CHAIN is some chain of variables with arcs in a Bayes Net s.t. $P(x,y,z) = P(x)P(y|x)P(z|y)$.  A COMMON CAUSE is a set of three variables where one variable\nhas an arc to two different variables, but the two different variables are unrelated to each other.  A COMMON EFFECT is the opposite case: for a set of three variables,\ntwo variables have arcs to the remaining variable, but not arcs to each other.  REACHABILITY is parameterized by the notion of active and inactive paths in a Bayes Net.\nA Path is ACTIVE if each triple of nodes with arcs between them is either a CAUSAL CHAIN, COMMON CAUSE, or COMMON EFFECT.  D-SEPARATION is used when we'd like to determine\nsome conditional independence between more than 3 variables, for instance $X_i \\bot X_j | {X_{k_1},..., X_{k_n}}$.  This is done by checking all UNDIRECTED PATHS between\nvariables $X_i$ and $X_j$.  If all undirected paths between these two variables are INACTIVE, then the conditional independence statement holds.  INFERENCE BY ENUMERATION\nis a method of inferencing which uses hidden variables summed out to get a Joint Distribution of a Query Variable and some evidence variables.   \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 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 59,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "cellView": "form",
        "outputId": "38089f61-f053-47b6-aa75-4534ad4b9264"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module12_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter19_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter19_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter19_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter19_4),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter19_5),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter19_6),\n",
        "  (\"SLP Chapter 4.1 Naive Bayes Classifiers\", slp_chapter4_1),\n",
        "  (\"SLP Chapter 4.2 Training the Naive Bayes Classifier\", slp_chapter4_2),\n",
        "  (\"SLP Chapter 4.3 Worked Example\", slp_chapter4_3),\n",
        "  (\"SLP Chapter 4.4 Optimizing for Sentiment Analysis\", slp_chapter4_4),\n",
        "  (\"SLP Chapter 4.5 Naive Bayes for other text classification tasks\", slp_chapter4_5),\n",
        "  (\"SLP Chapter 4.6 Naive Bayes as a Language Model\", slp_chapter4_6),\n",
        "  (\"SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\", slp_chapter4_7),\n",
        "  (\"SLP Chapter 4.8 Test sets and Cross-validation\", slp_chapter4_8),\n",
        "  (\"SLP Chapter 4.9 Statistical Significance Testing\", slp_chapter4_9),\n",
        "  (\"SLP Chapter 4.10 Avoiding Harms in Classification\", slp_chapter4_10),\n",
        "  (\"Module 12 Lecture Notes\", module12_lecture_notes),\n",
        "]\n",
        "\n",
        "module12_markdown = format_module(12, \"Naive Bayes and Perceptrons\", \n",
        "                         module12_sections, \n",
        "                         module12_definitions)\n",
        "display(Markdown(module12_markdown))"
      ],
      "execution_count": 60,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n Your summary here \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 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 61,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "cellView": "form",
        "outputId": "33e729c7-1e59-4902-9ffe-a38208c0b50c"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": 62,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 13 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 63,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "c8a0ef65-080c-47ff-d124-187e0c8d232a"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module14_sections = [\n",
        "  (\"SLP Chapter 9.1 Language Models Revisited\", slp_chapter9_1),\n",
        "  (\"SLP Chapter 9.2 Recurrent Neural Networks\", slp_chapter9_2),\n",
        "  (\"SLP Chapter 9.3 RNNs as Language Models\", slp_chapter9_3),\n",
        "\n",
        "  (\"SLP Chapter 6.1 Lexical Semantics\", slp_chapter6_1),\n",
        "  (\"SLP Chapter 6.2 Vector Semantics\", slp_chapter6_2),\n",
        "  (\"SLP Chapter 6.3 Words and Vectors\", slp_chapter6_3),\n",
        "  (\"SLP Chapter 6.4 Cosine for measuring similarity\", slp_chapter6_4),\n",
        "  (\"SLP Chapter 6.8 Word2vec\", slp_chapter6_8),\n",
        "  (\"SLP Chapter 6.10 Semantic properties of embeddings\", slp_chapter6_10),\n",
        "  (\"SLP Chapter 6.11 Bias and Embeddings\", slp_chapter6_11),\n",
        "  (\"SLP Chapter 6.12 Evaluating Vector Models\", slp_chapter6_12),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module14_markdown = format_module(14, \"Natural Language Processing\", \n",
        "                         module14_sections, \n",
        "                         module14_definitions)\n",
        "display(Markdown(module14_markdown))"
      ],
      "execution_count": 64,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n Your summary here \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": 7473
        },
        "id": "T3cm1WV542_a",
        "outputId": "2629fec1-cdcb-4e3b-a60f-6f012234ca4c"
      },
      "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": 68,
      "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 Our Problem space is given by a FULLY-OBSERVABLE environments where an agent\nsequentially picks actions.  The game or episode TERMINATES when the agent reaches a goal-state (failure or success). \nWe also assume our environment to be STOCHASTIC, which means there is some uncertainty with each agent's action.  Thus, the\nlonger the chain of fixed actions we give to our agent, the less likely it is to exactly follow all of the actions.  The\nStochastic TRANSITION MODEL is given by $T(s, a, s') = p(s' | s, a)$, which in english tells us that the probability of reaching state s' from state s\nusing action a, is independent of other prior events or states.  We also need to give our agent some REWARD or UTILITY FUNCTION, which is computed\nusing a sequence of states and actions.  The REWARD FUNCTION usually gives positive rewards for success goal states, negative rewards for failure goal states, \nand small negative rewards for non-terminal states.  Rewards are ADDITIVE.  The solution of an MDP is called the POLICY, denoted as $\\pi^*$, which gives the\noptimal action at each state.  We must compute the expected utility of all possible paths realized in sampling from our Stochastic world.  The total\nREWARD or UTILITY is the sum of the rewards from each transition it makes.  Because we care more about the more recent rewards, we often discount rewards\nfrom earlier actions.  This is realized with a DISCOUNT FACTOR $\\gamma$.  Each MDP state projects and EXPECTIMAX-LIKE search tree, where there are transitions from\nthe current state to various q-states of state-action pairs (similar to expectimax nodes), and then there are transitions from each q-state to each possible resulting\nstate.  We denote the converged expected VALUE (utility) of a state as $V^*(s)$, and the expected Q-VALUE (utility) of a q-state as $Q^*(s,a)$.  Value Iteration\nis comprised of two main steps: Perform one-ply expectimax search for values at all states, and update them according to the recursive Optimal Value equation until convergence.\nThe Bellman Update rules tell us that optimality conditions on taking the correct first action and taking optimal actions afterwards.  Policy oftentimes converges\nfaster than values because our agent can perform optimally even with a suboptimal reward function.  Policy iteration leverages this fact and does the following: Fix $pi^i$.\nUpdate values until convergence for fixed poicy.  Update policy according to one-ply expectimax.  Repeat until convergence.  Both VALUE ITERATION and POLICY ITERATION are\nvariations and applications of BELLMAN UPDATES. \n\n\nA NOTE ON UTILITIES: We use the principle of maximum expected utility because the environment is stochastic.  Our utility function must therefore have appropriate magnitudes,\nnot just relative preferences preserved.  UTILITIES are mappings from states to real numbers which describe an agent's preferences.  By only enforcing preferences,\nour agent can learn optimal behavior to achieve it's goal, rather than being constrained to behavior.  There are several axioms of preferences/utility, they are listed in\nthe definitions.  For any preferences meet these constraints, there exists a utility function s.t. $U(A) \\geq U(B) \\Leftrightarrow A \\geq B$ and \n$U([p_1, S_1;...; [p_n, S_n]]) = \\sum_i p_iU(S_i)$.\n\n\n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Optimal value** - $V^*(s) = max_a Q^*(s,a)$\n* **Optimal q-value** - $Q^*(s,a) = \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gammaV^*(s')]$\n* **Optimal value (recursive)** - $V^*(s) = max_a \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma V^*(s')]$\n* **Value iteration** - $V_{k+1}(s) \\leftarrow max_a \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gamma V_k(s')]$\n* **Policy iteration (evaluation)** - $V^{\\pi_i}_{k+1}(s) \\leftarrow \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s') + \\gamma V^{\\pi_i}_k(s')]$\n* **Policy iteration (improvement)** - $\\pi_{i+1}(s) = argmax_a \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s') + \\gamma V^{\\pi_i}_k(s')]$\n* **Rational preferences (axiom of transitivity)** - $(A>B) \\wedge (B>C) \\Rightarrow (A>C)$\n* **Rational preferences (axiom of orderability)** - $(A>B) \\lor (B>A) \\lor (A \\sim B)$\n* **Rational preferences (axiom of continuity)** - $A>B>C \\Rightarrow \\exists p, [p,A; 1-p,C] \\sim B$\n* **Rational preferences (axiom of substitutability)** - $A \\sim B \\Rightarrow [p,A; 1-p,C] \\sim [p,B; 1-p,C]$\n* **Rational preferences (axiom of monotonicity)** - $A>B \\Rightarrow (p \\geq q \\Leftrightarrow [p,A; 1-p,B] \\geq [q,A; 1-q,B])$\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 Reinforcement Learning differs from an MDP beacause we don't/can't know\nall of the possible states, and therefore state/action pairs.  As such, our agent needs to take actions\nto learn it's policy, and find such a policy that maximizes expected rewards.  To formalize our setup,\nwe still have a set of states and a set of actions for each state, but we no longer know the TRANSITION\nMODEL nor the REWARD FUNCTION.  In MODEL-BASED LEARNING, our agent learns an approximate transition model and\nreward function based on its experiences.  Our agent then solves the learned MDP using say value or policy iteration.\nIn MODEL-FREE LEARNING, we do not explicitly develop a probabilistic model of transitions and rewards.  Instead, we \nonly keep track of VALUES, so whenever an outcome deviates from our expectation, we only need to update values. \nIn PASSIVE REINFORCEMENT LEARNING, we take actions according to the policy and learn from this experience.  Our goal is\nthus to compute the values for each state under a particular $\\pi$.  TEMPORAL DIFFERENCE LEARNING essentially updates\nV(s) each time we experience a particular transition (s,a,s',r).  With fixed policy, we update $V^{\\pi}(s)$ by an exponential\nmoving average with the most recent sample.  This effectively weighs current estimates for a value more than the most recent samples. \nTD Learning learns values but cannot update policy according to values because Q-values are needed. \n\nIn ACTIVE REINFORCEMENT LEARNING, the learner makes choices, according to exploration and exploitation, and learns the optimal policy\nby Q-values and therefore by values.  Q-LEARNING uses the same idea as TD Learning, but uses q-values instead of values.  We still keep\nan exponential moving average of the samples for the Q-state for a particular state-action pair.  Q-LEARNING converges to optimal policy\neven if the agent is acting suboptimally.  However, in order to achieve this, the agent must balance EXPLORATION VS. EXPLOITATION, and make\nsure that the learning rate for incorporating new samples is small enough but won't decrease too quickly.  On the note of EXPLORATION VS. EXPLOITATION,\none strategy to balance this tradeoff is with small probability $\\epsilon$, act randomly, and with large probability $(1 - \\epsilon)$, act on policy.  This \nensures that new actions are explored sometimes, but in convergence, this probability should decrease.  REGRET is a measure of our agents \ntotal mistake cost over the course of learning.  APPROXIMATE Q-LEARNING uses a linear approximation of Q-values via a weighted summation of features. \nThis idea is what generalizes into deep reinforcement learning.  By approximating the Q-values with a weighting function, we only need to update weights of\nour approximator.  With a neural network, this principle is leveraged by backpropogation.\n\n\n## Module 9 Definitions\n* **Offline planning** - Solving an MDP with fully-observable states and actions\n* **Online planning** - Taking actions to learn an approximate MDP\n* **Sample-based policy evaluation** - $V^{\\pi}_{k+1}(s) \\leftarrow \\frac{1}{n} \\sum_i R(s,\\pi(s),s_i') + \\gamma V^{\\pi}_k(s_i')$\n* **Temporal difference learning** - $V^{\\pi}(s) \\leftarrow (1 - \\alpha)V^{\\pi}(s) + \\alpha(R(s,\\pi(s),s') + \\gamma V^{\\pi}(s'))$\n* **Q-value iteration** - $Q_{k+1}(s,a) \\leftarrow \\sum_{s'}T(s,a,s')(R(s,a,s') + \\gamma max_{a'}Q_k(s',a'))$\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 We'd now like to move forward with a probabilistic understanding of our world.  RANDOM VARIABLES\nare aspects of the world which we may have uncertainty about.  Given some set of states for random variables $w$, we way that\nif the state is possible, then its probability must be between 0 and 1.  PROBABILITY DISTRIBUTIONS are either discrete or \ncontinous, but regardless, they describe the probabilities of each possible state/value of a random variable. JOINT DISTRIBUTIONS\ndescribe the probabilities of each possible combination of states/values for two or more random variables.  The size of a joint\ndistribution is $O(d^n)$ where d is the largest domain size and n is the number of variables.  A PROBABALISTIC MODEL is a joint\ndistribution over a set of random variables.  The probability of an EVENT is the probability of a particular combination or set of \ncombinations of states/values, are assigned to the variables in a Probabilistic Model.  MARGINAL DISTRIBUTIONS can be subtables of\na joint distribution, but intuitively are the probability of one variable's assignment to a particular value or set of values, reagardless\nof the values of other variables.  CONDITIONAL PROBABILITY is one of our most important rules of probability, and it relates the JOINT DISTRIBUTION,\nMARGINAL DISTRIBUTION, and CONDITIONAL DISTRIBUTION.  This formulation for conditional probability then gives us BAYES RULE.\nWe use the CHAIN RULE to help us compute joint distributions of more than two variables.  Bayes Rule allows us to compute and use the simplest\ndistributions as inputs and output their joint.  \n\nProbabilistic Language Modeling builds on the framework we have laid.  One of the fundamental tasks is to compute the probability of an upcoming word: \n$P(w_5 | w_1, w_2, w_3, w_4)$.  A LANGUAGE MODEL either computes this, or the probability of a sequence of words.  The joint probability\nof words in a sentence is given by: $P(w_1, w_2, ..., w_n) = \\Pi_i P(w_i | w_1w_2...w_{i-1})$.  This can be extremely computationally\nintensive to compute, especially for long sentences, so it pays off to make a Markovian Assumption that the next word depends only on the prior $k$ words.\nThis limits the preceding context of a particular word to improve computation efficiency, while also enriching our model's ability to generalize on\nnew patterns.  These simple models are called N_GRAM MODELS, and are limited by the fact that language has long-distance dependencies that cannot be captured\nby near neighbor word associations.\n \n\n## Module 10 Definitions\n* **Marginal probability distribution** - $P(t) = \\sum_{s}P(t,s)$\n* **Conditional probability distribution** - $P(a|b) = \\frac{P(a,b)}{P(b)}$\n* **Bayes rule** - $P(x|y) = \\frac{P(y|x)}{P(y)}P(x)$\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n Two variables are INDEPENDENT if for all x,y: P(x, y) = P(x)P(y).  We can\nwrite this in terms of conditional probability as: for all x,y: P(x|y) = P(x).  We write this as $X \\bot Y$.\nCONDITIONAL INDEPENDENCE tells us that X is conditionally independent of Y given Z $\\Leftrightarrow \\forall$ x,y,z: P(x|z,y) = P(x|z).\nBAYES NETS are a technique for describing complex joint probability distributions (models) using simple, local distributions (conditional probabilities).\nNodes in a Bayes Net are variables with domains which can be assigned if the variable is observed or unassigned if the variable is unobserved.\nDirected Edges are called Arcs, which indicate direct influence between variables.  An arc from A to B means that A has strong implication on the value of \nB.  The conditional distribution at each node is conditioned by all of the incoming arcs to the node.  Thus, a Bayes Net is a DAG whose nodes contain \na distribution conditioned on all variables with arcs to that node, such that it is a representation of a joint distribution.  In this formulation,\nwe only need to condition on the parents of the current node, which simplifies computation.  Bayes Nets which reflect causal relationships are often\nsimpler and more intuitive.  Not all Bayes Nets need to reflect causality.  Bayes Nets provide a massive space complexity improvement over a joint distribution\ntable.  In fact, an N boolean variable joint distribution requires $2^N$ rows, while an N-node Bayes Net with maximal indegree of k requires $O(N*2^{k+1})$ space. \nA CAUSAL CHAIN is some chain of variables with arcs in a Bayes Net s.t. $P(x,y,z) = P(x)P(y|x)P(z|y)$.  A COMMON CAUSE is a set of three variables where one variable\nhas an arc to two different variables, but the two different variables are unrelated to each other.  A COMMON EFFECT is the opposite case: for a set of three variables,\ntwo variables have arcs to the remaining variable, but not arcs to each other.  REACHABILITY is parameterized by the notion of active and inactive paths in a Bayes Net.\nA Path is ACTIVE if each triple of nodes with arcs between them is either a CAUSAL CHAIN, COMMON CAUSE, or COMMON EFFECT.  D-SEPARATION is used when we'd like to determine\nsome conditional independence between more than 3 variables, for instance $X_i \\bot X_j | {X_{k_1},..., X_{k_n}}$.  This is done by checking all UNDIRECTED PATHS between\nvariables $X_i$ and $X_j$.  If all undirected paths between these two variables are INACTIVE, then the conditional independence statement holds.  INFERENCE BY ENUMERATION\nis a method of inferencing which uses hidden variables summed out to get a Joint Distribution of a Query Variable and some evidence variables.   \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 Your summary here \n\n## Module 12 Definitions\n* **Concept** - definition\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 13 Definitions\n* **Concept** - definition\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}