{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Final 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": "54580f1e-22eb-4657-8e14-104a615b6276"
      },
      "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": null,
      "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": "2cd4c8a2-805b-483a-8fae-409ce38e0560"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" Chapter 16.1 summary. \"\"\"  + sample_equation\n",
        "chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter17_2 =  \"\"\" value iteration, policy iteration, and linear programming generate exact solutions offline. Monte Carlo planning is online.\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\" \n",
        "fully observable, pick action at time step, terminate at goal state, stochastic environment\n",
        "\n",
        "stochastic transition model !!! p(s' | s, a) probability of arriving in s' given we are in state s and select action a\n",
        "\n",
        "markovian - probability of arriving in s' only depends on s and not history of earlier states\n",
        "\n",
        "utility/reward function - pos/neg bounded by max value, sequential, reward at each time step based on transition, additive rewards\n",
        "- utility is sum of discounted rewards\n",
        "\n",
        "A Markov decision process or MDP is\n",
        "• a sequential decision problem\n",
        "• for a fully observable environment\n",
        "• with a stochastic transition model\n",
        "• that has additive rewards\n",
        "MDPs are non-deterministic search problems, can use expectimax search.\n",
        "- set of states\n",
        "- set of actions\n",
        "- transition function T(s, a, s'), probability (the model)\n",
        "- reward function R(s, a, s')\n",
        "- initial state s_0\n",
        "- optional, terminal states\n",
        "\n",
        "solution to inf\n",
        "- finite horizon (similar to depth liited search, term after fixed t steps)\n",
        "- discounting 0 < x < 1\n",
        "- absorbing state, guarantee for each policy terminal state will eventually be reached\n",
        "\n",
        "value iteration complexity = O(S^2 * A) slow, max at each state rarely changes, policy converges before values\n",
        "• Basic idea: approximations get refined towards optimal values\n",
        "• Policy may converge long before values do\n",
        "\n",
        "policy evaluation complexity = O(S^2)\n",
        "• turn recurisve bellman into updates to calculate V's for a fixed policy\n",
        "• Without the maxes, the Bellman equations are just a linear system\n",
        "\n",
        "policy extraction\n",
        "- easier with q-values than values (argmaxQ*(s,a) vs argmax sum T * (R * discount * V))\n",
        "\n",
        "policy iteration optimal, converges much faster under some conditions\n",
        "• calculate utilities for some fixed policy (not optimal utilities!) until convergence \n",
        "• update policy using one-step lookahead with resulting converged (but not optimal!) utilities as future values\n",
        "• Repeat steps until policy converges\n",
        "\n",
        "\n",
        "In value iteration:\n",
        "• Every iteration updates both the values and (implicitly) the policy\n",
        "• We don’t track the policy, but taking the max over actions implicitly recomputes it\n",
        "\n",
        "In policy iteration:\n",
        "• We do several passes that update utilities with fixed policy (each pass is fast because we consider only one action, not all of them)\n",
        "• After the policy is evaluated, a new policy is chosen (slow like a value iteration pass)\n",
        "• The new policy will be better (or we’re done)\n",
        "\n",
        "Both are dynamic programs for solving MDPs\n",
        "\n",
        "axioms of rationality\n",
        "- orderability, transitivity, continuity, substitutability, monotonicity \n",
        "\n",
        "Maximum expected utility (MEU) principle:\n",
        "▪ Choose the action that maximizes expected utility\n",
        "▪ Note: an agent can be entirely rational (consistent with MEU) without ever representing or manipulating utilities and probabilities\n",
        "▪ E.g., a lookup table for perfect tic-tac-toe, a reflex vacuum cleaner\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utilities\" : \" functions from outcomes (states of the world) to real numbers that describe an agent’s preferences\",\n",
        "\"utility function\" : \"assigns number ot express desirability of a state\",\n",
        "\"expected utility\" : \"average utility value of the outcomes weighted by the probability that the outcome occurs\",\n",
        "\"policy\": \"pi(s) = a, policy maps from a state onto the action to take if agent is in state, pi* for optimal\",\n",
        "\"policy extraction\" : \"gets the policy implied by the values\",\n",
        "\"MEU\" : \"maximum expected utility, rational agent should choose action that maxes its expected utility, given its knowledge\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 23,
      "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": 882
        },
        "cellView": "form",
        "outputId": "d8d3b94b-bc2f-42d4-a2b2-97f74b55d359"
      },
      "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": 24,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n \nfully observable, pick action at time step, terminate at goal state, stochastic environment\n\nstochastic transition model !!! p(s' | s, a) probability of arriving in s' given we are in state s and select action a\n\nmarkovian - probability of arriving in s' only depends on s and not history of earlier states\n\nutility/reward function - pos/neg bounded by max value, sequential, reward at each time step based on transition, additive rewards\n\n\nA Markov decision process or MDP is\n• a sequential decision problem\n• for a fully observable environment\n• with a stochastic transition model\n• that has additive rewards\nMDPs are non-deterministic search problems, can use expectimax search.\n- set of states\n- set of actions\n- transition function T(s, a, s'), probability (the model)\n- reward function R(s, a, s')\n- initial state s_0\n- optional, terminal states\n \n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Policy** - pi(s) = a, policy maps from a state onto the action to take if agent is in state, pi* for optimal\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "chapter17_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_2 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_3 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_4 =  \"\"\" Your summary here \"\"\"\n",
        "chapter22_5 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\" need to actually act to figure out things \n",
        "\n",
        "Basic idea:\n",
        "- receive feedback in the form of rewards\n",
        "- agent’s utility is defined by the reward function\n",
        "- must (learn to) act so as to maximize expected rewards\n",
        "- all learning is based on observed samples of outcomes\n",
        "\n",
        "Requirements\n",
        "- set of states s ∈ S\n",
        "- set of actions (per state) A\n",
        "- a transition model T(s,a,s’)\n",
        "- reward function R(s,a,s’)\n",
        "- till looking for a policy π(s)\n",
        "- don’t know T or R ****\n",
        "\n",
        "model based vs passive reinforcement learning\n",
        "- create model vs learning as you go\n",
        "\n",
        "direction evaluation\n",
        "- easy, no knowledge of t and r, eventually computes correct avg values\n",
        "- wastes info about state connections, learn each state separately, takes too long !!!\n",
        "\n",
        "sample-based policy evaluation?\n",
        "- take samples of outcomes s' and average, to improve estimate of V\n",
        "\n",
        "decreasing learning rate can give converging averages\n",
        "\n",
        "q-learning - converges to optimal policy even acting suboptimally, off-policy learning\n",
        "- Learn Q(s,a) values as you go\n",
        "- Receive a sample (s,a,s’,r)\n",
        "- Consider your old estimate:\n",
        "- Consider your new sample estimate\n",
        "- Incorporate the new estimate into a running average\n",
        "- have to explore enough, make learning rate small but not dec too quick\n",
        "- takes too much space so we generalize\n",
        "\n",
        "exploration \n",
        "- greedy random actions, thrashing around, solution lower it over time?\n",
        "- exploration functions - explore unknowns\n",
        "\n",
        "linear value functions - q function using few weights\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"exploration\" : \"you have to try unknown actions to get information\",\n",
        "\"exploitation\" : \"eventually, you have to use what you know\",\n",
        "\"regret\" : \" measure of total mistake cost: difference between (expected) rewards and optimal (expected) rewards (relative goodness)\",\n",
        "\"sampling\" : \"because of chance, you have to try things repeatedly\",\n",
        "\"difficulty\" : \"learning can be much harder than solving a known MDP\",\n",
        "\"direct evaluation\" : \"act according to policy, every time visit state write down sum of discounted rewards, average samples\",\n",
        "\"off-policy learning\" : \"Q-learning can learn the optimal Q-function Q without ever executing the optimal policy.\"\n",
        "}"
      ],
      "execution_count": 38,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "d740ac2f-7d0b-45a6-e9fc-999ac734404e"
      },
      "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": 39,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n need to actually act to figure out things \n\nBasic idea:\n- receive feedback in the form of rewards\n- agent’s utility is defined by the reward function\n- must (learn to) act so as to maximize expected rewards\n- all learning is based on observed samples of outcomes\n\nRequirements\n- set of states s ∈ S\n- set of actions (per state) A\n- a transition model T(s,a,s’)\n- reward function R(s,a,s’)\n- till looking for a policy π(s)\n- don’t know T or R ****\n\nmodel based vs passive reinforcement learning\n- create model vs learning as you go\n\ndirection evaluation\n- easy, no knowledge of t and r, eventually computes correct avg values\n- wastes info about state connections, learn each state separately, takes too long !!!\n\nsample-based policy evaluation?\n- take samples of outcomes s' and average, to improve estimate of V\n\ndecreasing learning rate can give converging averages\n\nq-learning - converges to optimal policy even acting suboptimally, off-policy learning\n- Learn Q(s,a) values as you go\n- Receive a sample (s,a,s’,r)\n- Consider your old estimate:\n- Consider your new sample estimate\n- Incorporate the new estimate into a running average\n- have to explore enough, make learning rate small but not dec too quick\n- takes too much space so we generalize\n\nexploration \n- greedy random actions, thrashing around, solution lower it over time?\n- exploration functions - explore unknowns\n\nlinear value functions - q function using few weights\n\n\n\n## Module 9 Definitions\n* **Exploration** - you have to try unknown actions to get information\n* **Exploitation** - eventually, you have to use what you know\n* **Regret** -  measure of total mistake cost: difference between (expected) rewards and optimal (expected) rewards (relative goodness)\n* **Sampling** - because of chance, you have to try things repeatedly\n* **Difficulty** - learning can be much harder than solving a known MDP\n* **Direct evaluation** - act according to policy, every time visit state write down sum of discounted rewards, average samples\n* **Off-policy learning** - Q-learning can learn the optimal Q-function Q without ever executing the optimal policy.\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\" \n",
        "**natural language processing** \n",
        "\n",
        "P(\"the underdog Philadelphia Eagles won\") = P(the) * P(underdog | the) * P(Philadelphia | the underdog) ....\n",
        "\n",
        "maximum likelihood estimation (MLE) - not practical, some sentences might not appear so need huge dataset, not enough data\n",
        "\n",
        "simplying assumption markov assumption only depends on the previous k words, not the whole context\n",
        "\n",
        "P(won | underdog team), P(x, y, z) = $\\prod_i^n P(w_i | w_{i-k}...w_{i-1})$\n",
        "\n",
        "unigram - no history, bigram, trigram, 4-gram etc etc\n",
        "\n",
        "n-gram models are evaluated by perplexity on a test set\n",
        "\n",
        "there are N! ways to apply the chain rule to a joint distribution with N random variables\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"Conditional Probability\" : \"P(a | b) = P(a, b) / P(b), probability of a given b is the probability of a and b over the probability of b\",\n",
        "\"Chain Rule\" : \"P(a, b, c) = P(a) * P(b|a) * P(c|b,a)\",\n",
        "\"Baye's Rule\" : \"P(a | b) = P(b | a) / P(a) * P(b)\",\n",
        "\"Markov Property\" : \" Given the present state, the future and past are independent\",\n",
        "\"stationary process\" : \"the conditional probability table does not change over time\"\n",
        "}"
      ],
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "127807b5-d67f-44a2-d5c4-3403151d3311"
      },
      "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": 8,
      "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 \n**natural language processing** \n\nP(\"the underdog Philadelphia Eagles won\") = P(the) * P(underdog | the) * P(Philadelphia | the underdog) ....\n\nmaximum likelihood estimation (MLE) - not practical, some sentences might not appear so need huge dataset, not enough data\n\nsimplying assumption markov assumption only depends on the previous k words, not the whole context\n\nP(won | underdog team), P(x, y, z) = $\\prod_i^n P(w_i | w_{i-k}...w_{i-1})$\n\nunigram - no history, bigram, trigram, 4-gram etc etc\n\nn-gram models are evaluated by perplexity on a test set\n\nthere are N! ways to apply the chain rule to a joint distribution with N random variables\n \n\n## Module 10 Definitions\n* **Conditional probability** - P(a | b) = P(a, b) / P(b), probability of a given b is the probability of a and b over the probability of b\n* **Chain rule** - P(a, b, c) = P(a) * P(b|a) * P(c|b,a)\n* **Baye's rule** - P(a | b) = P(b | a) / P(a) * P(b)\n* **Markov property** -  Given the present state, the future and past are independent\n* **Stationary process** - the conditional probability table does not change over time\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" Bayes nets use chain rule, additional conditional independences, and can be read off the graph.\n",
        "\n",
        "if two nodes don't share a path they're conditionally independent\n",
        "\n",
        "paths - active if every triple is active, if no paths active (all paths are inactive) then independence is guaranteed\n",
        "- A -> B -> C any direction, or A <- B -> C, where B is unobserved\n",
        "- A -> B <- C where B or descendent is observed\n",
        "- any other config is inactive\n",
        "- observed means given, so for X ⫫ Y | T, if X -> T -> Y then inactive\n",
        "\n",
        "d-separation algorithm: check if all paths are inactive, refer to above\n",
        "\n",
        "inference by enumeration:\n",
        "evidence variables, query variable, hidden variables \n",
        "1. select entries consistent with evidence\n",
        "2. sum out h (hidden var) to get joint of query and evidence\n",
        "3. normalize\n",
        "\n",
        "inference by enumeration in bayes' nets, easy given unlimited time but slow\n",
        "- variable elimination, interleave joining and marginalizing, still np-hard but faster\n",
        "- refer to textbook\n",
        "\n",
        "in locally structured (sparse) systems, structure grows linearly in complexity (rather than\n",
        "exponentially)\n",
        "\n",
        "more than one Bayesian network can be used to represent the same joint distribution.\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"Independent\" : \"P(x, y) = P(x) * P(y)\",\n",
        "\"Conditionally Independent\" : \"⫫ P(x, y|z) = P(x | z) * P(y | z), or P(z|x, y) = P(x, y, z) / P(x, y)\",\n",
        "\"casual chain\" : \"P(x, y, z) = P(x)P(y|x)P(z|y), x and z are not independent, but given y they are\",\n",
        "\"common cause\" : \"P(x, y, z) = P(y)P(x|y)P(z|y), x and z are not independent, but given y they are\",\n",
        "\"common effect\" : \"two causes (x, y) of one effect (z), x and y are independent, but not given z\",\n",
        "\"inference\" : \"calculating some useful quantity from a joint probability distribution\"\n",
        "}\n"
      ],
      "execution_count": 9,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 929
        },
        "cellView": "form",
        "outputId": "69010dc9-f438-4c03-8ff7-c8d96c755577"
      },
      "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": 10,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n Bayes nets use chain rule, additional conditional independences, and can be read off the graph.\n\nif two nodes don't share a path they're conditionally independent\n\npaths - active if every triple is active, if no paths active (all paths are inactive) then independence is guaranteed\n- A -> B -> C any direction, or A <- B -> C, where B is unobserved\n- A -> B <- C where B or descendent is observed\n- any other config is inactive\n- observed means given, so for X ⫫ Y | T, if X -> T -> Y then inactive\n\nd-separation algorithm: check if all paths are inactive, refer to above\n\ninference by enumeration:\nevidence variables, query variable, hidden variables \n1. select entries consistent with evidence\n2. sum out h (hidden var) to get joint of query and evidence\n3. normalize\n\ninference by enumeration in bayes' nets, easy given unlimited time but slow\n- variable elimination, interleave joining and marginalizing, still np-hard but faster\n- refer to textbook\n\nin locally structured (sparse) systems, structure grows linearly in complexity (rather than\nexponentially)\n\nmore than one Bayesian network can be used to represent the same joint distribution.\n\n\n\n## Module 11 Definitions\n* **Independent** - P(x, y) = P(x) * P(y)\n* **Conditionally independent** - ⫫ P(x, y|z) = P(x | z) * P(y | z), or P(z|x, y) = P(x, y, z) / P(x, y)\n* **Casual chain** - P(x, y, z) = P(x)P(y|x)P(z|y), x and z are not independent, but given y they are\n* **Common cause** - P(x, y, z) = P(y)P(x|y)P(z|y), x and z are not independent, but given y they are\n* **Common effect** - two causes (x, y) of one effect (z), x and y are independent, but not given z\n* **Inference** - calculating some useful quantity from a joint probability distribution\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\" \n",
        "\n",
        "conditional probability distribution of a variable in a Bayesian network should be specified based on the probability distributions of parents\n",
        "\n",
        "estimating probabilities from data!\n",
        "- building a model (bayes' net) where label and features are random variables\n",
        "- instantiate any observed features\n",
        "- query for the distribution of the label conditioned on the features\n",
        "\n",
        "full joint solution is exponential to number of features (|Y| * |F| ^ n), after independence assumption (naive) number of probability tables to populate is linear (n x |F| x |Y|)\n",
        "\n",
        "joint probability model of $P(X_1, X_2, X_3, Y )$ is $P(Y)P(X_1|Y)P(X_2|Y)P(X_3|Y)$\n",
        "- X's are all features, only have to specify how each feature depends on the class\n",
        "- total number of parameters is linear in number of features\n",
        "- simplistic but can still estimate effectively\n",
        "\n",
        "inference for naive bayes\n",
        "1. get joint probability of label and evidence for each label, normalize\n",
        "- (P(y_1, f_1...f_n)) -> P(y_1) * P(f_1|y_1) * ... \n",
        "- (P(y_2), f_1...f_n)) -> P(y_2) * P(f_1|y_2) * ...\n",
        "2. sum to get probability of evidence\n",
        "- / P(f_1...f_n)\n",
        "3. normalize by dividing step 1 by step 2\n",
        "- P(Y|f_1...f_n)\n",
        "\n",
        "start with bunch of (parameters/theta) probabilities P(Y) (prior) and P(f_i|Y) (feature) tables, use standard inference to compute P(Y|f_1...f_n)\n",
        "\n",
        " In a bag-of-words model\n",
        "• Each position is identically distributed ***\n",
        "• All positions share the same conditional probs P(W|Y)\n",
        "• predict label conditioned on feature variables (spam vs. ham)\n",
        "\n",
        "To generalize better: we need to smooth or regularize the estimates, words that don't appear or are specific to training set can overfit\n",
        "\n",
        "Relative frequencies are the maximum likelihood estimates\n",
        "\n",
        "Laplace’s estimate: Pretend you saw every outcome once more than you actually did, or k times\n",
        "\n",
        "Linear interpolation\n",
        "\n",
        "baseline\n",
        "• Baselines are very simple “straw man” procedures\n",
        "• Help determine how hard the task is\n",
        "• Help know what a “good” accuracy is\n",
        "\n",
        "A parametric model has a fixed size on the number of parameters.\n",
        "\n",
        "Summary\n",
        "- Bayes rule lets us do diagnostic queries with causal probabilities\n",
        "- The naïve Bayes assumption takes all features to be independent given the class label\n",
        "- We can build classifiers out of a naïve Bayes model using training data\n",
        "- Smoothing estimates is important in real systems\n",
        "- Classifier confidences are useful, when you can get them\n",
        "\n",
        "\n",
        "Linear classifiers: Inputs are feature values, each feature has a weight, sum is the activation\n",
        "When using the perceptron learning rule, the weights are updated when the actual output does not match the hypothesis output\n",
        "- adjust the weight vector by adding or subtracting the feature vector. Subtract if y* is -1.\n",
        "- can be multiple decision boundaries, if multiple classes we have weight vectors for each class, score (activation) of a class y and prediction highest score wins, lower score of wrong and raise score of right\n",
        " \n",
        "issues with perceptrons\n",
        "- noise, if data isn't separable weights might thrash, fix is averaging weight vectors over time\n",
        "- mediocre generalization, \"barely\" separating solution\n",
        "- overtraining, test accuracy rises and then falls, overtraining is a type of overfitting\n",
        "\n",
        "fixes\n",
        "- adjust weight update to minimum correcting update MIRA, choose update size that fixes mistake but minimizes change to w\n",
        "- set a maximum step size\n",
        "- maximize margin? only support vectors matter, SVM are MIRA optimizing over all examples at once\n",
        " \n",
        "Naïve Bayes\n",
        "• Builds a model training data\n",
        "• Gives prediction probabilities\n",
        "• Strong assumptions about feature independence\n",
        "• One pass through data (counting)\n",
        "Perceptrons / MIRA:\n",
        "• Makes less assumptions about data\n",
        "• Mistake-driven learning\n",
        "• Multiple passes through data (prediction)\n",
        "• Often more accurate \n",
        "\n",
        "activation functions: sigmoid function, tanh function, rectified linear unit ReLU\n",
        " \n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"naive bayes'\" : \"model is naive because it assumes that the features are conditionally independent of each other, given the class.\",\n",
        "\"parametric model\" : \"\", \n",
        "\"non-parametric model\" : \"\",  \n",
        "\"perceptrons\" : \"weight associated with each\",\n",
        "\"overfitting\" : \"fitting the training data very closely, but not generalizing well\",\n",
        "\"separability\" : \"true if some parameters get the training set perfectly correct\",\n",
        "\"convergence\" : \"if the training is separable, perceptron will eventually converge (binary case)\",\n",
        "\"mistake bound\" : \" the maximum number of mistakes (binary case) related to the margin or degree of separability $mistakes < \\frac{k}{a^2}$\"\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "abc666a1-4447-4638-dbe9-fc576076fb8d"
      },
      "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": 12,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n \n\nconditional probability distribution of a variable in a Bayesian network should be specified based on the probability distributions of parents\n\nestimating probabilities from data!\n- building a model (bayes' net) where label and features are random variables\n- instantiate any observed features\n- query for the distribution of the label conditioned on the features\n\nfull joint solution is exponential to number of features (|Y| * |F| ^ n), after independence assumption (naive) number of probability tables to populate is linear (n x |F| x |Y|)\n\njoint probability model of $P(X_1, X_2, X_3, Y )$ is $P(Y)P(X_1|Y)P(X_2|Y)P(X_3|Y)$\n- X's are all features, only have to specify how each feature depends on the class\n- total number of parameters is linear in number of features\n- simplistic but can still estimate effectively\n\ninference for naive bayes\n1. get joint probability of label and evidence for each label, normalize\n- (P(y_1, f_1...f_n)) -> P(y_1) * P(f_1|y_1) * ... \n- (P(y_2), f_1...f_n)) -> P(y_2) * P(f_1|y_2) * ...\n2. sum to get probability of evidence\n- / P(f_1...f_n)\n3. normalize by dividing step 1 by step 2\n- P(Y|f_1...f_n)\n\nstart with bunch of (parameters/theta) probabilities P(Y) (prior) and P(f_i|Y) (feature) tables, use standard inference to compute P(Y|f_1...f_n)\n\n In a bag-of-words model\n• Each position is identically distributed ***\n• All positions share the same conditional probs P(W|Y)\n• predict label conditioned on feature variables (spam vs. ham)\n\nTo generalize better: we need to smooth or regularize the estimates, words that don't appear or are specific to training set can overfit\n\nRelative frequencies are the maximum likelihood estimates\n\nLaplace’s estimate: Pretend you saw every outcome once more than you actually did, or k times\n\nLinear interpolation\n\nbaseline\n• Baselines are very simple “straw man” procedures\n• Help determine how hard the task is\n• Help know what a “good” accuracy is\n\nA parametric model has a fixed size on the number of parameters.\n\nSummary\n- Bayes rule lets us do diagnostic queries with causal probabilities\n- The naïve Bayes assumption takes all features to be independent given the class label\n- We can build classifiers out of a naïve Bayes model using training data\n- Smoothing estimates is important in real systems\n- Classifier confidences are useful, when you can get them\n\n\nLinear classifiers: Inputs are feature values, each feature has a weight, sum is the activation\nWhen using the perceptron learning rule, the weights are updated when the actual output does not match the hypothesis output\n- adjust the weight vector by adding or subtracting the feature vector. Subtract if y* is -1.\n- can be multiple decision boundaries, if multiple classes we have weight vectors for each class, score (activation) of a class y and prediction highest score wins, lower score of wrong and raise score of right\n \nissues with perceptrons\n- noise, if data isn't separable weights might thrash, fix is averaging weight vectors over time\n- mediocre generalization, \"barely\" separating solution\n- overtraining, test accuracy rises and then falls, overtraining is a type of overfitting\n\nfixes\n- adjust weight update to minimum correcting update MIRA, choose update size that fixes mistake but minimizes change to w\n- set a maximum step size\n- maximize margin? only support vectors matter, SVM are MIRA optimizing over all examples at once\n \nNaïve Bayes\n• Builds a model training data\n• Gives prediction probabilities\n• Strong assumptions about feature independence\n• One pass through data (counting)\nPerceptrons / MIRA:\n• Makes less assumptions about data\n• Mistake-driven learning\n• Multiple passes through data (prediction)\n• Often more accurate \n\nactivation functions: sigmoid function, tanh function, rectified linear unit ReLU\n \n \n\n## Module 12 Definitions\n* **Naive bayes'** - model is naive because it assumes that the features are conditionally independent of each other, given the class.\n* **Parametric model** - \n* **Non-parametric model** - \n* **Perceptrons** - weight associated with each\n* **Overfitting** - fitting the training data very closely, but not generalizing well\n* **Separability** - true if some parameters get the training set perfectly correct\n* **Convergence** - if the training is separable, perceptron will eventually converge (binary case)\n* **Mistake bound** -  the maximum number of mistakes (binary case) related to the margin or degree of separability $mistakes < \frac{k}{a^2}$\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" \n",
        "Machine learning classifiers require a training corpus of M observations input/output pairs (x^(i),y^(i)).\n",
        "1. A feature representation of the input. for ach input observation x(i) we have a vector of features [x1,x2,...,xn].\n",
        "2. A classification function that computes the estimated class y' via p(y|x).\n",
        "3. An objective function for learning, usually involving minimizing error on training examples.\n",
        "4. An algorithm for optimizing the objective function.\n",
        "\n",
        "sentiment classifier: We want to estimate P(y = 1|x).\n",
        "Logistic regression solves this task by learning, from a training set, a vector of weights and a bias term. \n",
        "- z = w * x + b\n",
        "- $z = \\sum_i w_i * x_i + b$\n",
        "- then take sigmoid(z)\n",
        "- fyi: pos = 1, neg = 0\n",
        "\n",
        "$P(y=1) = \\sigma(w \\dot x + b = \\frac{1}{1+e^{-(w\\dot x + b)}$\n",
        "\n",
        "any grad. descent starting from any point guaranteed to find minimum, convex function has just one min.\n",
        "\n",
        "for many dimensions we update each dimension $w_i$\n",
        "\n",
        "stochastic grad. descent chooses single random example and updates on that example, so updates can fluctuate\n",
        "\n",
        "batch training computes gradient over entire dataset which gives better est. but takes long\n",
        "\n",
        "mini-batch training trains on smaller batch and is usually processed in parallel, so loss is accumulated\n",
        " \n",
        "feed-forward neural network - simplest kind of NN\n",
        "- multilayer network\n",
        "- all units usually fully connected\n",
        "- no cycles\n",
        "- each output is passed to next layer, none are passed backwards\n",
        "- use single weight matrx W and single bias vector b for entire layer\n",
        "- computation can be done with simple matrix operations\n",
        "1. multiply weight matrix by input vector x \n",
        "2. add bias vector b\n",
        "3. apply activation function g (such as sigmoid)\n",
        "- h = \\sig(Wx+b)\n",
        "- output later has weight matrix U, z (intermed. output) = Uh (input vector)\n",
        "- y=softmax(z)\n",
        "\n",
        "training neural nets\n",
        "- A loss function – cross-entropy loss\n",
        "- An optimization algorithm – gradient descent\n",
        "- A way of computing the gradient of the loss function – error propagation \n",
        "\n",
        "Neural Networks combine many perceptron-like neural units, we have many more parameters in the models (weights and biases). This allows us to train systems to perform even more sophisticated tasks. \n",
        " \n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"decision boundary\" : \"probability needed to get 1, 0 otherwise\",\n",
        "\"loss function\" : \"tells distance between system output and goal output, we use cross entropy loss\",\n",
        "\"optimize obj function\" : \"we use stochastic gradient descent to minimize the loss function\",\n",
        "\"gradient descent\" : \"method that finds a min of a funct by figuring out which direction in space of parameter theta function steep slope and moves opposite\",\n",
        "\"regularization\" : \"way to penalize large weights, term is added to loss function\",\n",
        "\"soft max function\" : \"generalization of the sigmoid function, takes in input vector z and outputs vector of values normalized into probabilities\",\n",
        "\"backward pass\" : \"\"    \n",
        "}\n"
      ],
      "execution_count": 21,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "a3c3974d-f8f7-4cf9-8e8e-73168da3a506"
      },
      "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": 22,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n \nMachine learning classifiers require a training corpus of M observations input/output pairs (x^(i),y^(i)).\n1. A feature representation of the input. for ach input observation x(i) we have a vector of features [x1,x2,...,xn].\n2. A classification function that computes the estimated class y' via p(y|x).\n3. An objective function for learning, usually involving minimizing error on training examples.\n4. An algorithm for optimizing the objective function.\n\nsentiment classifier: We want to estimate P(y = 1|x).\nLogistic regression solves this task by learning, from a training set, a vector of weights and a bias term. \n- z = w * x + b\n- $z = \\sum_i w_i * x_i + b$\n- then take sigmoid(z)\n- fyi: pos = 1, neg = 0\n\n$P(y=1) = \\sigma(w \\dot x + b = \frac{1}{1+e^{-(w\\dot x + b)}$\n\nany grad. descent starting from any point guaranteed to find minimum, convex function has just one min.\n\nfor many dimensions we update each dimension $w_i$\n\nstochastic grad. descent chooses single random example and updates on that example, so updates can fluctuate\n\nbatch training computes gradient over entire dataset which gives better est. but takes long\n\nmini-batch training trains on smaller batch and is usually processed in parallel, so loss is accumulated\n \nfeed-forward neural network - simplest kind of NN\n- multilayer network\n- all units usually fully connected\n- no cycles\n- each output is passed to next layer, none are passed backwards\n- use single weight matrx W and single bias vector b for entire layer\n- computation can be done with simple matrix operations\n1. multiply weight matrix by input vector x \n2. add bias vector b\n3. apply activation function g (such as sigmoid)\n- h = \\sig(Wx+b)\n- output later has weight matrix U, z (intermed. output) = Uh (input vector)\n- y=softmax(z)\n\ntraining neural nets\n- A loss function – cross-entropy loss\n- An optimization algorithm – gradient descent\n- A way of computing the gradient of the loss function – error propagation \n\nNeural Networks combine many perceptron-like neural units, we have many more parameters in the models (weights and biases). This allows us to train systems to perform even more sophisticated tasks. \n \n \n\n## Module 13 Definitions\n* **Decision boundary** - probability needed to get 1, 0 otherwise\n* **Loss function** - tells distance between system output and goal output, we use cross entropy loss\n* **Optimize obj function** - we use stochastic gradient descent to minimize the loss function\n* **Gradient descent** - method that finds a min of a funct by figuring out which direction in space of parameter theta function steep slope and moves opposite\n* **Regularization** - way to penalize large weights, term is added to loss function\n* **Soft max function** - generalization of the sigmoid function, takes in input vector z and outputs vector of values normalized into probabilities\n* **Backward pass** - \n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" refer to written for matrices\n",
        "\n",
        "context windows - w-2, w-1, word, w+1, w+2\n",
        "\n",
        "alternative to count since they skew stuff like the, of etc\n",
        "- use TF-IDF or PPMI (term freq * inverse doc freq)\n",
        "\n",
        "language models estimate the probability of a sentence consisting of word sequences\n",
        "\n",
        "- learn function that returns joint probability\n",
        "1. too many parameters to be accurate in estimation\n",
        "2. n-gram based models fail to generalize to related words / word sequences we have observed\n",
        "\n",
        "\n",
        "neural language models over n-gram LMs\n",
        "- don't need smoothing, can handle longer histories, generalize over contexts of similar words, higher predictive acc\n",
        "- slower to train\n",
        "1. associate each words in vocab with vector-rep\n",
        "2. express joint probability function of word sequence in terms of word vectors for words in sequence\n",
        "3. simultaneously learn word vectors and parameters of the function\n",
        "- use multi-layer, feed forward neural network\n",
        "- input is k-gram of words, output is probability dist. over next word\n",
        "\n",
        "neural probabilisitc LM\n",
        "- same steps except learn probability function from data in step 3\n",
        "\n",
        "embeddings capture relational meanings\n",
        "\n",
        "Why dense vectors?\n",
        "• Short vectors may be easier to use as features in machine learning (fewer weights to tune)\n",
        "• Dense vectors may generalize better than storing explicit counts\n",
        "• They may do better at capturing synonymy:\n",
        "• car and automobile are synonyms; but are distinct dimensions in sparse vectors\n",
        "• a word with car as a neighbor and a word with automobile as a neighbor should be similar, but aren't\n",
        "• In practice work better\n",
        "\n",
        "word2vec - rather than count we train classifier on a binary prediction task, use distance to word\n",
        "\n",
        "Skip-gram algorithm\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",
        "- Given a tuple (t,c) = target, context\n",
        "• (apricot, jam)\n",
        "• (apricot, aardvark)\n",
        "- Return probability that c is a real context word:\n",
        "• P(+|t,c)\n",
        "\n",
        "sigmoids and stuff from dot product to probability\n",
        "\n",
        "Embeddings = vector models of meaning\n",
        "• More fine-grained than just a string or index\n",
        "• Especially good at modeling similarity/analogy\n",
        "• Just download them and use cosines!!\n",
        "• Can use sparse models (tf-idf) or dense models (word2vec, GLoVE)\n",
        "• Useful in practice but know they encode cultural stereotypes\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 35,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "a8451270-177c-4e79-e27a-690241e818d3"
      },
      "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 14 Lecture Notes\", module14_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": 36,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 14 Lecture Notes\n refer to written for matrices\n\ncontext windows - w-2, w-1, word, w+1, w+2\n\nalternative to count since they skew stuff like the, of etc\n- use TF-IDF or PPMI (term freq * inverse doc freq)\n\nlanguage models estimate the probability of a sentence consisting of word sequences\n\n- learn function that returns joint probability\n1. too many parameters to be accurate in estimation\n2. n-gram based models fail to generalize to related words / word sequences we have observed\n\n\nneural language models over n-gram LMs\n- don't need smoothing, can handle longer histories, generalize over contexts of similar words, higher predictive acc\n- slower to train\n1. associate each words in vocab with vector-rep\n2. express joint probability function of word sequence in terms of word vectors for words in sequence\n3. simultaneously learn word vectors and parameters of the function\n- use multi-layer, feed forward neural network\n- input is k-gram of words, output is probability dist. over next word\n\nneural probabilisitc LM\n- same steps except learn probability function from data in step 3\n\nembeddings capture relational meanings\n\nWhy dense vectors?\n• Short vectors may be easier to use as features in machine learning (fewer weights to tune)\n• Dense vectors may generalize better than storing explicit counts\n• They may do better at capturing synonymy:\n• car and automobile are synonyms; but are distinct dimensions in sparse vectors\n• a word with car as a neighbor and a word with automobile as a neighbor should be similar, but aren't\n• In practice work better\n\nword2vec - rather than count we train classifier on a binary prediction task, use distance to word\n\nSkip-gram algorithm\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- Given a tuple (t,c) = target, context\n• (apricot, jam)\n• (apricot, aardvark)\n- Return probability that c is a real context word:\n• P(+|t,c)\n\nsigmoids and stuff from dot product to probability\n\nEmbeddings = vector models of meaning\n• More fine-grained than just a string or index\n• Especially good at modeling similarity/analogy\n• Just download them and use cosines!!\n• Can use sparse models (tf-idf) or dense models (word2vec, GLoVE)\n• Useful in practice but know they encode cultural stereotypes\n\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "8a54179c-1063-42dd-9e68-a51aa5b9deb3"
      },
      "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": 34,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n \nfully observable, pick action at time step, terminate at goal state, stochastic environment\n\nstochastic transition model !!! p(s' | s, a) probability of arriving in s' given we are in state s and select action a\n\nmarkovian - probability of arriving in s' only depends on s and not history of earlier states\n\nutility/reward function - pos/neg bounded by max value, sequential, reward at each time step based on transition, additive rewards\n\n\nA Markov decision process or MDP is\n• a sequential decision problem\n• for a fully observable environment\n• with a stochastic transition model\n• that has additive rewards\nMDPs are non-deterministic search problems, can use expectimax search.\n- set of states\n- set of actions\n- transition function T(s, a, s'), probability (the model)\n- reward function R(s, a, s')\n- initial state s_0\n- optional, terminal states\n \n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Policy** - pi(s) = a, policy maps from a state onto the action to take if agent is in state, pi* for optimal\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n need to actually act to figure out things \n\nBasic idea:\n- receive feedback in the form of rewards\n- agent’s utility is defined by the reward function\n- must (learn to) act so as to maximize expected rewards\n- all learning is based on observed samples of outcomes\n\nRequirements\n- set of states s ∈ S\n- set of actions (per state) A\n- a transition model T(s,a,s’)\n- reward function R(s,a,s’)\n- till looking for a policy π(s)\n- don’t know T or R ****\n\nmodel based vs passive reinforcement learning\n- create model vs learning as you go\n\ndirection evaluation\n- easy, no knowledge of t and r, eventually computes correct avg values\n- wastes info about state connections, learn each state separately, takes too long !!!\n\nsample-based policy evaluation?\n- take samples of outcomes s' and average, to improve estimate of V\n\ndecreasing learning rate can give converging averages\n\nq-learning - converges to optimal policy even acting suboptimally, off-policy learning\n- Learn Q(s,a) values as you go\n- Receive a sample (s,a,s’,r)\n- Consider your old estimate:\n- Consider your new sample estimate\n- Incorporate the new estimate into a running average\n- have to explore enough, make learning rate small but not dec too quick\n- takes too much space so we generalize\n\nexploration \n- greedy random actions, thrashing around, solution lower it over time?\n- exploration functions - explore unknowns\n\nlinear value functions - q function using few weights\n\n\n\n## Module 9 Definitions\n* **Exploration** - you have to try unknown actions to get information\n* **Exploitation** - eventually, you have to use what you know\n* **Regret** -  measure of total mistake cost: difference between (expected) rewards and optimal (expected) rewards\n* **Sampling** - because of chance, you have to try things repeatedly\n* **Difficulty** - learning can be much harder than solving a known MDP\n* **Direct evaluation** - act according to policy, every time visit state write down sum of discounted rewards, average samples\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 \n**natural language processing** \n\nP(\"the underdog Philadelphia Eagles won\") = P(the) * P(underdog | the) * P(Philadelphia | the underdog) ....\n\nmaximum likelihood estimation (MLE) - not practical, some sentences might not appear so need huge dataset, not enough data\n\nsimplying assumption markov assumption only depends on the previous k words, not the whole context\n\nP(won | underdog team), P(x, y, z) = $\\prod_i^n P(w_i | w_{i-k}...w_{i-1})$\n\nunigram - no history, bigram, trigram, 4-gram etc etc\n\nn-gram models are evaluated by perplexity on a test set\n\nthere are N! ways to apply the chain rule to a joint distribution with N random variables\n \n\n## Module 10 Definitions\n* **Conditional probability** - P(a | b) = P(a, b) / P(b), probability of a given b is the probability of a and b over the probability of b\n* **Chain rule** - P(a, b, c) = P(a) * P(b|a) * P(c|b,a)\n* **Baye's rule** - P(a | b) = P(b | a) / P(a) * P(b)\n* **Markov property** -  Given the present state, the future and past are independent\n* **Stationary process** - the conditional probability table does not change over time\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n Bayes nets use chain rule, additional conditional independences, and can be read off the graph.\n\nif two nodes don't share a path they're conditionally independent\n\npaths - active if every triple is active, if no paths active (all paths are inactive) then independence is guaranteed\n- A -> B -> C any direction, or A <- B -> C, where B is unobserved\n- A -> B <- C where B or descendent is observed\n- any other config is inactive\n- observed means given, so for X ⫫ Y | T, if X -> T -> Y then inactive\n\nd-separation algorithm: check if all paths are inactive, refer to above\n\ninference by enumeration:\nevidence variables, query variable, hidden variables \n1. select entries consistent with evidence\n2. sum out h (hidden var) to get joint of query and evidence\n3. normalize\n\ninference by enumeration in bayes' nets, easy given unlimited time but slow\n- variable elimination, interleave joining and marginalizing, still np-hard but faster\n- refer to textbook\n\nin locally structured (sparse) systems, structure grows linearly in complexity (rather than\nexponentially)\n\nmore than one Bayesian network can be used to represent the same joint distribution.\n\n\n\n## Module 11 Definitions\n* **Independent** - P(x, y) = P(x) * P(y)\n* **Conditionally independent** - ⫫ P(x, y|z) = P(x | z) * P(y | z), or P(z|x, y) = P(x, y, z) / P(x, y)\n* **Casual chain** - P(x, y, z) = P(x)P(y|x)P(z|y), x and z are not independent, but given y they are\n* **Common cause** - P(x, y, z) = P(y)P(x|y)P(z|y), x and z are not independent, but given y they are\n* **Common effect** - two causes (x, y) of one effect (z), x and y are independent, but not given z\n* **Inference** - calculating some useful quantity from a joint probability distribution\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n \n\nconditional probability distribution of a variable in a Bayesian network should be specified based on the probability distributions of parents\n\nestimating probabilities from data!\n- building a model (bayes' net) where label and features are random variables\n- instantiate any observed features\n- query for the distribution of the label conditioned on the features\n\nfull joint solution is exponential to number of features (|Y| * |F| ^ n), after independence assumption (naive) number of probability tables to populate is linear (n x |F| x |Y|)\n\njoint probability model of $P(X_1, X_2, X_3, Y )$ is $P(Y)P(X_1|Y)P(X_2|Y)P(X_3|Y)$\n- X's are all features, only have to specify how each feature depends on the class\n- total number of parameters is linear in number of features\n- simplistic but can still estimate effectively\n\ninference for naive bayes\n1. get joint probability of label and evidence for each label, normalize\n- (P(y_1, f_1...f_n)) -> P(y_1) * P(f_1|y_1) * ... \n- (P(y_2), f_1...f_n)) -> P(y_2) * P(f_1|y_2) * ...\n2. sum to get probability of evidence\n- / P(f_1...f_n)\n3. normalize by dividing step 1 by step 2\n- P(Y|f_1...f_n)\n\nstart with bunch of (parameters/theta) probabilities P(Y) (prior) and P(f_i|Y) (feature) tables, use standard inference to compute P(Y|f_1...f_n)\n\n In a bag-of-words model\n• Each position is identically distributed ***\n• All positions share the same conditional probs P(W|Y)\n• predict label conditioned on feature variables (spam vs. ham)\n\nTo generalize better: we need to smooth or regularize the estimates, words that don't appear or are specific to training set can overfit\n\nRelative frequencies are the maximum likelihood estimates\n\nLaplace’s estimate: Pretend you saw every outcome once more than you actually did, or k times\n\nLinear interpolation\n\nbaseline\n• Baselines are very simple “straw man” procedures\n• Help determine how hard the task is\n• Help know what a “good” accuracy is\n\nA parametric model has a fixed size on the number of parameters.\n\nSummary\n- Bayes rule lets us do diagnostic queries with causal probabilities\n- The naïve Bayes assumption takes all features to be independent given the class label\n- We can build classifiers out of a naïve Bayes model using training data\n- Smoothing estimates is important in real systems\n- Classifier confidences are useful, when you can get them\n\n\nLinear classifiers: Inputs are feature values, each feature has a weight, sum is the activation\nWhen using the perceptron learning rule, the weights are updated when the actual output does not match the hypothesis output\n- adjust the weight vector by adding or subtracting the feature vector. Subtract if y* is -1.\n- can be multiple decision boundaries, if multiple classes we have weight vectors for each class, score (activation) of a class y and prediction highest score wins, lower score of wrong and raise score of right\n \nissues with perceptrons\n- noise, if data isn't separable weights might thrash, fix is averaging weight vectors over time\n- mediocre generalization, \"barely\" separating solution\n- overtraining, test accuracy rises and then falls, overtraining is a type of overfitting\n\nfixes\n- adjust weight update to minimum correcting update MIRA, choose update size that fixes mistake but minimizes change to w\n- set a maximum step size\n- maximize margin? only support vectors matter, SVM are MIRA optimizing over all examples at once\n \nNaïve Bayes\n• Builds a model training data\n• Gives prediction probabilities\n• Strong assumptions about feature independence\n• One pass through data (counting)\nPerceptrons / MIRA:\n• Makes less assumptions about data\n• Mistake-driven learning\n• Multiple passes through data (prediction)\n• Often more accurate \n\nactivation functions: sigmoid function, tanh function, rectified linear unit ReLU\n \n \n\n## Module 12 Definitions\n* **Naive bayes'** - model is naive because it assumes that the features are conditionally independent of each other, given the class.\n* **Parametric model** - \n* **Non-parametric model** - \n* **Perceptrons** - weight associated with each\n* **Overfitting** - fitting the training data very closely, but not generalizing well\n* **Separability** - true if some parameters get the training set perfectly correct\n* **Convergence** - if the training is separable, perceptron will eventually converge (binary case)\n* **Mistake bound** -  the maximum number of mistakes (binary case) related to the margin or degree of separability $mistakes < \frac{k}{a^2}$\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n \nMachine learning classifiers require a training corpus of M observations input/output pairs (x^(i),y^(i)).\n1. A feature representation of the input. for ach input observation x(i) we have a vector of features [x1,x2,...,xn].\n2. A classification function that computes the estimated class y' via p(y|x).\n3. An objective function for learning, usually involving minimizing error on training examples.\n4. An algorithm for optimizing the objective function.\n\nsentiment classifier: We want to estimate P(y = 1|x).\nLogistic regression solves this task by learning, from a training set, a vector of weights and a bias term. \n- z = w * x + b\n- $z = \\sum_i w_i * x_i + b$\n- then take sigmoid(z)\n- fyi: pos = 1, neg = 0\n\n$P(y=1) = \\sigma(w \\dot x + b = \frac{1}{1+e^{-(w\\dot x + b)}$\n\nany grad. descent starting from any point guaranteed to find minimum, convex function has just one min.\n\nfor many dimensions we update each dimension $w_i$\n\nstochastic grad. descent chooses single random example and updates on that example, so updates can fluctuate\n\nbatch training computes gradient over entire dataset which gives better est. but takes long\n\nmini-batch training trains on smaller batch and is usually processed in parallel, so loss is accumulated\n \nfeed-forward neural network - simplest kind of NN\n- multilayer network\n- all units usually fully connected\n- no cycles\n- each output is passed to next layer, none are passed backwards\n- use single weight matrx W and single bias vector b for entire layer\n- computation can be done with simple matrix operations\n1. multiply weight matrix by input vector x \n2. add bias vector b\n3. apply activation function g (such as sigmoid)\n- h = \\sig(Wx+b)\n- output later has weight matrix U, z (intermed. output) = Uh (input vector)\n- y=softmax(z)\n\ntraining neural nets\n- A loss function – cross-entropy loss\n- An optimization algorithm – gradient descent\n- A way of computing the gradient of the loss function – error propagation \n\nNeural Networks combine many perceptron-like neural units, we have many more parameters in the models (weights and biases). This allows us to train systems to perform even more sophisticated tasks. \n \n \n\n## Module 13 Definitions\n* **Decision boundary** - probability needed to get 1, 0 otherwise\n* **Loss function** - tells distance between system output and goal output, we use cross entropy loss\n* **Optimize obj function** - we use stochastic gradient descent to minimize the loss function\n* **Gradient descent** - method that finds a min of a funct by figuring out which direction in space of parameter theta function steep slope and moves opposite\n* **Regularization** - way to penalize large weights, term is added to loss function\n* **Soft max function** - generalization of the sigmoid function, takes in input vector z and outputs vector of values normalized into probabilities\n* **Backward pass** - \n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 14 Lecture Notes\n Your summary here \n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}