{
 "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",
   "execution_count": 55,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "lzaavW96tcxM",
    "outputId": "8e8746a9-dbc7-40cc-e2f9-c08142cd5bd3"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The example summary is 116 words long, so you could write an additional 384 words.\n"
     ]
    }
   ],
   "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)))"
   ]
  },
  {
   "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",
   "execution_count": 56,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "8DvZ57A-djo1",
    "outputId": "4d5dd686-4939-4e7c-a605-5e57de85f651"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The length in words is 500\n",
      "The length in characters is 3030\n"
     ]
    }
   ],
   "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))"
   ]
  },
  {
   "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",
   "execution_count": 57,
   "metadata": {
    "id": "2RECnJArJew4"
   },
   "outputs": [],
   "source": [
    "name = \"\"\n",
    "permission = True\n",
    "anonymous = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "GZZXyrV-xuAp"
   },
   "source": [
    "# Module 8 - Markov Decision Process"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "id": "Y2NfE1CKxzS-"
   },
   "outputs": [],
   "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 = \"\"\"Transitions are Markovian: the probability of arriving in s’ only depends on s and not the history of earlier states.\\n\n",
    "Instead of only giving a reward at the goal states, the agent can **receive a reward at each time step**, based on its transition from **s** to **s’** via action **a**.\\n\n",
    "A Markov decision process or MDP is\\n\n",
    "• a sequential decision problem\\n\n",
    "• for a fully observable environment\\n\n",
    "• with a stochastic transition model\\n\n",
    "• that has additive rewards\\n\n",
    "MDPs are non-deterministic search problems. One way of solving them is via expectimax search.\\n\n",
    "To find a solution to an MDP, you need to define the following things: A set of states s, A set of actions a, A transition function T(s, a, s’),\n",
    " A reward function R(s, a, s’), An initial state s0, Optionally, one or more terminal states\\n\n",
    "game lasts forever solution: Finite horizon: (similar to depth-limited search), Discounting\\n\n",
    "\n",
    "\"\"\"  + sample_equation\n",
    "chapter16_2 =  \"\"\"$$V^*(s)=max_a Q^*(s,a)$$\\n\n",
    "$$Q^*(s,a)=\\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^*(s')]$$\\n\n",
    "$$V^*(s)=max_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^*(s')]$$\\n\n",
    "Value iteration: $$V_{k+1}(s)\\leftarrow max_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V_k(s')]$$\\n\n",
    "Complexity of each iteration: O(S^2A)\\n\n",
    "fixed policy recursive relation(one-step look-ahead / Bellman equation): $$V^{\\pi}(s)=\\sum_{s'}T(s,\\pi(s),s')[R(s,\\pi(s),s')+\\gamma V^{\\pi}(s')]$$\\n\n",
    "actions are easier to select from q-values than values!\\n\n",
    "Problems with Value Iteration: : It’s slow – O(S2A) per iteration, The “max” at each state rarely change, The policy often converges long before the values\\n\n",
    "Policy Iteration: \n",
    "Policy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence\\n\n",
    "$$V_{k+1}^{\\pi_i}(s)\\leftarrow \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s')+\\gamma V_k^{\\pi_i}(s')]$$\\n\n",
    "Policy improvement: update policy using one-step lookahead with resulting converged utilities as future values\\n\n",
    "$$\\pi_{i+1}(s)= argmax_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^{\\pi_i}(s')]$$\\n\n",
    "\"\"\"\n",
    "chapter16_3 =  \"\"\"Comparison: \\n\n",
    "In value iteration:\\n\n",
    "• Every iteration updates both the values and (implicitly) the policy\\n\n",
    "• We don’t track the policy, but taking the max over actions implicitly recomputes it\\n\n",
    "\n",
    "In policy iteration:\\n\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\n",
    "• After the policy is evaluated, a new policy is chosen (slow like a value iteration pass)\\n\n",
    "• The new policy will be better (or we’re done)\\n\n",
    "Both are dynamic programs for solving MDPs\\n\n",
    "preference: $$A\\succ B$$\\n\n",
    "indifference: $$A\\sim B$$\\n\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
    "chapter17_1 = \"\"\" Your summary here \"\"\"\n",
    "chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Lecture notes \n",
    "module8_lecture_notes = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "\n",
    "# Definitions of concepts from Module 8.\n",
    "# You can define any term in the textbook or lecture, \n",
    "# but you most use your own words for the definitions.\n",
    "# Each definition should be at most 25 words long.\n",
    "\n",
    "module8_definitions = {\n",
    "\"utility function\" : \"Your definition here\",\n",
    "\"expected utility\" : \"your definition here\",\n",
    "\"the model\": \"Probability that executing action a in s will lead to s’ P(s’ | s, a)\",\n",
    "\"Absorbing state\": \"guarantee that for every policy, a terminal state will eventually be reached\",\n",
    "\"Utility\": \"sum of (discounted) rewards\",\n",
    "\"Policy\": \"Choice of action for each state\",\n",
    "\"The value (utility) of a state s\": \"V*(s) = expected utility starting in s and acting optimally\",\n",
    "\"The value (utility) of a q-state (s,a)\": \"Q*(s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally\",\n",
    "\"The optimal policy\": \"pi*(s) = optimal action from state s\",\n",
    "\"Lotteries\": \"situations with uncertain prizes\",\n",
    "\"Orderability\": \"$$(A\\\\succ B)\\\\vee (B\\\\succ A) \\\\vee (A\\sim B)$$\",\n",
    "\"Transitivity\": \"$$(A\\\\succ B)\\\\wedge (B\\\\succ C) \\Rightarrow (A\\\\succ C)$$\",\n",
    "\"Continuity\": \"$$ A\\\\succ B \\\\succ C \\Rightarrow \\exists p [p,A; 1-p,C] \\sim B)$$\",\n",
    "\"Substitutability\": \"$$A\\sim B \\Rightarrow [p,A; 1-p,C] \\sim [p,B; 1-p,C]$$\",\n",
    "\"Monotonicity\": \"$$A\\\\succ B \\Rightarrow (p\\ge q \\Leftrightarrow [p,A; 1-p,B] \\\\succeq [q,A; 1-q,B])$$\"\n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "elCCgY64spuq"
   },
   "source": [
    "## Preview of your notes for Module 8\n",
    "\n",
    "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "gYYeNcdM_maE",
    "outputId": "8b3f9337-8dba-4d4d-e68e-ea37c1ab3d46"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 8: Markov Decision Processes\n",
       "## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n",
       "Transitions are Markovian: the probability of arriving in s’ only depends on s and not the history of earlier states.\n",
       "\n",
       "Instead of only giving a reward at the goal states, the agent can **receive a reward at each time step**, based on its transition from **s** to **s’** via action **a**.\n",
       "\n",
       "A Markov decision process or MDP is\n",
       "\n",
       "• a sequential decision problem\n",
       "\n",
       "• for a fully observable environment\n",
       "\n",
       "• with a stochastic transition model\n",
       "\n",
       "• that has additive rewards\n",
       "\n",
       "MDPs are non-deterministic search problems. One way of solving them is via expectimax search.\n",
       "\n",
       "To find a solution to an MDP, you need to define the following things: A set of states s, A set of actions a, A transition function T(s, a, s’),\n",
       " A reward function R(s, a, s’), An initial state s0, Optionally, one or more terminal states\n",
       "\n",
       "game lasts forever solution: Finite horizon: (similar to depth-limited search), Discounting\n",
       "\n",
       "\n",
       " $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n",
       "\n",
       "## AIMA Chapter 16.2 The Basis of Utility Theory\n",
       "$$V^*(s)=max_a Q^*(s,a)$$\n",
       "\n",
       "$$Q^*(s,a)=\\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^*(s')]$$\n",
       "\n",
       "$$V^*(s)=max_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^*(s')]$$\n",
       "\n",
       "Value iteration: $$V_{k+1}(s)\\leftarrow max_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V_k(s')]$$\n",
       "\n",
       "Complexity of each iteration: O(S^2A)\n",
       "\n",
       "fixed policy recursive relation(one-step look-ahead / Bellman equation): $$V^{\\pi}(s)=\\sum_{s'}T(s,\\pi(s),s')[R(s,\\pi(s),s')+\\gamma V^{\\pi}(s')]$$\n",
       "\n",
       "actions are easier to select from q-values than values!\n",
       "\n",
       "Problems with Value Iteration: : It’s slow – O(S2A) per iteration, The “max” at each state rarely change, The policy often converges long before the values\n",
       "\n",
       "Policy Iteration: \n",
       "Policy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence\n",
       "\n",
       "$$V_{k+1}^{\\pi_i}(s)\\leftarrow \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s')+\\gamma V_k^{\\pi_i}(s')]$$\n",
       "\n",
       "Policy improvement: update policy using one-step lookahead with resulting converged utilities as future values\n",
       "\n",
       "$$\\pi_{i+1}(s)= argmax_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^{\\pi_i}(s')]$$\n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 16.3 Utility Functions\n",
       "Comparison: \n",
       "\n",
       "In value iteration:\n",
       "\n",
       "• Every iteration updates both the values and (implicitly) the policy\n",
       "\n",
       "• We don’t track the policy, but taking the max over actions implicitly recomputes it\n",
       "\n",
       "\n",
       "In policy iteration:\n",
       "\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",
       "\n",
       "• After the policy is evaluated, a new policy is chosen (slow like a value iteration pass)\n",
       "\n",
       "• The new policy will be better (or we’re done)\n",
       "\n",
       "Both are dynamic programs for solving MDPs\n",
       "\n",
       "preference: $$A\\succ B$$\n",
       "\n",
       "indifference: $$A\\sim B$$\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 17.1 Sequential Decision Problems\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 17.2 Algorithms for MDPs\n",
       " Your summary here \n",
       "\n",
       "## Module 8 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 8 Definitions\n",
       "* **Utility function** - Your definition here\n",
       "* **Expected utility** - your definition here\n",
       "* **The model** - Probability that executing action a in s will lead to s’ P(s’ | s, a)\n",
       "* **Absorbing state** - guarantee that for every policy, a terminal state will eventually be reached\n",
       "* **Utility** - sum of (discounted) rewards\n",
       "* **Policy** - Choice of action for each state\n",
       "* **The value (utility) of a state s** - V*(s) = expected utility starting in s and acting optimally\n",
       "* **The value (utility) of a q-state (s,a)** - Q*(s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally\n",
       "* **The optimal policy** - pi*(s) = optimal action from state s\n",
       "* **Lotteries** - situations with uncertain prizes\n",
       "* **Orderability** - $$(A\\succ B)\\vee (B\\succ A) \\vee (A\\sim B)$$\n",
       "* **Transitivity** - $$(A\\succ B)\\wedge (B\\succ C) \\Rightarrow (A\\succ C)$$\n",
       "* **Continuity** - $$ A\\succ B \\succ C \\Rightarrow \\exists p [p,A; 1-p,C] \\sim B)$$\n",
       "* **Substitutability** - $$A\\sim B \\Rightarrow [p,A; 1-p,C] \\sim [p,B; 1-p,C]$$\n",
       "* **Monotonicity** - $$A\\succ B \\Rightarrow (p\\ge q \\Leftrightarrow [p,A; 1-p,B] \\succeq [q,A; 1-q,B])$$\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "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, Image\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))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9xRbdqDox2zD"
   },
   "source": [
    "#Module 9 - Reinforcement Learning"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "id": "DpBvu7EMx7sy"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
    "chapter17_3 =  \"\"\" Reinforcement learning(online): don’t know T or R. we don’t know which states are good or what the actions do Must actually try actions and states out to learn\\n\n",
    "Model-Based Idea: Learn an approximate model based on experiences Solve for values as if the learned model were correct\\n\n",
    "**passive RL**: \n",
    "Input: a fixed policy π(s), no transitions T and rewards R\\n\n",
    "Goal: learn the state values\\n\n",
    "In this case:\\n \n",
    "Learner is “along for the ride”\\n\n",
    "No choice about what actions to take\\n\n",
    "Just execute the policy and learn from experience\\n\n",
    "\n",
    "Direct Evaluation(model free): Compute values for each state under π, Average together observed sample values\\n\n",
    "problems: wastes information about state connections, Each state must be learned separately. so it takes a long time to learn\\n\n",
    "Sample-Based Policy Evaluation: Take samples of outcomes s’ (by doing the action!) and average\\n\n",
    "Temporal Difference Learning: learn from every experience\\n\n",
    "Sample of V(s): $sample=R(s,\\pi(s),s')+\\gamma V^{\\pi}(s')$ \\n\n",
    "Update to V(s): $ V^{\\pi}(s) \\leftarrow (1- \\\\alpha )V^{\\pi}(s)+( \\\\alpha )sample $ \\n\n",
    "Exponential moving average: Makes recent samples more important and Forgets about the past:\\n\n",
    "$$\\overline{x}_n=\\\\frac{x_n+(1-\\\\alpha)x_{n-1}+(1-\\\\alpha)^2x_{n-2}+...}{1+(1-\\\\alpha)+(1-\\\\alpha)^2+...}$$\n",
    "**TD value leaning** is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages\\n\n",
    "problem: can't turn values into a new policy\\n\n",
    "**Full reinforcement learning**: optimal policies\\n\n",
    "no transitions T and rewards R\\n\n",
    "You choose the actions now\\n\n",
    "Goal: learn the optimal policy / values\\n\n",
    "In this case:\\n\n",
    "Learner makes choices!\\n\n",
    "Fundamental tradeoff: exploration vs. exploitation\\n\n",
    "This is NOT offline planning! You actually take actions in the world and find out what happens...\\n\n",
    "sample-based Q-value iteration: $Q_{k+1}(s,a)\\leftarrow \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma max_{a'}Q_k(s',a')]$\\n\n",
    "This is called off-policy learning\\n\n",
    "Caveats: explore enough, eventually make the learning rate small enough but not decrease it too quickly\\n\n",
    "Several schemes for forcing exploration: random actions (ε-greedy)\\n\n",
    "problem: keep thrashing around once learning is done.\\n\n",
    "solution: lower ε over time, exploration function(explore areas whose badness is not (yet) established, eventually stop exploring)\\n\n",
    "Takes a value estimate u and a visit count n, and returns an optimistic utility: $f(u,n)=u+k/n$\\n\n",
    "$Q(s,a)\\leftarrow_{\\\\alpha} R(s,a,s')+\\gamma max_{a'}f(Q(s',a'),N(s',a'))$\\n\n",
    "this propagates the “bonus” back to states that lead to unknown states as well!\n",
    "\"\"\"\n",
    "\n",
    "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
    "chapter22_1 =  \"\"\"\n",
    "In realistic situations, we cannot possibly learn about every single state!\\n\n",
    "**Evaluation functions** score non-terminals in depth-limited search\\n\n",
    "Ideal function: returns the actual minimax value of the position\\n\n",
    "In practice: typically weighted linear sum of features\\n\n",
    "**Linear Value Functions:** Using a feature representation, we can write a q function (or value function) for any state using a few weightsUsing a feature representation,\n",
    "we can write a q function (or value function) for any state using a few weights\\n\n",
    "Advantage: our experience is summed up in a few powerful numbers\\n\n",
    "Disadvantage: states may share features but actually be very different in value!\\n\n",
    "Q-learning with linear Q-functions:\\n\n",
    "difference=$[r+\\gamma max_{a'}Q(s',a')]-Q(s,a)$\\n\n",
    "$Q(s,a)\\leftarrow Q(s,a)+\\\\alpha[difference]$\\n\n",
    "$w_i\\leftarrow w_i + \\\\alpha[difference]f_i(s,a)$\\n\n",
    "Minimizing regret goes beyond learning to be optimal – it requires optimally learning to be optimal\\n\n",
    "Example: random exploration and exploration functions both end up optimal, but random exploration has higher **regret**\n",
    "\"\"\"\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 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Each definition should be at most 25 words long.\n",
    "module9_definitions = {\n",
    "\"Regret\" : \"Regret is a measure of your total mistake cost. the difference between your (expected) rewards, including youthful suboptimality, and optimal (expected) rewards\",\n",
    "\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "ydOK__lwWgdp",
    "outputId": "9f13bca9-6a85-4085-80dc-3956668aa31d"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 9: Reinforcement Learning\n",
       "## AIMA Chapter 17.3 Bandit Problems\n",
       " Reinforcement learning(online): don’t know T or R. we don’t know which states are good or what the actions do Must actually try actions and states out to learn\n",
       "\n",
       "Model-Based Idea: Learn an approximate model based on experiences Solve for values as if the learned model were correct\n",
       "\n",
       "**passive RL**: \n",
       "Input: a fixed policy π(s), no transitions T and rewards R\n",
       "\n",
       "Goal: learn the state values\n",
       "\n",
       "In this case:\n",
       " \n",
       "Learner is “along for the ride”\n",
       "\n",
       "No choice about what actions to take\n",
       "\n",
       "Just execute the policy and learn from experience\n",
       "\n",
       "\n",
       "Direct Evaluation(model free): Compute values for each state under π, Average together observed sample values\n",
       "\n",
       "problems: wastes information about state connections, Each state must be learned separately. so it takes a long time to learn\n",
       "\n",
       "Sample-Based Policy Evaluation: Take samples of outcomes s’ (by doing the action!) and average\n",
       "\n",
       "Temporal Difference Learning: learn from every experience\n",
       "\n",
       "Sample of V(s): $sample=R(s,\\pi(s),s')+\\gamma V^{\\pi}(s')$ \n",
       "\n",
       "Update to V(s): $ V^{\\pi}(s) \\leftarrow (1- \\alpha )V^{\\pi}(s)+( \\alpha )sample $ \n",
       "\n",
       "Exponential moving average: Makes recent samples more important and Forgets about the past:\n",
       "\n",
       "$$\\overline{x}_n=\\frac{x_n+(1-\\alpha)x_{n-1}+(1-\\alpha)^2x_{n-2}+...}{1+(1-\\alpha)+(1-\\alpha)^2+...}$$\n",
       "**TD value leaning** is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages\n",
       "\n",
       "problem: can't turn values into a new policy\n",
       "\n",
       "**Full reinforcement learning**: optimal policies\n",
       "\n",
       "no transitions T and rewards R\n",
       "\n",
       "You choose the actions now\n",
       "\n",
       "Goal: learn the optimal policy / values\n",
       "\n",
       "In this case:\n",
       "\n",
       "Learner makes choices!\n",
       "\n",
       "Fundamental tradeoff: exploration vs. exploitation\n",
       "\n",
       "This is NOT offline planning! You actually take actions in the world and find out what happens...\n",
       "\n",
       "sample-based Q-value iteration: $Q_{k+1}(s,a)\\leftarrow \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma max_{a'}Q_k(s',a')]$\n",
       "\n",
       "This is called off-policy learning\n",
       "\n",
       "Caveats: explore enough, eventually make the learning rate small enough but not decrease it too quickly\n",
       "\n",
       "Several schemes for forcing exploration: random actions (ε-greedy)\n",
       "\n",
       "problem: keep thrashing around once learning is done.\n",
       "\n",
       "solution: lower ε over time, exploration function(explore areas whose badness is not (yet) established, eventually stop exploring)\n",
       "\n",
       "Takes a value estimate u and a visit count n, and returns an optimistic utility: $f(u,n)=u+k/n$\n",
       "\n",
       "$Q(s,a)\\leftarrow_{\\alpha} R(s,a,s')+\\gamma max_{a'}f(Q(s',a'),N(s',a'))$\n",
       "\n",
       "this propagates the “bonus” back to states that lead to unknown states as well!\n",
       "\n",
       "\n",
       "## AIMA Chapter 22.1 Learning from Rewards\n",
       "\n",
       "In realistic situations, we cannot possibly learn about every single state!\n",
       "\n",
       "**Evaluation functions** score non-terminals in depth-limited search\n",
       "\n",
       "Ideal function: returns the actual minimax value of the position\n",
       "\n",
       "In practice: typically weighted linear sum of features\n",
       "\n",
       "**Linear Value Functions:** Using a feature representation, we can write a q function (or value function) for any state using a few weightsUsing a feature representation,\n",
       "we can write a q function (or value function) for any state using a few weights\n",
       "\n",
       "Advantage: our experience is summed up in a few powerful numbers\n",
       "\n",
       "Disadvantage: states may share features but actually be very different in value!\n",
       "\n",
       "Q-learning with linear Q-functions:\n",
       "\n",
       "difference=$[r+\\gamma max_{a'}Q(s',a')]-Q(s,a)$\n",
       "\n",
       "$Q(s,a)\\leftarrow Q(s,a)+\\alpha[difference]$\n",
       "\n",
       "$w_i\\leftarrow w_i + \\alpha[difference]f_i(s,a)$\n",
       "\n",
       "Minimizing regret goes beyond learning to be optimal – it requires optimally learning to be optimal\n",
       "\n",
       "Example: random exploration and exploration functions both end up optimal, but random exploration has higher **regret**\n",
       "\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",
       " Your summary here \n",
       "\n",
       "## Module 9 Definitions\n",
       "* **Regret** - Regret is a measure of your total mistake cost. the difference between your (expected) rewards, including youthful suboptimality, and optimal (expected) rewards\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "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))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "46MQLR-Gx8dZ"
   },
   "source": [
    "#Module 10 - Probabilities and Language Models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "id": "BN0b1eVYx-nd"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
    "chapter12_1 = \"\"\" Probabilistic models: A probabilistic model is a joint distribution over a set of random variables\\n\n",
    "(Random) variables with domains\\n\n",
    "Assignments are called outcomes\\n\n",
    "Joint distributions: say whether assignments (outcomes) are likely\\n\n",
    "Normalized: sum to 1.0\\n\n",
    "Ideally: only certain variables directly interact\n",
    "An event is a set E of outcomes $P(E)=\\sum_{(x_1...x_n)\\in E}P(x_1...x_n)$\\n\n",
    "Conditional Probabilities: $P(a|b)=\\\\frac{P(a,b)}{P(b)}$\\n\n",
    "Probabilistic inference: compute a desired probability from other known probabilities (e.g. conditional from joint)\\n\n",
    "chain rule: $P(x_1,x_2,...x_n)=\\\\prod_i P(x_i|x_1...x_{i-1})$\n",
    "Bayes' Rule: $P(x,y)=P(x|y)P(y)=P(y|x)P(x)$\\n\n",
    "Goal of language model:  compute the probability of a sentence or sequence of words or an upcoming word\\n\n",
    "Simplifying Assumption = Markov Assumption: Only depends on the previous k words, not the whole context\\n\n",
    "N-grams models: insufficient because language has long-distance dependencies\\n\n",
    "Estimating bigram probabilities: $P(w_i|w_{i-1})=\\\\frac{c(w_{i-1},w_i)}{c(w_{i-1})}$\\n\n",
    "Problems for MLE: Out of vocabulary items (OOV)\\n\n",
    "Avoid zeros with smoothing\\n\n",
    "If a process is **stationary**, it means that the conditional probability table does not change over time\\n\n",
    "n-gram language models typically evaluated by Perplexity on a test set\\n\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
    "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
    "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
    "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
    "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
    "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "\n",
    "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
    "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
    "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
    "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
    "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
    "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
    "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "\n",
    "# Lecture notes \n",
    "module10_lecture_notes = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "\n",
    "# Each definition should be at most 25 words long.\n",
    "module10_definitions = {\n",
    "\"Observed variables (evidence)\" : \"Agent knows certain things about the state of the world\",\n",
    "\"Unobserved variables (states)\": \"Agent needs to reason about other aspects\",\n",
    "\"Model\": \"Agent knows something about how the known variables relate to the unknown variables\",\n",
    "\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "lvtN3p7ET3Tx",
    "outputId": "4df1783f-edcf-434f-ad2e-19a32a4d10bf"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 10: Probabilies and Language Models\n",
       "## AIMA Chapter 12.1 Acting under Uncertainty\n",
       " Probabilistic models: A probabilistic model is a joint distribution over a set of random variables\n",
       "\n",
       "(Random) variables with domains\n",
       "\n",
       "Assignments are called outcomes\n",
       "\n",
       "Joint distributions: say whether assignments (outcomes) are likely\n",
       "\n",
       "Normalized: sum to 1.0\n",
       "\n",
       "Ideally: only certain variables directly interact\n",
       "An event is a set E of outcomes $P(E)=\\sum_{(x_1...x_n)\\in E}P(x_1...x_n)$\n",
       "\n",
       "Conditional Probabilities: $P(a|b)=\\frac{P(a,b)}{P(b)}$\n",
       "\n",
       "Probabilistic inference: compute a desired probability from other known probabilities (e.g. conditional from joint)\n",
       "\n",
       "chain rule: $P(x_1,x_2,...x_n)=\\prod_i P(x_i|x_1...x_{i-1})$\n",
       "Bayes' Rule: $P(x,y)=P(x|y)P(y)=P(y|x)P(x)$\n",
       "\n",
       "Goal of language model:  compute the probability of a sentence or sequence of words or an upcoming word\n",
       "\n",
       "Simplifying Assumption = Markov Assumption: Only depends on the previous k words, not the whole context\n",
       "\n",
       "N-grams models: insufficient because language has long-distance dependencies\n",
       "\n",
       "Estimating bigram probabilities: $P(w_i|w_{i-1})=\\frac{c(w_{i-1},w_i)}{c(w_{i-1})}$\n",
       "\n",
       "Problems for MLE: Out of vocabulary items (OOV)\n",
       "\n",
       "Avoid zeros with smoothing\n",
       "\n",
       "If a process is **stationary**, it means that the conditional probability table does not change over time\n",
       "\n",
       "n-gram language models typically evaluated by Perplexity on a test set\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 12.2 Basic Probability Notation\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.4 Independence\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.6 Naive Bayes Models\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.7 The Wumpus World Revisited\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.1 N-Grams\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.2 Evaluating Language Models\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.3 Sampling sentences from a language model\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.4 Generalization and Zeros\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.5 Smoothing\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n",
       " Your summary here \n",
       "\n",
       "## Module 10 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 10 Definitions\n",
       "* **Observed variables (evidence)** - Agent knows certain things about the state of the world\n",
       "* **Unobserved variables (states)** - Agent needs to reason about other aspects\n",
       "* **Model** - Agent knows something about how the known variables relate to the unknown variables\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "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))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WHREsHSSyA-h"
   },
   "source": [
    "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {
    "id": "tuFC8w7CyCns"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
    "chapter13_1 = \"\"\"Indepenence: $X{\\perp\\!\\!\\!\\perp}Y$.\\n\n",
    "$\\\\forall x,y:P(x,y)=P(x)P(y)$\\n\n",
    "Conditional indenpendence: \n",
    "$X{\\perp\\!\\!\\!\\perp}Y|Z$\\n\n",
    "iff $\\\\forall x,y,z :P(x,y|z)=P(x|z)P(y|z)$ or $P(x|z,y)=P(z|z)$\\n\n",
    "Two problems with using full joint distribution tables as our probabilistic models:\\n\n",
    "Unless there are only a few variables, the joint is WAY too big to represent explicitly. Hard to learn (estimate) anything empirically about more than a few variables at a time\\n\n",
    "A Bayes net = Topology (graph) + Local Conditional Probabilities\\n\n",
    "active trail (Variables connected by active trails are not conditionally independent):\\n\n",
    "If $X_i$ is not observed, $X_{i-1}\\\\rightarrow X_i \\\\rightarrow X_{i+1}$, $X_{i-1}\\\\leftarrow X_i \\\\rightarrow X_{i+1}$\\n\n",
    "If $X_i$ is observed or one of its descendants is observed: $X_{i-1}\\\\rightarrow X_i \\\\leftarrow X_{i+1}$\\n\n",
    "BNs need not actually be causal\\n\n",
    "Topology may happen to encode causal structure but really encodes conditional independence\\n\n",
    "joint distribution over N Boolean variables: $2^N$\\n\n",
    "an N-node net if nodes have up to k parents: $O(N*2^{k+1})$ Huge space savings\\n\n",
    "Bayes Nets Representation Summary:\\n\n",
    "§ Bayes nets compactly encode joint distributions\\n\n",
    "§ Guaranteed independencies of distributions can be deduced from BN graph structure\\n\n",
    "§ D-separation gives precise conditional independence guarantees from graph alone\\n\n",
    "§ A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\\n\n",
    "Inference: calculating some useful quantity from a joint probability distribution\\n\n",
    "Why is inference by enumeration so slow? You join up the whole joint distribution before you sum out the hidden variables\\n\n",
    "Variable Elimination: Interleave joining and marginalizing. do the calculation once and save the results for later use\\n\n",
    "\n",
    "\"\"\"\n",
    "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
    "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "\n",
    "# Lecture notes \n",
    "module11_lecture_notes = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Definitions\n",
    "module11_definitions = {\n",
    "\"concept\" : \"definition\",    \n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "vqtEs0gHs9sO",
    "outputId": "3880c8a5-1b1a-4a09-9b61-9cf92a169d8b"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n",
       "## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n",
       "Indepenence: $X{\\perp\\!\\!\\!\\perp}Y$.\n",
       "\n",
       "$\\forall x,y:P(x,y)=P(x)P(y)$\n",
       "\n",
       "Conditional indenpendence: \n",
       "$X{\\perp\\!\\!\\!\\perp}Y|Z$\n",
       "\n",
       "iff $\\forall x,y,z :P(x,y|z)=P(x|z)P(y|z)$ or $P(x|z,y)=P(z|z)$\n",
       "\n",
       "Two problems with using full joint distribution tables as our probabilistic models:\n",
       "\n",
       "Unless there are only a few variables, the joint is WAY too big to represent explicitly. Hard to learn (estimate) anything empirically about more than a few variables at a time\n",
       "\n",
       "A Bayes net = Topology (graph) + Local Conditional Probabilities\n",
       "\n",
       "active trail (Variables connected by active trails are not conditionally independent):\n",
       "\n",
       "If $X_i$ is not observed, $X_{i-1}\\rightarrow X_i \\rightarrow X_{i+1}$, $X_{i-1}\\leftarrow X_i \\rightarrow X_{i+1}$\n",
       "\n",
       "If $X_i$ is observed or one of its descendants is observed: $X_{i-1}\\rightarrow X_i \\leftarrow X_{i+1}$\n",
       "\n",
       "BNs need not actually be causal\n",
       "\n",
       "Topology may happen to encode causal structure but really encodes conditional independence\n",
       "\n",
       "joint distribution over N Boolean variables: $2^N$\n",
       "\n",
       "an N-node net if nodes have up to k parents: $O(N*2^{k+1})$ Huge space savings\n",
       "\n",
       "Bayes Nets Representation Summary:\n",
       "\n",
       "§ Bayes nets compactly encode joint distributions\n",
       "\n",
       "§ Guaranteed independencies of distributions can be deduced from BN graph structure\n",
       "\n",
       "§ D-separation gives precise conditional independence guarantees from graph alone\n",
       "\n",
       "§ A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\n",
       "\n",
       "Inference: calculating some useful quantity from a joint probability distribution\n",
       "\n",
       "Why is inference by enumeration so slow? You join up the whole joint distribution before you sum out the hidden variables\n",
       "\n",
       "Variable Elimination: Interleave joining and marginalizing. do the calculation once and save the results for later use\n",
       "\n",
       "\n",
       "\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",
       " Your summary here \n",
       "\n",
       "## Module 11 Definitions\n",
       "* **Concept** - definition\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 392476 characters]\n",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {
      "image/png": {
       "height": 200,
       "width": 300
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.image as mpimg\n",
    "#@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))\n",
    "display(Image('./Burglar_belief_net.png',width=300, height=200))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "F3FPMzG9yUls"
   },
   "source": [
    "#Module 12 - Naive Bayes and Perceptrons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {
    "id": "iEIOpL7vyWcc"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
    "\n",
    "chapter19_1 = \"\"\"Naïve Bayes: Assume all features are independent effects of the label $P(X_1,X_2,X_3,Y)=P(Y)P(X_1|Y)P(X_2|Y)P(X_3|Y)$\\n\n",
    "In a bag-of-words model\n",
    "• Each position is identically distributed\\n\n",
    "• All positions share the same conditional probs P(W|Y)\\n\n",
    "• Called “bag-of-words” because model is insensitive to word order or reordering\\n\n",
    "Relative frequency parameters will overfit the training data! Unlikely that every occurrence of “minute” is 100% spam\\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\\n\n",
    "$P_{LAP,k}(x)=\\\\frac{c(x)+k}{N+k|X|}$ k is the strength of the prior\\n\n",
    "The naïve Bayes assumption takes all features to be independent given the class label\\n\n",
    "Naïve Bayes models can incorporate a variety of features, but tend to do best in homogeneous cases\\n\n",
    "Binary Perceptron： If wrong: adjust the weight vector by adding or subtracting the feature vector：$w=w+y^*\\cdot f$\\n\n",
    "Multiclass Decision Rule: $y=argmax_y w_y\\cdot f(x)$\\n\n",
    "If wrong: lower score of wrong answer, raise score of right answer\\n\n",
    "Separability: true if some parameters get the training set perfectly correct\\n\n",
    "Convergence: if the training is separable, perceptron will eventually converge (binary case)\\n\n",
    "Mistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\\n\n",
    "Problems with the Perceptron:\\n\n",
    "Noise: if the data isn’t separable, weights might thrash. Averaging weight vectors over time can help (averaged perceptron)\\n\n",
    "Mediocre generalization: finds a “barely” separating solution\\n\n",
    "Overtraining: test / held-out accuracy usually rises, then falls(kind of overfitting)\\n\n",
    "Fixing the Perceptron: adjust the weight update to mitigate these effects\\n\n",
    "MIRA: choose an update size that fixes the current mistake but, minimizes the change to w\\n\n",
    "Minimum Correcting Update： $\\\\tau=\\\\frac{(w'_y-w'_{y^*})\\cdot f+1}{2f\\cdot f}$\\n\n",
    "Maximum Step Size: cap the maximum possible value of t with some constant C: $\\\\tau^*=min(\\\\tau,C)$\\n\n",
    "Support Vector Machines: Maximizing the margin, Only support vectors matter\\n\n",
    "Basically, SVMs are MIRA where you optimize over all examples at once\n",
    "Naïve Bayes:\\n\n",
    "• Builds a model training data\\n\n",
    "• Gives prediction probabilities\\n\n",
    "• Strong assumptions about feature independence\\n\n",
    "• One pass through data (counting)\\n\n",
    "Perceptrons / MIRA:\\n\n",
    "• Makes less assumptions about data\\n\n",
    "• Mistake-driven learning\\n\n",
    "• Multiple passes through data (prediction)\\n\n",
    "• Often more accurate\\n\n",
    "Two notational changes simplify the way that perceptrons are described: replace the weighted sum as a dot product and move the threshold to the other side of\n",
    "the inequality, and to replace it by a bias\\n\n",
    "\n",
    "\"\"\"\n",
    "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
    "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
    "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
    "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
    "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
    "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Lecture notes \n",
    "module12_lecture_notes = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Definitions\n",
    "module12_definitions = {\n",
    "\"concept\" : \"definition\",    \n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "KUc_LgzDvWf-",
    "outputId": "18cbddf7-5e31-43ef-d563-72c906207626"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 12: Naive Bayes and Perceptrons\n",
       "## AIMA Chapter 5.1 Game Theory\n",
       "Naïve Bayes: Assume all features are independent effects of the label $P(X_1,X_2,X_3,Y)=P(Y)P(X_1|Y)P(X_2|Y)P(X_3|Y)$\n",
       "\n",
       "In a bag-of-words model\n",
       "• Each position is identically distributed\n",
       "\n",
       "• All positions share the same conditional probs P(W|Y)\n",
       "\n",
       "• Called “bag-of-words” because model is insensitive to word order or reordering\n",
       "\n",
       "Relative frequency parameters will overfit the training data! Unlikely that every occurrence of “minute” is 100% spam\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\n",
       "\n",
       "$P_{LAP,k}(x)=\\frac{c(x)+k}{N+k|X|}$ k is the strength of the prior\n",
       "\n",
       "The naïve Bayes assumption takes all features to be independent given the class label\n",
       "\n",
       "Naïve Bayes models can incorporate a variety of features, but tend to do best in homogeneous cases\n",
       "\n",
       "Binary Perceptron： If wrong: adjust the weight vector by adding or subtracting the feature vector：$w=w+y^*\\cdot f$\n",
       "\n",
       "Multiclass Decision Rule: $y=argmax_y w_y\\cdot f(x)$\n",
       "\n",
       "If wrong: lower score of wrong answer, raise score of right answer\n",
       "\n",
       "Separability: true if some parameters get the training set perfectly correct\n",
       "\n",
       "Convergence: if the training is separable, perceptron will eventually converge (binary case)\n",
       "\n",
       "Mistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\n",
       "\n",
       "Problems with the Perceptron:\n",
       "\n",
       "Noise: if the data isn’t separable, weights might thrash. Averaging weight vectors over time can help (averaged perceptron)\n",
       "\n",
       "Mediocre generalization: finds a “barely” separating solution\n",
       "\n",
       "Overtraining: test / held-out accuracy usually rises, then falls(kind of overfitting)\n",
       "\n",
       "Fixing the Perceptron: adjust the weight update to mitigate these effects\n",
       "\n",
       "MIRA: choose an update size that fixes the current mistake but, minimizes the change to w\n",
       "\n",
       "Minimum Correcting Update： $\\tau=\\frac{(w'_y-w'_{y^*})\\cdot f+1}{2f\\cdot f}$\n",
       "\n",
       "Maximum Step Size: cap the maximum possible value of t with some constant C: $\\tau^*=min(\\tau,C)$\n",
       "\n",
       "Support Vector Machines: Maximizing the margin, Only support vectors matter\n",
       "\n",
       "Basically, SVMs are MIRA where you optimize over all examples at once\n",
       "Naïve Bayes:\n",
       "\n",
       "• Builds a model training data\n",
       "\n",
       "• Gives prediction probabilities\n",
       "\n",
       "• Strong assumptions about feature independence\n",
       "\n",
       "• One pass through data (counting)\n",
       "\n",
       "Perceptrons / MIRA:\n",
       "\n",
       "• Makes less assumptions about data\n",
       "\n",
       "• Mistake-driven learning\n",
       "\n",
       "• Multiple passes through data (prediction)\n",
       "\n",
       "• Often more accurate\n",
       "\n",
       "Two notational changes simplify the way that perceptrons are described: replace the weighted sum as a dot product and move the threshold to the other side of\n",
       "the inequality, and to replace it by a bias\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 5.2 Optimal Decisions in Games\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 5.5 Stochastic Games\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 16.2 The Basis of Utility Theory\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.1 Naive Bayes Classifiers\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.2 Training the Naive Bayes Classifier\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.3 Worked Example\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.6 Naive Bayes as a Language Model\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.8 Test sets and Cross-validation\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.9 Statistical Significance Testing\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.10 Avoiding Harms in Classification\n",
       " Your summary here \n",
       "\n",
       "## Module 12 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 12 Definitions\n",
       "* **Concept** - definition\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "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))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "qVSQhTVSyYYO"
   },
   "source": [
    "# Module 13 - Neural Networks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {
    "id": "Wm4mfW82yaRH"
   },
   "outputs": [],
   "source": [
    "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
    "\n",
    "slp_chapter5_1 = \"\"\"Classifier components: feature representation of the input\\n\n",
    "classification function that computes the estimated class $\\\\hat{y}$ via p(y|x)\\n\n",
    "objective function for learning, usually involving minimizing error on training examples.\\n\n",
    "An algorithm for optimizing the objective function.\\n\n",
    "sigmoid: $y=\\\\frac{1}{1+e^{-z}}$\\n\n",
    "Loss functions for probabilistic classification: $p(y|x)=\\\\hat{y}^y(1-\\\\hat{y})^{1-y}$\\n\n",
    "call the log and flip the sign(to minimize), The result is cross-entropy loss:\\n \n",
    "$L_{CE}(\\\\hat{y},y)=-\\\\log p(y|x)=-[y\\\\log \\\\hat{y}+(1-y)\\\\log(1-\\\\hat{y})]$\\n\n",
    "**Gradient descent** is a method that finds a minimum of a function by figuring out in which direction (in the space of the parameters θ) the function’s slope is rising the most steeply, and moving in the opposite direction.\\n\n",
    "The gradient for multiple data points is the sum of the individual gradients\\n\n",
    "**Stochastic gradient descent** chooses a single random example at a time and updates its weights on that example. As a result the updates can fluctuate.\\n\n",
    "An alternate is batch training, which computes the gradient over the entire dataset.\\n\n",
    "A commonly used compromise is mini-batch training, where we train on a small batch.\\n\n",
    "Regularization is a way to penalize large weights. A regularization term is added to the loss function.\\n\n",
    "logistic vs perceptron: sigmoid vs step function\\n\n",
    "Smoothness of σ means that small changes in the weights wj and in the bias b will produce a small change the output from the neuron\\n\n",
    "Training Neural Nets: \\n\n",
    "A loss function – cross-entropy loss\\n\n",
    "An optimization algorithm – gradient descent\\n\n",
    "A way of computing the gradient of the loss function – error propagation\\n\n",
    "multinomial classification cross-entropy loss: $L_{CE}(\\\\hat{y},y)=-\\sum^C_{i=1}y_i \\log \\\\hat{y_i}$\\n\n",
    "Although backpropagation was invented for neural nets, it is related to general procedure called backward differentiation, which depends on the notion of computation graphs.\\n\n",
    "Chain rule: $\\\\frac{df}{dx}=\\\\frac{du}{dv}\\\\cdot \\\\frac{dv}{dx}$\n",
    "\"\"\"\n",
    "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
    "\n",
    "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Lecture notes \n",
    "module13_lecture_notes = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Definitions\n",
    "module13_definitions = {\n",
    "\"concept\" : \"definition\",    \n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "kKWbCsbfxL3R",
    "outputId": "22502a5f-44fa-4e67-f055-ab0bee1a8007"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 13: Neural Networks\n",
       "## SLP Chapter 5.1 Classification: the sigmoid\n",
       "Classifier components: feature representation of the input\n",
       "\n",
       "classification function that computes the estimated class $\\hat{y}$ via p(y|x)\n",
       "\n",
       "objective function for learning, usually involving minimizing error on training examples.\n",
       "\n",
       "An algorithm for optimizing the objective function.\n",
       "\n",
       "sigmoid: $y=\\frac{1}{1+e^{-z}}$\n",
       "\n",
       "Loss functions for probabilistic classification: $p(y|x)=\\hat{y}^y(1-\\hat{y})^{1-y}$\n",
       "\n",
       "call the log and flip the sign(to minimize), The result is cross-entropy loss:\n",
       " \n",
       "$L_{CE}(\\hat{y},y)=-\\log p(y|x)=-[y\\log \\hat{y}+(1-y)\\log(1-\\hat{y})]$\n",
       "\n",
       "**Gradient descent** is a method that finds a minimum of a function by figuring out in which direction (in the space of the parameters θ) the function’s slope is rising the most steeply, and moving in the opposite direction.\n",
       "\n",
       "The gradient for multiple data points is the sum of the individual gradients\n",
       "\n",
       "**Stochastic gradient descent** chooses a single random example at a time and updates its weights on that example. As a result the updates can fluctuate.\n",
       "\n",
       "An alternate is batch training, which computes the gradient over the entire dataset.\n",
       "\n",
       "A commonly used compromise is mini-batch training, where we train on a small batch.\n",
       "\n",
       "Regularization is a way to penalize large weights. A regularization term is added to the loss function.\n",
       "\n",
       "logistic vs perceptron: sigmoid vs step function\n",
       "\n",
       "Smoothness of σ means that small changes in the weights wj and in the bias b will produce a small change the output from the neuron\n",
       "\n",
       "Training Neural Nets: \n",
       "\n",
       "A loss function – cross-entropy loss\n",
       "\n",
       "An optimization algorithm – gradient descent\n",
       "\n",
       "A way of computing the gradient of the loss function – error propagation\n",
       "\n",
       "multinomial classification cross-entropy loss: $L_{CE}(\\hat{y},y)=-\\sum^C_{i=1}y_i \\log \\hat{y_i}$\n",
       "\n",
       "Although backpropagation was invented for neural nets, it is related to general procedure called backward differentiation, which depends on the notion of computation graphs.\n",
       "\n",
       "Chain rule: $\\frac{df}{dx}=\\frac{du}{dv}\\cdot \\frac{dv}{dx}$\n",
       "\n",
       "\n",
       "## SLP Chapter 5.2 Learning in Logistic Regression\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 5.3 The cross-entropy loss function\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 5.4 Gradient Descent\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 5.5 Regularization\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 5.6 Multinomial logistic regression\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.1 Units\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.2 The XOR problem\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.3 Feedforward Neural Networks\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.5 Feedforward Neural Language Modeling\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.6 Training Neural Nets\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.7 Training the neural language model\n",
       " Your summary here \n",
       "\n",
       "## Module 13 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 13 Definitions\n",
       "* **Concept** - definition\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "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))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RYESi2kMybL8"
   },
   "source": [
    "# Module 14 - Natural Language Processing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {
    "id": "qIRJ4YYCzNHL"
   },
   "outputs": [],
   "source": [
    "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
    "\n",
    "slp_chapter9_1 = \"\"\" Ideally, we want a meaning representation to encode:\\n\n",
    "Synonyms – words that have similar meanings\\n\n",
    "Antonyms – words that have opposite meanings\\n\n",
    "Connotations – words that are positive or negative\\n\n",
    "Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event\\n\n",
    "Support for entailment\\n\n",
    "Distributional Hypothesis: Two words are similar if they have similar word contexts.\\n\n",
    "TF-IDF = Term frequency(how often a word occurred in a document) * inverse document frequency(1 over the number of documents that it occurred in)\\n\n",
    "Co-occurrence matrix is Long and Sparse. We want to learn verctors that are Short and Dense\\n\n",
    "LM: Goal: Learn a function that returns the joint probability\\n\n",
    "Difficulty: There are too many parameters to accurately estimate. This is sometimes called the “curse of dimensionality”\\n\n",
    "In n-gram-based models we fail to generalize to related words / word sequences that we have observed.\\n\n",
    "assumption we make in n-gram LMs: The probability of the next word only depends on the previous n-1 words.\\n\n",
    "Neural LM advantages over n-gram LMs:\\n\n",
    "1. They don’t need smoothing\\n\n",
    "2. They can handle much longer histories.\\n\n",
    "3. They can generalize over contexts of similar words.\\n\n",
    "4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\\n\n",
    "Disadvantage: slower to train\\n\n",
    "Advantages of NN LMs: Better results, larger N, generalize across context. A by-product is word embeddings.\\n\n",
    "Word2Vec: Learn embeddings as part of the process of word prediction. Train a classifier to predict neighboring words\\n\n",
    "Skip-gram algorithm:\\n\n",
    "1. Treat the target word and a neighboring context\n",
    "word as positive examples.\\n\n",
    "2. Randomly sample other words in the lexicon to get\n",
    "negative samples\\n\n",
    "3. Use logistic regression to train a classifier to\n",
    "distinguish those two cases\\n\n",
    "4. Use the weights as the embeddings\\n\n",
    "$P(+|t,c)=\\\\frac{1}{1+e^{-t\\\\cdot c}}$\\n\n",
    "get embeddings from word2vec!\\n\n",
    "It starts with an initial set of embedding vectors and then iteratively shifts\n",
    "the embedding of each word w to be more like the embeddings of words\n",
    "that occur nearby in texts, and less like the embeddings of words that\n",
    "don’t occur nearby. \n",
    "\"\"\"\n",
    "slp_chapter9_2 = \"\"\"Choosing noise words:\n",
    "More common to chose them according to $p_{\\\\alpha}(w)=\\\\frac{count(w)^\\\\alpha}{\\sum_w count(w)^\\\\alpha}$\\n\n",
    "$\\\\alpha=3/4$ works well because it gives rare noise words slightly higher probability\\n\n",
    "Evaluating embeddings: Compare to human scores on word similarity-type tasks\\n\n",
    "Solving analogies with embeddings: Vector Arithmetic\\n\n",
    "a:a∗ as b:b∗. b∗ is a hidden vector. b∗ should be similar to the vector b − a + a∗\\n\n",
    "If all word-vectors are normalized to unit length then optimize: $argmax_{b^*\\in V}(cos(b^*,b-a+a^*))$\\n\n",
    "alternatively, we can require that the direction of the transformation be maintained: $argmax_{b^*\\in V}(cos(b^*-b,a^*-a))$\\n\n",
    "Embeddings reflect cultural bias and can be used for studying language change\\n\n",
    "Directions: Debiasing algorithms for embeddings and Use embeddings as a tool to study historical bias\\n\n",
    "Embeddings = vector models of meaning\\n\n",
    "• More fine-grained than just a string or index\\n\n",
    "• Especially good at modeling similarity/analogy\\n\n",
    "• Just download them and use cosines!!\\n\n",
    "• Can use sparse models (tf-idf) or dense models (word2vec, GLoVE)\\n\n",
    "• Useful in practice but know they encode cultural stereotypes\\n\n",
    "\n",
    "\"\"\"\n",
    "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
    "\n",
    "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
    "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "\n",
    "\n",
    "# Lecture notes \n",
    "module14_lecture_notes = \"\"\" Your summary here \"\"\"\n",
    "\n",
    "# Definitions\n",
    "module14_definitions = {\n",
    "\"concept\" : \"definition\",    \n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "lXNcHuKjyNXa",
    "outputId": "12e4d155-f1cf-4e24-ebb4-7e76a0975169"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 14: Natural Language Processing\n",
       "## SLP Chapter 9.1 Language Models Revisited\n",
       " Ideally, we want a meaning representation to encode:\n",
       "\n",
       "Synonyms – words that have similar meanings\n",
       "\n",
       "Antonyms – words that have opposite meanings\n",
       "\n",
       "Connotations – words that are positive or negative\n",
       "\n",
       "Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event\n",
       "\n",
       "Support for entailment\n",
       "\n",
       "Distributional Hypothesis: Two words are similar if they have similar word contexts.\n",
       "\n",
       "TF-IDF = Term frequency(how often a word occurred in a document) * inverse document frequency(1 over the number of documents that it occurred in)\n",
       "\n",
       "Co-occurrence matrix is Long and Sparse. We want to learn verctors that are Short and Dense\n",
       "\n",
       "LM: Goal: Learn a function that returns the joint probability\n",
       "\n",
       "Difficulty: There are too many parameters to accurately estimate. This is sometimes called the “curse of dimensionality”\n",
       "\n",
       "In n-gram-based models we fail to generalize to related words / word sequences that we have observed.\n",
       "\n",
       "assumption we make in n-gram LMs: The probability of the next word only depends on the previous n-1 words.\n",
       "\n",
       "Neural LM advantages over n-gram LMs:\n",
       "\n",
       "1. They don’t need smoothing\n",
       "\n",
       "2. They can handle much longer histories.\n",
       "\n",
       "3. They can generalize over contexts of similar words.\n",
       "\n",
       "4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\n",
       "\n",
       "Disadvantage: slower to train\n",
       "\n",
       "Advantages of NN LMs: Better results, larger N, generalize across context. A by-product is word embeddings.\n",
       "\n",
       "Word2Vec: Learn embeddings as part of the process of word prediction. Train a classifier to predict neighboring words\n",
       "\n",
       "Skip-gram algorithm:\n",
       "\n",
       "1. Treat the target word and a neighboring context\n",
       "word as positive examples.\n",
       "\n",
       "2. Randomly sample other words in the lexicon to get\n",
       "negative samples\n",
       "\n",
       "3. Use logistic regression to train a classifier to\n",
       "distinguish those two cases\n",
       "\n",
       "4. Use the weights as the embeddings\n",
       "\n",
       "$P(+|t,c)=\\frac{1}{1+e^{-t\\codt c}}$\n",
       "\n",
       "get embeddings from word2vec!\n",
       "\n",
       "It starts with an initial set of embedding vectors and then iteratively shifts\n",
       "the embedding of each word w to be more like the embeddings of words\n",
       "that occur nearby in texts, and less like the embeddings of words that\n",
       "don’t occur nearby. \n",
       "\n",
       "\n",
       "## SLP Chapter 9.2 Recurrent Neural Networks\n",
       "Choosing noise words:\n",
       "More common to chose them according to $p_{\\alpha}(w)=\\frac{count(w)^\\alpha}{\\sum_w count(w)^\\alpha}$\n",
       "\n",
       "$\\alpha=3/4$ works well because it gives rare noise words slightly higher probability\n",
       "\n",
       "Evaluating embeddings: Compare to human scores on word similarity-type tasks\n",
       "\n",
       "Solving analogies with embeddings: Vector Arithmetic\n",
       "\n",
       "a:a∗ as b:b∗. b∗ is a hidden vector. b∗ should be similar to the vector b − a + a∗\n",
       "\n",
       "If all word-vectors are normalized to unit length then optimize: $argmax_{b^*\\in V}(cos(b^*,b-a+a^*))$\n",
       "\n",
       "alternatively, we can require that the direction of the transformation be maintained: $argmax_{b^*\\in V}(cos(b^*-b,a^*-a))$\n",
       "\n",
       "Embeddings reflect cultural bias and can be used for studying language change\n",
       "\n",
       "Directions: Debiasing algorithms for embeddings and Use embeddings as a tool to study historical bias\n",
       "\n",
       "Embeddings = vector models of meaning\n",
       "\n",
       "• More fine-grained than just a string or index\n",
       "\n",
       "• Especially good at modeling similarity/analogy\n",
       "\n",
       "• Just download them and use cosines!!\n",
       "\n",
       "• Can use sparse models (tf-idf) or dense models (word2vec, GLoVE)\n",
       "\n",
       "• Useful in practice but know they encode cultural stereotypes\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "## SLP Chapter 9.3 RNNs as Language Models\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.1 Lexical Semantics\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.2 Vector Semantics\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.3 Words and Vectors\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.4 Cosine for measuring similarity\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.8 Word2vec\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.10 Semantic properties of embeddings\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.11 Bias and Embeddings\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.12 Evaluating Vector Models\n",
       " Your summary here \n",
       "\n",
       "## Module 13 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 14 Definitions\n",
       "* **Concept** - definition\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#@title Preview of your summary\n",
    "#@markdown You don't need to modify anything in this cell. Just press play.\n",
    "module14_sections = [\n",
    "  (\"SLP Chapter 9.1 Language Models Revisited\", slp_chapter9_1),\n",
    "  (\"SLP Chapter 9.2 Recurrent Neural Networks\", slp_chapter9_2),\n",
    "  (\"SLP Chapter 9.3 RNNs as Language Models\", slp_chapter9_3),\n",
    "\n",
    "  (\"SLP Chapter 6.1 Lexical Semantics\", slp_chapter6_1),\n",
    "  (\"SLP Chapter 6.2 Vector Semantics\", slp_chapter6_2),\n",
    "  (\"SLP Chapter 6.3 Words and Vectors\", slp_chapter6_3),\n",
    "  (\"SLP Chapter 6.4 Cosine for measuring similarity\", slp_chapter6_4),\n",
    "  (\"SLP Chapter 6.8 Word2vec\", slp_chapter6_8),\n",
    "  (\"SLP Chapter 6.10 Semantic properties of embeddings\", slp_chapter6_10),\n",
    "  (\"SLP Chapter 6.11 Bias and Embeddings\", slp_chapter6_11),\n",
    "  (\"SLP Chapter 6.12 Evaluating Vector Models\", slp_chapter6_12),\n",
    "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
    "]\n",
    "\n",
    "module14_markdown = format_module(14, \"Natural Language Processing\", \n",
    "                         module14_sections, \n",
    "                         module14_definitions)\n",
    "display(Markdown(module14_markdown))"
   ]
  },
  {
   "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",
   "execution_count": 73,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "T3cm1WV542_a",
    "outputId": "573f4953-385d-4ade-fe6f-a6dc29805154"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 8: Markov Decision Processes\n",
       "## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n",
       "Transitions are Markovian: the probability of arriving in s’ only depends on s and not the history of earlier states.\n",
       "\n",
       "Instead of only giving a reward at the goal states, the agent can **receive a reward at each time step**, based on its transition from **s** to **s’** via action **a**.\n",
       "\n",
       "A Markov decision process or MDP is\n",
       "\n",
       "• a sequential decision problem\n",
       "\n",
       "• for a fully observable environment\n",
       "\n",
       "• with a stochastic transition model\n",
       "\n",
       "• that has additive rewards\n",
       "\n",
       "MDPs are non-deterministic search problems. One way of solving them is via expectimax search.\n",
       "\n",
       "To find a solution to an MDP, you need to define the following things: A set of states s, A set of actions a, A transition function T(s, a, s’),\n",
       " A reward function R(s, a, s’), An initial state s0, Optionally, one or more terminal states\n",
       "\n",
       "game lasts forever solution: Finite horizon: (similar to depth-limited search), Discounting\n",
       "\n",
       "\n",
       " $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n",
       "\n",
       "## AIMA Chapter 16.2 The Basis of Utility Theory\n",
       "$$V^*(s)=max_a Q^*(s,a)$$\n",
       "\n",
       "$$Q^*(s,a)=\\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^*(s')]$$\n",
       "\n",
       "$$V^*(s)=max_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^*(s')]$$\n",
       "\n",
       "Value iteration: $$V_{k+1}(s)\\leftarrow max_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V_k(s')]$$\n",
       "\n",
       "Complexity of each iteration: O(S^2A)\n",
       "\n",
       "fixed policy recursive relation(one-step look-ahead / Bellman equation): $$V^{\\pi}(s)=\\sum_{s'}T(s,\\pi(s),s')[R(s,\\pi(s),s')+\\gamma V^{\\pi}(s')]$$\n",
       "\n",
       "actions are easier to select from q-values than values!\n",
       "\n",
       "Problems with Value Iteration: : It’s slow – O(S2A) per iteration, The “max” at each state rarely change, The policy often converges long before the values\n",
       "\n",
       "Policy Iteration: \n",
       "Policy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence\n",
       "\n",
       "$$V_{k+1}^{\\pi_i}(s)\\leftarrow \\sum_{s'}T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s')+\\gamma V_k^{\\pi_i}(s')]$$\n",
       "\n",
       "Policy improvement: update policy using one-step lookahead with resulting converged utilities as future values\n",
       "\n",
       "$$\\pi_{i+1}(s)= argmax_a \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma V^{\\pi_i}(s')]$$\n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 16.3 Utility Functions\n",
       "Comparison: \n",
       "\n",
       "In value iteration:\n",
       "\n",
       "• Every iteration updates both the values and (implicitly) the policy\n",
       "\n",
       "• We don’t track the policy, but taking the max over actions implicitly recomputes it\n",
       "\n",
       "\n",
       "In policy iteration:\n",
       "\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",
       "\n",
       "• After the policy is evaluated, a new policy is chosen (slow like a value iteration pass)\n",
       "\n",
       "• The new policy will be better (or we’re done)\n",
       "\n",
       "Both are dynamic programs for solving MDPs\n",
       "\n",
       "preference: $$A\\succ B$$\n",
       "\n",
       "indifference: $$A\\sim B$$\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 17.1 Sequential Decision Problems\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 17.2 Algorithms for MDPs\n",
       " Your summary here \n",
       "\n",
       "## Module 8 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 8 Definitions\n",
       "* **Utility function** - Your definition here\n",
       "* **Expected utility** - your definition here\n",
       "* **The model** - Probability that executing action a in s will lead to s’ P(s’ | s, a)\n",
       "* **Absorbing state** - guarantee that for every policy, a terminal state will eventually be reached\n",
       "* **Utility** - sum of (discounted) rewards\n",
       "* **Policy** - Choice of action for each state\n",
       "* **The value (utility) of a state s** - V*(s) = expected utility starting in s and acting optimally\n",
       "* **The value (utility) of a q-state (s,a)** - Q*(s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally\n",
       "* **The optimal policy** - pi*(s) = optimal action from state s\n",
       "* **Lotteries** - situations with uncertain prizes\n",
       "* **Orderability** - $$(A\\succ B)\\vee (B\\succ A) \\vee (A\\sim B)$$\n",
       "* **Transitivity** - $$(A\\succ B)\\wedge (B\\succ C) \\Rightarrow (A\\succ C)$$\n",
       "* **Continuity** - $$ A\\succ B \\succ C \\Rightarrow \\exists p [p,A; 1-p,C] \\sim B)$$\n",
       "* **Substitutability** - $$A\\sim B \\Rightarrow [p,A; 1-p,C] \\sim [p,B; 1-p,C]$$\n",
       "* **Monotonicity** - $$A\\succ B \\Rightarrow (p\\ge q \\Leftrightarrow [p,A; 1-p,B] \\succeq [q,A; 1-q,B])$$\n",
       "\n",
       "\n",
       "# Module 9: Reinforcement Learning\n",
       "## AIMA Chapter 17.3 Bandit Problems\n",
       " Reinforcement learning(online): don’t know T or R. we don’t know which states are good or what the actions do Must actually try actions and states out to learn\n",
       "\n",
       "Model-Based Idea: Learn an approximate model based on experiences Solve for values as if the learned model were correct\n",
       "\n",
       "**passive RL**: \n",
       "Input: a fixed policy π(s), no transitions T and rewards R\n",
       "\n",
       "Goal: learn the state values\n",
       "\n",
       "In this case:\n",
       " \n",
       "Learner is “along for the ride”\n",
       "\n",
       "No choice about what actions to take\n",
       "\n",
       "Just execute the policy and learn from experience\n",
       "\n",
       "\n",
       "Direct Evaluation(model free): Compute values for each state under π, Average together observed sample values\n",
       "\n",
       "problems: wastes information about state connections, Each state must be learned separately. so it takes a long time to learn\n",
       "\n",
       "Sample-Based Policy Evaluation: Take samples of outcomes s’ (by doing the action!) and average\n",
       "\n",
       "Temporal Difference Learning: learn from every experience\n",
       "\n",
       "Sample of V(s): $sample=R(s,\\pi(s),s')+\\gamma V^{\\pi}(s')$ \n",
       "\n",
       "Update to V(s): $ V^{\\pi}(s) \\leftarrow (1- \\alpha )V^{\\pi}(s)+( \\alpha )sample $ \n",
       "\n",
       "Exponential moving average: Makes recent samples more important and Forgets about the past:\n",
       "\n",
       "$$\\overline{x}_n=\\frac{x_n+(1-\\alpha)x_{n-1}+(1-\\alpha)^2x_{n-2}+...}{1+(1-\\alpha)+(1-\\alpha)^2+...}$$\n",
       "**TD value leaning** is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages\n",
       "\n",
       "problem: can't turn values into a new policy\n",
       "\n",
       "**Full reinforcement learning**: optimal policies\n",
       "\n",
       "no transitions T and rewards R\n",
       "\n",
       "You choose the actions now\n",
       "\n",
       "Goal: learn the optimal policy / values\n",
       "\n",
       "In this case:\n",
       "\n",
       "Learner makes choices!\n",
       "\n",
       "Fundamental tradeoff: exploration vs. exploitation\n",
       "\n",
       "This is NOT offline planning! You actually take actions in the world and find out what happens...\n",
       "\n",
       "sample-based Q-value iteration: $Q_{k+1}(s,a)\\leftarrow \\sum_{s'}T(s,a,s')[R(s,a,s')+\\gamma max_{a'}Q_k(s',a')]$\n",
       "\n",
       "This is called off-policy learning\n",
       "\n",
       "Caveats: explore enough, eventually make the learning rate small enough but not decrease it too quickly\n",
       "\n",
       "Several schemes for forcing exploration: random actions (ε-greedy)\n",
       "\n",
       "problem: keep thrashing around once learning is done.\n",
       "\n",
       "solution: lower ε over time, exploration function(explore areas whose badness is not (yet) established, eventually stop exploring)\n",
       "\n",
       "Takes a value estimate u and a visit count n, and returns an optimistic utility: $f(u,n)=u+k/n$\n",
       "\n",
       "$Q(s,a)\\leftarrow_{\\alpha} R(s,a,s')+\\gamma max_{a'}f(Q(s',a'),N(s',a'))$\n",
       "\n",
       "this propagates the “bonus” back to states that lead to unknown states as well!\n",
       "\n",
       "\n",
       "## AIMA Chapter 22.1 Learning from Rewards\n",
       "\n",
       "In realistic situations, we cannot possibly learn about every single state!\n",
       "\n",
       "**Evaluation functions** score non-terminals in depth-limited search\n",
       "\n",
       "Ideal function: returns the actual minimax value of the position\n",
       "\n",
       "In practice: typically weighted linear sum of features\n",
       "\n",
       "**Linear Value Functions:** Using a feature representation, we can write a q function (or value function) for any state using a few weightsUsing a feature representation,\n",
       "we can write a q function (or value function) for any state using a few weights\n",
       "\n",
       "Advantage: our experience is summed up in a few powerful numbers\n",
       "\n",
       "Disadvantage: states may share features but actually be very different in value!\n",
       "\n",
       "Q-learning with linear Q-functions:\n",
       "\n",
       "difference=$[r+\\gamma max_{a'}Q(s',a')]-Q(s,a)$\n",
       "\n",
       "$Q(s,a)\\leftarrow Q(s,a)+\\alpha[difference]$\n",
       "\n",
       "$w_i\\leftarrow w_i + \\alpha[difference]f_i(s,a)$\n",
       "\n",
       "Minimizing regret goes beyond learning to be optimal – it requires optimally learning to be optimal\n",
       "\n",
       "Example: random exploration and exploration functions both end up optimal, but random exploration has higher **regret**\n",
       "\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",
       " Your summary here \n",
       "\n",
       "## Module 9 Definitions\n",
       "* **Regret** - Regret is a measure of your total mistake cost. the difference between your (expected) rewards, including youthful suboptimality, and optimal (expected) rewards\n",
       "\n",
       "\n",
       "# Module 10: Probabilies and Language Models\n",
       "## AIMA Chapter 12.1 Acting under Uncertainty\n",
       " Probabilistic models: A probabilistic model is a joint distribution over a set of random variables\n",
       "\n",
       "(Random) variables with domains\n",
       "\n",
       "Assignments are called outcomes\n",
       "\n",
       "Joint distributions: say whether assignments (outcomes) are likely\n",
       "\n",
       "Normalized: sum to 1.0\n",
       "\n",
       "Ideally: only certain variables directly interact\n",
       "An event is a set E of outcomes $P(E)=\\sum_{(x_1...x_n)\\in E}P(x_1...x_n)$\n",
       "\n",
       "Conditional Probabilities: $P(a|b)=\\frac{P(a,b)}{P(b)}$\n",
       "\n",
       "Probabilistic inference: compute a desired probability from other known probabilities (e.g. conditional from joint)\n",
       "\n",
       "chain rule: $P(x_1,x_2,...x_n)=\\prod_i P(x_i|x_1...x_{i-1})$\n",
       "Bayes' Rule: $P(x,y)=P(x|y)P(y)=P(y|x)P(x)$\n",
       "\n",
       "Goal of language model:  compute the probability of a sentence or sequence of words or an upcoming word\n",
       "\n",
       "Simplifying Assumption = Markov Assumption: Only depends on the previous k words, not the whole context\n",
       "\n",
       "N-grams models: insufficient because language has long-distance dependencies\n",
       "\n",
       "Estimating bigram probabilities: $P(w_i|w_{i-1})=\\frac{c(w_{i-1},w_i)}{c(w_{i-1})}$\n",
       "\n",
       "Problems for MLE: Out of vocabulary items (OOV)\n",
       "\n",
       "Avoid zeros with smoothing\n",
       "\n",
       "If a process is **stationary**, it means that the conditional probability table does not change over time\n",
       "\n",
       "n-gram language models typically evaluated by Perplexity on a test set\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 12.2 Basic Probability Notation\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.4 Independence\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.6 Naive Bayes Models\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 12.7 The Wumpus World Revisited\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.1 N-Grams\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.2 Evaluating Language Models\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.3 Sampling sentences from a language model\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.4 Generalization and Zeros\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.5 Smoothing\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n",
       " Your summary here \n",
       "\n",
       "## Module 10 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 10 Definitions\n",
       "* **Observed variables (evidence)** - Agent knows certain things about the state of the world\n",
       "* **Unobserved variables (states)** - Agent needs to reason about other aspects\n",
       "* **Model** - Agent knows something about how the known variables relate to the unknown variables\n",
       "\n",
       "\n",
       "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n",
       "## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n",
       "Indepenence: $X{\\perp\\!\\!\\!\\perp}Y$.\n",
       "\n",
       "$\\forall x,y:P(x,y)=P(x)P(y)$\n",
       "\n",
       "Conditional indenpendence: \n",
       "$X{\\perp\\!\\!\\!\\perp}Y|Z$\n",
       "\n",
       "iff $\\forall x,y,z :P(x,y|z)=P(x|z)P(y|z)$ or $P(x|z,y)=P(z|z)$\n",
       "\n",
       "Two problems with using full joint distribution tables as our probabilistic models:\n",
       "\n",
       "Unless there are only a few variables, the joint is WAY too big to represent explicitly. Hard to learn (estimate) anything empirically about more than a few variables at a time\n",
       "\n",
       "A Bayes net = Topology (graph) + Local Conditional Probabilities\n",
       "\n",
       "active trail (Variables connected by active trails are not conditionally independent):\n",
       "\n",
       "If $X_i$ is not observed, $X_{i-1}\\rightarrow X_i \\rightarrow X_{i+1}$, $X_{i-1}\\leftarrow X_i \\rightarrow X_{i+1}$\n",
       "\n",
       "If $X_i$ is observed or one of its descendants is observed: $X_{i-1}\\rightarrow X_i \\leftarrow X_{i+1}$\n",
       "\n",
       "BNs need not actually be causal\n",
       "\n",
       "Topology may happen to encode causal structure but really encodes conditional independence\n",
       "\n",
       "joint distribution over N Boolean variables: $2^N$\n",
       "\n",
       "an N-node net if nodes have up to k parents: $O(N*2^{k+1})$ Huge space savings\n",
       "\n",
       "Bayes Nets Representation Summary:\n",
       "\n",
       "§ Bayes nets compactly encode joint distributions\n",
       "\n",
       "§ Guaranteed independencies of distributions can be deduced from BN graph structure\n",
       "\n",
       "§ D-separation gives precise conditional independence guarantees from graph alone\n",
       "\n",
       "§ A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\n",
       "\n",
       "Inference: calculating some useful quantity from a joint probability distribution\n",
       "\n",
       "Why is inference by enumeration so slow? You join up the whole joint distribution before you sum out the hidden variables\n",
       "\n",
       "Variable Elimination: Interleave joining and marginalizing. do the calculation once and save the results for later use\n",
       "\n",
       "\n",
       "\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",
       " Your summary here \n",
       "\n",
       "## Module 11 Definitions\n",
       "* **Concept** - definition\n",
       "\n",
       "\n",
       "# Module 12: Naive Bayes and Perceptrons\n",
       "## AIMA Chapter 5.1 Game Theory\n",
       "Naïve Bayes: Assume all features are independent effects of the label $P(X_1,X_2,X_3,Y)=P(Y)P(X_1|Y)P(X_2|Y)P(X_3|Y)$\n",
       "\n",
       "In a bag-of-words model\n",
       "• Each position is identically distributed\n",
       "\n",
       "• All positions share the same conditional probs P(W|Y)\n",
       "\n",
       "• Called “bag-of-words” because model is insensitive to word order or reordering\n",
       "\n",
       "Relative frequency parameters will overfit the training data! Unlikely that every occurrence of “minute” is 100% spam\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\n",
       "\n",
       "$P_{LAP,k}(x)=\\frac{c(x)+k}{N+k|X|}$ k is the strength of the prior\n",
       "\n",
       "The naïve Bayes assumption takes all features to be independent given the class label\n",
       "\n",
       "Naïve Bayes models can incorporate a variety of features, but tend to do best in homogeneous cases\n",
       "\n",
       "Binary Perceptron： If wrong: adjust the weight vector by adding or subtracting the feature vector：$w=w+y^*\\cdot f$\n",
       "\n",
       "Multiclass Decision Rule: $y=argmax_y w_y\\cdot f(x)$\n",
       "\n",
       "If wrong: lower score of wrong answer, raise score of right answer\n",
       "\n",
       "Separability: true if some parameters get the training set perfectly correct\n",
       "\n",
       "Convergence: if the training is separable, perceptron will eventually converge (binary case)\n",
       "\n",
       "Mistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\n",
       "\n",
       "Problems with the Perceptron:\n",
       "\n",
       "Noise: if the data isn’t separable, weights might thrash. Averaging weight vectors over time can help (averaged perceptron)\n",
       "\n",
       "Mediocre generalization: finds a “barely” separating solution\n",
       "\n",
       "Overtraining: test / held-out accuracy usually rises, then falls(kind of overfitting)\n",
       "\n",
       "Fixing the Perceptron: adjust the weight update to mitigate these effects\n",
       "\n",
       "MIRA: choose an update size that fixes the current mistake but, minimizes the change to w\n",
       "\n",
       "Minimum Correcting Update： $\\tau=\\frac{(w'_y-w'_{y^*})\\cdot f+1}{2f\\cdot f}$\n",
       "\n",
       "Maximum Step Size: cap the maximum possible value of t with some constant C: $\\tau^*=min(\\tau,C)$\n",
       "\n",
       "Support Vector Machines: Maximizing the margin, Only support vectors matter\n",
       "\n",
       "Basically, SVMs are MIRA where you optimize over all examples at once\n",
       "Naïve Bayes:\n",
       "\n",
       "• Builds a model training data\n",
       "\n",
       "• Gives prediction probabilities\n",
       "\n",
       "• Strong assumptions about feature independence\n",
       "\n",
       "• One pass through data (counting)\n",
       "\n",
       "Perceptrons / MIRA:\n",
       "\n",
       "• Makes less assumptions about data\n",
       "\n",
       "• Mistake-driven learning\n",
       "\n",
       "• Multiple passes through data (prediction)\n",
       "\n",
       "• Often more accurate\n",
       "\n",
       "Two notational changes simplify the way that perceptrons are described: replace the weighted sum as a dot product and move the threshold to the other side of\n",
       "the inequality, and to replace it by a bias\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 5.2 Optimal Decisions in Games\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 5.5 Stochastic Games\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n",
       " Your summary here \n",
       "\n",
       "## AIMA Chapter 16.2 The Basis of Utility Theory\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.1 Naive Bayes Classifiers\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.2 Training the Naive Bayes Classifier\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.3 Worked Example\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.6 Naive Bayes as a Language Model\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.8 Test sets and Cross-validation\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.9 Statistical Significance Testing\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 4.10 Avoiding Harms in Classification\n",
       " Your summary here \n",
       "\n",
       "## Module 12 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 12 Definitions\n",
       "* **Concept** - definition\n",
       "\n",
       "\n",
       "# Module 13: Neural Networks\n",
       "## SLP Chapter 5.1 Classification: the sigmoid\n",
       "Classifier components: feature representation of the input\n",
       "\n",
       "classification function that computes the estimated class $\\hat{y}$ via p(y|x)\n",
       "\n",
       "objective function for learning, usually involving minimizing error on training examples.\n",
       "\n",
       "An algorithm for optimizing the objective function.\n",
       "\n",
       "sigmoid: $y=\\frac{1}{1+e^{-z}}$\n",
       "\n",
       "Loss functions for probabilistic classification: $p(y|x)=\\hat{y}^y(1-\\hat{y})^{1-y}$\n",
       "\n",
       "call the log and flip the sign(to minimize), The result is cross-entropy loss:\n",
       " \n",
       "$L_{CE}(\\hat{y},y)=-\\log p(y|x)=-[y\\log \\hat{y}+(1-y)\\log(1-\\hat{y})]$\n",
       "\n",
       "**Gradient descent** is a method that finds a minimum of a function by figuring out in which direction (in the space of the parameters θ) the function’s slope is rising the most steeply, and moving in the opposite direction.\n",
       "\n",
       "The gradient for multiple data points is the sum of the individual gradients\n",
       "\n",
       "**Stochastic gradient descent** chooses a single random example at a time and updates its weights on that example. As a result the updates can fluctuate.\n",
       "\n",
       "An alternate is batch training, which computes the gradient over the entire dataset.\n",
       "\n",
       "A commonly used compromise is mini-batch training, where we train on a small batch.\n",
       "\n",
       "Regularization is a way to penalize large weights. A regularization term is added to the loss function.\n",
       "\n",
       "logistic vs perceptron: sigmoid vs step function\n",
       "\n",
       "Smoothness of σ means that small changes in the weights wj and in the bias b will produce a small change the output from the neuron\n",
       "\n",
       "Training Neural Nets: \n",
       "\n",
       "A loss function – cross-entropy loss\n",
       "\n",
       "An optimization algorithm – gradient descent\n",
       "\n",
       "A way of computing the gradient of the loss function – error propagation\n",
       "\n",
       "multinomial classification cross-entropy loss: $L_{CE}(\\hat{y},y)=-\\sum^C_{i=1}y_i \\log \\hat{y_i}$\n",
       "\n",
       "Although backpropagation was invented for neural nets, it is related to general procedure called backward differentiation, which depends on the notion of computation graphs.\n",
       "\n",
       "Chain rule: $\\frac{df}{dx}=\\frac{du}{dv}\\cdot \\frac{dv}{dx}$\n",
       "\n",
       "\n",
       "## SLP Chapter 5.2 Learning in Logistic Regression\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 5.3 The cross-entropy loss function\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 5.4 Gradient Descent\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 5.5 Regularization\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 5.6 Multinomial logistic regression\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.1 Units\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.2 The XOR problem\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.3 Feedforward Neural Networks\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.5 Feedforward Neural Language Modeling\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.6 Training Neural Nets\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 7.7 Training the neural language model\n",
       " Your summary here \n",
       "\n",
       "## Module 13 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 13 Definitions\n",
       "* **Concept** - definition\n",
       "\n",
       "\n",
       "# Module 14: Natural Language Processing\n",
       "## SLP Chapter 9.1 Language Models Revisited\n",
       " Ideally, we want a meaning representation to encode:\n",
       "\n",
       "Synonyms – words that have similar meanings\n",
       "\n",
       "Antonyms – words that have opposite meanings\n",
       "\n",
       "Connotations – words that are positive or negative\n",
       "\n",
       "Semantic Roles – buy, sell, and pay are different parts of the same underlying purchasing event\n",
       "\n",
       "Support for entailment\n",
       "\n",
       "Distributional Hypothesis: Two words are similar if they have similar word contexts.\n",
       "\n",
       "TF-IDF = Term frequency(how often a word occurred in a document) * inverse document frequency(1 over the number of documents that it occurred in)\n",
       "\n",
       "Co-occurrence matrix is Long and Sparse. We want to learn verctors that are Short and Dense\n",
       "\n",
       "LM: Goal: Learn a function that returns the joint probability\n",
       "\n",
       "Difficulty: There are too many parameters to accurately estimate. This is sometimes called the “curse of dimensionality”\n",
       "\n",
       "In n-gram-based models we fail to generalize to related words / word sequences that we have observed.\n",
       "\n",
       "assumption we make in n-gram LMs: The probability of the next word only depends on the previous n-1 words.\n",
       "\n",
       "Neural LM advantages over n-gram LMs:\n",
       "\n",
       "1. They don’t need smoothing\n",
       "\n",
       "2. They can handle much longer histories.\n",
       "\n",
       "3. They can generalize over contexts of similar words.\n",
       "\n",
       "4. Neural LMs tend to have much higher predictive accuracy than n-gram LMs.\n",
       "\n",
       "Disadvantage: slower to train\n",
       "\n",
       "Advantages of NN LMs: Better results, larger N, generalize across context. A by-product is word embeddings.\n",
       "\n",
       "Word2Vec: Learn embeddings as part of the process of word prediction. Train a classifier to predict neighboring words\n",
       "\n",
       "Skip-gram algorithm:\n",
       "\n",
       "1. Treat the target word and a neighboring context\n",
       "word as positive examples.\n",
       "\n",
       "2. Randomly sample other words in the lexicon to get\n",
       "negative samples\n",
       "\n",
       "3. Use logistic regression to train a classifier to\n",
       "distinguish those two cases\n",
       "\n",
       "4. Use the weights as the embeddings\n",
       "\n",
       "$P(+|t,c)=\\frac{1}{1+e^{-t\\codt c}}$\n",
       "\n",
       "get embeddings from word2vec!\n",
       "\n",
       "It starts with an initial set of embedding vectors and then iteratively shifts\n",
       "the embedding of each word w to be more like the embeddings of words\n",
       "that occur nearby in texts, and less like the embeddings of words that\n",
       "don’t occur nearby. \n",
       "\n",
       "\n",
       "## SLP Chapter 9.2 Recurrent Neural Networks\n",
       "Choosing noise words:\n",
       "More common to chose them according to $p_{\\alpha}(w)=\\frac{count(w)^\\alpha}{\\sum_w count(w)^\\alpha}$\n",
       "\n",
       "$\\alpha=3/4$ works well because it gives rare noise words slightly higher probability\n",
       "\n",
       "Evaluating embeddings: Compare to human scores on word similarity-type tasks\n",
       "\n",
       "Solving analogies with embeddings: Vector Arithmetic\n",
       "\n",
       "a:a∗ as b:b∗. b∗ is a hidden vector. b∗ should be similar to the vector b − a + a∗\n",
       "\n",
       "If all word-vectors are normalized to unit length then optimize: $argmax_{b^*\\in V}(cos(b^*,b-a+a^*))$\n",
       "\n",
       "alternatively, we can require that the direction of the transformation be maintained: $argmax_{b^*\\in V}(cos(b^*-b,a^*-a))$\n",
       "\n",
       "Embeddings reflect cultural bias and can be used for studying language change\n",
       "\n",
       "Directions: Debiasing algorithms for embeddings and Use embeddings as a tool to study historical bias\n",
       "\n",
       "Embeddings = vector models of meaning\n",
       "\n",
       "• More fine-grained than just a string or index\n",
       "\n",
       "• Especially good at modeling similarity/analogy\n",
       "\n",
       "• Just download them and use cosines!!\n",
       "\n",
       "• Can use sparse models (tf-idf) or dense models (word2vec, GLoVE)\n",
       "\n",
       "• Useful in practice but know they encode cultural stereotypes\n",
       "\n",
       "\n",
       "\n",
       "\n",
       "## SLP Chapter 9.3 RNNs as Language Models\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.1 Lexical Semantics\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.2 Vector Semantics\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.3 Words and Vectors\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.4 Cosine for measuring similarity\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.8 Word2vec\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.10 Semantic properties of embeddings\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.11 Bias and Embeddings\n",
       " Your summary here \n",
       "\n",
       "## SLP Chapter 6.12 Evaluating Vector Models\n",
       " Your summary here \n",
       "\n",
       "## Module 13 Lecture Notes\n",
       " Your summary here \n",
       "\n",
       "## Module 14 Definitions\n",
       "* **Concept** - definition\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 392476 characters]\n",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {
      "image/png": {
       "height": 200,
       "width": 300
      }
     },
     "output_type": "display_data"
    }
   ],
   "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))\n",
    "display(Image('./Burglar_belief_net.png',width=300, height=200))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "Template_for CIS521_midterm_2_notes.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
