{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of Template_for CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f543bce0-26a5-4a2c-aeb0-242853395dc9"
      },
      "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": 71,
      "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": "f7989896-576a-41b6-cb90-4aa8aef6b848"
      },
      "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": 72,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = True"
      ],
      "execution_count": 73,
      "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",
        "\n",
        "chapter16_1 = \"\"\" Markov decision process is a sequential decision problem, fully observable environment, stochastic transition model (probabilities), with additive rewards.\n",
        "                  To find solution you need set of states + actions, transition function T(s, a, s') (probability that executing action a in s leads to s'), reward function, initial states, and terminal states (optional).\n",
        "\n",
        "\n",
        " \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\"Value iteration: Do one ply of expectimax from each state until convergence \"\"\"\n",
        "chapter16_3 =  \"\"\" Computing actions from values is hard, but from Q-values is easy (just choose the highest). Problems with \n",
        "                   value iteration: slow, max rarely changes for the states, policy converges before the values. \n",
        "\n",
        "                   Policy iteration: calculate utilities for fixed policy until convergence, update policy using one-step look ahead using the converged\n",
        "                   utilities as future values, repeat until policy converges\n",
        "\n",
        " \"\"\"\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 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"assigns single number to express how desirable a state is\",\n",
        "\"expected utility\" : \"average utility value of outcomes\",\n",
        "\"MEU\": \"maximizing average utility\",\n",
        "\"preference elicitation\" : \"presenting choices and using observed preferences to make utility function\",\n",
        "\"descriptive theory\": \"how actual agents actually act\",\n",
        "\"policy\": \"what the agent should do for any state\",\n",
        "\"optimal policy\" : \"yields highest expected utility\",\n",
        "\"finite horizon\" : \"fixed time after which game ends (nothing will matter anymore)\",\n",
        "\"nonstationary\" : \"policy that depends on time\",\n",
        "\"discount factor\" : \"agent prefers current rewards over future (0 = future is insignificant)\",\n",
        "\"Q function\" : \"expected utility of taking an action given a state Q(s, a)\",\n",
        "\"contraction\" : \"____________________\",\n",
        "\"markov assumption\" : \"given present, past and future are independent\",\n",
        "\"Dynamic Bayesian model\" : \"Sensor/transition model and prior distribution over state variable(s) needed \"\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 74,
      "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": 890
        },
        "outputId": "dd53caee-0789-4177-a05d-5a7b3dbf54c0"
      },
      "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": 75,
      "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 Markov decision process is a sequential decision problem, fully observable environment, stochastic transition model (probabilities), with additive rewards.\n                  To find solution you need set of states + actions, transition function T(s, a, s') (probability that executing action a in s leads to s'), reward function, initial states, and terminal states (optional).\n\n\n  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\nValue iteration: Do one ply of expectimax from each state until convergence \n\n## AIMA Chapter 16.3 Utility Functions\n Computing actions from values is hard, but from Q-values is easy (just choose the highest). Problems with \n                   value iteration: slow, max rarely changes for the states, policy converges before the values. \n\n                   Policy iteration: calculate utilities for fixed policy until convergence, update policy using one-step look ahead using the converged\n                   utilities as future values, repeat until policy converges\n\n \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 Your summary here \n\n## Module 8 Definitions\n* **Utility function** - assigns single number to express how desirable a state is\n* **Expected utility** - average utility value of outcomes\n* **Meu** - maximizing average utility\n* **Preference elicitation** - presenting choices and using observed preferences to make utility function\n* **Descriptive theory** - how actual agents actually act\n* **Policy** - what the agent should do for any state\n* **Optimal policy** - yields highest expected utility\n* **Finite horizon** - fixed time after which game ends (nothing will matter anymore)\n* **Nonstationary** - policy that depends on time\n* **Discount factor** - agent prefers current rewards over future (0 = future is insignificant)\n* **Q function** - expected utility of taking an action given a state Q(s, a)\n* **Contraction** - ____________________\n* **Markov assumption** - given present, past and future are independent\n* **Dynamic bayesian model** - Sensor/transition model and prior distribution over state variable(s) needed \n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "chapter17_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" Exploration: you have to try unknown actions to get information\n",
        "Exploitation: eventually, you have to use what you know\n",
        "Regret: even if you learn intelligently, you make mistakes\n",
        "Sampling: because of chance, you have to try things repeatedly\n",
        "Difficulty: learning can be much harder than solving a known MDP \"\"\"\n",
        "chapter22_2 =  \"\"\" Problems with direct evaluation:  It wastes information about state connections, Each state must be learned separately, takes a long time to learn\n",
        "\"\"\"\n",
        "chapter22_3 =  \"\"\" Active reinforcement learning: You don’t know the transitions T(s,a,s’) or rewards R(s,a,s’).\n",
        "You choose the actions now and want to learn the optimal policy / values\"\"\"\n",
        "chapter22_4 =  \"\"\" Exploration function: takes value estimate and visit count to return utility. Will lead to exploring more uknown states. \"\"\"\n",
        "chapter22_5 =  \"\"\" Approximate Q learning: learn about small number of training states and then generalize. Can make a q-function for any state\n",
        "                   by using weights (ie Q(s,a) = w1f1(s,a) + w2f2(s,a) +...)  \"\"\"\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",
        "\"passive reinforcement learning\" : \"Execute policy and learn from experience (online planning)\",\n",
        "\"direct evaluation\" : \"Follow policy, when at state note the sum of the rewards, average those samples (finds values for each state) \",\n",
        "\"Sample based policy evaluation\" : \"take samples of outcome (by performing action) and average results (then do policy evalutaion) \",\n",
        "\"temporal difference learning\" : \"update V(s) after every transition (s,a,s',r) and keep running average (decay factor)\",\n",
        "\"exponential moving average\" : \"makes recent info more important\",\n",
        "\"off-policy learning\": \"q-learning converges to optimal policy, even when acting suboptimally\",\n",
        "\"regret\" : \"total mistake cost (difference between achieved rewards and optimal rewards)\",\n",
        "\"activation function\" : \"mathematical equations that determine the output of a neural network (ie sigmoid)\",\n",
        "\"logistic regression\" : \"vector of weights + bias term which is then transformed with sigmoid function (smooth unlike perceptrons)\",\n",
        "\"feed forward NN\" : \"all units fully connected and no cycles\"\n",
        "}"
      ],
      "execution_count": 76,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 717
        },
        "cellView": "form",
        "outputId": "0f4ded19-7430-4df1-8ad7-37a7a0e786f0"
      },
      "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": 77,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Exploration: you have to try unknown actions to get information\nExploitation: eventually, you have to use what you know\nRegret: even if you learn intelligently, you make mistakes\nSampling: because of chance, you have to try things repeatedly\nDifficulty: learning can be much harder than solving a known MDP \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Problems with direct evaluation:  It wastes information about state connections, Each state must be learned separately, takes a long time to learn\n\n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Active reinforcement learning: You don’t know the transitions T(s,a,s’) or rewards R(s,a,s’).\nYou choose the actions now and want to learn the optimal policy / values\n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Exploration function: takes value estimate and visit count to return utility. Will lead to exploring more uknown states. \n\n## Module 9 Lecture Notes\n Your summary here \n\n## Module 9 Definitions\n* **Passive reinforcement learning** - Execute policy and learn from experience (online planning)\n* **Direct evaluation** - Follow policy, when at state note the sum of the rewards, average those samples (finds values for each state) \n* **Sample based policy evaluation** - take samples of outcome (by performing action) and average results (then do policy evalutaion) \n* **Temporal difference learning** - update V(s) after every transition (s,a,s',r) and keep running average (decay factor)\n* **Exponential moving average** - makes recent info more important\n* **Off-policy learning** - q-learning converges to optimal policy, even when acting suboptimally\n* **Regret** - total mistake cost (difference between achieved rewards and optimal rewards)\n* **Activation function** - mathematical equations that determine the output of a neural network (ie sigmoid)\n* **Logistic regression** - vector of weights + bias term which is then transformed with sigmoid function (smooth unlike perceptrons)\n* **Feed forward nn** - all units fully connected and no cycles\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"probabilistic model\" : \"joint distribution over set of random variables (sum to 1)\",\n",
        "\"event\" : \"set E of outcomes (ie probability that it's hot AND sunny\",\n",
        "\"marginal distributions\" : \"sub-tables that eliminate variables (ie P(T,W) -> P(T) or P(W))\",\n",
        "\"conditional distributions\" : \"Distributions over variables given others are fixed P(W|T=hot)\",\n",
        "\"probabilistic inference\" : \"compute desired probability from other known probabilities (P(on time|no accidends))\",\n",
        "\"product rule\" : \"P(y)P(x|y) = P(x, y)\",\n",
        "\"chain rule\" : \"P(x,y,z) = P(x)P(y|x)P(z|x,y)\",\n",
        "\"bayes rule\" : \"P(x|y) = P(y|x)*P(x)/P(y)\",\n",
        "\"unigram\" : \"no history for guessing next word\",\n",
        "\"bigram\" : \"1 word as history\",\n",
        "\"trigram\" : \"2 words as history\",\n",
        "\"n-gram evaluation\" : \"evaluated by perplexity of test set\",\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "}"
      ],
      "execution_count": 78,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "c07d7ecc-0158-4e4f-a462-211dd42c0038"
      },
      "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": 79,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n Your summary here \n\n## Module 10 Definitions\n* **Probabilistic model** - joint distribution over set of random variables (sum to 1)\n* **Event** - set E of outcomes (ie probability that it's hot AND sunny\n* **Marginal distributions** - sub-tables that eliminate variables (ie P(T,W) -> P(T) or P(W))\n* **Conditional distributions** - Distributions over variables given others are fixed P(W|T=hot)\n* **Probabilistic inference** - compute desired probability from other known probabilities (P(on time|no accidends))\n* **Product rule** - P(y)P(x|y) = P(x, y)\n* **Chain rule** - P(x,y,z) = P(x)P(y|x)P(z|x,y)\n* **Bayes rule** - P(x|y) = P(y|x)*P(x)/P(y)\n* **Unigram** - no history for guessing next word\n* **Bigram** - 1 word as history\n* **Trigram** - 2 words as history\n* **N-gram evaluation** - evaluated by perplexity of test set\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 = \"\"\" X is conditionally independent of y given z iff P(x, y| z) = P(x|z)P(y|z) or equivalently iff P(x|z,y) = P(x|z) \"\"\"\n",
        "chapter13_2 = \"\"\" Bayes nets has one node per variable x where the edges represent what else is true if x is true. This lets us write\n",
        "                  P(xi | x1...xi-1) as P(xi | parents(xi)). Model is created based on which variables affect each other.\n",
        "                  \n",
        "                  D-separation: Shows what is independent of each other. \n",
        "              \n",
        "                  X and Z independent given Y? P(z|x,y) = P(x,y,z)/P(x,y) -> manipulate to show P(z|x,y) = P(z|x) or P(z|y) then X and Z conditionally independent\n",
        "                   \n",
        "                   Are two variables in Bayes Nets independent? Use causal chain, common cause, and common effect. Check all triples on each path\n",
        "                   to see if they are active. If 1+ triple is not active, then that path is inactive. If all paths are inactive then independence is guaranteed\n",
        "                   \"\"\"\n",
        "chapter13_3 = \"\"\" Inference by enumeration is very slow (exponentially proportional to hidden variables) \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"independent variables\" : \"P(x,y) = P(x)P(y)\",\n",
        "\"causal chain\" : \"x -> y -> z (x independent of z given y)\" ,\n",
        "\"P(x,y,z)\" : \"P(x)P(y|x)P(z|y)\",\n",
        "\"Common cause\" : \"Y -> X, Y -> Z (x independent of z given y)\",\n",
        "\"Common effect\" : \"X -> Z, Y -> Z (x,y independent, x,y not independent given z)\" ,\n",
        "\"Causal Chain Active\" : \"x -> y -> z where y is unobserved\",\n",
        "\"Common cause active\" : \"Y -> X, Y -> Z where Y is unobserved\",\n",
        "\"Common effect\" : \"X -> Z, Y -> Z where Z or one of its descendants is observed\",\n",
        "\"active triple\" : \"one of three effects above\",\n",
        "\"active path\" : \"when every triple in path is active\",\n",
        "\"conditional probability distribution of variable\" : \"depends only on parents\",\n",
        "\"sparse system\" : \"grows in linear complexity\",\n",
        "\n",
        "\n",
        "\n",
        "}\n"
      ],
      "execution_count": 80,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 711
        },
        "cellView": "form",
        "outputId": "82ff9adc-5c23-46cc-f088-c2f716729b66"
      },
      "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": 81,
      "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 X is conditionally independent of y given z iff P(x, y| z) = P(x|z)P(y|z) or equivalently iff P(x|z,y) = P(x|z) \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Bayes nets has one node per variable x where the edges represent what else is true if x is true. This lets us write\n                  P(xi | x1...xi-1) as P(xi | parents(xi)). Model is created based on which variables affect each other.\n                  \n                  D-separation: Shows what is independent of each other. \n              \n                  X and Z independent given Y? P(z|x,y) = P(x,y,z)/P(x,y) -> manipulate to show P(z|x,y) = P(z|x) or P(z|y) then X and Z conditionally independent\n                   \n                   Are two variables in Bayes Nets independent? Use causal chain, common cause, and common effect. Check all triples on each path\n                   to see if they are active. If 1+ triple is not active, then that path is inactive. If all paths are inactive then independence is guaranteed\n                   \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Inference by enumeration is very slow (exponentially proportional to hidden variables) \n\n## Module 11 Lecture Notes\n Your summary here \n\n## Module 11 Definitions\n* **Independent variables** - P(x,y) = P(x)P(y)\n* **Causal chain** - x -> y -> z (x independent of z given y)\n* **P(x,y,z)** - P(x)P(y|x)P(z|y)\n* **Common cause** - Y -> X, Y -> Z (x independent of z given y)\n* **Common effect** - X -> Z, Y -> Z where Z or one of its descendants is observed\n* **Causal chain active** - x -> y -> z where y is unobserved\n* **Common cause active** - Y -> X, Y -> Z where Y is unobserved\n* **Active triple** - one of three effects above\n* **Active path** - when every triple in path is active\n* **Conditional probability distribution of variable** - depends only on parents\n* **Sparse system** - grows in linear complexity\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 = \"\"\"model-based classification:  \n",
        "                 1) Build model (eg Bayes Nets) with label and features as random variables \\n\n",
        "                 2) Instantiate observed features\\n\n",
        "                 3) Query for the distribution of the label conditioned on the features (query variable is class ie spam or ham) \\n   \"\"\"\n",
        "\n",
        "\n",
        "chapter19_2 = \"\"\"Inference for Naive Bayes:\\n\n",
        "                 1) Get joint probability of label and evidence for each label (P(y, f1, .. fn) for each)\\n\n",
        "                 2) Sum to get probability of evidence\\n\n",
        "                 3) Normalize by dividing 1) by 2)  \\n  \"\"\"\n",
        "\n",
        "\n",
        "chapter19_3 = \"\"\" Naive Bays: builds a model training data, gives prediction probabilities, strong assumptions about feature independence, one pass through data \"\"\"\n",
        "chapter19_4 = \"\"\" Perceptrons: makes less assumptions about data, mistake-driven learning, multiple passes through data, often more accurate\"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"features\" : \"attributes used to make classification decision\",\n",
        "\"classification\" : \"given inputs x, predict labels y\",\n",
        "\"Naive Bayes\" : \"Assume all features are independent effects of label\",\n",
        "\"Naive Bayes model\" : \"P(y, F1, ..., Fn) =   P(y) CID P(F|y) for each feature F\",\n",
        "\"model paramaters\" : \"P(Label) and P(Feature i |Label)\",\n",
        "\"training data\" : \"inputs and correct labels\",\n",
        "\"held out data (dev set)\" : \"optimize hyperparamaters (such as laplace smoothing amount)\",\n",
        "\"test set\" : \"test model's accuracy\",\n",
        "\"overfitting\" : \"Cam't give unseen events zero probability\",\n",
        "\"maximum likelihood estimate\" : \"pick parameter settings that maximize likelihood of data given those settings (count(x)/total)\",\n",
        "\"laplace smoothing\" : \"pretend everything has been seen 1 extra time (count(x)+1)/(total+1)\",\n",
        "\"bias\" : \"shifts hyperplane (that separates labels)\",\n",
        "\"multiclass perceptron\" : \"weight vector for each class, highest prediction score wins\",\n",
        "\"perceptron\" : \"each feature has a weight, tune until feature vector * weight vector -> label\",\n",
        "\"separability\" : \"if some paramaters get the training set perfectly correct\",\n",
        "\"convergence\" : \"If seperable, perceptron will eventually converge\",\n",
        "\"mistake bound\" : \"max number of mistakes related to margin of separability\",\n",
        "\"noise\" : \"if data isn't separable wieghts might not work\",\n",
        "\"mediocre generalization\" : 'finds a barely separating solution',\n",
        "\"margin infused relaxed algorithm\" : \"choose update size that fixes current mistake but minimizes change to w\",\n",
        "\"non-linear separators\" : \"map to higher dimensional feature space where training set is separable\",\n",
        "\"P(x1,x2,x3,y) join probability\"  :\" P(Y)P(X1|Y)P(X2|Y)P(X3|Y)\",\n",
        "\"parametric models\" : \"fixed number of paramaters\",\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 82,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "ea3e1614-d9f8-4244-a34a-3f796011a5ff"
      },
      "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": 83,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\nmodel-based classification:  \n                 1) Build model (eg Bayes Nets) with label and features as random variables \n\n                 2) Instantiate observed features\n\n                 3) Query for the distribution of the label conditioned on the features (query variable is class ie spam or ham) \n   \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\nInference for Naive Bayes:\n\n                 1) Get joint probability of label and evidence for each label (P(y, f1, .. fn) for each)\n\n                 2) Sum to get probability of evidence\n\n                 3) Normalize by dividing 1) by 2)  \n  \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Naive Bays: builds a model training data, gives prediction probabilities, strong assumptions about feature independence, one pass through data \n\n## AIMA Chapter 5.5 Stochastic Games\n Perceptrons: makes less assumptions about data, mistake-driven learning, multiple passes through data, often more accurate\n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n Your summary here \n\n## Module 12 Definitions\n* **Features** - attributes used to make classification decision\n* **Classification** - given inputs x, predict labels y\n* **Naive bayes** - Assume all features are independent effects of label\n* **Naive bayes model** - P(y, F1, ..., Fn) =   P(y) CID P(F|y) for each feature F\n* **Model paramaters** - P(Label) and P(Feature i |Label)\n* **Training data** - inputs and correct labels\n* **Held out data (dev set)** - optimize hyperparamaters (such as laplace smoothing amount)\n* **Test set** - test model's accuracy\n* **Overfitting** - Cam't give unseen events zero probability\n* **Maximum likelihood estimate** - pick parameter settings that maximize likelihood of data given those settings (count(x)/total)\n* **Laplace smoothing** - pretend everything has been seen 1 extra time (count(x)+1)/(total+1)\n* **Bias** - shifts hyperplane (that separates labels)\n* **Multiclass perceptron** - weight vector for each class, highest prediction score wins\n* **Perceptron** - each feature has a weight, tune until feature vector * weight vector -> label\n* **Separability** - if some paramaters get the training set perfectly correct\n* **Convergence** - If seperable, perceptron will eventually converge\n* **Mistake bound** - max number of mistakes related to margin of separability\n* **Noise** - if data isn't separable wieghts might not work\n* **Mediocre generalization** - finds a barely separating solution\n* **Margin infused relaxed algorithm** - choose update size that fixes current mistake but minimizes change to w\n* **Non-linear separators** - map to higher dimensional feature space where training set is separable\n* **P(x1,x2,x3,y) join probability** -  P(Y)P(X1|Y)P(X2|Y)P(X3|Y)\n* **Parametric models** - fixed number of paramaters\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 = \"\"\" Classifier components:\n",
        "1. A feature representation of the input. For each input observation\n",
        "x(i), this will be a vector of features [x1,x2,...,xn].\n",
        "2. A classification function that computes the estimated class �! via\n",
        "p(y|x).\n",
        "3. An objective function for learning, usually involving minimizing\n",
        "error on training examples.\n",
        "4. An algorithm for optimizing the objective function.\n",
        "\"\"\"\n",
        "slp_chapter5_2 = \"\"\" P(y=1) = sigmoid(w*x+b)  P(y=0) = 1 - P(y=1) \"\"\"\n",
        "slp_chapter5_3 = \"\"\"Logistic Regression Learning (setting the weights):\n",
        "                  1. An objective/loss function that finds distance between\n",
        "                  the system output and the gold output. We will use cross-entropy\n",
        "                  loss.\n",
        "                  2. An algorithm for optimizing the objective function. Use\n",
        "                  stochastic gradient descent to minimize loss function.\n",
        "\n",
        " \"\"\"\n",
        "slp_chapter5_4 = \"\"\"Training neural nets: loss function (cross-entropy loss), optimization algo (gradient descent), \n",
        "                    way of computing gradient of loss function (error propogation)  \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"sigmoid function\" : \"squishes value to be between 0-1\",  \n",
        "\"decision boundary\" : \"y = 1 if P(y=1|x) > .5, y=0 if otherwise. .5 is decision boundary\",\n",
        "\"conditional maximum likelihood estimation\" : \"choose parameters w,b that maximize probabilities of true labels\",\n",
        "\"cross entropy loss\" : \"higher if prediction is incorrect\",\n",
        "\"gradient descent\" : \"finds good settings for weights + bias by minimizing loss function (move opposite direction of slope rising steeply)\",\n",
        "\"step size\" : \"how big step is when finding min (if too large may never find min)\",\n",
        "\"batch training\" : \"computes gradient over entire data set\",\n",
        "\"mini-batch training\" : \"train on batch usually of size 512 or 1024 (so that everything can be parallelized)\",\n",
        "\"regularization\" : \"penalizes large weights taht cause over fitting\",\n",
        "\"multinomial logistic regression\" : \"uses softmax function (generalization of sigmoid function) (z=[.6,1.1,-1.5,3.2,-1.1]->[.056,.09,.007,.099,.74,.01]\",\n",
        "\"back-propagation algorithm \" : \"derivatives of the paramaters get passed back (shows which parameters affect outcome the most)\",\n",
        "\"activation function\" : \"defines how the weighted sum of the input is transformed into an output from a node or nodes in a layer of the network.\",\n",
        "\"error back-propogation\" : \"allows the correct layers to be updated\"\n",
        "\n",
        "\n",
        "\n",
        "}\n"
      ],
      "execution_count": 84,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "272fa6be-1312-46e8-d027-3daa2fa05aa3"
      },
      "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": 85,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Classifier components:\n1. A feature representation of the input. For each input observation\nx(i), this will be a vector of features [x1,x2,...,xn].\n2. A classification function that computes the estimated class �! via\np(y|x).\n3. An objective function for learning, usually involving minimizing\nerror on training examples.\n4. An algorithm for optimizing the objective function.\n\n\n## SLP Chapter 5.2 Learning in Logistic Regression\n P(y=1) = sigmoid(w*x+b)  P(y=0) = 1 - P(y=1) \n\n## SLP Chapter 5.3 The cross-entropy loss function\nLogistic Regression Learning (setting the weights):\n                  1. An objective/loss function that finds distance between\n                  the system output and the gold output. We will use cross-entropy\n                  loss.\n                  2. An algorithm for optimizing the objective function. Use\n                  stochastic gradient descent to minimize loss function.\n\n \n\n## SLP Chapter 5.4 Gradient Descent\nTraining neural nets: loss function (cross-entropy loss), optimization algo (gradient descent), \n                    way of computing gradient of loss function (error propogation)  \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 13 Definitions\n* **Sigmoid function** - squishes value to be between 0-1\n* **Decision boundary** - y = 1 if P(y=1|x) > .5, y=0 if otherwise. .5 is decision boundary\n* **Conditional maximum likelihood estimation** - choose parameters w,b that maximize probabilities of true labels\n* **Cross entropy loss** - higher if prediction is incorrect\n* **Gradient descent** - finds good settings for weights + bias by minimizing loss function (move opposite direction of slope rising steeply)\n* **Step size** - how big step is when finding min (if too large may never find min)\n* **Batch training** - computes gradient over entire data set\n* **Mini-batch training** - train on batch usually of size 512 or 1024 (so that everything can be parallelized)\n* **Regularization** - penalizes large weights taht cause over fitting\n* **Multinomial logistic regression** - uses softmax function (generalization of sigmoid function) (z=[.6,1.1,-1.5,3.2,-1.1]->[.056,.09,.007,.099,.74,.01]\n* **Back-propagation algorithm ** - derivatives of the paramaters get passed back (shows which parameters affect outcome the most)\n* **Activation function** - defines how the weighted sum of the input is transformed into an output from a node or nodes in a layer of the network.\n* **Error back-propogation** - allows the correct layers to be updated\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 = \"\"\" Neural Language models have several advantages over n-gram LMs:\n",
        "1. They don’t need smoothing\n",
        "2. They can handle much longer histories.\n",
        "3. They can generalize over contexts of similar words.\n",
        "4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\n",
        "Disadvantage: slower to train than traditional n-gram LMs \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Neural LMs:\n",
        "\n",
        "1. Associate each word in the vocabulary with a vector-representation, thereby\n",
        "creating a notion of similarity between words.\n",
        "2. Express the joint probability function of a word sequence in terms of the word\n",
        "vectors for the words in that sequence.\n",
        "3. Simultaneously learn the word vectors and the parameters of the function.\n",
        "The word vectors are low-dimensional (d=30 to d=100) dense vectors, like we’ve seen\n",
        "before\n",
        "\n",
        "\n",
        "Input is k-gram of words, and output is probability distribution over next word\n",
        " \"\"\"\n",
        "slp_chapter9_3 = \"\"\" How to get dense vectors:train a classifier!\n",
        "1. Treat the target word and a neighboring context word as positive examples.\n",
        "2. Randomly sample other words in the lexicon to get negative samples.\n",
        "3. Use logistic regression to train a classifier to distinguish those two cases.\n",
        "4. Use the weights as the embeddings. \n",
        "\"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"training\" : \"word k-grams from corpus\",\n",
        "\"generalizing\" : \"representing words as vector space models (ie makes 'cat' and 'dog' be seen similarly\",\n",
        "\"Word Meaning\" : \"ie Synonym, antonym, connotations (+/-), semantic roles (buy, sell, pay all relate to purchasing), entailment\",\n",
        "\"entailment\" : \"All animals have an ulnar artery => all DOGS have an ulnar artery\",\n",
        "\"word similarity\" : \"most words don't have synonyms but do have similar words (tall=height)\",\n",
        "\"Distributional Hypothesis\" : \"If A and B have almost identical environments they are synonyms\",\n",
        "\"term-document matrix\" : \"Rows = words, cols = documents. 1 when word is in document\",\n",
        "\"document similarity\" : \"compare two columns of matrix\",\n",
        "\"word similarity\" : \"compare two rows of matrix (normalize vector length and find euclidean distance or cosine distance)\",\n",
        "\"Term-Term matrix\" : \"Words as row and columns (how often did words occur near another word)\",\n",
        "\"context windows\" : \"word A occurs in a window of +/- k words to word B\",\n",
        "\"syntactic distribution\" : \"words are similar if they are used in similar syntax\",\n",
        "\"TF-IDF\" : \"Term frequency * inverse document frequency (1/docs it occurred in) (to prevent 'the' being overpowered\",\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 86,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "21271b96-351f-4585-d48b-9a8e981f3626"
      },
      "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": 87,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Neural Language models have several advantages over n-gram LMs:\n1. They don’t need smoothing\n2. They can handle much longer histories.\n3. They can generalize over contexts of similar words.\n4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\nDisadvantage: slower to train than traditional n-gram LMs \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Neural LMs:\n\n1. Associate each word in the vocabulary with a vector-representation, thereby\ncreating a notion of similarity between words.\n2. Express the joint probability function of a word sequence in terms of the word\nvectors for the words in that sequence.\n3. Simultaneously learn the word vectors and the parameters of the function.\nThe word vectors are low-dimensional (d=30 to d=100) dense vectors, like we’ve seen\nbefore\n\n\nInput is k-gram of words, and output is probability distribution over next word\n \n\n## SLP Chapter 9.3 RNNs as Language Models\n How to get dense vectors:train a classifier!\n1. Treat the target word and a neighboring context word as positive examples.\n2. Randomly sample other words in the lexicon to get negative samples.\n3. Use logistic regression to train a classifier to distinguish those two cases.\n4. Use the weights as the embeddings. \n\n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 14 Definitions\n* **Training** - word k-grams from corpus\n* **Generalizing** - representing words as vector space models (ie makes 'cat' and 'dog' be seen similarly\n* **Word meaning** - ie Synonym, antonym, connotations (+/-), semantic roles (buy, sell, pay all relate to purchasing), entailment\n* **Entailment** - All animals have an ulnar artery => all DOGS have an ulnar artery\n* **Word similarity** - compare two rows of matrix (normalize vector length and find euclidean distance or cosine distance)\n* **Distributional hypothesis** - If A and B have almost identical environments they are synonyms\n* **Term-document matrix** - Rows = words, cols = documents. 1 when word is in document\n* **Document similarity** - compare two columns of matrix\n* **Term-term matrix** - Words as row and columns (how often did words occur near another word)\n* **Context windows** - word A occurs in a window of +/- k words to word B\n* **Syntactic distribution** - words are similar if they are used in similar syntax\n* **Tf-idf** - Term frequency * inverse document frequency (1/docs it occurred in) (to prevent 'the' being overpowered\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": "094085aa-a2bd-4fd4-eb1d-a9f1021af6d5"
      },
      "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": 88,
      "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 Markov decision process is a sequential decision problem, fully observable environment, stochastic transition model (probabilities), with additive rewards.\n                  To find solution you need set of states + actions, transition function T(s, a, s') (probability that executing action a in s leads to s'), reward function, initial states, and terminal states (optional).\n\n\n  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\nValue iteration: Do one ply of expectimax from each state until convergence \n\n## AIMA Chapter 16.3 Utility Functions\n Computing actions from values is hard, but from Q-values is easy (just choose the highest). Problems with \n                   value iteration: slow, max rarely changes for the states, policy converges before the values. \n\n                   Policy iteration: calculate utilities for fixed policy until convergence, update policy using one-step look ahead using the converged\n                   utilities as future values, repeat until policy converges\n\n \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 Your summary here \n\n## Module 8 Definitions\n* **Utility function** - assigns single number to express how desirable a state is\n* **Expected utility** - average utility value of outcomes\n* **Meu** - maximizing average utility\n* **Preference elicitation** - presenting choices and using observed preferences to make utility function\n* **Descriptive theory** - how actual agents actually act\n* **Policy** - what the agent should do for any state\n* **Optimal policy** - yields highest expected utility\n* **Finite horizon** - fixed time after which game ends (nothing will matter anymore)\n* **Nonstationary** - policy that depends on time\n* **Discount factor** - agent prefers current rewards over future (0 = future is insignificant)\n* **Q function** - expected utility of taking an action given a state Q(s, a)\n* **Contraction** - ____________________\n* **Markov assumption** - given present, past and future are independent\n* **Dynamic bayesian model** - Sensor/transition model and prior distribution over state variable(s) needed \n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Exploration: you have to try unknown actions to get information\nExploitation: eventually, you have to use what you know\nRegret: even if you learn intelligently, you make mistakes\nSampling: because of chance, you have to try things repeatedly\nDifficulty: learning can be much harder than solving a known MDP \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Problems with direct evaluation:  It wastes information about state connections, Each state must be learned separately, takes a long time to learn\n\n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Active reinforcement learning: You don’t know the transitions T(s,a,s’) or rewards R(s,a,s’).\nYou choose the actions now and want to learn the optimal policy / values\n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Exploration function: takes value estimate and visit count to return utility. Will lead to exploring more uknown states. \n\n## Module 9 Lecture Notes\n Your summary here \n\n## Module 9 Definitions\n* **Passive reinforcement learning** - Execute policy and learn from experience (online planning)\n* **Direct evaluation** - Follow policy, when at state note the sum of the rewards, average those samples (finds values for each state) \n* **Sample based policy evaluation** - take samples of outcome (by performing action) and average results (then do policy evalutaion) \n* **Temporal difference learning** - update V(s) after every transition (s,a,s',r) and keep running average (decay factor)\n* **Exponential moving average** - makes recent info more important\n* **Off-policy learning** - q-learning converges to optimal policy, even when acting suboptimally\n* **Regret** - total mistake cost (difference between achieved rewards and optimal rewards)\n* **Activation function** - mathematical equations that determine the output of a neural network (ie sigmoid)\n* **Logistic regression** - vector of weights + bias term which is then transformed with sigmoid function (smooth unlike perceptrons)\n* **Feed forward nn** - all units fully connected and no cycles\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n Your summary here \n\n## Module 10 Definitions\n* **Probabilistic model** - joint distribution over set of random variables (sum to 1)\n* **Event** - set E of outcomes (ie probability that it's hot AND sunny\n* **Marginal distributions** - sub-tables that eliminate variables (ie P(T,W) -> P(T) or P(W))\n* **Conditional distributions** - Distributions over variables given others are fixed P(W|T=hot)\n* **Probabilistic inference** - compute desired probability from other known probabilities (P(on time|no accidends))\n* **Product rule** - P(y)P(x|y) = P(x, y)\n* **Chain rule** - P(x,y,z) = P(x)P(y|x)P(z|x,y)\n* **Bayes rule** - P(x|y) = P(y|x)*P(x)/P(y)\n* **Unigram** - no history for guessing next word\n* **Bigram** - 1 word as history\n* **Trigram** - 2 words as history\n* **N-gram evaluation** - evaluated by perplexity of test set\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n X is conditionally independent of y given z iff P(x, y| z) = P(x|z)P(y|z) or equivalently iff P(x|z,y) = P(x|z) \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Bayes nets has one node per variable x where the edges represent what else is true if x is true. This lets us write\n                  P(xi | x1...xi-1) as P(xi | parents(xi)). Model is created based on which variables affect each other.\n                  \n                  D-separation: Shows what is independent of each other. \n              \n                  X and Z independent given Y? P(z|x,y) = P(x,y,z)/P(x,y) -> manipulate to show P(z|x,y) = P(z|x) or P(z|y) then X and Z conditionally independent\n                   \n                   Are two variables in Bayes Nets independent? Use causal chain, common cause, and common effect. Check all triples on each path\n                   to see if they are active. If 1+ triple is not active, then that path is inactive. If all paths are inactive then independence is guaranteed\n                   \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Inference by enumeration is very slow (exponentially proportional to hidden variables) \n\n## Module 11 Lecture Notes\n Your summary here \n\n## Module 11 Definitions\n* **Independent variables** - P(x,y) = P(x)P(y)\n* **Causal chain** - x -> y -> z (x independent of z given y)\n* **P(x,y,z)** - P(x)P(y|x)P(z|y)\n* **Common cause** - Y -> X, Y -> Z (x independent of z given y)\n* **Common effect** - X -> Z, Y -> Z where Z or one of its descendants is observed\n* **Causal chain active** - x -> y -> z where y is unobserved\n* **Common cause active** - Y -> X, Y -> Z where Y is unobserved\n* **Active triple** - one of three effects above\n* **Active path** - when every triple in path is active\n* **Conditional probability distribution of variable** - depends only on parents\n* **Sparse system** - grows in linear complexity\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\nmodel-based classification:  \n                 1) Build model (eg Bayes Nets) with label and features as random variables \n\n                 2) Instantiate observed features\n\n                 3) Query for the distribution of the label conditioned on the features (query variable is class ie spam or ham) \n   \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\nInference for Naive Bayes:\n\n                 1) Get joint probability of label and evidence for each label (P(y, f1, .. fn) for each)\n\n                 2) Sum to get probability of evidence\n\n                 3) Normalize by dividing 1) by 2)  \n  \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Naive Bays: builds a model training data, gives prediction probabilities, strong assumptions about feature independence, one pass through data \n\n## AIMA Chapter 5.5 Stochastic Games\n Perceptrons: makes less assumptions about data, mistake-driven learning, multiple passes through data, often more accurate\n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n Your summary here \n\n## Module 12 Definitions\n* **Features** - attributes used to make classification decision\n* **Classification** - given inputs x, predict labels y\n* **Naive bayes** - Assume all features are independent effects of label\n* **Naive bayes model** - P(y, F1, ..., Fn) =   P(y) CID P(F|y) for each feature F\n* **Model paramaters** - P(Label) and P(Feature i |Label)\n* **Training data** - inputs and correct labels\n* **Held out data (dev set)** - optimize hyperparamaters (such as laplace smoothing amount)\n* **Test set** - test model's accuracy\n* **Overfitting** - Cam't give unseen events zero probability\n* **Maximum likelihood estimate** - pick parameter settings that maximize likelihood of data given those settings (count(x)/total)\n* **Laplace smoothing** - pretend everything has been seen 1 extra time (count(x)+1)/(total+1)\n* **Bias** - shifts hyperplane (that separates labels)\n* **Multiclass perceptron** - weight vector for each class, highest prediction score wins\n* **Perceptron** - each feature has a weight, tune until feature vector * weight vector -> label\n* **Separability** - if some paramaters get the training set perfectly correct\n* **Convergence** - If seperable, perceptron will eventually converge\n* **Mistake bound** - max number of mistakes related to margin of separability\n* **Noise** - if data isn't separable wieghts might not work\n* **Mediocre generalization** - finds a barely separating solution\n* **Margin infused relaxed algorithm** - choose update size that fixes current mistake but minimizes change to w\n* **Non-linear separators** - map to higher dimensional feature space where training set is separable\n* **P(x1,x2,x3,y) join probability** -  P(Y)P(X1|Y)P(X2|Y)P(X3|Y)\n* **Parametric models** - fixed number of paramaters\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Classifier components:\n1. A feature representation of the input. For each input observation\nx(i), this will be a vector of features [x1,x2,...,xn].\n2. A classification function that computes the estimated class �! via\np(y|x).\n3. An objective function for learning, usually involving minimizing\nerror on training examples.\n4. An algorithm for optimizing the objective function.\n\n\n## SLP Chapter 5.2 Learning in Logistic Regression\n P(y=1) = sigmoid(w*x+b)  P(y=0) = 1 - P(y=1) \n\n## SLP Chapter 5.3 The cross-entropy loss function\nLogistic Regression Learning (setting the weights):\n                  1. An objective/loss function that finds distance between\n                  the system output and the gold output. We will use cross-entropy\n                  loss.\n                  2. An algorithm for optimizing the objective function. Use\n                  stochastic gradient descent to minimize loss function.\n\n \n\n## SLP Chapter 5.4 Gradient Descent\nTraining neural nets: loss function (cross-entropy loss), optimization algo (gradient descent), \n                    way of computing gradient of loss function (error propogation)  \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 13 Definitions\n* **Sigmoid function** - squishes value to be between 0-1\n* **Decision boundary** - y = 1 if P(y=1|x) > .5, y=0 if otherwise. .5 is decision boundary\n* **Conditional maximum likelihood estimation** - choose parameters w,b that maximize probabilities of true labels\n* **Cross entropy loss** - higher if prediction is incorrect\n* **Gradient descent** - finds good settings for weights + bias by minimizing loss function (move opposite direction of slope rising steeply)\n* **Step size** - how big step is when finding min (if too large may never find min)\n* **Batch training** - computes gradient over entire data set\n* **Mini-batch training** - train on batch usually of size 512 or 1024 (so that everything can be parallelized)\n* **Regularization** - penalizes large weights taht cause over fitting\n* **Multinomial logistic regression** - uses softmax function (generalization of sigmoid function) (z=[.6,1.1,-1.5,3.2,-1.1]->[.056,.09,.007,.099,.74,.01]\n* **Back-propagation algorithm ** - derivatives of the paramaters get passed back (shows which parameters affect outcome the most)\n* **Activation function** - defines how the weighted sum of the input is transformed into an output from a node or nodes in a layer of the network.\n* **Error back-propogation** - allows the correct layers to be updated\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Neural Language models have several advantages over n-gram LMs:\n1. They don’t need smoothing\n2. They can handle much longer histories.\n3. They can generalize over contexts of similar words.\n4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\nDisadvantage: slower to train than traditional n-gram LMs \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Neural LMs:\n\n1. Associate each word in the vocabulary with a vector-representation, thereby\ncreating a notion of similarity between words.\n2. Express the joint probability function of a word sequence in terms of the word\nvectors for the words in that sequence.\n3. Simultaneously learn the word vectors and the parameters of the function.\nThe word vectors are low-dimensional (d=30 to d=100) dense vectors, like we’ve seen\nbefore\n\n\nInput is k-gram of words, and output is probability distribution over next word\n \n\n## SLP Chapter 9.3 RNNs as Language Models\n How to get dense vectors:train a classifier!\n1. Treat the target word and a neighboring context word as positive examples.\n2. Randomly sample other words in the lexicon to get negative samples.\n3. Use logistic regression to train a classifier to distinguish those two cases.\n4. Use the weights as the embeddings. \n\n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 14 Definitions\n* **Training** - word k-grams from corpus\n* **Generalizing** - representing words as vector space models (ie makes 'cat' and 'dog' be seen similarly\n* **Word meaning** - ie Synonym, antonym, connotations (+/-), semantic roles (buy, sell, pay all relate to purchasing), entailment\n* **Entailment** - All animals have an ulnar artery => all DOGS have an ulnar artery\n* **Word similarity** - compare two rows of matrix (normalize vector length and find euclidean distance or cosine distance)\n* **Distributional hypothesis** - If A and B have almost identical environments they are synonyms\n* **Term-document matrix** - Rows = words, cols = documents. 1 when word is in document\n* **Document similarity** - compare two columns of matrix\n* **Term-term matrix** - Words as row and columns (how often did words occur near another word)\n* **Context windows** - word A occurs in a window of +/- k words to word B\n* **Syntactic distribution** - words are similar if they are used in similar syntax\n* **Tf-idf** - Term frequency * inverse document frequency (1/docs it occurred in) (to prevent 'the' being overpowered\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}