{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Final_Exam_Notes",
      "provenance": [],
      "collapsed_sections": [
        "F3FPMzG9yUls",
        "qVSQhTVSyYYO",
        "RYESi2kMybL8"
      ]
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "31b1e202-ebe8-4c32-9e1d-410522d6a579"
      },
      "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": 43,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "174bde11-7991-400e-ddee-b2f9a99ad513"
      },
      "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": 44,
      "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 = False"
      ],
      "execution_count": 45,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" Chapter 16.1 summary. \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\" Solution for an MDP is called a Policy - takes in a state and returns the best action an agent could take. Non-deterministic search.\n",
        "**Stochastic** : each action doesn't always have the same result. there is a % like 80% of the time when I select an action, I end up where I expect. \n",
        "\n",
        "- Our transition model has changed. Instead of having successors, we have to have a transition function that takes in the current state s, some action that could be performed a, and the\n",
        "resulting state, s'. This function will return the probability of arriving in state s' given that we are in state s and we selected action a. Transitions only depend on s and not the \n",
        "history of earlier states.\n",
        "\n",
        "-reward function. \n",
        "\n",
        "- sequential deciion problem\n",
        "  - fully observable environment\n",
        "  - stochastic transition model\n",
        "  - additive rewards\n",
        "  \n",
        "- MDP:\n",
        " 1. a set of states\n",
        " 2. a set of actions\n",
        " 3. transition function T(s, a, s')\n",
        "    - probability that executing a in s will lead to s'\n",
        "    - called the model\n",
        " 4. a reward function R(s, a, s')\n",
        " 5. an initial state\n",
        " 6. optionally, one or more terminal states\n",
        " \n",
        " \n",
        " \n",
        " - solution to MDP is different. It's not a sequence of actions because it's non deterministic. We need a **policy**\n",
        " \n",
        " **policy** given that i find myself in state s, whats the best action i should take. maps from a state onto the action to take if the agent is in that state.\n",
        "\n",
        " $\\pi$(s) = a. policy $\\pi$ tells the agent what action to take at state s\n",
        "\n",
        "\n",
        "\n",
        "-utilities of sequences? we want more and we want it sooner. Because it's a stochastic environment, if we defer, there's some chance of not getting it\n",
        "\n",
        "**Discounting**\n",
        "- reasonable to maximize the sum of rewards\n",
        "- also reasonable to prefer rewards now to rewards later\n",
        "- one solution: values of rewards decay exponentially. i.e. if we have to wait, we multiply the reward by some discount factor($\\gamma$) (less than 1). and if we have to wait 2 times in the future, we multiply it by $\\gamma ^2$\n",
        "- sooner rewards are going to have higher utility to us than later \n",
        "\n",
        "i.e. dicount of 0.5:\n",
        "U(1,2,3) = 0.5^0 * 1 + 0.5^1 * 2 + 0.5^2 *3\n",
        "        = 1*1 + 0.5*2 + 0.25*3\n",
        "        = U(1,2,3) < U(3,2,1)\n",
        "\n",
        "\n",
        "Solutions to inifinte utilities:\n",
        "- finite horizon: similar to depth limited search. terminate after fixed T steps\n",
        "- discounting: use 0 < $\\gamma$ < 1\n",
        "- absorbing state: guarantee that for every policy, a terminal state will eventually be reached\n",
        "\n",
        "\n",
        "Optimal Quantities:\n",
        "- V*(s) = expected utility starting in s and acting optimally \n",
        "- Q *(s, a) = value (utility) of a q-state(s,a). expected utility starting out having taken action a from state s and therafter acting optimally\n",
        "= $\\pi$ (s) = optimal action from state s\n",
        "\n",
        "\n",
        "\n",
        "Value Iteration:\n",
        "\n",
        "Start with $V_0$(S) = 0: no time steps left means an expected reward sum of zero\n",
        "\n",
        "Given vector of $V_k(s) values, do one ply of expectimax from each state\n",
        "\n",
        "Theorem: will converge to unique optimal values\n",
        "- basic idea: approximations get refined towards optimal values\n",
        "\n",
        "\n",
        "Policy Evaluation:\n",
        "\n",
        "- another basic operation: compute the utility of a state s under a fixed policy (non optimal)\n",
        "- define the utility of a state s, under a fixed policy $\\pi$\n",
        "\n",
        "\n",
        "- Step 1: Policy Evaluation - calculate utilities for some fixed policy (not optimal utilities) until convergence. For fixed current policy $\\pi$, find values with policy evaluation\n",
        "- Step 2: Policy improvement - update policy using one-step look-ahead with resulting converged (but not optimal) utilities as future values\n",
        "- Repeat until policy converges using policy extraction\n",
        "\n",
        "- This is policy iteration\n",
        "\n",
        "**you want to:**\n",
        "\n",
        "- compute optimal values: use value iteration or policy iteration\n",
        "- compute values for a particular policy: use policy evaluation\n",
        "- turn your values into a policy: use policy extraction\n",
        "Both value iteration and policy iteration compute the same thing (all optimal values)\n",
        "\n",
        "\n",
        "- if given a particular policy, compute values using policy evaluation\n",
        "- to turn your values into a policy: use policy extraction (one step lookahead)\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "**Maximum Expected Utility**\n",
        "- a rational agent should choose the action that maximizes its expected utility, given its knowledge\n",
        "- Utilities: functions from outcomes(states of the world) to real numbers that describe an agent's preferences \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",
        "\"etc.\": \"your definition here\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 46,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "d21b7c67-c1ca-49c7-d3b0-90b7b0ad7f68"
      },
      "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": 47,
      "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 Solution for an MDP is called a Policy - takes in a state and returns the best action an agent could take. Non-deterministic search.\n**Stochastic** : each action doesn't always have the same result. there is a % like 80% of the time when I select an action, I end up where I expect. \n\n- Our transition model has changed. Instead of having successors, we have to have a transition function that takes in the current state s, some action that could be performed a, and the\nresulting state, s'. This function will return the probability of arriving in state s' given that we are in state s and we selected action a. Transitions only depend on s and not the \nhistory of earlier states.\n\n-reward function. \n\n- sequential deciion problem\n  - fully observable environment\n  - stochastic transition model\n  - additive rewards\n  \n- MDP:\n 1. a set of states\n 2. a set of actions\n 3. transition function T(s, a, s')\n    - probability that executing a in s will lead to s'\n    - called the model\n 4. a reward function R(s, a, s')\n 5. an initial state\n 6. optionally, one or more terminal states\n \n \n \n - solution to MDP is different. It's not a sequence of actions because it's non deterministic. We need a **policy**\n \n **policy** given that i find myself in state s, whats the best action i should take. maps from a state onto the action to take if the agent is in that state.\n\n $\\pi$(s) = a. policy $\\pi$ tells the agent what action to take at state s\n\n\n\n-utilities of sequences? we want more and we want it sooner. Because it's a stochastic environment, if we defer, there's some chance of not getting it\n\n**Discounting**\n- reasonable to maximize the sum of rewards\n- also reasonable to prefer rewards now to rewards later\n- one solution: values of rewards decay exponentially. i.e. if we have to wait, we multiply the reward by some discount factor($\\gamma$) (less than 1). and if we have to wait 2 times in the future, we multiply it by $\\gamma ^2$\n- sooner rewards are going to have higher utility to us than later \n\ni.e. dicount of 0.5:\nU(1,2,3) = 0.5^0 * 1 + 0.5^1 * 2 + 0.5^2 *3\n        = 1*1 + 0.5*2 + 0.25*3\n        = U(1,2,3) < U(3,2,1)\n\n\nSolutions to inifinte utilities:\n- finite horizon: similar to depth limited search. terminate after fixed T steps\n- discounting: use 0 < $\\gamma$ < 1\n- absorbing state: guarantee that for every policy, a terminal state will eventually be reached\n\n\nOptimal Quantities:\n- V*(s) = expected utility starting in s and acting optimally \n- Q *(s, a) = value (utility) of a q-state(s,a). expected utility starting out having taken action a from state s and therafter acting optimally\n= $\\pi$ (s) = optimal action from state s\n\n\n\nValue Iteration:\n\nStart with $V_0$(S) = 0: no time steps left means an expected reward sum of zero\n\nGiven vector of $V_k(s) values, do one ply of expectimax from each state\n\nTheorem: will converge to unique optimal values\n- basic idea: approximations get refined towards optimal values\n\n\nPolicy Evaluation:\n\n- another basic operation: compute the utility of a state s under a fixed policy (non optimal)\n- define the utility of a state s, under a fixed policy $\\pi$\n\n\n- Step 1: Policy Evaluation - calculate utilities for some fixed policy (not optimal utilities) until convergence. For fixed current policy $\\pi$, find values with policy evaluation\n- Step 2: Policy improvement - update policy using one-step look-ahead with resulting converged (but not optimal) utilities as future values\n- Repeat until policy converges using policy extraction\n\n- This is policy iteration\n\n**you want to:**\n\n- compute optimal values: use value iteration or policy iteration\n- compute values for a particular policy: use policy evaluation\n- turn your values into a policy: use policy extraction\nBoth value iteration and policy iteration compute the same thing (all optimal values)\n\n\n- if given a particular policy, compute values using policy evaluation\n- to turn your values into a policy: use policy extraction (one step lookahead)\n\n\n\n\n**Maximum Expected Utility**\n- a rational agent should choose the action that maximizes its expected utility, given its knowledge\n- Utilities: functions from outcomes(states of the world) to real numbers that describe an agent's preferences \n\n  \n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "chapter17_3 =  \"\"\"**exploration**: you have to try unknown actions to get information\n",
        "\n",
        "**exploitation**: eventually, you have to use what you know\n",
        "\n",
        "**regret**: evgen if you learn intelligently, you make mistakes\n",
        "\n",
        "**sampling**: bc of chance you have to try things repeatedly MDP \n",
        "\n",
        "\n",
        "BAsic idea:\n",
        "\n",
        "- recieve feedback in the form of rewards\n",
        "- agent's utility is defined by the reward function\n",
        "- must learn to act so as to maximize expected rewards\n",
        "- all learning is based on observed samples of outcomes\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" ***Reinforcement Learning***\n",
        "- still assume a markov decision process:\n",
        "   - a set of states s\n",
        "   - a set of actions per state A\n",
        "   - a model T (s,a,s')\n",
        "   - a reward function R(s,a,s')\n",
        "- still looking for a policy $\\pi$(s)\n",
        "- new twist: we don't know T or R\n",
        "  - i.e. we dont know which states are good or what the actions do\n",
        "  - must try actions and states to learn\n",
        "   \n",
        "\n",
        "\n",
        "\n",
        "Offline (MDPs) vs Online (RL)\n",
        "\n",
        "Two different approaches:\n",
        "\n",
        "1. Model-Based Learning\n",
        "\n",
        "    - learn an apprx model based on experiences\n",
        "    - solve for values as if the learned model were correct\n",
        "    - Learn empirical MDP model:\n",
        "      a. count outcomes s' for each s, a\n",
        "      b. normalize to give an estimate of T\n",
        "      c. discover each R(s,a,s') when we experience (s,a,s')\n",
        "    - Solve the learned MDP\n",
        "      i.e. use value iteration\"\"\"\n",
        "chapter22_2 =  \"\"\" Model-Free: not maintaining estimates of probabilities. akin to a moving avg\n",
        "\n",
        "Type 1: Passive Reinforcement Learning- \n",
        "\n",
        "- Simplified task: policy evaluation\n",
        "  - input: a fixed policy $\\pi$(s)\n",
        "  - you don't know the transitions T(s,a,s')\n",
        "  - you don't know the rewards R(s,a,s')\n",
        "  - goal: learn the state values\n",
        "  - learner is along for the ride\n",
        "  - no choice about what actions to take\n",
        "  - just execute the policy and learn from experience\n",
        "\n",
        "  **Direct Evaluation**\n",
        "  - goal: compute vals for each state under $\\pi$\n",
        "  - idea: average together observed sample values\n",
        "    - act according to $\\pi$\n",
        "    - every time you visit a state, write down what the sum of discounted rewards turned out to be\n",
        "    - avg those samples\n",
        "    \n",
        "    **bad about direct evalution**: wastes info about state connects, each state is learned separately so it takes a long time to learn\n",
        "    \n",
        "    Sample-based Policy Evaluation\n",
        "\n",
        "    Temporal Difference Learning\n",
        "\n",
        "\n",
        "    Active Reinforcement Learning\n",
        "    - full reinforcement learning: optimal policies (like value iteration)\n",
        "    - you don't know the Transitions T(s,a,s')\n",
        "    - you don't know the reards R(s,a,s')\n",
        "    - you choose the actions now\n",
        "    - goal: learn the optimal policy/values\n",
        "\n",
        "\n",
        "    Q-value Iteration\n",
        "    - value iteration: find successive (depth-limited) values\n",
        "    - start with $V_0(s) =0 $ which we know is right\n",
        "    - given $V_k$, calc the depth k+1 values for all states\n",
        "    \n",
        "    \n",
        "    \n",
        "    \n",
        "    \n",
        "    \"\"\"\n",
        "chapter22_3 =  \"\"\" Exploration vs Exploitation\n",
        "\n",
        "\n",
        "Several schemes for forcing exploration:\n",
        "\n",
        "- simplest: random actions ($\\epsilon$ - greedy):\n",
        "  - every time step, flip a coin\n",
        "  - with small probability $\\epsilon$, act randomly\n",
        "  - with large probability 1 - $\\epsioln$, act on current policy\n",
        "  \n",
        "  problems with random actions? \n",
        "  - you do eventually explore but keep picking things repeatedly\n",
        "  - one solution, lower $\\epsilon$ over time (the chance of choosing randomly decreases over time)\n",
        "  - another solution: exploration functions\n",
        "  \n",
        "  \n",
        "  \n",
        "Exploration Functions:\n",
        "- when to explore?\n",
        "- random - explore a fixed amount\n",
        "- better idea: explore areas whose badness is not yet established, eventually stop exploring\"\"\"\n",
        "chapter22_4 =  \"\"\" Approximate Q-Learning\n",
        "\n",
        "  \"\"\"\n",
        "chapter22_5 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 48,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "5af1fbdb-3e3b-420e-f2e0-36182ddf1b12"
      },
      "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": 49,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n**exploration**: you have to try unknown actions to get information\n\n**exploitation**: eventually, you have to use what you know\n\n**regret**: evgen if you learn intelligently, you make mistakes\n\n**sampling**: bc of chance you have to try things repeatedly MDP \n\n\nBAsic idea:\n\n- recieve feedback in the form of rewards\n- agent's utility is defined by the reward function\n- must learn to act so as to maximize expected rewards\n- all learning is based on observed samples of outcomes\n\n\n\n \n\n## AIMA Chapter 22.1 Learning from Rewards\n ***Reinforcement Learning***\n- still assume a markov decision process:\n   - a set of states s\n   - a set of actions per state A\n   - a model T (s,a,s')\n   - a reward function R(s,a,s')\n- still looking for a policy $\\pi$(s)\n- new twist: we don't know T or R\n  - i.e. we dont know which states are good or what the actions do\n  - must try actions and states to learn\n   \n\n\n\nOffline (MDPs) vs Online (RL)\n\nTwo different approaches:\n\n1. Model-Based Learning\n\n    - learn an apprx model based on experiences\n    - solve for values as if the learned model were correct\n    - Learn empirical MDP model:\n      a. count outcomes s' for each s, a\n      b. normalize to give an estimate of T\n      c. discover each R(s,a,s') when we experience (s,a,s')\n    - Solve the learned MDP\n      i.e. use value iteration\n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Model-Free: not maintaining estimates of probabilities. akin to a moving avg\n\nType 1: Passive Reinforcement Learning- \n\n- Simplified task: policy evaluation\n  - input: a fixed policy $\\pi$(s)\n  - you don't know the transitions T(s,a,s')\n  - you don't know the rewards R(s,a,s')\n  - goal: learn the state values\n  - learner is along for the ride\n  - no choice about what actions to take\n  - just execute the policy and learn from experience\n\n  **Direct Evaluation**\n  - goal: compute vals for each state under $\\pi$\n  - idea: average together observed sample values\n    - act according to $\\pi$\n    - every time you visit a state, write down what the sum of discounted rewards turned out to be\n    - avg those samples\n    \n    **bad about direct evalution**: wastes info about state connects, each state is learned separately so it takes a long time to learn\n    \n    Sample-based Policy Evaluation\n\n    Temporal Difference Learning\n\n\n    Active Reinforcement Learning\n    - full reinforcement learning: optimal policies (like value iteration)\n    - you don't know the Transitions T(s,a,s')\n    - you don't know the reards R(s,a,s')\n    - you choose the actions now\n    - goal: learn the optimal policy/values\n\n\n    Q-value Iteration\n    - value iteration: find successive (depth-limited) values\n    - start with $V_0(s) =0 $ which we know is right\n    - given $V_k$, calc the depth k+1 values for all states\n    \n    \n    \n    \n    \n    \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Exploration vs Exploitation\n\n\nSeveral schemes for forcing exploration:\n\n- simplest: random actions ($\\epsilon$ - greedy):\n  - every time step, flip a coin\n  - with small probability $\\epsilon$, act randomly\n  - with large probability 1 - $\\epsioln$, act on current policy\n  \n  problems with random actions? \n  - you do eventually explore but keep picking things repeatedly\n  - one solution, lower $\\epsilon$ over time (the chance of choosing randomly decreases over time)\n  - another solution: exploration functions\n  \n  \n  \nExploration Functions:\n- when to explore?\n- random - explore a fixed amount\n- better idea: explore areas whose badness is not yet established, eventually stop exploring\n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Approximate Q-Learning\n\n  \n\n## Module 9 Lecture Notes\n Your summary here \n\n## Module 9 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" ***Probability***\n",
        "\n",
        "\n",
        " Size distribution of n variables with domain sizes d? $d^n$ \n",
        " \n",
        " \n",
        " Inference by Enumeration\n",
        " \n",
        " - evidence variables: things we've observed\n",
        " - query variables: we actually care about them - wanna know how likely\n",
        " - hidden variables: things that occur but not that we've actively observed\n",
        " \n",
        " \n",
        " P(Q | $e_1$...$e_k$)\n",
        " \n",
        " Step 1: select the entries that are consistent with evidence observed\n",
        " step 2: sum out Hidden variables to get joint of query and evidence \n",
        "\n",
        " $\\sum_b$ P(a, b, c) = P( a, c)\n",
        "\n",
        " step 3: normalize. sum over all q - this gives us the denominator\n",
        " \"\"\"\n",
        "chapter12_2 = \"\"\" \n",
        "\n",
        "- It is inescapable in complex, nondeterministic, or partially observable environments.\n",
        "\n",
        "- Probabilities express the agent’s inability to reach a definite decision regarding the truth of a sentence.\n",
        "\n",
        "- Probabilities summarize the agent’s beliefs relative to the evidence. \n",
        "\n",
        "- Basic probability statements include prior or unconditional probabilities and posterior or conditional probabilities over simple and complex propositions.\n",
        "\n",
        "- The axioms of probability constrain the probabilities of logically related propositions. An agent that violates the axioms must behave irrationally in some cases.\n",
        "\n",
        "- The full joint probability distribution specifies the probability of each complete assignment of values to random variables. It is usually too large to create or use in its explicit form, but when it is available it can be used to answer queries simply by adding up entries for the possible worlds corresponding to the query propositions.\n",
        "\n",
        "- Bayes’ rule allows unknown probabilities to be computed from known conditional probabilities, usually in the causal direction. Applying Bayes’ rule with many pieces of evidence runs into the same scaling problems as does the full joint distribution. Conditional independence brought about by direct causal relationships in the domain allows the full joint distribution to be factored into smaller, conditional distributions. The naive Bayes model assumes the conditional independence of all effect variables, given a single cause variable; its size grows linearly with the number of effects.\n",
        "\n",
        "\"\"\"\n",
        "chapter12_3 = \"\"\" \"\"\" \n",
        "chapter12_4 = \"\"\" \"\"\" \n",
        "chapter12_5 = \"\"\" \"\"\" \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 = \"\"\" \n",
        "\n",
        "\"\"\"\n",
        "SLP_chapter3_2 = \"\"\" \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" MArkov says: Given the present state, the future and past are independent.\"\"\"\n",
        "SLP_chapter3_5 = \"\"\" How many ways are there to apply the chain rule to a joint distribution with NN random variables? N! \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" What is a contraction?\n",
        "\n",
        "b. Part of the proof of convergence for the value iteration algorithm.\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 50,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "dc7f7acb-aa72-47b5-fe8b-2f2db197ea73"
      },
      "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": 51,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n ***Probability***\n\n\n Size distribution of n variables with domain sizes d? $d^n$ \n \n \n Inference by Enumeration\n \n - evidence variables: things we've observed\n - query variables: we actually care about them - wanna know how likely\n - hidden variables: things that occur but not that we've actively observed\n \n \n P(Q | $e_1$...$e_k$)\n \n Step 1: select the entries that are consistent with evidence observed\n step 2: sum out Hidden variables to get joint of query and evidence \n\n $\\sum_b$ P(a, b, c) = P( a, c)\n\n step 3: normalize. sum over all q - this gives us the denominator\n \n\n## AIMA Chapter 12.2 Basic Probability Notation\n \n\n- It is inescapable in complex, nondeterministic, or partially observable environments.\n\n- Probabilities express the agent’s inability to reach a definite decision regarding the truth of a sentence.\n\n- Probabilities summarize the agent’s beliefs relative to the evidence. \n\n- Basic probability statements include prior or unconditional probabilities and posterior or conditional probabilities over simple and complex propositions.\n\n- The axioms of probability constrain the probabilities of logically related propositions. An agent that violates the axioms must behave irrationally in some cases.\n\n- The full joint probability distribution specifies the probability of each complete assignment of values to random variables. It is usually too large to create or use in its explicit form, but when it is available it can be used to answer queries simply by adding up entries for the possible worlds corresponding to the query propositions.\n\n- Bayes’ rule allows unknown probabilities to be computed from known conditional probabilities, usually in the causal direction. Applying Bayes’ rule with many pieces of evidence runs into the same scaling problems as does the full joint distribution. Conditional independence brought about by direct causal relationships in the domain allows the full joint distribution to be factored into smaller, conditional distributions. The naive Bayes model assumes the conditional independence of all effect variables, given a single cause variable; its size grows linearly with the number of effects.\n\n\n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n \n\n## AIMA Chapter 12.4 Independence\n \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n \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 \n\n\n\n## SLP Chapter 3.2 Evaluating Language Models\n \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n \n\n## SLP Chapter 3.4 Generalization and Zeros\n MArkov says: Given the present state, the future and past are independent.\n\n## SLP Chapter 3.5 Smoothing\n How many ways are there to apply the chain rule to a joint distribution with NN random variables? N! \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n What is a contraction?\n\nb. Part of the proof of convergence for the value iteration algorithm.\n\n\n## Module 10 Lecture Notes\n Your summary here \n\n## Module 10 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Bayes NEts\n",
        "\n",
        "Nodes: variables with domains\n",
        "- can be assigned(obswerved) or unassigned (unobserved)\n",
        "\n",
        "Arcs: interactions\n",
        "- indicate \"direct influence\" between variables\n",
        "- formally: enconde conditional independence\n",
        "\n",
        "\n",
        "Semantics:\n",
        "- a set of nodes, one per variable X\n",
        "- a directed, acyclic graph\n",
        "- a conditiona distribution for each node\n",
        "- CPT: conditional probability table\n",
        "- description of a noisy causal\n",
        "\n",
        "\n",
        "-Bayes Nets implicitly encode joint distributions\n",
        "  - as a product of local conditional distributions\n",
        "\n",
        "Size:\n",
        "- how big is a joint distribution over N Boolean variables?\n",
        "  - $2^N$\n",
        "- How big is an N-node net if nodes have up to k parents?\n",
        "  - O(N * $2^{k+1}$)\n",
        "\n",
        "Both give you the power to calculate the Probability of any row\n",
        "- BN has huge space savings\n",
        "\n",
        "Bayes Net Assumptions\n",
        "\n",
        "\n",
        "D-Separation: \n",
        "study independence properties between triples in the graphs\n",
        "1. Causal Chain - x causes y causes z\n",
        "  - is it guaranteed that x is totally independent of Z? no\n",
        "  - one example set of CPTs for which x is not independent of Z is sufficient\n",
        "  - ex. low pressure causes rain causes traffic\n",
        "    - high pressure causes no rain causes no traffic\n",
        "    - P(+y| +x) = 1, P(-y|-x) = 1, P(+z|+y) = 1, P(-z|-y) = 1\n",
        "  - P(x,y,z) = P(x)P(y|x) P(z|y)\n",
        "  - **evidence along the chain \"blocks\" the influence**  \n",
        "  \n",
        "\n",
        "\n",
        "2. Common Cause\n",
        "  - **observing the cause blocks influence between effects**\n",
        "\n",
        "\n",
        "3.Common Effect\n",
        "  - **observing an effect activates influence between possible causes**\n",
        "\n",
        "  General Question:\n",
        "  - in a given BN, are two variables independent (given evidence)\n",
        "\n",
        "\n",
        "\n",
        "  \"\"\"\n",
        "chapter13_2 = \"\"\" Reachability:\n",
        "\n",
        "- attempt 1: if two nodes are conneted by an undirected path not blocked by a shaded node, the \"\"\"\n",
        "chapter13_3 = \"\"\" \n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" C⫫A∣G : F\n",
        "\n",
        "A⫫D∣B,C: T\n",
        "\n",
        "D⫫F∣B,C: T\n",
        "\n",
        "C⫫E∣A: T\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 52,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "b4fa208f-794b-4fde-f095-aa49d55e90b7"
      },
      "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": 53,
      "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 Bayes NEts\n\nNodes: variables with domains\n- can be assigned(obswerved) or unassigned (unobserved)\n\nArcs: interactions\n- indicate \"direct influence\" between variables\n- formally: enconde conditional independence\n\n\nSemantics:\n- a set of nodes, one per variable X\n- a directed, acyclic graph\n- a conditiona distribution for each node\n- CPT: conditional probability table\n- description of a noisy causal\n\n\n-Bayes Nets implicitly encode joint distributions\n  - as a product of local conditional distributions\n\nSize:\n- how big is a joint distribution over N Boolean variables?\n  - $2^N$\n- How big is an N-node net if nodes have up to k parents?\n  - O(N * $2^{k+1}$)\n\nBoth give you the power to calculate the Probability of any row\n- BN has huge space savings\n\nBayes Net Assumptions\n\n\nD-Separation: \nstudy independence properties between triples in the graphs\n1. Causal Chain - x causes y causes z\n  - is it guaranteed that x is totally independent of Z? no\n  - one example set of CPTs for which x is not independent of Z is sufficient\n  - ex. low pressure causes rain causes traffic\n    - high pressure causes no rain causes no traffic\n    - P(+y| +x) = 1, P(-y|-x) = 1, P(+z|+y) = 1, P(-z|-y) = 1\n  - P(x,y,z) = P(x)P(y|x) P(z|y)\n  - **evidence along the chain \"blocks\" the influence**  \n  \n\n\n2. Common Cause\n  - **observing the cause blocks influence between effects**\n\n\n3.Common Effect\n  - **observing an effect activates influence between possible causes**\n\n  General Question:\n  - in a given BN, are two variables independent (given evidence)\n\n\n\n  \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Reachability:\n\n- attempt 1: if two nodes are conneted by an undirected path not blocked by a shaded node, the \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n \n\n\n## Module 11 Lecture Notes\n C⫫A∣G : F\n\nA⫫D∣B,C: T\n\nD⫫F∣B,C: T\n\nC⫫E∣A: T\n\n\n \n\n## Module 11 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\"\n",
        "\n",
        "Model-based approach\n",
        "\n",
        "• Build a model (e.g. Bayes’ net) where both the label and\n",
        "features are random variables\n",
        "• Instantiate any observed features\n",
        "• Query for the distribution of the\n",
        "label conditioned on the features\n",
        "Challenges\n",
        "• What structure should the BN\n",
        "have?\n",
        "• How should we learn its\n",
        "parameters?\n",
        "What do we need in order to use Naïve Bayes?\n",
        "\n",
        "\n",
        "\n",
        "Naïve Bayes: Assume all features are independent effects of the label\n",
        "\n",
        "Simple digit recognition version:\n",
        "• One feature (variable) Fij for each grid position <i,j>\n",
        "• Feature values are on / off, based on whether intensity\n",
        "is more or less than 0.5 in underlying image\n",
        "• Each input maps to a feature vector, e.g\n",
        "\n",
        "\n",
        "\n",
        "• Inference method (we just saw this part)\n",
        "• Start with a bunch of probabilities: P(Y) and the P(Fi|Y) tables\n",
        "• Use standard inference to compute P(Y|F1…Fn)\n",
        "• Nothing new here\n",
        "• Estimates of local conditional probability tables\n",
        "• P(Y), the prior over labels\n",
        "• P(Fi|Y) for each feature (evidence variable)\n",
        "• These probabilities are collectively called the parameters of the\n",
        "model and denoted by q\n",
        "• Up until now, we assumed these appeared by magic, but…\n",
        "• …they typically come from training data counts: we’ll look at this\n",
        "soon\n",
        "\n",
        "\n",
        "Naïve Bayes for Text\n",
        "\n",
        "Bag-of-words Naïve Bayes:\n",
        "• Features: Wi is the word at positon i\n",
        "• As before: predict label conditioned on feature variables (spam vs. ham)\n",
        "• As before: assume features are conditionally independent given label\n",
        "Generative model:\n",
        "“Tied” distributions and bag-of-words\n",
        "• Usually, each variable gets its own conditional probability distribution P(F|Y)\n",
        "• Each position is identically distributed\n",
        "• Why make this assumption?\n",
        "• Called “bag-of-words” because model is insensitive to word order or reordering \"\"\"\n",
        "chapter19_2 = \"\"\" \n",
        "\n",
        "\n",
        "Data: labeled instances, e.g. emails marked spam/ham\n",
        "• Training set\n",
        "• Held out set\n",
        "• Test set\n",
        "\n",
        "\n",
        "Features: attribute-value pairs which characterize each x\n",
        "\n",
        "\n",
        "Experimentation cycle\n",
        "• Learn parameters (e.g. model probabilities) on training set\n",
        "• (Tune hyperparameters on held-out set)\n",
        "• Very important: never “peek” at the test set!\n",
        "\n",
        "\n",
        "Evaluation\n",
        "• Accuracy: fraction of instances predicted correctly\n",
        "\n",
        "\n",
        "Overfitting and generalization\n",
        "• Want a classifier which does well on test data\n",
        "• Overfitting: fitting the training data very closely, but not generalizing well\n",
        "\"\"\"\n",
        "chapter19_3 = \"\"\" \n",
        "\n",
        "Relative frequency parameters will overfit the training data!\n",
        "\n",
        "• Unlikely that every occurrence of “minute” is 100% spam\n",
        "• Unlikely that every occurrence of “seriously” is 100% ham\n",
        "\n",
        "As an extreme case, imagine using the entire email as the only feature\n",
        "• Would get the training data perfect (if deterministic labeling)\n",
        "• Wouldn’t generalize at all\n",
        "\n",
        "To generalize better: we need to smooth or regularize the estimates \"\"\"\n",
        "chapter19_4 = \"\"\" Tuning on Held-Out Data\n",
        "\n",
        "Now we’ve got two kinds of unknowns\n",
        "\n",
        "\n",
        "• Parameters: the probabilities P(X|Y), P(Y)\n",
        "• Hyperparameters: e.g. the amount / type of smoothing to do, k, a\n",
        "\n",
        "\n",
        "What should we learn where?\n",
        "\n",
        "• Learn parameters from training data\n",
        "\n",
        "and test on the held-out data\n",
        "• Choose the best value and do a final test on\n",
        "the test data \"\"\"\n",
        "chapter19_5 = \"\"\" BAselines\n",
        "\n",
        "\n",
        "First step: get a baseline\n",
        "\n",
        "\n",
        "• Baselines are very simple “straw man” procedures\n",
        "• Help determine how hard the task is\n",
        "• Help know what a “good” accuracy is\n",
        "Weak baseline: most frequent label classifier\"\"\"\n",
        "chapter19_6 = \"\"\" The confidence of a probabilistic classifier:\n",
        "\n",
        "• Posterior over the top label\n",
        "• Represents how sure the classifier is of\n",
        "the classification\n",
        "• Any probabilistic model will have\n",
        "confidences\n",
        "\"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Bayes rule lets us do diagnostic queries with causal probabilities\n",
        "The naïve Bayes assumption takes all features to be independent given\n",
        "the class label\n",
        "\n",
        "Classifier confidences are useful, when you can get them \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Binary case: compare features to a weight vector\n",
        "Learning: figure out the weight vector from examples1aq 1 \"\"\"\n",
        "slp_chapter4_3 = \"\"\" In the space of feature vectors\n",
        "• Examples are points\n",
        "• Any weight vector is a hyperplane\n",
        " \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Start with weights = 0\n",
        "For each training instance:\n",
        "• Classify with current weights\n",
        "• If correct (i.e., y=y*), no change!\n",
        "• If wrong: adjust the weight vector \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Properties of perceptrons:\n",
        "\n",
        "Separability: true if some parameters get the training\n",
        "set perfectly correct\n",
        "\n",
        "\n",
        "Convergence: if the training is separable, perceptron\n",
        "will eventually converge (binary case)\n",
        "\n",
        "\n",
        "Mistake Bound: the maximum number of mistakes\n",
        "(binary case) related to the margin or degree of\n",
        "separability\n",
        "\n",
        "\n",
        "Problems with perceptrons:\n",
        "\n",
        "Noise: if the data isn’t separable,\n",
        "weights might thrash\n",
        "• Averaging weight vectors over\n",
        "time can help (averaged\n",
        "perceptron)\n",
        "\n",
        "Mediocre generalization: finds a\n",
        "“barely” separating solution\n",
        "\n",
        "\n",
        "Overtraining: test / held-out\n",
        "accuracy usually rises, then falls\n",
        "• Overtraining is a kind of overfitting\n",
        "\"\"\"\n",
        "slp_chapter4_6 = \"\"\" Maximizing the margin: good according to intuition, theory, practice\n",
        "Only support vectors matter; other training examples are ignorable\n",
        "Support vector machines (SVMs) find the separator with max\n",
        "margin\n",
        "Basically, SVMs are MIRA where you optimize over all examples at\n",
        "once \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Naïve Bayes\n",
        "• Builds a model training data\n",
        "\n",
        "Perceptrons / MIRA:\n",
        "• Makes less assumptions about data\n",
        "\"\"\"\n",
        "slp_chapter4_8 = \"\"\" Activation function:\n",
        "\n",
        "Instead of directly outputting z = w·x+b, which is a linear function of x, neuron units\n",
        "apply a non-linear function f to z.\n",
        "\n",
        "\n",
        "The output of this function is called the activation value for the unit, represented by\n",
        "the variable a. The output of a neural network is called y, so if the activation of a node\n",
        "is the final output of a network then\n",
        "y=a= f(z)\n",
        "\n",
        "\n",
        "There are 3 commonly used non-linear functions used for f:\n",
        "-The sigmoid function\n",
        "-The tanh function\n",
        "-The rectified linear unit ReLU\n",
        "\n",
        " \"\"\"\n",
        "slp_chapter4_9 = \"\"\"\n",
        "\n",
        "\"\"\"\n",
        "slp_chapter4_10 = \"\"\" \n",
        "      \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\" This chapter introduced the naive Bayes model for classification and applied it to\n",
        "the text categorization task of sentiment analysis.\n",
        "\n",
        "\n",
        "• Text categorization, in which an entire text is assigned a class from a finite set,\n",
        "includes such tasks as sentiment analysis, spam detection, language identification, and authorship attribution.\n",
        "\n",
        "• Sentiment analysis classifies a text as reflecting the positive or negative orientation (sentiment) that a writer expresses toward some object.\n",
        "\n",
        "• Naive Bayes is a generative model that makes the bag of words assumption\n",
        "(position doesn’t matter) and the conditional independence assumption (words\n",
        "are conditionally independent of each other given the class)\n",
        "\n",
        "\n",
        "• Classifiers are evaluated based on precision and recall.\n",
        "\n",
        "• Classifiers are trained using distinct training, dev, and test sets, including the\n",
        "use of cross-validation in the training set.\n",
        "\n",
        "• Statistical significance tests should be used to determine whether we can be\n",
        "confident that one version of a classifier is better than another.\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 54,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "028783a4-3db9-4afb-8c52-ffed7595da85"
      },
      "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": 55,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n\n\nModel-based approach\n\n• Build a model (e.g. Bayes’ net) where both the label and\nfeatures are random variables\n• Instantiate any observed features\n• Query for the distribution of the\nlabel conditioned on the features\nChallenges\n• What structure should the BN\nhave?\n• How should we learn its\nparameters?\nWhat do we need in order to use Naïve Bayes?\n\n\n\nNaïve Bayes: Assume all features are independent effects of the label\n\nSimple digit recognition version:\n• One feature (variable) Fij for each grid position <i,j>\n• Feature values are on / off, based on whether intensity\nis more or less than 0.5 in underlying image\n• Each input maps to a feature vector, e.g\n\n\n\n• Inference method (we just saw this part)\n• Start with a bunch of probabilities: P(Y) and the P(Fi|Y) tables\n• Use standard inference to compute P(Y|F1…Fn)\n• Nothing new here\n• Estimates of local conditional probability tables\n• P(Y), the prior over labels\n• P(Fi|Y) for each feature (evidence variable)\n• These probabilities are collectively called the parameters of the\nmodel and denoted by q\n• Up until now, we assumed these appeared by magic, but…\n• …they typically come from training data counts: we’ll look at this\nsoon\n\n\nNaïve Bayes for Text\n\nBag-of-words Naïve Bayes:\n• Features: Wi is the word at positon i\n• As before: predict label conditioned on feature variables (spam vs. ham)\n• As before: assume features are conditionally independent given label\nGenerative model:\n“Tied” distributions and bag-of-words\n• Usually, each variable gets its own conditional probability distribution P(F|Y)\n• Each position is identically distributed\n• Why make this assumption?\n• Called “bag-of-words” because model is insensitive to word order or reordering \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n \n\n\nData: labeled instances, e.g. emails marked spam/ham\n• Training set\n• Held out set\n• Test set\n\n\nFeatures: attribute-value pairs which characterize each x\n\n\nExperimentation cycle\n• Learn parameters (e.g. model probabilities) on training set\n• (Tune hyperparameters on held-out set)\n• Very important: never “peek” at the test set!\n\n\nEvaluation\n• Accuracy: fraction of instances predicted correctly\n\n\nOverfitting and generalization\n• Want a classifier which does well on test data\n• Overfitting: fitting the training data very closely, but not generalizing well\n\n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \n\nRelative frequency parameters will overfit the training data!\n\n• Unlikely that every occurrence of “minute” is 100% spam\n• Unlikely that every occurrence of “seriously” is 100% ham\n\nAs an extreme case, imagine using the entire email as the only feature\n• Would get the training data perfect (if deterministic labeling)\n• Wouldn’t generalize at all\n\nTo generalize better: we need to smooth or regularize the estimates \n\n## AIMA Chapter 5.5 Stochastic Games\n Tuning on Held-Out Data\n\nNow we’ve got two kinds of unknowns\n\n\n• Parameters: the probabilities P(X|Y), P(Y)\n• Hyperparameters: e.g. the amount / type of smoothing to do, k, a\n\n\nWhat should we learn where?\n\n• Learn parameters from training data\n\nand test on the held-out data\n• Choose the best value and do a final test on\nthe test data \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n BAselines\n\n\nFirst step: get a baseline\n\n\n• Baselines are very simple “straw man” procedures\n• Help determine how hard the task is\n• Help know what a “good” accuracy is\nWeak baseline: most frequent label classifier\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n The confidence of a probabilistic classifier:\n\n• Posterior over the top label\n• Represents how sure the classifier is of\nthe classification\n• Any probabilistic model will have\nconfidences\n\n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Bayes rule lets us do diagnostic queries with causal probabilities\nThe naïve Bayes assumption takes all features to be independent given\nthe class label\n\nClassifier confidences are useful, when you can get them \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Binary case: compare features to a weight vector\nLearning: figure out the weight vector from examples1aq 1 \n\n## SLP Chapter 4.3 Worked Example\n In the space of feature vectors\n• Examples are points\n• Any weight vector is a hyperplane\n \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Start with weights = 0\nFor each training instance:\n• Classify with current weights\n• If correct (i.e., y=y*), no change!\n• If wrong: adjust the weight vector \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Properties of perceptrons:\n\nSeparability: true if some parameters get the training\nset perfectly correct\n\n\nConvergence: if the training is separable, perceptron\nwill eventually converge (binary case)\n\n\nMistake Bound: the maximum number of mistakes\n(binary case) related to the margin or degree of\nseparability\n\n\nProblems with perceptrons:\n\nNoise: if the data isn’t separable,\nweights might thrash\n• Averaging weight vectors over\ntime can help (averaged\nperceptron)\n\nMediocre generalization: finds a\n“barely” separating solution\n\n\nOvertraining: test / held-out\naccuracy usually rises, then falls\n• Overtraining is a kind of overfitting\n\n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Maximizing the margin: good according to intuition, theory, practice\nOnly support vectors matter; other training examples are ignorable\nSupport vector machines (SVMs) find the separator with max\nmargin\nBasically, SVMs are MIRA where you optimize over all examples at\nonce \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Naïve Bayes\n• Builds a model training data\n\nPerceptrons / MIRA:\n• Makes less assumptions about data\n\n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Activation function:\n\nInstead of directly outputting z = w·x+b, which is a linear function of x, neuron units\napply a non-linear function f to z.\n\n\nThe output of this function is called the activation value for the unit, represented by\nthe variable a. The output of a neural network is called y, so if the activation of a node\nis the final output of a network then\ny=a= f(z)\n\n\nThere are 3 commonly used non-linear functions used for f:\n-The sigmoid function\n-The tanh function\n-The rectified linear unit ReLU\n\n \n\n## SLP Chapter 4.9 Statistical Significance Testing\n\n\n\n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n \n      \n\n## Module 12 Lecture Notes\n This chapter introduced the naive Bayes model for classification and applied it to\nthe text categorization task of sentiment analysis.\n\n\n• Text categorization, in which an entire text is assigned a class from a finite set,\nincludes such tasks as sentiment analysis, spam detection, language identification, and authorship attribution.\n\n• Sentiment analysis classifies a text as reflecting the positive or negative orientation (sentiment) that a writer expresses toward some object.\n\n• Naive Bayes is a generative model that makes the bag of words assumption\n(position doesn’t matter) and the conditional independence assumption (words\nare conditionally independent of each other given the class)\n\n\n• Classifiers are evaluated based on precision and recall.\n\n• Classifiers are trained using distinct training, dev, and test sets, including the\nuse of cross-validation in the training set.\n\n• Statistical significance tests should be used to determine whether we can be\nconfident that one version of a classifier is better than another.\n\n\n## Module 12 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" \"\"\"\n",
        "slp_chapter5_2 = \"\"\" \"\"\"\n",
        "slp_chapter5_3 = \"\"\" \"\"\"\n",
        "slp_chapter5_4 = \"\"\" \n",
        "\n",
        "\"\"\"\n",
        "slp_chapter5_5 = \"\"\"  \"\"\"\n",
        "slp_chapter5_6 = \"\"\" \n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" logistic regression model of classification.\n",
        "\n",
        "• Logistic regression is a supervised machine learning classifier that extracts\n",
        "real-valued features from the input, multiplies each by a weight, sums them,\n",
        "and passes the sum through a sigmoid function to generate a probability. A\n",
        "threshold is used to make a decision.\n",
        "\n",
        "• **Logistic regression** can be used with two classes (e.g., positive and negative\n",
        "sentiment) or with multiple classes (multinomial logistic regression, for example for n-ary text classification, part-of-speech labeling, etc.).\n",
        "\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" • **Multinomial** logistic regression uses the softmax function to compute probabilities.\n",
        "\n",
        "• The weights (vector w and bias b) are learned from a labeled training set via a\n",
        "loss function, such as the cross-entropy loss, that must be minimized.\n",
        "\n",
        "• Minimizing this **loss function** is a convex optimization problem, and iterative\n",
        "algorithms like gradient descent are used to find the optimal weights.\"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" • **Regularization** is used to avoid overfitting.\n",
        "\n",
        "• Logistic regression is also one of the most useful analytic tools, because of its\n",
        "ability to transparently study the importance of individual features.  \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Neural networks are built out of neural units, originally inspired by human\n",
        "neurons but now simply an abstract computational device.\n",
        "\n",
        "\n",
        "\n",
        "• In a **fully-connected, feedforward network**, each unit in layer i is connected\n",
        "to each unit in layer i+1, and there are no cycles.\n",
        "\n",
        "\n",
        "• The power of neural networks comes from the ability of early layers to learn\n",
        "representations that can be utilized by later layers in the network.\n",
        "\n",
        "\n",
        "• **Neural networks** are trained by optimization algorithms like gradient descent.\n",
        "\n",
        "\n",
        "• **Error backpropagation**, backward differentiation on a computation graph,\n",
        "is used to compute the gradients of the loss function for a network.\n",
        "\n",
        "\n",
        "• **Neural language** models use a neural network as a probabilistic classifier, to\n",
        "compute the probability of the next word given the previous n words.\n",
        "\n",
        "\n",
        "• Neural language models can use **pretrained embeddings**, or can learn embeddings from scratch in the process of language modeling. \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 56,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "0aef705b-284f-43b8-fc3a-996bd2908dec"
      },
      "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": 57,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n \n\n## SLP Chapter 5.3 The cross-entropy loss function\n \n\n## SLP Chapter 5.4 Gradient Descent\n \n\n\n\n## SLP Chapter 5.5 Regularization\n  \n\n## SLP Chapter 5.6 Multinomial logistic regression\n \n\n\n \n\n## SLP Chapter 7.1 Units\n logistic regression model of classification.\n\n• Logistic regression is a supervised machine learning classifier that extracts\nreal-valued features from the input, multiplies each by a weight, sums them,\nand passes the sum through a sigmoid function to generate a probability. A\nthreshold is used to make a decision.\n\n• **Logistic regression** can be used with two classes (e.g., positive and negative\nsentiment) or with multiple classes (multinomial logistic regression, for example for n-ary text classification, part-of-speech labeling, etc.).\n\n\n\n\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 • **Multinomial** logistic regression uses the softmax function to compute probabilities.\n\n• The weights (vector w and bias b) are learned from a labeled training set via a\nloss function, such as the cross-entropy loss, that must be minimized.\n\n• Minimizing this **loss function** is a convex optimization problem, and iterative\nalgorithms like gradient descent are used to find the optimal weights.\n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n • **Regularization** is used to avoid overfitting.\n\n• Logistic regression is also one of the most useful analytic tools, because of its\nability to transparently study the importance of individual features.  \n\n## SLP Chapter 7.7 Training the neural language model\n Neural networks are built out of neural units, originally inspired by human\nneurons but now simply an abstract computational device.\n\n\n\n• In a **fully-connected, feedforward network**, each unit in layer i is connected\nto each unit in layer i+1, and there are no cycles.\n\n\n• The power of neural networks comes from the ability of early layers to learn\nrepresentations that can be utilized by later layers in the network.\n\n\n• **Neural networks** are trained by optimization algorithms like gradient descent.\n\n\n• **Error backpropagation**, backward differentiation on a computation graph,\nis used to compute the gradients of the loss function for a network.\n\n\n• **Neural language** models use a neural network as a probabilistic classifier, to\ncompute the probability of the next word given the previous n words.\n\n\n• Neural language models can use **pretrained embeddings**, or can learn embeddings from scratch in the process of language modeling. \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 = \"\"\" **recurrent neural networks** and **transformers** and how they can be applied to language problems. Here’s a summary of\n",
        "the main points that we covered:\n",
        "• In simple Recurrent Neural Networks sequences are processed one element at\n",
        "a time, with the output of each neural unit at time t based both on the current\n",
        "input at t and the hidden layer from time t −1.\n",
        "• **RNNs can be trained** with a straightforward extension of the backpropagation\n",
        "algorithm, known as **backpropagation through time (BPTT)**.\n",
        "• Simple recurrent networks fail on long inputs because of problems like **vanishing gradients**; instead modern systems use more complex gated architectures such as **LSTMs** that explicitly decide what to remember and forget in\n",
        "their hidden and context layers.\n",
        "\"\"\"\n",
        "slp_chapter9_2 = \"\"\" • **Transformers are non-recurrent networks** based on self-attention. A **selfattention layer** maps input sequences to output sequences of the same length,\n",
        ".\n",
        "• A **transformer block** consists of a single attention layer followed by a feedforward layer with residual connections and layer normalizations following\n",
        "each. **Transformer blocks can be stacked** to make deeper and more powerful\n",
        "networks.\n",
        "\"\"\"\n",
        "slp_chapter9_3 = \"\"\" • Common language-based applications for RNNs and transformers include:\n",
        "– Probabilistic language modeling: assigning a probability to a sequence\n",
        "\n",
        "– Auto-regressive generation using a trained language model.\n",
        "\n",
        "– Sequence classification\"\"\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 = \"\"\" In vector semantics, a word is modeled as a **vector**—a point in high-dimensional\n",
        "space, also called an **embedding**. In this chapter we focus on **static embeddings**, in each **each word is mapped to a fixed embedding**.\n",
        "• Vector semantic models fall into two classes: **sparse and dense**. \n",
        "\n",
        "In sparse models each dimension corresponds to a word in the vocabulary V and cells\n",
        "are functions of co-occurrence counts. The term-document matrix has a row\n",
        "for each word (term) in the vocabulary and a column for each document. The\n",
        "word-context or term-term matrix has a row for each (target) word in the\n",
        "vocabulary and a column for each context term in the vocabulary. Two sparse\n",
        "weightings are common: the tf-idf weighting which weights each cell by its\n",
        "term frequency and inverse document frequency, and PPMI (pointwise\n",
        "positive mutual information) most common for for word-context matrices.\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "slp_chapter6_2 = \"\"\" • Dense vector models have dimensionality 50–1000. Word2vec algorithms\n",
        "like skip-gram are a popular way to compute dense embeddings. Skip-gram\n",
        "trains a logistic regression classifier to compute the probability that two words\n",
        "are ‘likely to occur nearby in text’. This probability is computed from the dot\n",
        "product between the embeddings for the two words.\"\"\"\n",
        "slp_chapter6_3 = \"\"\" • Skip-gram uses stochastic gradient descent to train the classifier, by learning\n",
        "embeddings that have a high dot product with embeddings of words that occur\n",
        "nearby and a low dot product with noise words. \"\"\"\n",
        "slp_chapter6_4 = \"\"\" \n",
        "• Other important embedding algorithms include GloVe, a method based on\n",
        "ratios of word co-occurrence probabilities.\"\"\"\n",
        "slp_chapter6_8 = \"\"\" \n",
        "• Whether using sparse or dense vectors, word and document similarities are\n",
        "computed by some function of the dot product between vectors. The cosine\n",
        "of two vectors—a normalized dot product—is the most popular such metric. \"\"\"\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": 58,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "ce683f30-7127-4cd4-b2a4-e7b6b632f86e"
      },
      "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": 59,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n **recurrent neural networks** and **transformers** and how they can be applied to language problems. Here’s a summary of\nthe main points that we covered:\n• In simple Recurrent Neural Networks sequences are processed one element at\na time, with the output of each neural unit at time t based both on the current\ninput at t and the hidden layer from time t −1.\n• **RNNs can be trained** with a straightforward extension of the backpropagation\nalgorithm, known as **backpropagation through time (BPTT)**.\n• Simple recurrent networks fail on long inputs because of problems like **vanishing gradients**; instead modern systems use more complex gated architectures such as **LSTMs** that explicitly decide what to remember and forget in\ntheir hidden and context layers.\n\n\n## SLP Chapter 9.2 Recurrent Neural Networks\n • **Transformers are non-recurrent networks** based on self-attention. A **selfattention layer** maps input sequences to output sequences of the same length,\n.\n• A **transformer block** consists of a single attention layer followed by a feedforward layer with residual connections and layer normalizations following\neach. **Transformer blocks can be stacked** to make deeper and more powerful\nnetworks.\n\n\n## SLP Chapter 9.3 RNNs as Language Models\n • Common language-based applications for RNNs and transformers include:\n– Probabilistic language modeling: assigning a probability to a sequence\n\n– Auto-regressive generation using a trained language model.\n\n– Sequence classification\"\"\n\n# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n\n## SLP Chapter 6.1 Lexical Semantics\n In vector semantics, a word is modeled as a **vector**—a point in high-dimensional\nspace, also called an **embedding**. In this chapter we focus on **static embeddings**, in each **each word is mapped to a fixed embedding**.\n• Vector semantic models fall into two classes: **sparse and dense**. \n\nIn sparse models each dimension corresponds to a word in the vocabulary V and cells\nare functions of co-occurrence counts. The term-document matrix has a row\nfor each word (term) in the vocabulary and a column for each document. The\nword-context or term-term matrix has a row for each (target) word in the\nvocabulary and a column for each context term in the vocabulary. Two sparse\nweightings are common: the tf-idf weighting which weights each cell by its\nterm frequency and inverse document frequency, and PPMI (pointwise\npositive mutual information) most common for for word-context matrices.\n\n\n \n\n## SLP Chapter 6.2 Vector Semantics\n • Dense vector models have dimensionality 50–1000. Word2vec algorithms\nlike skip-gram are a popular way to compute dense embeddings. Skip-gram\ntrains a logistic regression classifier to compute the probability that two words\nare ‘likely to occur nearby in text’. This probability is computed from the dot\nproduct between the embeddings for the two words.\n\n## SLP Chapter 6.3 Words and Vectors\n • Skip-gram uses stochastic gradient descent to train the classifier, by learning\nembeddings that have a high dot product with embeddings of words that occur\nnearby and a low dot product with noise words. \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n \n• Other important embedding algorithms include GloVe, a method based on\nratios of word co-occurrence probabilities.\n\n## SLP Chapter 6.8 Word2vec\n \n• Whether using sparse or dense vectors, word and document similarities are\ncomputed by some function of the dot product between vectors. The cosine\nof two vectors—a normalized dot product—is the most popular such metric. \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": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "8f4f1b4b-bcad-452c-9774-a4b99bc57451"
      },
      "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": 60,
      "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 Solution for an MDP is called a Policy - takes in a state and returns the best action an agent could take. Non-deterministic search.\n**Stochastic** : each action doesn't always have the same result. there is a % like 80% of the time when I select an action, I end up where I expect. \n\n- Our transition model has changed. Instead of having successors, we have to have a transition function that takes in the current state s, some action that could be performed a, and the\nresulting state, s'. This function will return the probability of arriving in state s' given that we are in state s and we selected action a. Transitions only depend on s and not the \nhistory of earlier states.\n\n-reward function. \n\n- sequential deciion problem\n  - fully observable environment\n  - stochastic transition model\n  - additive rewards\n  \n- MDP:\n 1. a set of states\n 2. a set of actions\n 3. transition function T(s, a, s')\n    - probability that executing a in s will lead to s'\n    - called the model\n 4. a reward function R(s, a, s')\n 5. an initial state\n 6. optionally, one or more terminal states\n \n \n \n - solution to MDP is different. It's not a sequence of actions because it's non deterministic. We need a **policy**\n \n **policy** given that i find myself in state s, whats the best action i should take. maps from a state onto the action to take if the agent is in that state.\n\n $\\pi$(s) = a. policy $\\pi$ tells the agent what action to take at state s\n\n\n\n-utilities of sequences? we want more and we want it sooner. Because it's a stochastic environment, if we defer, there's some chance of not getting it\n\n**Discounting**\n- reasonable to maximize the sum of rewards\n- also reasonable to prefer rewards now to rewards later\n- one solution: values of rewards decay exponentially. i.e. if we have to wait, we multiply the reward by some discount factor($\\gamma$) (less than 1). and if we have to wait 2 times in the future, we multiply it by $\\gamma ^2$\n- sooner rewards are going to have higher utility to us than later \n\ni.e. dicount of 0.5:\nU(1,2,3) = 0.5^0 * 1 + 0.5^1 * 2 + 0.5^2 *3\n        = 1*1 + 0.5*2 + 0.25*3\n        = U(1,2,3) < U(3,2,1)\n\n\nSolutions to inifinte utilities:\n- finite horizon: similar to depth limited search. terminate after fixed T steps\n- discounting: use 0 < $\\gamma$ < 1\n- absorbing state: guarantee that for every policy, a terminal state will eventually be reached\n\n\nOptimal Quantities:\n- V*(s) = expected utility starting in s and acting optimally \n- Q *(s, a) = value (utility) of a q-state(s,a). expected utility starting out having taken action a from state s and therafter acting optimally\n= $\\pi$ (s) = optimal action from state s\n\n\n\nValue Iteration:\n\nStart with $V_0$(S) = 0: no time steps left means an expected reward sum of zero\n\nGiven vector of $V_k(s) values, do one ply of expectimax from each state\n\nTheorem: will converge to unique optimal values\n- basic idea: approximations get refined towards optimal values\n\n\nPolicy Evaluation:\n\n- another basic operation: compute the utility of a state s under a fixed policy (non optimal)\n- define the utility of a state s, under a fixed policy $\\pi$\n\n\n- Step 1: Policy Evaluation - calculate utilities for some fixed policy (not optimal utilities) until convergence. For fixed current policy $\\pi$, find values with policy evaluation\n- Step 2: Policy improvement - update policy using one-step look-ahead with resulting converged (but not optimal) utilities as future values\n- Repeat until policy converges using policy extraction\n\n- This is policy iteration\n\n**you want to:**\n\n- compute optimal values: use value iteration or policy iteration\n- compute values for a particular policy: use policy evaluation\n- turn your values into a policy: use policy extraction\nBoth value iteration and policy iteration compute the same thing (all optimal values)\n\n\n- if given a particular policy, compute values using policy evaluation\n- to turn your values into a policy: use policy extraction (one step lookahead)\n\n\n\n\n**Maximum Expected Utility**\n- a rational agent should choose the action that maximizes its expected utility, given its knowledge\n- Utilities: functions from outcomes(states of the world) to real numbers that describe an agent's preferences \n\n  \n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n**exploration**: you have to try unknown actions to get information\n\n**exploitation**: eventually, you have to use what you know\n\n**regret**: evgen if you learn intelligently, you make mistakes\n\n**sampling**: bc of chance you have to try things repeatedly MDP \n\n\nBAsic idea:\n\n- recieve feedback in the form of rewards\n- agent's utility is defined by the reward function\n- must learn to act so as to maximize expected rewards\n- all learning is based on observed samples of outcomes\n\n\n\n \n\n## AIMA Chapter 22.1 Learning from Rewards\n ***Reinforcement Learning***\n- still assume a markov decision process:\n   - a set of states s\n   - a set of actions per state A\n   - a model T (s,a,s')\n   - a reward function R(s,a,s')\n- still looking for a policy $\\pi$(s)\n- new twist: we don't know T or R\n  - i.e. we dont know which states are good or what the actions do\n  - must try actions and states to learn\n   \n\n\n\nOffline (MDPs) vs Online (RL)\n\nTwo different approaches:\n\n1. Model-Based Learning\n\n    - learn an apprx model based on experiences\n    - solve for values as if the learned model were correct\n    - Learn empirical MDP model:\n      a. count outcomes s' for each s, a\n      b. normalize to give an estimate of T\n      c. discover each R(s,a,s') when we experience (s,a,s')\n    - Solve the learned MDP\n      i.e. use value iteration\n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Model-Free: not maintaining estimates of probabilities. akin to a moving avg\n\nType 1: Passive Reinforcement Learning- \n\n- Simplified task: policy evaluation\n  - input: a fixed policy $\\pi$(s)\n  - you don't know the transitions T(s,a,s')\n  - you don't know the rewards R(s,a,s')\n  - goal: learn the state values\n  - learner is along for the ride\n  - no choice about what actions to take\n  - just execute the policy and learn from experience\n\n  **Direct Evaluation**\n  - goal: compute vals for each state under $\\pi$\n  - idea: average together observed sample values\n    - act according to $\\pi$\n    - every time you visit a state, write down what the sum of discounted rewards turned out to be\n    - avg those samples\n    \n    **bad about direct evalution**: wastes info about state connects, each state is learned separately so it takes a long time to learn\n    \n    Sample-based Policy Evaluation\n\n    Temporal Difference Learning\n\n\n    Active Reinforcement Learning\n    - full reinforcement learning: optimal policies (like value iteration)\n    - you don't know the Transitions T(s,a,s')\n    - you don't know the reards R(s,a,s')\n    - you choose the actions now\n    - goal: learn the optimal policy/values\n\n\n    Q-value Iteration\n    - value iteration: find successive (depth-limited) values\n    - start with $V_0(s) =0 $ which we know is right\n    - given $V_k$, calc the depth k+1 values for all states\n    \n    \n    \n    \n    \n    \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Exploration vs Exploitation\n\n\nSeveral schemes for forcing exploration:\n\n- simplest: random actions ($\\epsilon$ - greedy):\n  - every time step, flip a coin\n  - with small probability $\\epsilon$, act randomly\n  - with large probability 1 - $\\epsioln$, act on current policy\n  \n  problems with random actions? \n  - you do eventually explore but keep picking things repeatedly\n  - one solution, lower $\\epsilon$ over time (the chance of choosing randomly decreases over time)\n  - another solution: exploration functions\n  \n  \n  \nExploration Functions:\n- when to explore?\n- random - explore a fixed amount\n- better idea: explore areas whose badness is not yet established, eventually stop exploring\n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Approximate Q-Learning\n\n  \n\n## Module 9 Lecture Notes\n Your summary here \n\n## Module 9 Definitions\n* **Term** - your definition here\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n ***Probability***\n\n\n Size distribution of n variables with domain sizes d? $d^n$ \n \n \n Inference by Enumeration\n \n - evidence variables: things we've observed\n - query variables: we actually care about them - wanna know how likely\n - hidden variables: things that occur but not that we've actively observed\n \n \n P(Q | $e_1$...$e_k$)\n \n Step 1: select the entries that are consistent with evidence observed\n step 2: sum out Hidden variables to get joint of query and evidence \n\n $\\sum_b$ P(a, b, c) = P( a, c)\n\n step 3: normalize. sum over all q - this gives us the denominator\n \n\n## AIMA Chapter 12.2 Basic Probability Notation\n \n\n- It is inescapable in complex, nondeterministic, or partially observable environments.\n\n- Probabilities express the agent’s inability to reach a definite decision regarding the truth of a sentence.\n\n- Probabilities summarize the agent’s beliefs relative to the evidence. \n\n- Basic probability statements include prior or unconditional probabilities and posterior or conditional probabilities over simple and complex propositions.\n\n- The axioms of probability constrain the probabilities of logically related propositions. An agent that violates the axioms must behave irrationally in some cases.\n\n- The full joint probability distribution specifies the probability of each complete assignment of values to random variables. It is usually too large to create or use in its explicit form, but when it is available it can be used to answer queries simply by adding up entries for the possible worlds corresponding to the query propositions.\n\n- Bayes’ rule allows unknown probabilities to be computed from known conditional probabilities, usually in the causal direction. Applying Bayes’ rule with many pieces of evidence runs into the same scaling problems as does the full joint distribution. Conditional independence brought about by direct causal relationships in the domain allows the full joint distribution to be factored into smaller, conditional distributions. The naive Bayes model assumes the conditional independence of all effect variables, given a single cause variable; its size grows linearly with the number of effects.\n\n\n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n \n\n## AIMA Chapter 12.4 Independence\n \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n \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 \n\n\n\n## SLP Chapter 3.2 Evaluating Language Models\n \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n \n\n## SLP Chapter 3.4 Generalization and Zeros\n MArkov says: Given the present state, the future and past are independent.\n\n## SLP Chapter 3.5 Smoothing\n How many ways are there to apply the chain rule to a joint distribution with NN random variables? N! \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n What is a contraction?\n\nb. Part of the proof of convergence for the value iteration algorithm.\n\n\n## Module 10 Lecture Notes\n Your summary here \n\n## Module 10 Definitions\n* **Term** - your definition here\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Bayes NEts\n\nNodes: variables with domains\n- can be assigned(obswerved) or unassigned (unobserved)\n\nArcs: interactions\n- indicate \"direct influence\" between variables\n- formally: enconde conditional independence\n\n\nSemantics:\n- a set of nodes, one per variable X\n- a directed, acyclic graph\n- a conditiona distribution for each node\n- CPT: conditional probability table\n- description of a noisy causal\n\n\n-Bayes Nets implicitly encode joint distributions\n  - as a product of local conditional distributions\n\nSize:\n- how big is a joint distribution over N Boolean variables?\n  - $2^N$\n- How big is an N-node net if nodes have up to k parents?\n  - O(N * $2^{k+1}$)\n\nBoth give you the power to calculate the Probability of any row\n- BN has huge space savings\n\nBayes Net Assumptions\n\n\nD-Separation: \nstudy independence properties between triples in the graphs\n1. Causal Chain - x causes y causes z\n  - is it guaranteed that x is totally independent of Z? no\n  - one example set of CPTs for which x is not independent of Z is sufficient\n  - ex. low pressure causes rain causes traffic\n    - high pressure causes no rain causes no traffic\n    - P(+y| +x) = 1, P(-y|-x) = 1, P(+z|+y) = 1, P(-z|-y) = 1\n  - P(x,y,z) = P(x)P(y|x) P(z|y)\n  - **evidence along the chain \"blocks\" the influence**  \n  \n\n\n2. Common Cause\n  - **observing the cause blocks influence between effects**\n\n\n3.Common Effect\n  - **observing an effect activates influence between possible causes**\n\n  General Question:\n  - in a given BN, are two variables independent (given evidence)\n\n\n\n  \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Reachability:\n\n- attempt 1: if two nodes are conneted by an undirected path not blocked by a shaded node, the \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n \n\n\n## Module 11 Lecture Notes\n C⫫A∣G : F\n\nA⫫D∣B,C: T\n\nD⫫F∣B,C: T\n\nC⫫E∣A: T\n\n\n \n\n## Module 11 Definitions\n* **Concept** - definition\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n\n\nModel-based approach\n\n• Build a model (e.g. Bayes’ net) where both the label and\nfeatures are random variables\n• Instantiate any observed features\n• Query for the distribution of the\nlabel conditioned on the features\nChallenges\n• What structure should the BN\nhave?\n• How should we learn its\nparameters?\nWhat do we need in order to use Naïve Bayes?\n\n\n\nNaïve Bayes: Assume all features are independent effects of the label\n\nSimple digit recognition version:\n• One feature (variable) Fij for each grid position <i,j>\n• Feature values are on / off, based on whether intensity\nis more or less than 0.5 in underlying image\n• Each input maps to a feature vector, e.g\n\n\n\n• Inference method (we just saw this part)\n• Start with a bunch of probabilities: P(Y) and the P(Fi|Y) tables\n• Use standard inference to compute P(Y|F1…Fn)\n• Nothing new here\n• Estimates of local conditional probability tables\n• P(Y), the prior over labels\n• P(Fi|Y) for each feature (evidence variable)\n• These probabilities are collectively called the parameters of the\nmodel and denoted by q\n• Up until now, we assumed these appeared by magic, but…\n• …they typically come from training data counts: we’ll look at this\nsoon\n\n\nNaïve Bayes for Text\n\nBag-of-words Naïve Bayes:\n• Features: Wi is the word at positon i\n• As before: predict label conditioned on feature variables (spam vs. ham)\n• As before: assume features are conditionally independent given label\nGenerative model:\n“Tied” distributions and bag-of-words\n• Usually, each variable gets its own conditional probability distribution P(F|Y)\n• Each position is identically distributed\n• Why make this assumption?\n• Called “bag-of-words” because model is insensitive to word order or reordering \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n \n\n\nData: labeled instances, e.g. emails marked spam/ham\n• Training set\n• Held out set\n• Test set\n\n\nFeatures: attribute-value pairs which characterize each x\n\n\nExperimentation cycle\n• Learn parameters (e.g. model probabilities) on training set\n• (Tune hyperparameters on held-out set)\n• Very important: never “peek” at the test set!\n\n\nEvaluation\n• Accuracy: fraction of instances predicted correctly\n\n\nOverfitting and generalization\n• Want a classifier which does well on test data\n• Overfitting: fitting the training data very closely, but not generalizing well\n\n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \n\nRelative frequency parameters will overfit the training data!\n\n• Unlikely that every occurrence of “minute” is 100% spam\n• Unlikely that every occurrence of “seriously” is 100% ham\n\nAs an extreme case, imagine using the entire email as the only feature\n• Would get the training data perfect (if deterministic labeling)\n• Wouldn’t generalize at all\n\nTo generalize better: we need to smooth or regularize the estimates \n\n## AIMA Chapter 5.5 Stochastic Games\n Tuning on Held-Out Data\n\nNow we’ve got two kinds of unknowns\n\n\n• Parameters: the probabilities P(X|Y), P(Y)\n• Hyperparameters: e.g. the amount / type of smoothing to do, k, a\n\n\nWhat should we learn where?\n\n• Learn parameters from training data\n\nand test on the held-out data\n• Choose the best value and do a final test on\nthe test data \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n BAselines\n\n\nFirst step: get a baseline\n\n\n• Baselines are very simple “straw man” procedures\n• Help determine how hard the task is\n• Help know what a “good” accuracy is\nWeak baseline: most frequent label classifier\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n The confidence of a probabilistic classifier:\n\n• Posterior over the top label\n• Represents how sure the classifier is of\nthe classification\n• Any probabilistic model will have\nconfidences\n\n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Bayes rule lets us do diagnostic queries with causal probabilities\nThe naïve Bayes assumption takes all features to be independent given\nthe class label\n\nClassifier confidences are useful, when you can get them \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Binary case: compare features to a weight vector\nLearning: figure out the weight vector from examples1aq 1 \n\n## SLP Chapter 4.3 Worked Example\n In the space of feature vectors\n• Examples are points\n• Any weight vector is a hyperplane\n \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Start with weights = 0\nFor each training instance:\n• Classify with current weights\n• If correct (i.e., y=y*), no change!\n• If wrong: adjust the weight vector \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Properties of perceptrons:\n\nSeparability: true if some parameters get the training\nset perfectly correct\n\n\nConvergence: if the training is separable, perceptron\nwill eventually converge (binary case)\n\n\nMistake Bound: the maximum number of mistakes\n(binary case) related to the margin or degree of\nseparability\n\n\nProblems with perceptrons:\n\nNoise: if the data isn’t separable,\nweights might thrash\n• Averaging weight vectors over\ntime can help (averaged\nperceptron)\n\nMediocre generalization: finds a\n“barely” separating solution\n\n\nOvertraining: test / held-out\naccuracy usually rises, then falls\n• Overtraining is a kind of overfitting\n\n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Maximizing the margin: good according to intuition, theory, practice\nOnly support vectors matter; other training examples are ignorable\nSupport vector machines (SVMs) find the separator with max\nmargin\nBasically, SVMs are MIRA where you optimize over all examples at\nonce \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Naïve Bayes\n• Builds a model training data\n\nPerceptrons / MIRA:\n• Makes less assumptions about data\n\n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Activation function:\n\nInstead of directly outputting z = w·x+b, which is a linear function of x, neuron units\napply a non-linear function f to z.\n\n\nThe output of this function is called the activation value for the unit, represented by\nthe variable a. The output of a neural network is called y, so if the activation of a node\nis the final output of a network then\ny=a= f(z)\n\n\nThere are 3 commonly used non-linear functions used for f:\n-The sigmoid function\n-The tanh function\n-The rectified linear unit ReLU\n\n \n\n## SLP Chapter 4.9 Statistical Significance Testing\n\n\n\n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n \n      \n\n## Module 12 Lecture Notes\n This chapter introduced the naive Bayes model for classification and applied it to\nthe text categorization task of sentiment analysis.\n\n\n• Text categorization, in which an entire text is assigned a class from a finite set,\nincludes such tasks as sentiment analysis, spam detection, language identification, and authorship attribution.\n\n• Sentiment analysis classifies a text as reflecting the positive or negative orientation (sentiment) that a writer expresses toward some object.\n\n• Naive Bayes is a generative model that makes the bag of words assumption\n(position doesn’t matter) and the conditional independence assumption (words\nare conditionally independent of each other given the class)\n\n\n• Classifiers are evaluated based on precision and recall.\n\n• Classifiers are trained using distinct training, dev, and test sets, including the\nuse of cross-validation in the training set.\n\n• Statistical significance tests should be used to determine whether we can be\nconfident that one version of a classifier is better than another.\n\n\n## Module 12 Definitions\n* **Concept** - definition\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n \n\n## SLP Chapter 5.3 The cross-entropy loss function\n \n\n## SLP Chapter 5.4 Gradient Descent\n \n\n\n\n## SLP Chapter 5.5 Regularization\n  \n\n## SLP Chapter 5.6 Multinomial logistic regression\n \n\n\n \n\n## SLP Chapter 7.1 Units\n logistic regression model of classification.\n\n• Logistic regression is a supervised machine learning classifier that extracts\nreal-valued features from the input, multiplies each by a weight, sums them,\nand passes the sum through a sigmoid function to generate a probability. A\nthreshold is used to make a decision.\n\n• **Logistic regression** can be used with two classes (e.g., positive and negative\nsentiment) or with multiple classes (multinomial logistic regression, for example for n-ary text classification, part-of-speech labeling, etc.).\n\n\n\n\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 • **Multinomial** logistic regression uses the softmax function to compute probabilities.\n\n• The weights (vector w and bias b) are learned from a labeled training set via a\nloss function, such as the cross-entropy loss, that must be minimized.\n\n• Minimizing this **loss function** is a convex optimization problem, and iterative\nalgorithms like gradient descent are used to find the optimal weights.\n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n • **Regularization** is used to avoid overfitting.\n\n• Logistic regression is also one of the most useful analytic tools, because of its\nability to transparently study the importance of individual features.  \n\n## SLP Chapter 7.7 Training the neural language model\n Neural networks are built out of neural units, originally inspired by human\nneurons but now simply an abstract computational device.\n\n\n\n• In a **fully-connected, feedforward network**, each unit in layer i is connected\nto each unit in layer i+1, and there are no cycles.\n\n\n• The power of neural networks comes from the ability of early layers to learn\nrepresentations that can be utilized by later layers in the network.\n\n\n• **Neural networks** are trained by optimization algorithms like gradient descent.\n\n\n• **Error backpropagation**, backward differentiation on a computation graph,\nis used to compute the gradients of the loss function for a network.\n\n\n• **Neural language** models use a neural network as a probabilistic classifier, to\ncompute the probability of the next word given the previous n words.\n\n\n• Neural language models can use **pretrained embeddings**, or can learn embeddings from scratch in the process of language modeling. \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 **recurrent neural networks** and **transformers** and how they can be applied to language problems. Here’s a summary of\nthe main points that we covered:\n• In simple Recurrent Neural Networks sequences are processed one element at\na time, with the output of each neural unit at time t based both on the current\ninput at t and the hidden layer from time t −1.\n• **RNNs can be trained** with a straightforward extension of the backpropagation\nalgorithm, known as **backpropagation through time (BPTT)**.\n• Simple recurrent networks fail on long inputs because of problems like **vanishing gradients**; instead modern systems use more complex gated architectures such as **LSTMs** that explicitly decide what to remember and forget in\ntheir hidden and context layers.\n\n\n## SLP Chapter 9.2 Recurrent Neural Networks\n • **Transformers are non-recurrent networks** based on self-attention. A **selfattention layer** maps input sequences to output sequences of the same length,\n.\n• A **transformer block** consists of a single attention layer followed by a feedforward layer with residual connections and layer normalizations following\neach. **Transformer blocks can be stacked** to make deeper and more powerful\nnetworks.\n\n\n## SLP Chapter 9.3 RNNs as Language Models\n • Common language-based applications for RNNs and transformers include:\n– Probabilistic language modeling: assigning a probability to a sequence\n\n– Auto-regressive generation using a trained language model.\n\n– Sequence classification\"\"\n\n# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n\n## SLP Chapter 6.1 Lexical Semantics\n In vector semantics, a word is modeled as a **vector**—a point in high-dimensional\nspace, also called an **embedding**. In this chapter we focus on **static embeddings**, in each **each word is mapped to a fixed embedding**.\n• Vector semantic models fall into two classes: **sparse and dense**. \n\nIn sparse models each dimension corresponds to a word in the vocabulary V and cells\nare functions of co-occurrence counts. The term-document matrix has a row\nfor each word (term) in the vocabulary and a column for each document. The\nword-context or term-term matrix has a row for each (target) word in the\nvocabulary and a column for each context term in the vocabulary. Two sparse\nweightings are common: the tf-idf weighting which weights each cell by its\nterm frequency and inverse document frequency, and PPMI (pointwise\npositive mutual information) most common for for word-context matrices.\n\n\n \n\n## SLP Chapter 6.2 Vector Semantics\n • Dense vector models have dimensionality 50–1000. Word2vec algorithms\nlike skip-gram are a popular way to compute dense embeddings. Skip-gram\ntrains a logistic regression classifier to compute the probability that two words\nare ‘likely to occur nearby in text’. This probability is computed from the dot\nproduct between the embeddings for the two words.\n\n## SLP Chapter 6.3 Words and Vectors\n • Skip-gram uses stochastic gradient descent to train the classifier, by learning\nembeddings that have a high dot product with embeddings of words that occur\nnearby and a low dot product with noise words. \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n \n• Other important embedding algorithms include GloVe, a method based on\nratios of word co-occurrence probabilities.\n\n## SLP Chapter 6.8 Word2vec\n \n• Whether using sparse or dense vectors, word and document similarities are\ncomputed by some function of the dot product between vectors. The cosine\nof two vectors—a normalized dot product—is the most popular such metric. \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": {}
        }
      ]
    }
  ]
}