{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Ana_Machaidze_CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "e34266b3-6434-424d-8c13-486f7dcae3ff"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": 36,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "e957c1e7-00b4-4b43-841f-82af1dafaf39"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": 38,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "chapter16_1 = \"\"\" utility function, U(s) assigns a single number to express the desirability of a state.\n",
        "\n",
        "The expected utility of an action given the evidence, EU(a) , is average utility value of the outcomes, weighted by the probability that the outcome occurs. \n",
        "\n",
        "The principle of maximum expected utility (MEU) says that a rational agent should choose the action that maximizes the agent’s expected utility \n",
        "Intelligent agents can’t use the MEU principle right away. It requires perception, learning, knowledge representation, and inference. \n",
        "If an agent acts so as to maximize a utility function that correctly reflects the performance measure, then the agent will achieve the highest possible performance score (averaged over all the possible environments) \n",
        " \"\"\"\n",
        "chapter16_2 =  \"\"\" MEU is not the only rational way to make decisions\n",
        "\n",
        "We use the following notation to describe an agent’s preferences: \n",
        "A > B: Prefers A over B \n",
        "A ~ B: Indifferent \n",
        "\n",
        "We can think of the set of outcomes for each action as a lottery \n",
        "L = [p1,S1; p2,S2; ..pnSn] \n",
        "\n",
        "ORDERABILITY: Given any two lotteries, a rational agent must either prefer one or else rate them as equally preferable. That is, the agent cannot avoid deciding \n",
        "TRANSITIVITY: (A > B) ∧ (B > C) ⇒ (A > C) \n",
        "CONTINUITY: If some lottery B is between A  and C in preference, then there is some probability p for which the rational agent will be indifferent between getting B for sure \n",
        "and the lottery that yields A with probability p and C with probability 1-p. \n",
        "\n",
        "SUBSTITUTABILITY: If an agent is indifferent between two lotteries A and B, then the agent is indifferent between two more complex lotteries that are the same \n",
        "except that B is substituted forA  in one of them. This holds regardless of the probabilities and the other outcome(s) in the lotteries \n",
        "\n",
        "MONOTONICITY: Suppose two lotteries have the same two possible outcomes, A and B. If an agent prefers A to B, then the agent must prefer the lottery\n",
        " that has a higher probability for A (and vice versa). \n",
        "\n",
        "DECOMPOSABILITY: Compound lotteries can be reduced to simpler ones using the laws of probability. This has been called the “no fun in gambling” rule. \n",
        "The agent has a utility function and we can compute the expected utility of a lottery. The utility function derived in his way is known as a von Neumann-Morgenstern utility function \n",
        "\n",
        "EXISTENCE OF UTILITY FUNCTION: If an agent’s preferences obey the axioms of utility, then there exists a function U such that U(A) > U(B) if and only if A is preferred to B ,\n",
        " U(A) = U(B) and if and only if the agent is indifferent between A and B. \n",
        "\n",
        "EXPECTED UTILITY OF A LOTTERY: The utility of a lottery is the sum of the probability of each outcome times the utility of that outcome \n",
        "\n",
        "agent’s behavior would not change if its utility function were transformed linearly \n",
        "As in game-playing, in a deterministic environment an agent needs only a preference ranking on states—the numbers don’t matter. This is called a value function or ordinal utility function. \n",
        "\n",
        " \"\"\"\n",
        "chapter16_3 =  \"\"\" \n",
        "preference elicitation, involves presenting choices to the human and using the observed preferences to pin down the underlying utility function\n",
        "Normalized utilities uses 1 as best outcome and 0 as worst \n",
        "\n",
        "Micromort - price for a one in a million chance of death \n",
        "\n",
        "QALY - quality-adjusted life year \n",
        "\n",
        "It will usually be the case that an agent prefers more money to less, all other things being equal. We say that the agent exhibits a\n",
        " monotonic preference for more money. This does not mean that money behaves as a utility function, because it says nothing about preferences between lotteries involving money. \n",
        "\n",
        "In a pioneering study of actual utility functions, Grayson (1960) found that the utility of money was almost exactly proportional to the logarithm of the amount \n",
        "\n",
        "Risk-averse: prefers sure thing \n",
        "Risk-seeking: otherwise \n",
        "The value an agent will accept in lieu of a lottery is called the certainty equivalent of the lottery. \n",
        "An agent that has a linear curve is said to be risk-neutral \n",
        "\n",
        "\n",
        "The rational way to choose the best action, , is to maximize expected utility. \n",
        "This tendency for the estimated expected utility of the best choice to be too high is called the optimizer’s curse \n",
        "\n",
        "\n",
        "This tendency for the estimated expected utility of the best choice to be too high is called the optimizer’s curse \n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\" Environment is fully observable \n",
        "\n",
        "We will assume that transitions are Markovian: the probability of reaching s’ from s depends only on s and not on the history of earlier states. \n",
        "For every action agent receives reward R(s, a, s’) \n",
        "a sequential decision problem for a fully observable, stochastic environment with a Markovian transition model and additive rewards is called a Markov \n",
        "decision process, or MDP, and consists of a set of states (with an initial state s0); a set ACTIONS(s) of actions in each state; a transition model P(s’ | s, a) ;\n",
        " and a reward function R. Methods for solving MDPs usually involve dynamic programming: simplifying a problem by recursively breaking it into smaller\n",
        "  pieces and remembering the optimal solutions to the pieces. \n",
        "\n",
        "Therefore, a solution must specify what the agent should do for any state that the agent might reach. A solution of this kind is called a policy. pi(s) - policy for state s \n",
        " \n",
        "An optimal policy pi* is a policy that yields the highest expected utility. \n",
        "\n",
        "The first question to answer is whether there is a finite horizon or an infinite horizon for decision making.\n",
        "\n",
        " A finite horizon means that there is a fixed time after which nothing matters—the game is over, so to speak \n",
        "\n",
        "Left. So, with a finite horizon, an optimal action in a given state may depend on how much time is left.\n",
        " A policy that depends on the time is called nonstationary. \n",
        "\n",
        "Hence, an optimal action depends only on the current state, and the optimal policy is stationary. Policies for the infinite-horizon case are therefore simpler than those for the finite-horizon case. \n",
        "\n",
        "we will additive discounted rewards: the utility of a history is where the discount factor is a number between 0 and 1. The discount factor describes\n",
        " the preference of an agent for current rewards over future rewards. When y is close to 0, rewards in the distant future are viewed as insignificant. \n",
        " When y is close to 1, an agent is more willing to wait for long-term rewards. \n",
        "\n",
        "When y is exactly 1, discounted rewards reduce to the special case of purely additive rewards. \n",
        "A policy that is guaranteed to reach a terminal state is called a proper policy.  \n",
        "\n",
        "Another important quantity is the action-utility function, or Q-function: is the expected utility of taking a given action in a given state. The Q-function is related to utilities in the obvious way: \n",
        "\n",
        "U(s) = max Q(s,a) \n",
        "pi*(s) = argumax Q(s,a) \n",
        "\n",
        " \"\"\"\n",
        "\n",
        "chapter17_2 =  \"\"\" \n",
        "The Bellman equation is the basis of the value iteration algorithm for solving MDPs. \n",
        "\n",
        "The Bellman equation lets us express the utility of a state recurisvely as the utilities of its neighbors. That is, it lets us express U(s)U(s) in terms of U(s')U(s’ ). \n",
        "We can then use that recursion to do dynamic programming. \n",
        "\n",
        "POLICY EVALUATION: given a policy , calculate , the utility of each state if were to be executed \n",
        "\n",
        "Policy iteration uses dynamic programming. \n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\" \n",
        "Transitions are Markovian: the probability of arriving in s’ only depends on s and not the history of earlier states.\n",
        "\n",
        "utility = reward function for the agent. The “rewards“ can be positive or negative but are bounded by some maximum value. \n",
        "Because the decision process is sequential, we must specify the utility function on a sequence of states and actions.\n",
        "\n",
        "MDP:\n",
        "a sequential decision problem\n",
        "fully observable environment\n",
        " stochastic transition model\n",
        "has additive rewards \n",
        "\n",
        "To define:\n",
        "Set of states\n",
        "Set of actions\n",
        "Transition function (probability = model)\n",
        "Reward function\n",
        "Initial state\n",
        "Terminal states\n",
        "discount\n",
        "\n",
        "MDPs are non-deterministic search problems. One way of solving them is via expectimax search.\n",
        "\n",
        "Solution of MDP is policy. Policy is a function that maps states to actions. pi* is an optimal policy\n",
        "\n",
        "\n",
        "The value (utility) of a state s:\n",
        "V * (s) = expected utility starting in s and acting optimally\n",
        "The value (utility) of a q-state (s,a): \n",
        "Q* (s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally \n",
        "The optimal policy:  * (s) = optimal action from state s \n",
        "\n",
        "Value iteration:\n",
        "\n",
        "Start with V0 (s) = 0: no time steps left means an expected reward sum of zero \n",
        "Given vector of Vk (s) values, do one ply of expectimax from each state.\n",
        "Repeat until convergence \n",
        "\n",
        "The Bellman Equations:\n",
        "Definition of “optimal utility” via expectimax recurrence gives a simple one-step lookahead relationship amongst optimal utility values \n",
        "\n",
        "Value iteration repeats the Bellman updates: \n",
        "Problem 1: It’s slow – O(S2A) per iteration Problem \n",
        "2: The “max” at each state rarely changes Problem\n",
        "3: The policy often converges long before the values \n",
        "\n",
        "Policy Iteration:\n",
        "\n",
        "Step 1: Policy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence\n",
        "Step 2: Policy improvement: update policy using one-step lookahead with resulting converged (but not optimal!) utilities as future values\n",
        "Repeat steps until policy converges\n",
        "\n",
        "• It’s still optimal! \n",
        "• Can converge (much) faster under some conditions\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"Your definition here\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "\"etc.\": \"your definition here\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 39,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 8\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 2236
        },
        "outputId": "3ba0500e-eaf7-419d-9c66-95c26da6fc29"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": 40,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n utility function, U(s) assigns a single number to express the desirability of a state.\n\nThe expected utility of an action given the evidence, EU(a) , is average utility value of the outcomes, weighted by the probability that the outcome occurs. \n\nThe principle of maximum expected utility (MEU) says that a rational agent should choose the action that maximizes the agent’s expected utility \nIntelligent agents can’t use the MEU principle right away. It requires perception, learning, knowledge representation, and inference. \nIf an agent acts so as to maximize a utility function that correctly reflects the performance measure, then the agent will achieve the highest possible performance score (averaged over all the possible environments) \n \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n MEU is not the only rational way to make decisions\n\nWe use the following notation to describe an agent’s preferences: \nA > B: Prefers A over B \nA ~ B: Indifferent \n\nWe can think of the set of outcomes for each action as a lottery \nL = [p1,S1; p2,S2; ..pnSn] \n\nORDERABILITY: Given any two lotteries, a rational agent must either prefer one or else rate them as equally preferable. That is, the agent cannot avoid deciding \nTRANSITIVITY: (A > B) ∧ (B > C) ⇒ (A > C) \nCONTINUITY: If some lottery B is between A  and C in preference, then there is some probability p for which the rational agent will be indifferent between getting B for sure \nand the lottery that yields A with probability p and C with probability 1-p. \n\nSUBSTITUTABILITY: If an agent is indifferent between two lotteries A and B, then the agent is indifferent between two more complex lotteries that are the same \nexcept that B is substituted forA  in one of them. This holds regardless of the probabilities and the other outcome(s) in the lotteries \n\nMONOTONICITY: Suppose two lotteries have the same two possible outcomes, A and B. If an agent prefers A to B, then the agent must prefer the lottery\n that has a higher probability for A (and vice versa). \n\nDECOMPOSABILITY: Compound lotteries can be reduced to simpler ones using the laws of probability. This has been called the “no fun in gambling” rule. \nThe agent has a utility function and we can compute the expected utility of a lottery. The utility function derived in his way is known as a von Neumann-Morgenstern utility function \n\nEXISTENCE OF UTILITY FUNCTION: If an agent’s preferences obey the axioms of utility, then there exists a function U such that U(A) > U(B) if and only if A is preferred to B ,\n U(A) = U(B) and if and only if the agent is indifferent between A and B. \n\nEXPECTED UTILITY OF A LOTTERY: The utility of a lottery is the sum of the probability of each outcome times the utility of that outcome \n\nagent’s behavior would not change if its utility function were transformed linearly \nAs in game-playing, in a deterministic environment an agent needs only a preference ranking on states—the numbers don’t matter. This is called a value function or ordinal utility function. \n\n \n\n## AIMA Chapter 16.3 Utility Functions\n \npreference elicitation, involves presenting choices to the human and using the observed preferences to pin down the underlying utility function\nNormalized utilities uses 1 as best outcome and 0 as worst \n\nMicromort - price for a one in a million chance of death \n\nQALY - quality-adjusted life year \n\nIt will usually be the case that an agent prefers more money to less, all other things being equal. We say that the agent exhibits a\n monotonic preference for more money. This does not mean that money behaves as a utility function, because it says nothing about preferences between lotteries involving money. \n\nIn a pioneering study of actual utility functions, Grayson (1960) found that the utility of money was almost exactly proportional to the logarithm of the amount \n\nRisk-averse: prefers sure thing \nRisk-seeking: otherwise \nThe value an agent will accept in lieu of a lottery is called the certainty equivalent of the lottery. \nAn agent that has a linear curve is said to be risk-neutral \n\n\nThe rational way to choose the best action, , is to maximize expected utility. \nThis tendency for the estimated expected utility of the best choice to be too high is called the optimizer’s curse \n\n\nThis tendency for the estimated expected utility of the best choice to be too high is called the optimizer’s curse \n \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Environment is fully observable \n\nWe will assume that transitions are Markovian: the probability of reaching s’ from s depends only on s and not on the history of earlier states. \nFor every action agent receives reward R(s, a, s’) \na sequential decision problem for a fully observable, stochastic environment with a Markovian transition model and additive rewards is called a Markov \ndecision process, or MDP, and consists of a set of states (with an initial state s0); a set ACTIONS(s) of actions in each state; a transition model P(s’ | s, a) ;\n and a reward function R. Methods for solving MDPs usually involve dynamic programming: simplifying a problem by recursively breaking it into smaller\n  pieces and remembering the optimal solutions to the pieces. \n\nTherefore, a solution must specify what the agent should do for any state that the agent might reach. A solution of this kind is called a policy. pi(s) - policy for state s \n \nAn optimal policy pi* is a policy that yields the highest expected utility. \n\nThe first question to answer is whether there is a finite horizon or an infinite horizon for decision making.\n\n A finite horizon means that there is a fixed time after which nothing matters—the game is over, so to speak \n\nLeft. So, with a finite horizon, an optimal action in a given state may depend on how much time is left.\n A policy that depends on the time is called nonstationary. \n\nHence, an optimal action depends only on the current state, and the optimal policy is stationary. Policies for the infinite-horizon case are therefore simpler than those for the finite-horizon case. \n\nwe will additive discounted rewards: the utility of a history is where the discount factor is a number between 0 and 1. The discount factor describes\n the preference of an agent for current rewards over future rewards. When y is close to 0, rewards in the distant future are viewed as insignificant. \n When y is close to 1, an agent is more willing to wait for long-term rewards. \n\nWhen y is exactly 1, discounted rewards reduce to the special case of purely additive rewards. \nA policy that is guaranteed to reach a terminal state is called a proper policy.  \n\nAnother important quantity is the action-utility function, or Q-function: is the expected utility of taking a given action in a given state. The Q-function is related to utilities in the obvious way: \n\nU(s) = max Q(s,a) \npi*(s) = argumax Q(s,a) \n\n \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n \nThe Bellman equation is the basis of the value iteration algorithm for solving MDPs. \n\nThe Bellman equation lets us express the utility of a state recurisvely as the utilities of its neighbors. That is, it lets us express U(s)U(s) in terms of U(s')U(s’ ). \nWe can then use that recursion to do dynamic programming. \n\nPOLICY EVALUATION: given a policy , calculate , the utility of each state if were to be executed \n\nPolicy iteration uses dynamic programming. \n\n \n\n## Module 8 Lecture Notes\n \nTransitions are Markovian: the probability of arriving in s’ only depends on s and not the history of earlier states.\n\nutility = reward function for the agent. The “rewards“ can be positive or negative but are bounded by some maximum value. \nBecause the decision process is sequential, we must specify the utility function on a sequence of states and actions.\n\nMDP:\na sequential decision problem\nfully observable environment\n stochastic transition model\nhas additive rewards \n\nTo define:\nSet of states\nSet of actions\nTransition function (probability = model)\nReward function\nInitial state\nTerminal states\ndiscount\n\nMDPs are non-deterministic search problems. One way of solving them is via expectimax search.\n\nSolution of MDP is policy. Policy is a function that maps states to actions. pi* is an optimal policy\n\n\nThe value (utility) of a state s:\nV * (s) = expected utility starting in s and acting optimally\nThe value (utility) of a q-state (s,a): \nQ* (s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally \nThe optimal policy:  * (s) = optimal action from state s \n\nValue iteration:\n\nStart with V0 (s) = 0: no time steps left means an expected reward sum of zero \nGiven vector of Vk (s) values, do one ply of expectimax from each state.\nRepeat until convergence \n\nThe Bellman Equations:\nDefinition of “optimal utility” via expectimax recurrence gives a simple one-step lookahead relationship amongst optimal utility values \n\nValue iteration repeats the Bellman updates: \nProblem 1: It’s slow – O(S2A) per iteration Problem \n2: The “max” at each state rarely changes Problem\n3: The policy often converges long before the values \n\nPolicy Iteration:\n\nStep 1: Policy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence\nStep 2: Policy improvement: update policy using one-step lookahead with resulting converged (but not optimal!) utilities as future values\nRepeat steps until policy converges\n\n• It’s still optimal! \n• Can converge (much) faster under some conditions\n \n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "chapter17_3 =  \"\"\" Bandit problem:  \n",
        "Each arm M_i is a Markov reward process or MRP. It has action, states, transition model and reward function. \n",
        "Overall problem: space is given as cartesian problem S = S1xS2..xSn. Discount factor is y. \n",
        "\n",
        "Gambler in multi-armed bandit problem has to choose lever. This is the explore-exploit tradeoff. \n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" An alternative is reinforcement learning (RL), in which an agent interacts with the world and periodically receives rewards (or, in the terminology of psychology, reinforcements) that reflect how well it is doing.\n",
        "\n",
        "MODEL-BASED REINFORCEMENT LEARNING: In these approaches the agent uses a transition model of the environment to help interpret the reward signals and to make decisions about how to act.\n",
        "\n",
        "\n",
        "MODEL-FREE REINFORCEMENT LEARNING: In these approaches the agent neither knows nor learns a transition model for the environment. Instead, it learns a more direct representation of how to behave.\n",
        "\n",
        "ACTION-UTILITY LEARNING:The most common form of action-utility learning is Q-learning, where the agent learns a Q-function, or quality-function, denoting the sum of rewards from state onward if action is taken. Given a Q-function, the agent can choose what to do in by finding the action with the highest Q-value.\n",
        "\n",
        "POLICY SEARCH: The agent learns a policy that maps directly from states to\n",
        "Actions.\n",
        "\n",
        "We start with the simple case of a fully observable environment with a small number of actions and states, in which an agent already has a fixed policy that determines its actions. The agent is trying to learn the utility function —the expected total discounted reward if policy is executed beginning in state . We call this a passive learning agent. \n",
        "\n",
        "An adaptive dynamic programming (or ADP) agent takes advantage of the constraints among the utilities of states by learning the transition model that connects them and solving the corresponding Markov decision process using dynamic programming.\n",
        "\n",
        "Sparse rewards make learning much harder. \n",
        "\n",
        "In reinforcement learning, the total reward from a particular state onwards is given a policy pi Reward-to-go. We use the reward-to-go in direct utility estimation.\n",
        "\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 = \"\"\"Exploration: you have to try unknown actions to get information \n",
        "Exploitation: eventually, you have to use what you know \n",
        "Regret: even if you learn intelligently, you make mistakes \n",
        "Sampling: because of chance, you have to try things repeatedly \n",
        "Difficulty: learning can be much harder than solving a known MDP\n",
        "\n",
        "Does not know transition and reward function\n",
        "\n",
        "Model-Based Idea: Learn an approximate model based on experiences Solve for values as if the learned model were correct\n",
        "\n",
        "Step 1: Learn empirical MDP model Count outcomes s’ for each s, a Normalize to give an estimate of T, Discover each R when we experience (s, a, s’)\n",
        "\n",
        "Step 2: Solve the learned MDP For example, use value iteration, as before\n",
        "\n",
        "\n",
        "Passive Reinforcement Learning \n",
        "Learner is “along for the ride” No choice about what actions to take Just execute the policy and learn from experience This is NOT offline planning! You actually take actions in the world.\n",
        "\n",
        "\n",
        "Direct Evaluation \n",
        "Goal: Compute values for each state under π\n",
        "Idea: Average together observed sample values Act according to π Every time you visit a state, write down what the sum of discounted rewards turned out to be Average those samples\n",
        "\n",
        "Good:\n",
        "It’s easy to understand \n",
        "It doesn’t require any knowledge of T, R \n",
        "It eventually computes the correct average values, using just sample transitions \n",
        "\n",
        "Bad:\n",
        " It wastes information about state connections \n",
        "Each state must be learned separately\n",
        "it takes a long time to learn\n",
        "\n",
        "Temporal Difference Learning:\n",
        "Update V(s) each time we experience a transition (s, a, s’, r) Likely outcomes s’ will contribute updates more often \n",
        "\n",
        "TD value leaning is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages However, if we want to turn values into a (new) policy, we’re sunk\n",
        "\n",
        "Reinforcement Learning:\n",
        " Q-learning converges to optimal policy -- even if you’re acting suboptimally\n",
        "Q-learning is called off-policy learning \n",
        "\n",
        "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",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 41,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1329
        },
        "cellView": "form",
        "outputId": "bfd07f3c-0f6a-4ac7-cf64-c561d16e5c85"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": 42,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Bandit problem:  \nEach arm M_i is a Markov reward process or MRP. It has action, states, transition model and reward function. \nOverall problem: space is given as cartesian problem S = S1xS2..xSn. Discount factor is y. \n\nGambler in multi-armed bandit problem has to choose lever. This is the explore-exploit tradeoff. \n\n\n \n\n## AIMA Chapter 22.1 Learning from Rewards\n An alternative is reinforcement learning (RL), in which an agent interacts with the world and periodically receives rewards (or, in the terminology of psychology, reinforcements) that reflect how well it is doing.\n\nMODEL-BASED REINFORCEMENT LEARNING: In these approaches the agent uses a transition model of the environment to help interpret the reward signals and to make decisions about how to act.\n\n\nMODEL-FREE REINFORCEMENT LEARNING: In these approaches the agent neither knows nor learns a transition model for the environment. Instead, it learns a more direct representation of how to behave.\n\nACTION-UTILITY LEARNING:The most common form of action-utility learning is Q-learning, where the agent learns a Q-function, or quality-function, denoting the sum of rewards from state onward if action is taken. Given a Q-function, the agent can choose what to do in by finding the action with the highest Q-value.\n\nPOLICY SEARCH: The agent learns a policy that maps directly from states to\nActions.\n\nWe start with the simple case of a fully observable environment with a small number of actions and states, in which an agent already has a fixed policy that determines its actions. The agent is trying to learn the utility function —the expected total discounted reward if policy is executed beginning in state . We call this a passive learning agent. \n\nAn adaptive dynamic programming (or ADP) agent takes advantage of the constraints among the utilities of states by learning the transition model that connects them and solving the corresponding Markov decision process using dynamic programming.\n\nSparse rewards make learning much harder. \n\nIn reinforcement learning, the total reward from a particular state onwards is given a policy pi Reward-to-go. We use the reward-to-go in direct utility estimation.\n\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\nExploration: you have to try unknown actions to get information \nExploitation: eventually, you have to use what you know \nRegret: even if you learn intelligently, you make mistakes \nSampling: because of chance, you have to try things repeatedly \nDifficulty: learning can be much harder than solving a known MDP\n\nDoes not know transition and reward function\n\nModel-Based Idea: Learn an approximate model based on experiences Solve for values as if the learned model were correct\n\nStep 1: Learn empirical MDP model Count outcomes s’ for each s, a Normalize to give an estimate of T, Discover each R when we experience (s, a, s’)\n\nStep 2: Solve the learned MDP For example, use value iteration, as before\n\n\nPassive Reinforcement Learning \nLearner is “along for the ride” No choice about what actions to take Just execute the policy and learn from experience This is NOT offline planning! You actually take actions in the world.\n\n\nDirect Evaluation \nGoal: Compute values for each state under π\nIdea: Average together observed sample values Act according to π Every time you visit a state, write down what the sum of discounted rewards turned out to be Average those samples\n\nGood:\nIt’s easy to understand \nIt doesn’t require any knowledge of T, R \nIt eventually computes the correct average values, using just sample transitions \n\nBad:\n It wastes information about state connections \nEach state must be learned separately\nit takes a long time to learn\n\nTemporal Difference Learning:\nUpdate V(s) each time we experience a transition (s, a, s’, r) Likely outcomes s’ will contribute updates more often \n\nTD value leaning is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages However, if we want to turn values into a (new) policy, we’re sunk\n\nReinforcement Learning:\n Q-learning converges to optimal policy -- even if you’re acting suboptimally\nQ-learning is called off-policy learning \n\nRegret is a measure of your total mistake cost: the difference between your (expected) rewards, including youthful suboptimality, and optimal (expected) rewards\n\n \n\n## Module 9 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 43,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1078
        },
        "cellView": "form",
        "outputId": "14138af7-f3d9-4322-83b0-09d3569cf8ac"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": 44,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n Your summary here \n\n## Module 10 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" 1. Bayes nets compactly encode joint distributions \n",
        "2. Guaranteed independencies of distributions can be deduced from BN graph structure\n",
        "3. D-separation gives precise conditional independence guarantees from graph alone\n",
        "4. A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\n",
        "\n",
        "Inference by Enumeration \n",
        "Step1: Select the entries consistent with the evidence\n",
        "Step 2: Sum out H to get joint of Query and evidence\n",
        "Step 3: Normalize (1/Z)\n",
        "\n",
        "Inference by Enumeration in Bayes’ Net \n",
        "Given unlimited time, inference in BNs is easy\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 45,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 620
        },
        "cellView": "form",
        "outputId": "bae2337b-d79c-48fe-f765-2390f91d9c1d"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": 46,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n 1. Bayes nets compactly encode joint distributions \n2. Guaranteed independencies of distributions can be deduced from BN graph structure\n3. D-separation gives precise conditional independence guarantees from graph alone\n4. A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\n\nInference by Enumeration \nStep1: Select the entries consistent with the evidence\nStep 2: Sum out H to get joint of Query and evidence\nStep 3: Normalize (1/Z)\n\nInference by Enumeration in Bayes’ Net \nGiven unlimited time, inference in BNs is easy\n \n\n## Module 11 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\" \n",
        "Bayes rule lets us do diagnostic queries with causal probabilities \n",
        "\n",
        "The naïve Bayes assumption takes all features to be independent given the class label\n",
        "\n",
        "We can build classifiers out of a naïve Bayes model using training data \n",
        "\n",
        "Smoothing estimates is important in real systems \n",
        "\n",
        "Classifier confidences are useful, when you can get them\n",
        "\n",
        "Linear Classifiers:\n",
        " Inputs are feature values \n",
        "Each feature has a weight \n",
        "Sum is the activation\n",
        "\n",
        "\n",
        "Properties of Perceptrons \n",
        "Separability: true if some parameters get the training set perfectly correct\n",
        "Convergence: if the training is separable, perceptron will eventually converge (binary case)\n",
        "Mistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\n",
        "\n",
        "Problems with the Perceptron \n",
        "Noise: if the data isn’t separable, weights might thrash \n",
        "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 \n",
        "Overtraining is a kind of overfitting\n",
        "\n",
        "Fix perceptrons:\n",
        "Idea: adjust the weight update to mitigate these effects \n",
        "\n",
        "Classification: Comparison \n",
        "Naïve Bayes\n",
        "• Builds a model training data\n",
        "• Gives prediction probabilities\n",
        "• Strong assumptions about feature independence\n",
        "• One pass through data (counting)\n",
        "\n",
        "Perceptrons / MIRA:\n",
        "• Makes less assumptions about data\n",
        "• Mistake-driven learning\n",
        "• Multiple passes through data (prediction)\n",
        "• Often more accurate\n",
        "\n",
        "Perceptrons:\n",
        "We can think about the perceptron or the sigmoid neuron as a device that makes decisions by weighing up evidence \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 47,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1617
        },
        "cellView": "form",
        "outputId": "f07ce23e-3e76-4954-eead-10f424e6e8a9"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module12_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter19_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter19_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter19_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter19_4),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter19_5),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter19_6),\n",
        "  (\"SLP Chapter 4.1 Naive Bayes Classifiers\", slp_chapter4_1),\n",
        "  (\"SLP Chapter 4.2 Training the Naive Bayes Classifier\", slp_chapter4_2),\n",
        "  (\"SLP Chapter 4.3 Worked Example\", slp_chapter4_3),\n",
        "  (\"SLP Chapter 4.4 Optimizing for Sentiment Analysis\", slp_chapter4_4),\n",
        "  (\"SLP Chapter 4.5 Naive Bayes for other text classification tasks\", slp_chapter4_5),\n",
        "  (\"SLP Chapter 4.6 Naive Bayes as a Language Model\", slp_chapter4_6),\n",
        "  (\"SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\", slp_chapter4_7),\n",
        "  (\"SLP Chapter 4.8 Test sets and Cross-validation\", slp_chapter4_8),\n",
        "  (\"SLP Chapter 4.9 Statistical Significance Testing\", slp_chapter4_9),\n",
        "  (\"SLP Chapter 4.10 Avoiding Harms in Classification\", slp_chapter4_10),\n",
        "  (\"Module 12 Lecture Notes\", module12_lecture_notes),\n",
        "]\n",
        "\n",
        "module12_markdown = format_module(12, \"Naive Bayes and Perceptrons\", \n",
        "                         module12_sections, \n",
        "                         module12_definitions)\n",
        "display(Markdown(module12_markdown))"
      ],
      "execution_count": 48,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n \nBayes rule lets us do diagnostic queries with causal probabilities \n\nThe naïve Bayes assumption takes all features to be independent given the class label\n\nWe can build classifiers out of a naïve Bayes model using training data \n\nSmoothing estimates is important in real systems \n\nClassifier confidences are useful, when you can get them\n\nLinear Classifiers:\n Inputs are feature values \nEach feature has a weight \nSum is the activation\n\n\nProperties of Perceptrons \nSeparability: true if some parameters get the training set perfectly correct\nConvergence: if the training is separable, perceptron will eventually converge (binary case)\nMistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\n\nProblems with the Perceptron \nNoise: if the data isn’t separable, weights might thrash \nAveraging weight vectors over time can help (averaged perceptron)\n\nMediocre generalization: finds a “barely” separating solution\n\nOvertraining: test / held-out accuracy usually rises, then falls \nOvertraining is a kind of overfitting\n\nFix perceptrons:\nIdea: adjust the weight update to mitigate these effects \n\nClassification: Comparison \nNaïve Bayes\n• Builds a model training data\n• Gives prediction probabilities\n• Strong assumptions about feature independence\n• One pass through data (counting)\n\nPerceptrons / MIRA:\n• Makes less assumptions about data\n• Mistake-driven learning\n• Multiple passes through data (prediction)\n• Often more accurate\n\nPerceptrons:\nWe can think about the perceptron or the sigmoid neuron as a device that makes decisions by weighing up evidence \n\n## Module 12 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" Learning in logistic regression \n",
        "1. An objective function or loss function that tells us distance between the system output and the gold output. We will use cross-entropy loss.\n",
        "2. An algorithm for optimizing the objective function. We will use stochastic gradient descent to minimize the loss function.\n",
        "\n",
        "\n",
        "Cross-entropy loss \n",
        "\n",
        "We want the loss to be smaller if the model’s estimate is close to correct, and we want the loss to be bigger if it is confused. \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",
        "Overfitting is a problem with many machine learning models. Overfitting results in\n",
        "poor generalization and poor performance on unseen test set.\n",
        "In logistic regression, if a feature only occurs in one class then it will get a high weight.\n",
        "Sometimes we are just modelling noisy factors that just accidentally correlate with the\n",
        "class.\n",
        "Regularization is a way to penalize large weights. A regularization term is added to\n",
        "the loss function\n",
        "\n",
        "\n",
        "Like the Perceptron, logistic regression uses a vector of weights and a bias term.  \n",
        "\n",
        "Feed-Forward Neural Network \n",
        "The simplest kind of NN is the Feed-Forward Neural Network\n",
        "Multilayer network, all units are usually fully-connected, and no cycles.\n",
        "The outputs from each layer are passed to units in the next higher layer, and no\n",
        "outputs are passed back to lower layers.\n",
        "\n",
        "\n",
        "Training Neural Nets \n",
        "A loss function – cross-entropy loss\n",
        "An optimization algorithm – gradient descent\n",
        "A way of computing the gradient of the loss function – error propagation\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 49,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1385
        },
        "cellView": "form",
        "outputId": "c8249772-c389-47b2-89d3-7d6479055eba"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": 50,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n Learning in logistic regression \n1. An objective function or loss function that tells us distance between the system output and the gold output. We will use cross-entropy loss.\n2. An algorithm for optimizing the objective function. We will use stochastic gradient descent to minimize the loss function.\n\n\nCross-entropy loss \n\nWe want the loss to be smaller if the model’s estimate is close to correct, and we want the loss to be bigger if it is confused. \n\nGradient 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\nOverfitting is a problem with many machine learning models. Overfitting results in\npoor generalization and poor performance on unseen test set.\nIn logistic regression, if a feature only occurs in one class then it will get a high weight.\nSometimes we are just modelling noisy factors that just accidentally correlate with the\nclass.\nRegularization is a way to penalize large weights. A regularization term is added to\nthe loss function\n\n\nLike the Perceptron, logistic regression uses a vector of weights and a bias term.  \n\nFeed-Forward Neural Network \nThe simplest kind of NN is the Feed-Forward Neural Network\nMultilayer network, all units are usually fully-connected, and no cycles.\nThe outputs from each layer are passed to units in the next higher layer, and no\noutputs are passed back to lower layers.\n\n\nTraining Neural Nets \nA loss function – cross-entropy loss\nAn optimization algorithm – gradient descent\nA way of computing the gradient of the loss function – error propagation\n \n\n## Module 13 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" Co-occurrence matrix (weighted by TF-IDF or mutual information)\n",
        "• Long (length |V| = 50,000+)\n",
        "• Sparse (most elements are zeros)\n",
        "Alternative: learn vectors that are\n",
        "• Short (length 200-1000)\n",
        "• Dense (most elements are non-zero)\n",
        "\n",
        "Language Modeling\n",
        "Goal: Learn a function that returns the joint probability\n",
        "Primary difficulty:\n",
        "1. There are too many parameters to accurately estimate. This is\n",
        "sometimes called the “curse of dimensionality”\n",
        "2. In n-gram-based models we fail to generalize to related words / word\n",
        "sequences that we have observed.\n",
        "\n",
        "Why dense vectors?\n",
        "• Short vectors may be easier to use as features in machine learning (fewer\n",
        "weights to tune)\n",
        "• Dense vectors may generalize better than storing explicit counts\n",
        "• They may do better at capturing synonymy:\n",
        "• car and automobile are synonyms; but are distinct dimensions in sparse\n",
        "vectors\n",
        "• a word with car as a neighbor and a word with automobile as a\n",
        "neighbor should be similar, but aren't\n",
        "• In practice, they work better\n",
        "\n",
        "Skip-gram algorithm\n",
        "1. Treat the target word and a neighboring context\n",
        "word as positive examples.\n",
        "2. Randomly sample other words in the lexicon to get\n",
        "negative samples\n",
        "3. Use logistic regression to train a classifier to\n",
        "distinguish those two cases\n",
        "4. Use the weights as the embeddings\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 51,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1207
        },
        "outputId": "ab87b589-84be-47e5-aa15-557106c6a0ec"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module14_sections = [\n",
        "  (\"SLP Chapter 9.1 Language Models Revisited\", slp_chapter9_1),\n",
        "  (\"SLP Chapter 9.2 Recurrent Neural Networks\", slp_chapter9_2),\n",
        "  (\"SLP Chapter 9.3 RNNs as Language Models\", slp_chapter9_3),\n",
        "\n",
        "  (\"SLP Chapter 6.1 Lexical Semantics\", slp_chapter6_1),\n",
        "  (\"SLP Chapter 6.2 Vector Semantics\", slp_chapter6_2),\n",
        "  (\"SLP Chapter 6.3 Words and Vectors\", slp_chapter6_3),\n",
        "  (\"SLP Chapter 6.4 Cosine for measuring similarity\", slp_chapter6_4),\n",
        "  (\"SLP Chapter 6.8 Word2vec\", slp_chapter6_8),\n",
        "  (\"SLP Chapter 6.10 Semantic properties of embeddings\", slp_chapter6_10),\n",
        "  (\"SLP Chapter 6.11 Bias and Embeddings\", slp_chapter6_11),\n",
        "  (\"SLP Chapter 6.12 Evaluating Vector Models\", slp_chapter6_12),\n",
        "  (\"Module 14 Lecture Notes\", module14_lecture_notes),\n",
        "]\n",
        "\n",
        "module14_markdown = format_module(14, \"Natural Language Processing\", \n",
        "                         module14_sections, \n",
        "                         module14_definitions)\n",
        "display(Markdown(module14_markdown))"
      ],
      "execution_count": 52,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 14 Lecture Notes\n Co-occurrence matrix (weighted by TF-IDF or mutual information)\n• Long (length |V| = 50,000+)\n• Sparse (most elements are zeros)\nAlternative: learn vectors that are\n• Short (length 200-1000)\n• Dense (most elements are non-zero)\n\nLanguage Modeling\nGoal: Learn a function that returns the joint probability\nPrimary difficulty:\n1. There are too many parameters to accurately estimate. This is\nsometimes called the “curse of dimensionality”\n2. In n-gram-based models we fail to generalize to related words / word\nsequences that we have observed.\n\nWhy dense vectors?\n• Short vectors may be easier to use as features in machine learning (fewer\nweights to tune)\n• Dense vectors may generalize better than storing explicit counts\n• They may do better at capturing synonymy:\n• car and automobile are synonyms; but are distinct dimensions in sparse\nvectors\n• a word with car as a neighbor and a word with automobile as a\nneighbor should be similar, but aren't\n• In practice, they work better\n\nSkip-gram algorithm\n1. Treat the target word and a neighboring context\nword as positive examples.\n2. Randomly sample other words in the lexicon to get\nnegative samples\n3. Use logistic regression to train a classifier to\ndistinguish those two cases\n4. Use the weights as the embeddings\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 10412
        },
        "id": "T3cm1WV542_a",
        "outputId": "e44cb5bd-0e3b-4421-ce12-bd5defbb11e4"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module8_markdown, \n",
        "                             module9_markdown, \n",
        "                             module10_markdown, \n",
        "                             module11_markdown, \n",
        "                             module12_markdown,\n",
        "                             module13_markdown,\n",
        "                             module14_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": 54,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n utility function, U(s) assigns a single number to express the desirability of a state.\n\nThe expected utility of an action given the evidence, EU(a) , is average utility value of the outcomes, weighted by the probability that the outcome occurs. \n\nThe principle of maximum expected utility (MEU) says that a rational agent should choose the action that maximizes the agent’s expected utility \nIntelligent agents can’t use the MEU principle right away. It requires perception, learning, knowledge representation, and inference. \nIf an agent acts so as to maximize a utility function that correctly reflects the performance measure, then the agent will achieve the highest possible performance score (averaged over all the possible environments) \n \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n MEU is not the only rational way to make decisions\n\nWe use the following notation to describe an agent’s preferences: \nA > B: Prefers A over B \nA ~ B: Indifferent \n\nWe can think of the set of outcomes for each action as a lottery \nL = [p1,S1; p2,S2; ..pnSn] \n\nORDERABILITY: Given any two lotteries, a rational agent must either prefer one or else rate them as equally preferable. That is, the agent cannot avoid deciding \nTRANSITIVITY: (A > B) ∧ (B > C) ⇒ (A > C) \nCONTINUITY: If some lottery B is between A  and C in preference, then there is some probability p for which the rational agent will be indifferent between getting B for sure \nand the lottery that yields A with probability p and C with probability 1-p. \n\nSUBSTITUTABILITY: If an agent is indifferent between two lotteries A and B, then the agent is indifferent between two more complex lotteries that are the same \nexcept that B is substituted forA  in one of them. This holds regardless of the probabilities and the other outcome(s) in the lotteries \n\nMONOTONICITY: Suppose two lotteries have the same two possible outcomes, A and B. If an agent prefers A to B, then the agent must prefer the lottery\n that has a higher probability for A (and vice versa). \n\nDECOMPOSABILITY: Compound lotteries can be reduced to simpler ones using the laws of probability. This has been called the “no fun in gambling” rule. \nThe agent has a utility function and we can compute the expected utility of a lottery. The utility function derived in his way is known as a von Neumann-Morgenstern utility function \n\nEXISTENCE OF UTILITY FUNCTION: If an agent’s preferences obey the axioms of utility, then there exists a function U such that U(A) > U(B) if and only if A is preferred to B ,\n U(A) = U(B) and if and only if the agent is indifferent between A and B. \n\nEXPECTED UTILITY OF A LOTTERY: The utility of a lottery is the sum of the probability of each outcome times the utility of that outcome \n\nagent’s behavior would not change if its utility function were transformed linearly \nAs in game-playing, in a deterministic environment an agent needs only a preference ranking on states—the numbers don’t matter. This is called a value function or ordinal utility function. \n\n \n\n## AIMA Chapter 16.3 Utility Functions\n \npreference elicitation, involves presenting choices to the human and using the observed preferences to pin down the underlying utility function\nNormalized utilities uses 1 as best outcome and 0 as worst \n\nMicromort - price for a one in a million chance of death \n\nQALY - quality-adjusted life year \n\nIt will usually be the case that an agent prefers more money to less, all other things being equal. We say that the agent exhibits a\n monotonic preference for more money. This does not mean that money behaves as a utility function, because it says nothing about preferences between lotteries involving money. \n\nIn a pioneering study of actual utility functions, Grayson (1960) found that the utility of money was almost exactly proportional to the logarithm of the amount \n\nRisk-averse: prefers sure thing \nRisk-seeking: otherwise \nThe value an agent will accept in lieu of a lottery is called the certainty equivalent of the lottery. \nAn agent that has a linear curve is said to be risk-neutral \n\n\nThe rational way to choose the best action, , is to maximize expected utility. \nThis tendency for the estimated expected utility of the best choice to be too high is called the optimizer’s curse \n\n\nThis tendency for the estimated expected utility of the best choice to be too high is called the optimizer’s curse \n \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Environment is fully observable \n\nWe will assume that transitions are Markovian: the probability of reaching s’ from s depends only on s and not on the history of earlier states. \nFor every action agent receives reward R(s, a, s’) \na sequential decision problem for a fully observable, stochastic environment with a Markovian transition model and additive rewards is called a Markov \ndecision process, or MDP, and consists of a set of states (with an initial state s0); a set ACTIONS(s) of actions in each state; a transition model P(s’ | s, a) ;\n and a reward function R. Methods for solving MDPs usually involve dynamic programming: simplifying a problem by recursively breaking it into smaller\n  pieces and remembering the optimal solutions to the pieces. \n\nTherefore, a solution must specify what the agent should do for any state that the agent might reach. A solution of this kind is called a policy. pi(s) - policy for state s \n \nAn optimal policy pi* is a policy that yields the highest expected utility. \n\nThe first question to answer is whether there is a finite horizon or an infinite horizon for decision making.\n\n A finite horizon means that there is a fixed time after which nothing matters—the game is over, so to speak \n\nLeft. So, with a finite horizon, an optimal action in a given state may depend on how much time is left.\n A policy that depends on the time is called nonstationary. \n\nHence, an optimal action depends only on the current state, and the optimal policy is stationary. Policies for the infinite-horizon case are therefore simpler than those for the finite-horizon case. \n\nwe will additive discounted rewards: the utility of a history is where the discount factor is a number between 0 and 1. The discount factor describes\n the preference of an agent for current rewards over future rewards. When y is close to 0, rewards in the distant future are viewed as insignificant. \n When y is close to 1, an agent is more willing to wait for long-term rewards. \n\nWhen y is exactly 1, discounted rewards reduce to the special case of purely additive rewards. \nA policy that is guaranteed to reach a terminal state is called a proper policy.  \n\nAnother important quantity is the action-utility function, or Q-function: is the expected utility of taking a given action in a given state. The Q-function is related to utilities in the obvious way: \n\nU(s) = max Q(s,a) \npi*(s) = argumax Q(s,a) \n\n \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n \nThe Bellman equation is the basis of the value iteration algorithm for solving MDPs. \n\nThe Bellman equation lets us express the utility of a state recurisvely as the utilities of its neighbors. That is, it lets us express U(s)U(s) in terms of U(s')U(s’ ). \nWe can then use that recursion to do dynamic programming. \n\nPOLICY EVALUATION: given a policy , calculate , the utility of each state if were to be executed \n\nPolicy iteration uses dynamic programming. \n\n \n\n## Module 8 Lecture Notes\n \nTransitions are Markovian: the probability of arriving in s’ only depends on s and not the history of earlier states.\n\nutility = reward function for the agent. The “rewards“ can be positive or negative but are bounded by some maximum value. \nBecause the decision process is sequential, we must specify the utility function on a sequence of states and actions.\n\nMDP:\na sequential decision problem\nfully observable environment\n stochastic transition model\nhas additive rewards \n\nTo define:\nSet of states\nSet of actions\nTransition function (probability = model)\nReward function\nInitial state\nTerminal states\ndiscount\n\nMDPs are non-deterministic search problems. One way of solving them is via expectimax search.\n\nSolution of MDP is policy. Policy is a function that maps states to actions. pi* is an optimal policy\n\n\nThe value (utility) of a state s:\nV * (s) = expected utility starting in s and acting optimally\nThe value (utility) of a q-state (s,a): \nQ* (s,a) = expected utility starting out having taken action a from state s and (thereafter) acting optimally \nThe optimal policy:  * (s) = optimal action from state s \n\nValue iteration:\n\nStart with V0 (s) = 0: no time steps left means an expected reward sum of zero \nGiven vector of Vk (s) values, do one ply of expectimax from each state.\nRepeat until convergence \n\nThe Bellman Equations:\nDefinition of “optimal utility” via expectimax recurrence gives a simple one-step lookahead relationship amongst optimal utility values \n\nValue iteration repeats the Bellman updates: \nProblem 1: It’s slow – O(S2A) per iteration Problem \n2: The “max” at each state rarely changes Problem\n3: The policy often converges long before the values \n\nPolicy Iteration:\n\nStep 1: Policy evaluation: calculate utilities for some fixed policy (not optimal utilities!) until convergence\nStep 2: Policy improvement: update policy using one-step lookahead with resulting converged (but not optimal!) utilities as future values\nRepeat steps until policy converges\n\n• It’s still optimal! \n• Can converge (much) faster under some conditions\n \n\n## Module 8 Definitions\n* **Utility function** - Your definition here\n* **Expected utility** - your definition here\n* **Etc.** - your definition here\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Bandit problem:  \nEach arm M_i is a Markov reward process or MRP. It has action, states, transition model and reward function. \nOverall problem: space is given as cartesian problem S = S1xS2..xSn. Discount factor is y. \n\nGambler in multi-armed bandit problem has to choose lever. This is the explore-exploit tradeoff. \n\n\n \n\n## AIMA Chapter 22.1 Learning from Rewards\n An alternative is reinforcement learning (RL), in which an agent interacts with the world and periodically receives rewards (or, in the terminology of psychology, reinforcements) that reflect how well it is doing.\n\nMODEL-BASED REINFORCEMENT LEARNING: In these approaches the agent uses a transition model of the environment to help interpret the reward signals and to make decisions about how to act.\n\n\nMODEL-FREE REINFORCEMENT LEARNING: In these approaches the agent neither knows nor learns a transition model for the environment. Instead, it learns a more direct representation of how to behave.\n\nACTION-UTILITY LEARNING:The most common form of action-utility learning is Q-learning, where the agent learns a Q-function, or quality-function, denoting the sum of rewards from state onward if action is taken. Given a Q-function, the agent can choose what to do in by finding the action with the highest Q-value.\n\nPOLICY SEARCH: The agent learns a policy that maps directly from states to\nActions.\n\nWe start with the simple case of a fully observable environment with a small number of actions and states, in which an agent already has a fixed policy that determines its actions. The agent is trying to learn the utility function —the expected total discounted reward if policy is executed beginning in state . We call this a passive learning agent. \n\nAn adaptive dynamic programming (or ADP) agent takes advantage of the constraints among the utilities of states by learning the transition model that connects them and solving the corresponding Markov decision process using dynamic programming.\n\nSparse rewards make learning much harder. \n\nIn reinforcement learning, the total reward from a particular state onwards is given a policy pi Reward-to-go. We use the reward-to-go in direct utility estimation.\n\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\nExploration: you have to try unknown actions to get information \nExploitation: eventually, you have to use what you know \nRegret: even if you learn intelligently, you make mistakes \nSampling: because of chance, you have to try things repeatedly \nDifficulty: learning can be much harder than solving a known MDP\n\nDoes not know transition and reward function\n\nModel-Based Idea: Learn an approximate model based on experiences Solve for values as if the learned model were correct\n\nStep 1: Learn empirical MDP model Count outcomes s’ for each s, a Normalize to give an estimate of T, Discover each R when we experience (s, a, s’)\n\nStep 2: Solve the learned MDP For example, use value iteration, as before\n\n\nPassive Reinforcement Learning \nLearner is “along for the ride” No choice about what actions to take Just execute the policy and learn from experience This is NOT offline planning! You actually take actions in the world.\n\n\nDirect Evaluation \nGoal: Compute values for each state under π\nIdea: Average together observed sample values Act according to π Every time you visit a state, write down what the sum of discounted rewards turned out to be Average those samples\n\nGood:\nIt’s easy to understand \nIt doesn’t require any knowledge of T, R \nIt eventually computes the correct average values, using just sample transitions \n\nBad:\n It wastes information about state connections \nEach state must be learned separately\nit takes a long time to learn\n\nTemporal Difference Learning:\nUpdate V(s) each time we experience a transition (s, a, s’, r) Likely outcomes s’ will contribute updates more often \n\nTD value leaning is a model-free way to do policy evaluation, mimicking Bellman updates with running sample averages However, if we want to turn values into a (new) policy, we’re sunk\n\nReinforcement Learning:\n Q-learning converges to optimal policy -- even if you’re acting suboptimally\nQ-learning is called off-policy learning \n\nRegret is a measure of your total mistake cost: the difference between your (expected) rewards, including youthful suboptimality, and optimal (expected) rewards\n\n \n\n## Module 9 Definitions\n* **Term** - your definition here\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n Your summary here \n\n## Module 10 Definitions\n* **Term** - your definition here\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n 1. Bayes nets compactly encode joint distributions \n2. Guaranteed independencies of distributions can be deduced from BN graph structure\n3. D-separation gives precise conditional independence guarantees from graph alone\n4. A Bayes’ Net’s joint distribution may have further (conditional) independence that is not detectable until you inspect its specific distribution\n\nInference by Enumeration \nStep1: Select the entries consistent with the evidence\nStep 2: Sum out H to get joint of Query and evidence\nStep 3: Normalize (1/Z)\n\nInference by Enumeration in Bayes’ Net \nGiven unlimited time, inference in BNs is easy\n \n\n## Module 11 Definitions\n* **Concept** - definition\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n \nBayes rule lets us do diagnostic queries with causal probabilities \n\nThe naïve Bayes assumption takes all features to be independent given the class label\n\nWe can build classifiers out of a naïve Bayes model using training data \n\nSmoothing estimates is important in real systems \n\nClassifier confidences are useful, when you can get them\n\nLinear Classifiers:\n Inputs are feature values \nEach feature has a weight \nSum is the activation\n\n\nProperties of Perceptrons \nSeparability: true if some parameters get the training set perfectly correct\nConvergence: if the training is separable, perceptron will eventually converge (binary case)\nMistake Bound: the maximum number of mistakes (binary case) related to the margin or degree of separability\n\nProblems with the Perceptron \nNoise: if the data isn’t separable, weights might thrash \nAveraging weight vectors over time can help (averaged perceptron)\n\nMediocre generalization: finds a “barely” separating solution\n\nOvertraining: test / held-out accuracy usually rises, then falls \nOvertraining is a kind of overfitting\n\nFix perceptrons:\nIdea: adjust the weight update to mitigate these effects \n\nClassification: Comparison \nNaïve Bayes\n• Builds a model training data\n• Gives prediction probabilities\n• Strong assumptions about feature independence\n• One pass through data (counting)\n\nPerceptrons / MIRA:\n• Makes less assumptions about data\n• Mistake-driven learning\n• Multiple passes through data (prediction)\n• Often more accurate\n\nPerceptrons:\nWe can think about the perceptron or the sigmoid neuron as a device that makes decisions by weighing up evidence \n\n## Module 12 Definitions\n* **Concept** - definition\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n Learning in logistic regression \n1. An objective function or loss function that tells us distance between the system output and the gold output. We will use cross-entropy loss.\n2. An algorithm for optimizing the objective function. We will use stochastic gradient descent to minimize the loss function.\n\n\nCross-entropy loss \n\nWe want the loss to be smaller if the model’s estimate is close to correct, and we want the loss to be bigger if it is confused. \n\nGradient 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\nOverfitting is a problem with many machine learning models. Overfitting results in\npoor generalization and poor performance on unseen test set.\nIn logistic regression, if a feature only occurs in one class then it will get a high weight.\nSometimes we are just modelling noisy factors that just accidentally correlate with the\nclass.\nRegularization is a way to penalize large weights. A regularization term is added to\nthe loss function\n\n\nLike the Perceptron, logistic regression uses a vector of weights and a bias term.  \n\nFeed-Forward Neural Network \nThe simplest kind of NN is the Feed-Forward Neural Network\nMultilayer network, all units are usually fully-connected, and no cycles.\nThe outputs from each layer are passed to units in the next higher layer, and no\noutputs are passed back to lower layers.\n\n\nTraining Neural Nets \nA loss function – cross-entropy loss\nAn optimization algorithm – gradient descent\nA way of computing the gradient of the loss function – error propagation\n \n\n## Module 13 Definitions\n* **Concept** - definition\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 14 Lecture Notes\n Co-occurrence matrix (weighted by TF-IDF or mutual information)\n• Long (length |V| = 50,000+)\n• Sparse (most elements are zeros)\nAlternative: learn vectors that are\n• Short (length 200-1000)\n• Dense (most elements are non-zero)\n\nLanguage Modeling\nGoal: Learn a function that returns the joint probability\nPrimary difficulty:\n1. There are too many parameters to accurately estimate. This is\nsometimes called the “curse of dimensionality”\n2. In n-gram-based models we fail to generalize to related words / word\nsequences that we have observed.\n\nWhy dense vectors?\n• Short vectors may be easier to use as features in machine learning (fewer\nweights to tune)\n• Dense vectors may generalize better than storing explicit counts\n• They may do better at capturing synonymy:\n• car and automobile are synonyms; but are distinct dimensions in sparse\nvectors\n• a word with car as a neighbor and a word with automobile as a\nneighbor should be similar, but aren't\n• In practice, they work better\n\nSkip-gram algorithm\n1. Treat the target word and a neighboring context\nword as positive examples.\n2. Randomly sample other words in the lexicon to get\nnegative samples\n3. Use logistic regression to train a classifier to\ndistinguish those two cases\n4. Use the weights as the embeddings\n\n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}