{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of Template_for_CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b77519e4-cbc5-4c3c-8fa6-21fccc62f33d"
      },
      "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": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "06a342ed-9f53-4d49-a3e3-fd894af60828"
      },
      "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": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = True"
      ],
      "execution_count": 3,
      "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",
        "chapter16_3 =  \"\"\"Decision theory is a **normative theory**: it describes how a rational agent *should* act. \\\n",
        "A **descriptive theory**, on the other hand, describes how actual agents — for example, humans — really *do* act\"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "chapter17_1 = \"\"\"A **Markov Decision Process** or **MDP** consists of a set of states (with an initial state); \\\n",
        "a set **ACTIONS(*s*)** of actions in each state; a transition model; a discount factor, and a reward function. Methods for solving \\\n",
        "MDPs usually involve dynamic programming.\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",
        "\"Bellman Equation\": r\"$U(s) = max_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U(s')] = max_a Q(s,a)$\",\n",
        "\"Bellman Update\": r\"$U_{i+1}(s) = max_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U_i(s')]$\",\n",
        "\"Continuity\": r\"$A \\succ B \\succ C \\Rightarrow \\exists p | [p, A; 1-p, C] \\sim B$\",\n",
        "\"Decomposability\": r\"$[p, A; 1-p, [q, B; 1-q, C]] \\sim [p, A; (1-p)q, B; (1-p)(1-q), C]$\",\n",
        "r\"Expected Utility of an action $a$\": r\"$EU(a) = \\sum_s' P(\\textnormal{RESULT}(a)=s') U(s')$\",\n",
        "r\"Expected Utility with policy $\\pi$ and state $s$\": r\"$U^\\pi(s) = E[\\sum_{t=0}^\\infty \\gamma^tR(S_t, \\pi(S_t), S_{t+1})]$\",\n",
        "\"MEU Principle\": \"a rational agent should choose the action that maximizes the agent’s expected utility\",\n",
        "\"Monotonicity\": r\"$A \\succ B \\Rightarrow (p \\gt q \\Leftrightarrow [p, A; 1-p, B] \\succ [q, A; 1-q, B])$\",\n",
        "r\"Optimal policy for state $s$\": r\"$\\pi^*(s) = argmax_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U(s')]$\",\n",
        "\"Orderability\": r\"Given any two lotteries $L_1, L_2$, $L_1 \\succ L_2 \\vee L_1 \\sim L_2 \\vee L_2 \\succ L_1$\",\n",
        "\"Policy Evaluation\": r\"Given a policy $\\pi_i$, calculate the utility of each state using this policy\",\n",
        "\"Policy Improvement\": r\"Determine the next policy to use, $\\pi_{i+1}$, looking ahead by one step and following MEU\",\n",
        "\"Preference Attributes\": \"Orderability, Transitivity, Continuity, Substitutability, Monotonicity, and Decomposability\",\n",
        "r\"Probability of reaching state $s'$ through action $a$\": r\"$P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$\",\n",
        "\"Substitutability\": r\"$A \\sim B \\Rightarrow [p, A; 1-p, C] \\sim [p, B; 1-p, C]$\",\n",
        "\"Transitivity\": r\"$A \\succ B \\land B \\succ C \\Rightarrow A \\succ C$\",\n",
        "\"Value iteration\": \"Apply Bellman updates successively until equilibrium\"\n",
        "}\n"
      ],
      "execution_count": 4,
      "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": 649
        },
        "outputId": "fd58c605-92e0-4c8d-f38d-9abf48e57ec1"
      },
      "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.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1)\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": 5,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.3 Utility Functions\nDecision theory is a **normative theory**: it describes how a rational agent *should* act. A **descriptive theory**, on the other hand, describes how actual agents — for example, humans — really *do* act\n\n## AIMA Chapter 17.1 Sequential Decision Problems\nA **Markov Decision Process** or **MDP** consists of a set of states (with an initial state); a set **ACTIONS(*s*)** of actions in each state; a transition model; a discount factor, and a reward function. Methods for solving MDPs usually involve dynamic programming.\n\n\n## Module 8 Definitions\n* **Bellman equation**: $U(s) = max_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U(s')] = max_a Q(s,a)$\n* **Bellman update**: $U_{i+1}(s) = max_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U_i(s')]$\n* **Continuity**: $A \\succ B \\succ C \\Rightarrow \\exists p | [p, A; 1-p, C] \\sim B$\n* **Decomposability**: $[p, A; 1-p, [q, B; 1-q, C]] \\sim [p, A; (1-p)q, B; (1-p)(1-q), C]$\n* **Expected utility of an action $a$**: $EU(a) = \\sum_s' P(\\textnormal{RESULT}(a)=s') U(s')$\n* **Expected utility with policy $\\pi$ and state $s$**: $U^\\pi(s) = E[\\sum_{t=0}^\\infty \\gamma^tR(S_t, \\pi(S_t), S_{t+1})]$\n* **Meu principle**: a rational agent should choose the action that maximizes the agent’s expected utility\n* **Monotonicity**: $A \\succ B \\Rightarrow (p \\gt q \\Leftrightarrow [p, A; 1-p, B] \\succ [q, A; 1-q, B])$\n* **Optimal policy for state $s$**: $\\pi^*(s) = argmax_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U(s')]$\n* **Orderability**: Given any two lotteries $L_1, L_2$, $L_1 \\succ L_2 \\vee L_1 \\sim L_2 \\vee L_2 \\succ L_1$\n* **Policy evaluation**: Given a policy $\\pi_i$, calculate the utility of each state using this policy\n* **Policy improvement**: Determine the next policy to use, $\\pi_{i+1}$, looking ahead by one step and following MEU\n* **Preference attributes**: Orderability, Transitivity, Continuity, Substitutability, Monotonicity, and Decomposability\n* **Probability of reaching state $s'$ through action $a$**: $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$\n* **Substitutability**: $A \\sim B \\Rightarrow [p, A; 1-p, C] \\sim [p, B; 1-p, C]$\n* **Transitivity**: $A \\succ B \\land B \\succ C \\Rightarrow A \\succ C$\n* **Value iteration**: Apply Bellman updates successively until equilibrium\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 Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\"The most common form of action-utility learning is **Q-learning**, where the agent learns a **Q-function** \\\n",
        ", or quality-function, denoting the sum of rewards from state onward if action is taken. Given a Q-function, the agent can \\\n",
        "choose what to do in by finding the action with the highest Q-value.\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\"\n",
        "Basic reinforcement learning loop: \n",
        "- The agent takes action a, and receives a reward r and a state s from the environment\n",
        "- The agent must learn to act so as to maximize expected rewards\n",
        "\n",
        "Model-based learning:\n",
        "- Learn an approximate model based on experiences\n",
        "- Solve for values as if the learned model were correct\n",
        "- Step 1: learn empirical MDP model\n",
        "  - Count outcomes s’ for each s, a\n",
        "  - Normalize to give an estimate of T(s,a,s’)\n",
        "  - Discover each R(s,a,s’) when we experience (s,a,s’)\n",
        "- Step 2: solve the learned MDP\n",
        "  - For example, use value iteration, as before\n",
        "\n",
        "Model-free learning:\n",
        "- Two kinds: passive and active reinforcement learning\n",
        "- Passive learning is where someone else tells us what to do - we simply execute the given policy and learn from experience\n",
        "- Direct evaluation is easy to understand, doesn’t require any knowledge of T or R, and it eventually computes the correct average values. \\\n",
        "However, it wastes information about state connections, each state must be learned separately, and it takes a long time to learn\n",
        "  - We can’t use policy evaluation since we don’t know T or R\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"Difficulty\": \"learning can be much harder than solving a known MDP\",\n",
        "\"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",
        "\"Reward-to-go\": \"the total reward from a given state onward\",\n",
        "\"Sampling\": \"because of chance, you have to try things repeatedly\"\n",
        "}\n"
      ],
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 768
        },
        "outputId": "6400ddc0-022b-4653-acd4-ab77ae34d038"
      },
      "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 22.1 Learning from Rewards\", chapter22_1),\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": 7,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 22.1 Learning from Rewards\nThe 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## Module 9 Lecture Notes\n\nBasic reinforcement learning loop: \n- The agent takes action a, and receives a reward r and a state s from the environment\n- The agent must learn to act so as to maximize expected rewards\n\nModel-based learning:\n- Learn an approximate model based on experiences\n- Solve for values as if the learned model were correct\n- Step 1: learn empirical MDP model\n  - Count outcomes s’ for each s, a\n  - Normalize to give an estimate of T(s,a,s’)\n  - Discover each R(s,a,s’) when we experience (s,a,s’)\n- Step 2: solve the learned MDP\n  - For example, use value iteration, as before\n\nModel-free learning:\n- Two kinds: passive and active reinforcement learning\n- Passive learning is where someone else tells us what to do - we simply execute the given policy and learn from experience\n- Direct evaluation is easy to understand, doesn’t require any knowledge of T or R, and it eventually computes the correct average values. However, it wastes information about state connections, each state must be learned separately, and it takes a long time to learn\n  - We can’t use policy evaluation since we don’t know T or R\n\n\n## Module 9 Definitions\n* **Difficulty**: learning can be much harder than solving a known MDP\n* **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* **Reward-to-go**: the total reward from a given state onward\n* **Sampling**: because of chance, you have to try things repeatedly\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 = \"\"\"\n",
        "```\n",
        "function DT-Agent(percept):\n",
        "  persistent: belief-state, probabilistic beliefs about the current state of the world\n",
        "              action, the agent's action\n",
        "\n",
        "  update belief-state based on action and percept\n",
        "  calculate outcome probabilities for actions, given action descriptions and current belief-state\n",
        "  select action with highest expected utility given probabilities of outcomes and utility information\n",
        "  return action \n",
        "```\n",
        "\"\"\"\n",
        "chapter12_7 = \"\"\"The **naive Bayes** model assumes the conditional independence of all effect variables, \\\n",
        "given a single cause variable; its size grows linearly with the number of effects.\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\"\n",
        "Inference by Enumeration:\n",
        "- Select entries consistent with evidence\n",
        "- Sum out hidden variables to get joint probability of Query and evidence variables\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"Probabilistic Inference\": \"the process of determining desired probabilities from a set of known other probabilities\",\n",
        "r\"Probability of $a$ given $b$\": r\"$P(a|b) = \\frac{P(a \\land b)}{P(b)}$\",\n",
        "\"Bayes' Law\": r\"$P(b|a) = \\frac{P(a|b)P(b)}{P(a)}$\"\n",
        "}"
      ],
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 576
        },
        "outputId": "77a2e8c9-e5ed-433d-faf4-2212bb586806"
      },
      "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.7 The Wumpus World Revisited\", chapter12_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": 9,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n\n```\nfunction DT-Agent(percept):\n  persistent: belief-state, probabilistic beliefs about the current state of the world\n              action, the agent's action\n\n  update belief-state based on action and percept\n  calculate outcome probabilities for actions, given action descriptions and current belief-state\n  select action with highest expected utility given probabilities of outcomes and utility information\n  return action \n```\n\n\n## AIMA Chapter 12.7 The Wumpus World Revisited\nThe **naive Bayes** model assumes the conditional independence of all effect variables, given a single cause variable; its size grows linearly with the number of effects.\n\n## Module 10 Lecture Notes\n\nInference by Enumeration:\n- Select entries consistent with evidence\n- Sum out hidden variables to get joint probability of Query and evidence variables\n\n\n## Module 10 Definitions\n* **Probabilistic inference**: the process of determining desired probabilities from a set of known other probabilities\n* **Probability of $a$ given $b$**: $P(a|b) = \\frac{P(a \\land b)}{P(b)}$\n* **Bayes' law**: $P(b|a) = \\frac{P(a|b)P(b)}{P(a)}$\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 = \"\"\"\n",
        "A **Bayesian network** is a directed graph in which each node is annotated with quantitative \\\n",
        "probability information. The full specification is as follows:\n",
        "1. Each node corresponds to a random variable, which may be discrete or continuous.\n",
        "2. Directed links or arrows connect pairs of nodes. If there is an arrow from node *X* to node *Y*, *X* is said to be a **parent** \\\n",
        "of *Y*. The graph has no directed cycles and hence is a directed acyclic graph, or DAG.\n",
        "3. Each node *X_i* has associated probability information *theta(X_i | Parents(X_i))* that quantifies the effect of the parents on the node using a \\\n",
        "finite number of **parameters**.\n",
        "\"\"\"\n",
        "chapter13_3 = \"\"\"\n",
        "```\n",
        "function Enumeration_Ask(X, e, bn):\n",
        "  inputs: X, the query variable\n",
        "          e, observed values for variables E\n",
        "          bn, a Bayes net with variables vars\n",
        "  \n",
        "  Q(X) = a distribution over X, initially empty\n",
        "  for x_i in X:\n",
        "    Q(x_i) = Enumerate_All(vars, e_x_i) where e_x_i is e extended with X = x_i\n",
        "  return Normalize(Q(X))\n",
        "\n",
        "function Enumerate_All(vars, e):\n",
        "  if vars is empty, return 1.0\n",
        "  V = vars[0]\n",
        "  if V is an evidence variable with value v in e:\n",
        "    return P(v|parents(V)) x Enumerate_All(vars[1:], e)\n",
        "  else return sum_v P(v|parents(V)) x Enumerate_All(vars[1:], e_v) where e_v is e extended with V = v\n",
        "```\n",
        "\"\"\"\n"
      ],
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 628
        },
        "outputId": "58db67e6-e7a7-4d96-abc5-10c4f03e49b9"
      },
      "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 13.3 Exact Inference in Bayesian Networks\", chapter13_3)\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, {})\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": 11,
      "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\nA **Bayesian network** is a directed graph in which each node is annotated with quantitative probability information. The full specification is as follows:\n1. Each node corresponds to a random variable, which may be discrete or continuous.\n2. Directed links or arrows connect pairs of nodes. If there is an arrow from node *X* to node *Y*, *X* is said to be a **parent** of *Y*. The graph has no directed cycles and hence is a directed acyclic graph, or DAG.\n3. Each node *X_i* has associated probability information *theta(X_i | Parents(X_i))* that quantifies the effect of the parents on the node using a finite number of **parameters**.\n\n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n\n```\nfunction Enumeration_Ask(X, e, bn):\n  inputs: X, the query variable\n          e, observed values for variables E\n          bn, a Bayes net with variables vars\n  \n  Q(X) = a distribution over X, initially empty\n  for x_i in X:\n    Q(x_i) = Enumerate_All(vars, e_x_i) where e_x_i is e extended with X = x_i\n  return Normalize(Q(X))\n\nfunction Enumerate_All(vars, e):\n  if vars is empty, return 1.0\n  V = vars[0]\n  if V is an evidence variable with value v in e:\n    return P(v|parents(V)) x Enumerate_All(vars[1:], e)\n  else return sum_v P(v|parents(V)) x Enumerate_All(vars[1:], e_v) where e_v is e extended with V = v\n```\n\n\n## Module 11 Definitions\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 = \"\"\"In **supervised learning** the agent observes input-output pairs and \\\n",
        "learns a function that maps from input to output. In **unsupervised learning** the agent \\\n",
        "learns patterns in the input without any explicit feedback. The most common unsupervised \\\n",
        "learning task is **clustering**: detecting potentially useful clusters of input examples. \\\n",
        "In **reinforcement learning** the agent learns from a series of reinforcements: rewards \\\n",
        "and punishments\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\"\n",
        "Inference for Naive Bayes\n",
        "- Goal: compute posterior distribution over label variable Y\n",
        "- Step 1: get joint probability of label and evidence for each label\n",
        "- Step 2: sum to get probability of evidence\n",
        "- Step 3: normalize by dividing Step 1 by Step 2\n",
        "\n",
        "Relative frequencies are the maximum likelihood estimates, but this doesn’t leave enough probability for things we haven’t seen yet\n",
        "- **Laplace Smoothing** is where you pretend you saw every outcome once more than you actually did (add one to all probability numerators and denominators)\n",
        "\n",
        "We can design a baseline to help determine how hard a given task is - which can then be used to determine how “good” a model’s accuracy is\n",
        "- In real research, the baseline is often a state-of-the-art model on which we are trying to improve\n",
        "- The confidence of a probabilistic classifier model is the posterior over the top label and represents how sure \\\n",
        "the classifier is of the classification (confidence(x) = max_y P(y|x))\n",
        "\n",
        "Learning for Binary Perceptrons\n",
        "- Start with all weights = 0\n",
        "- For each training instance:\n",
        "  - Classify with current weights\n",
        "  - If correct (i.e., y=y*), no change\n",
        "  - Otherwise, adjust the weight vector by adding or subtracting the feature vector. Subtract if y* is -1\n",
        "    - w = w + y* · f\n",
        "    - Note that this also changes our decision boundary\n",
        "\n",
        "If we have multiple classes, we need a multiclass decision rule\n",
        "- Each class has its own weight vector\n",
        "- Activation of a class y = w_y·f(x)\n",
        "- Prediction highest score wins (y = argmax_y wy·f(x))\n",
        "\n",
        "Learning with multiple classes is largely the same as for binary perceptrons, but if a prediction is wrong we lower the \\\n",
        "score of the wrong answer and raise the score of the right answer both by f(x) (don’t change irrelevant weight vectors)\n",
        "- Perceptrons have the properties of separability, convergence, and mistake bound\n",
        "- However, if data isn’t separable then the weights might thrash (i.e. with noise)\n",
        "- Can also have mediocre generalization where it finds a “barely” separating solution\n",
        "- Can often overtrain and lose accuracy on test and held-out data (but we can solve this by testing the weights each \\\n",
        "iteration and stop training once results begin to decrease)\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"Linear Interpolation\": r\"$P_{LIN}(x|y) = \\alpha P(x|y) + (1-\\alpha)P(x)$\"   \n",
        "}\n",
        "\n"
      ],
      "execution_count": 20,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 953
        },
        "outputId": "816b49ba-79e3-41dc-91b7-7e18f411336f"
      },
      "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",
        "  (\"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": 21,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\nIn **supervised learning** the agent observes input-output pairs and learns a function that maps from input to output. In **unsupervised learning** the agent learns patterns in the input without any explicit feedback. The most common unsupervised learning task is **clustering**: detecting potentially useful clusters of input examples. In **reinforcement learning** the agent learns from a series of reinforcements: rewards and punishments\n\n## Module 12 Lecture Notes\n\nInference for Naive Bayes\n- Goal: compute posterior distribution over label variable Y\n- Step 1: get joint probability of label and evidence for each label\n- Step 2: sum to get probability of evidence\n- Step 3: normalize by dividing Step 1 by Step 2\n\nRelative frequencies are the maximum likelihood estimates, but this doesn’t leave enough probability for things we haven’t seen yet\n- **Laplace Smoothing** is where you pretend you saw every outcome once more than you actually did (add one to all probability numerators and denominators)\n\nWe can design a baseline to help determine how hard a given task is - which can then be used to determine how “good” a model’s accuracy is\n- In real research, the baseline is often a state-of-the-art model on which we are trying to improve\n- The confidence of a probabilistic classifier model is the posterior over the top label and represents how sure the classifier is of the classification (confidence(x) = max_y P(y|x))\n\nLearning for Binary Perceptrons\n- Start with all weights = 0\n- For each training instance:\n  - Classify with current weights\n  - If correct (i.e., y=y*), no change\n  - Otherwise, adjust the weight vector by adding or subtracting the feature vector. Subtract if y* is -1\n    - w = w + y* · f\n    - Note that this also changes our decision boundary\n\nIf we have multiple classes, we need a multiclass decision rule\n- Each class has its own weight vector\n- Activation of a class y = w_y·f(x)\n- Prediction highest score wins (y = argmax_y wy·f(x))\n\nLearning with multiple classes is largely the same as for binary perceptrons, but if a prediction is wrong we lower the score of the wrong answer and raise the score of the right answer both by f(x) (don’t change irrelevant weight vectors)\n- Perceptrons have the properties of separability, convergence, and mistake bound\n- However, if data isn’t separable then the weights might thrash (i.e. with noise)\n- Can also have mediocre generalization where it finds a “barely” separating solution\n- Can often overtrain and lose accuracy on test and held-out data (but we can solve this by testing the weights each iteration and stop training once results begin to decrease)\n\n\n## Module 12 Definitions\n* **Linear interpolation**: $P_{LIN}(x|y) = \\alpha P(x|y) + (1-\\alpha)P(x)$\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": [
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\"\n",
        "Classifier components required for ML:\n",
        "- M observations of input/output pairs (x(i), y(i))\n",
        "- A **feature representation** of the input. For each input observation x(i), this will be a vector of features [x1, x2, …, x2]\n",
        "- A **classification function** that computes the estimated class y-hat via p(y | x)\n",
        "- An **objective function** for learning, usually involving minimizing error on training examples\n",
        "- An algorithm for **optimizing** the objective function\n",
        "\n",
        "Logistic regression solves the task of sentiment classification by learning, from a training set, a vector of weights and a bias term: z = w · x + b\n",
        "- This differs from perceptrons only in that it contains z to be in the range [0, 1) through a sigmoid function y-hat = 1 / (1+e-z), \\\n",
        "and we update the weights for every change, not just mistakes\n",
        "- We can then say, for binary classification, that y-hat = 1 if P(y = 1 | x) > 0.5 (the decision boundary) and 0 otherwise\n",
        "\n",
        "How do we get the weights of the model? We learn the parameters (weights + bias) from learning. This requires:\n",
        "- 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",
        "  - L(y-hat, y) = how much y-hat differs from the true y\n",
        "  - One example is mean squared error: L_MSE(y-hat, y) = ½ (y-hat - y)^2\n",
        "  - Cross-entropy loss is a conditional maximum likelihood estimation: choose parameters w, b that maximize the (log) probabilities of the \\\n",
        "  true labels in the training data: p(y | x) = y-haty (1 - y-hat)1-y \n",
        "  - Or to transform to a loss function in log space, -L_CE(y-hat, y) = -y log(y-hat) - (1 - y)log(1 - y-hat)\n",
        "- An algorithm for optimizing the loss function\n",
        "  - We use **gradient descent** to find good settings for our weights and bias by minimizing the loss function\n",
        "    - 𝜃-hat = argmin_𝜃 1/m * sum_i=1^m L_CE(y(i), x(i); 𝜃)\n",
        "    - This finds a minimum of a function by figuring out in which direction (in the space of the parameters 𝜃) the function’s slope \\\n",
        "    is rising the most steeply, and moving in the opposite direction\n",
        "  - For logistic regression, this loss function is **convex** (has only one global minimum value)\n",
        "  - The step size for this gradient descent is the same as our learning rate 𝜂\n",
        "- The magnitude of the amount to move in gradient descent is the value of the slope weighted by a learning rate 𝜂\n",
        "  - w^t+1 = wt - 𝜂 (d/dw L(f(x; w), y))\n",
        "\n",
        "The output of each hidden layer in a feedforward NN, the vector *h*, using the sigmoid function, is *h = sigmoid(Wx+b)*\n",
        "This produces a probability distribution *y = softmax(Uh)*\n",
        "\n",
        "To compute the gradient for the loss function, we now need to use error back propagation - in which values are computed \\\n",
        "on the network through a forward pass and weights are updated in a backward pass through backwards differentiation using \\\n",
        "the chain rule from calculus.\n",
        "\n",
        "\n",
        "```\n",
        "function SGD(L(), f(), x, y):\n",
        "    𝜃 = 0\n",
        "    repeat T times:\n",
        "        for each training tuple (x^i, y^i) (in random order):\n",
        "            compute y-hat^i = f(x^i; 𝜃)\n",
        "            compute the loss L(y-hat^i, y^i)\n",
        "            g = del_𝜃(L(f(x^i; 𝜃), y^i)\n",
        "            𝜃 = 𝜃 - 𝜂g\n",
        "    return 𝜃\n",
        "```\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "r\"$softmax(z_i)$\": r\"$\\frac{e^{z_j}}{\\sum_{j=1}^k e^{z_j}}$ where $1 \\le i \\le k$\",\n",
        "r\"$\\frac{\\triangledown(Cost(w,b))}{\\triangledown(w_j)}$\": r\"$\\sum_{i=1}^m [\\sigma(w · x^i + b) - y^i] x_j^i$\"\n",
        "}\n"
      ],
      "execution_count": 38,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "17f7e1f4-2768-4d59-ccc2-11963034978e"
      },
      "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",
        "  (\"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": 39,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## Module 13 Lecture Notes\n\nClassifier components required for ML:\n- M observations of input/output pairs (x(i), y(i))\n- A **feature representation** of the input. For each input observation x(i), this will be a vector of features [x1, x2, …, x2]\n- A **classification function** that computes the estimated class y-hat via p(y | x)\n- An **objective function** for learning, usually involving minimizing error on training examples\n- An algorithm for **optimizing** the objective function\n\nLogistic regression solves the task of sentiment classification by learning, from a training set, a vector of weights and a bias term: z = w · x + b\n- This differs from perceptrons only in that it contains z to be in the range [0, 1) through a sigmoid function y-hat = 1 / (1+e-z), and we update the weights for every change, not just mistakes\n- We can then say, for binary classification, that y-hat = 1 if P(y = 1 | x) > 0.5 (the decision boundary) and 0 otherwise\n\nHow do we get the weights of the model? We learn the parameters (weights + bias) from learning. This requires:\n- 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  - L(y-hat, y) = how much y-hat differs from the true y\n  - One example is mean squared error: L_MSE(y-hat, y) = ½ (y-hat - y)^2\n  - Cross-entropy loss is a conditional maximum likelihood estimation: choose parameters w, b that maximize the (log) probabilities of the   true labels in the training data: p(y | x) = y-haty (1 - y-hat)1-y \n  - Or to transform to a loss function in log space, -L_CE(y-hat, y) = -y log(y-hat) - (1 - y)log(1 - y-hat)\n- An algorithm for optimizing the loss function\n  - We use **gradient descent** to find good settings for our weights and bias by minimizing the loss function\n    - 𝜃-hat = argmin_𝜃 1/m * sum_i=1^m L_CE(y(i), x(i); 𝜃)\n    - This 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  - For logistic regression, this loss function is **convex** (has only one global minimum value)\n  - The step size for this gradient descent is the same as our learning rate 𝜂\n- The magnitude of the amount to move in gradient descent is the value of the slope weighted by a learning rate 𝜂\n  - w^t+1 = wt - 𝜂 (d/dw L(f(x; w), y))\n\nThe output of each hidden layer in a feedforward NN, the vector *h*, using the sigmoid function, is *h = sigmoid(Wx+b)*\nThis produces a probability distribution *y = softmax(Uh)*\n\nTo compute the gradient for the loss function, we now need to use error back propagation - in which values are computed on the network through a forward pass and weights are updated in a backward pass through backwards differentiation using the chain rule from calculus.\n\n\n```\nfunction SGD(L(), f(), x, y):\n    𝜃 = 0\n    repeat T times:\n        for each training tuple (x^i, y^i) (in random order):\n            compute y-hat^i = f(x^i; 𝜃)\n            compute the loss L(y-hat^i, y^i)\n            g = del_𝜃(L(f(x^i; 𝜃), y^i)\n            𝜃 = 𝜃 - 𝜂g\n    return 𝜃\n```\n\n\n## Module 13 Definitions\n* **$softmax(z_i)$**: $\\frac{e^{z_j}}{\\sum_{j=1}^k e^{z_j}}$ where $1 \\le i \\le k$\n* **$\\frac{\\triangledown(cost(w,b))}{\\triangledown(w_j)}$**: $\\sum_{i=1}^m [\\sigma(w · x^i + b) - y^i] x_j^i$\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": [
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\"\n",
        "N-gram LM’s are useful, but fail to generalize beyond what we’ve seen. Instead, Neural LM’s don’t need smoothing, \\\n",
        "can handle much longer histories, can generalize, but take longer to train.\n",
        "- The input for these Neural LM’s is a k-gram of words w_1:k\n",
        "- The output is a probability distribution over the next word\n",
        "- The *k* context words are treated as a word window. Each word is associated with an embedding vector\n",
        "\n",
        "Current SOTA Neural LM’s: \n",
        "- ELMo\n",
        "- GPT family\n",
        "- BERT\n",
        "\n",
        "How to learn Word2Vec embeddings:\n",
        "- Start with *V* random 300-dimensional vectors as initial embeddings\n",
        "- Use logistic regression:\n",
        "  - Take a corpus and take pairs of words that co-occur as positive examples\n",
        "  - Take pairs of words that don’t co-occur as negative examples\n",
        "  - Train the classifier to distinguish these by slowly adjusting all the embeddings to improve the classifier accuracy\n",
        "  - Throw away the classifier code and keep the embeddings\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {}\n"
      ],
      "execution_count": 40,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 972
        },
        "outputId": "a3498130-7905-4f51-8db7-f717e01f7980"
      },
      "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",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes)\n",
        "]\n",
        "\n",
        "module14_markdown = format_module(14, \"Natural Language Processing\", \n",
        "                         module14_sections, \n",
        "                         module14_definitions)\n",
        "display(Markdown(module14_markdown))"
      ],
      "execution_count": 41,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## Module 13 Lecture Notes\n\nClassifier components required for ML:\n- M observations of input/output pairs (x(i), y(i))\n- A **feature representation** of the input. For each input observation x(i), this will be a vector of features [x1, x2, …, x2]\n- A **classification function** that computes the estimated class y-hat via p(y | x)\n- An **objective function** for learning, usually involving minimizing error on training examples\n- An algorithm for **optimizing** the objective function\n\nLogistic regression solves the task of sentiment classification by learning, from a training set, a vector of weights and a bias term: z = w · x + b\n- This differs from perceptrons only in that it contains z to be in the range [0, 1) through a sigmoid function y-hat = 1 / (1+e-z), and we update the weights for every change, not just mistakes\n- We can then say, for binary classification, that y-hat = 1 if P(y = 1 | x) > 0.5 (the decision boundary) and 0 otherwise\n\nHow do we get the weights of the model? We learn the parameters (weights + bias) from learning. This requires:\n- 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  - L(y-hat, y) = how much y-hat differs from the true y\n  - One example is mean squared error: L_MSE(y-hat, y) = ½ (y-hat - y)^2\n  - Cross-entropy loss is a conditional maximum likelihood estimation: choose parameters w, b that maximize the (log) probabilities of the   true labels in the training data: p(y | x) = y-haty (1 - y-hat)1-y \n  - Or to transform to a loss function in log space, -L_CE(y-hat, y) = -y log(y-hat) - (1 - y)log(1 - y-hat)\n- An algorithm for optimizing the loss function\n  - We use **gradient descent** to find good settings for our weights and bias by minimizing the loss function\n    - 𝜃-hat = argmin_𝜃 1/m * sum_i=1^m L_CE(y(i), x(i); 𝜃)\n    - This 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  - For logistic regression, this loss function is **convex** (has only one global minimum value)\n  - The step size for this gradient descent is the same as our learning rate 𝜂\n- The magnitude of the amount to move in gradient descent is the value of the slope weighted by a learning rate 𝜂\n  - w^t+1 = wt - 𝜂 (d/dw L(f(x; w), y))\n\nThe output of each hidden layer in a feedforward NN, the vector *h*, using the sigmoid function, is *h = sigmoid(Wx+b)*\nThis produces a probability distribution *y = softmax(Uh)*\n\nTo compute the gradient for the loss function, we now need to use error back propagation - in which values are computed on the network through a forward pass and weights are updated in a backward pass through backwards differentiation using the chain rule from calculus.\n\n\n```\nfunction SGD(L(), f(), x, y):\n    𝜃 = 0\n    repeat T times:\n        for each training tuple (x^i, y^i) (in random order):\n            compute y-hat^i = f(x^i; 𝜃)\n            compute the loss L(y-hat^i, y^i)\n            g = del_𝜃(L(f(x^i; 𝜃), y^i)\n            𝜃 = 𝜃 - 𝜂g\n    return 𝜃\n```\n\n\n## Module 14 Definitions\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "c1b6fa72-2840-4ee8-dcb1-59e4dd7a2be6"
      },
      "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": 42,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.3 Utility Functions\nDecision theory is a **normative theory**: it describes how a rational agent *should* act. A **descriptive theory**, on the other hand, describes how actual agents — for example, humans — really *do* act\n\n## AIMA Chapter 17.1 Sequential Decision Problems\nA **Markov Decision Process** or **MDP** consists of a set of states (with an initial state); a set **ACTIONS(*s*)** of actions in each state; a transition model; a discount factor, and a reward function. Methods for solving MDPs usually involve dynamic programming.\n\n\n## Module 8 Definitions\n* **Bellman equation**: $U(s) = max_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U(s')] = max_a Q(s,a)$\n* **Bellman update**: $U_{i+1}(s) = max_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U_i(s')]$\n* **Continuity**: $A \\succ B \\succ C \\Rightarrow \\exists p | [p, A; 1-p, C] \\sim B$\n* **Decomposability**: $[p, A; 1-p, [q, B; 1-q, C]] \\sim [p, A; (1-p)q, B; (1-p)(1-q), C]$\n* **Expected utility of an action $a$**: $EU(a) = \\sum_s' P(\\textnormal{RESULT}(a)=s') U(s')$\n* **Expected utility with policy $\\pi$ and state $s$**: $U^\\pi(s) = E[\\sum_{t=0}^\\infty \\gamma^tR(S_t, \\pi(S_t), S_{t+1})]$\n* **Meu principle**: a rational agent should choose the action that maximizes the agent’s expected utility\n* **Monotonicity**: $A \\succ B \\Rightarrow (p \\gt q \\Leftrightarrow [p, A; 1-p, B] \\succ [q, A; 1-q, B])$\n* **Optimal policy for state $s$**: $\\pi^*(s) = argmax_{a \\in A(s)} \\sum_{s'} P(s' | s,a) [R(s,a,s') + \\gamma U(s')]$\n* **Orderability**: Given any two lotteries $L_1, L_2$, $L_1 \\succ L_2 \\vee L_1 \\sim L_2 \\vee L_2 \\succ L_1$\n* **Policy evaluation**: Given a policy $\\pi_i$, calculate the utility of each state using this policy\n* **Policy improvement**: Determine the next policy to use, $\\pi_{i+1}$, looking ahead by one step and following MEU\n* **Preference attributes**: Orderability, Transitivity, Continuity, Substitutability, Monotonicity, and Decomposability\n* **Probability of reaching state $s'$ through action $a$**: $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$\n* **Substitutability**: $A \\sim B \\Rightarrow [p, A; 1-p, C] \\sim [p, B; 1-p, C]$\n* **Transitivity**: $A \\succ B \\land B \\succ C \\Rightarrow A \\succ C$\n* **Value iteration**: Apply Bellman updates successively until equilibrium\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 22.1 Learning from Rewards\nThe 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## Module 9 Lecture Notes\n\nBasic reinforcement learning loop: \n- The agent takes action a, and receives a reward r and a state s from the environment\n- The agent must learn to act so as to maximize expected rewards\n\nModel-based learning:\n- Learn an approximate model based on experiences\n- Solve for values as if the learned model were correct\n- Step 1: learn empirical MDP model\n  - Count outcomes s’ for each s, a\n  - Normalize to give an estimate of T(s,a,s’)\n  - Discover each R(s,a,s’) when we experience (s,a,s’)\n- Step 2: solve the learned MDP\n  - For example, use value iteration, as before\n\nModel-free learning:\n- Two kinds: passive and active reinforcement learning\n- Passive learning is where someone else tells us what to do - we simply execute the given policy and learn from experience\n- Direct evaluation is easy to understand, doesn’t require any knowledge of T or R, and it eventually computes the correct average values. However, it wastes information about state connections, each state must be learned separately, and it takes a long time to learn\n  - We can’t use policy evaluation since we don’t know T or R\n\n\n## Module 9 Definitions\n* **Difficulty**: learning can be much harder than solving a known MDP\n* **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* **Reward-to-go**: the total reward from a given state onward\n* **Sampling**: because of chance, you have to try things repeatedly\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n\n```\nfunction DT-Agent(percept):\n  persistent: belief-state, probabilistic beliefs about the current state of the world\n              action, the agent's action\n\n  update belief-state based on action and percept\n  calculate outcome probabilities for actions, given action descriptions and current belief-state\n  select action with highest expected utility given probabilities of outcomes and utility information\n  return action \n```\n\n\n## AIMA Chapter 12.7 The Wumpus World Revisited\nThe **naive Bayes** model assumes the conditional independence of all effect variables, given a single cause variable; its size grows linearly with the number of effects.\n\n## Module 10 Lecture Notes\n\nInference by Enumeration:\n- Select entries consistent with evidence\n- Sum out hidden variables to get joint probability of Query and evidence variables\n\n\n## Module 10 Definitions\n* **Probabilistic inference**: the process of determining desired probabilities from a set of known other probabilities\n* **Probability of $a$ given $b$**: $P(a|b) = \\frac{P(a \\land b)}{P(b)}$\n* **Bayes' law**: $P(b|a) = \\frac{P(a|b)P(b)}{P(a)}$\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n\nA **Bayesian network** is a directed graph in which each node is annotated with quantitative probability information. The full specification is as follows:\n1. Each node corresponds to a random variable, which may be discrete or continuous.\n2. Directed links or arrows connect pairs of nodes. If there is an arrow from node *X* to node *Y*, *X* is said to be a **parent** of *Y*. The graph has no directed cycles and hence is a directed acyclic graph, or DAG.\n3. Each node *X_i* has associated probability information *theta(X_i | Parents(X_i))* that quantifies the effect of the parents on the node using a finite number of **parameters**.\n\n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n\n```\nfunction Enumeration_Ask(X, e, bn):\n  inputs: X, the query variable\n          e, observed values for variables E\n          bn, a Bayes net with variables vars\n  \n  Q(X) = a distribution over X, initially empty\n  for x_i in X:\n    Q(x_i) = Enumerate_All(vars, e_x_i) where e_x_i is e extended with X = x_i\n  return Normalize(Q(X))\n\nfunction Enumerate_All(vars, e):\n  if vars is empty, return 1.0\n  V = vars[0]\n  if V is an evidence variable with value v in e:\n    return P(v|parents(V)) x Enumerate_All(vars[1:], e)\n  else return sum_v P(v|parents(V)) x Enumerate_All(vars[1:], e_v) where e_v is e extended with V = v\n```\n\n\n## Module 11 Definitions\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\nIn **supervised learning** the agent observes input-output pairs and learns a function that maps from input to output. In **unsupervised learning** the agent learns patterns in the input without any explicit feedback. The most common unsupervised learning task is **clustering**: detecting potentially useful clusters of input examples. In **reinforcement learning** the agent learns from a series of reinforcements: rewards and punishments\n\n## Module 12 Lecture Notes\n\nInference for Naive Bayes\n- Goal: compute posterior distribution over label variable Y\n- Step 1: get joint probability of label and evidence for each label\n- Step 2: sum to get probability of evidence\n- Step 3: normalize by dividing Step 1 by Step 2\n\nRelative frequencies are the maximum likelihood estimates, but this doesn’t leave enough probability for things we haven’t seen yet\n- **Laplace Smoothing** is where you pretend you saw every outcome once more than you actually did (add one to all probability numerators and denominators)\n\nWe can design a baseline to help determine how hard a given task is - which can then be used to determine how “good” a model’s accuracy is\n- In real research, the baseline is often a state-of-the-art model on which we are trying to improve\n- The confidence of a probabilistic classifier model is the posterior over the top label and represents how sure the classifier is of the classification (confidence(x) = max_y P(y|x))\n\nLearning for Binary Perceptrons\n- Start with all weights = 0\n- For each training instance:\n  - Classify with current weights\n  - If correct (i.e., y=y*), no change\n  - Otherwise, adjust the weight vector by adding or subtracting the feature vector. Subtract if y* is -1\n    - w = w + y* · f\n    - Note that this also changes our decision boundary\n\nIf we have multiple classes, we need a multiclass decision rule\n- Each class has its own weight vector\n- Activation of a class y = w_y·f(x)\n- Prediction highest score wins (y = argmax_y wy·f(x))\n\nLearning with multiple classes is largely the same as for binary perceptrons, but if a prediction is wrong we lower the score of the wrong answer and raise the score of the right answer both by f(x) (don’t change irrelevant weight vectors)\n- Perceptrons have the properties of separability, convergence, and mistake bound\n- However, if data isn’t separable then the weights might thrash (i.e. with noise)\n- Can also have mediocre generalization where it finds a “barely” separating solution\n- Can often overtrain and lose accuracy on test and held-out data (but we can solve this by testing the weights each iteration and stop training once results begin to decrease)\n\n\n## Module 12 Definitions\n* **Linear interpolation**: $P_{LIN}(x|y) = \\alpha P(x|y) + (1-\\alpha)P(x)$\n\n\n# Module 13: Neural Networks\n## Module 13 Lecture Notes\n\nClassifier components required for ML:\n- M observations of input/output pairs (x(i), y(i))\n- A **feature representation** of the input. For each input observation x(i), this will be a vector of features [x1, x2, …, x2]\n- A **classification function** that computes the estimated class y-hat via p(y | x)\n- An **objective function** for learning, usually involving minimizing error on training examples\n- An algorithm for **optimizing** the objective function\n\nLogistic regression solves the task of sentiment classification by learning, from a training set, a vector of weights and a bias term: z = w · x + b\n- This differs from perceptrons only in that it contains z to be in the range [0, 1) through a sigmoid function y-hat = 1 / (1+e-z), and we update the weights for every change, not just mistakes\n- We can then say, for binary classification, that y-hat = 1 if P(y = 1 | x) > 0.5 (the decision boundary) and 0 otherwise\n\nHow do we get the weights of the model? We learn the parameters (weights + bias) from learning. This requires:\n- 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  - L(y-hat, y) = how much y-hat differs from the true y\n  - One example is mean squared error: L_MSE(y-hat, y) = ½ (y-hat - y)^2\n  - Cross-entropy loss is a conditional maximum likelihood estimation: choose parameters w, b that maximize the (log) probabilities of the   true labels in the training data: p(y | x) = y-haty (1 - y-hat)1-y \n  - Or to transform to a loss function in log space, -L_CE(y-hat, y) = -y log(y-hat) - (1 - y)log(1 - y-hat)\n- An algorithm for optimizing the loss function\n  - We use **gradient descent** to find good settings for our weights and bias by minimizing the loss function\n    - 𝜃-hat = argmin_𝜃 1/m * sum_i=1^m L_CE(y(i), x(i); 𝜃)\n    - This 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  - For logistic regression, this loss function is **convex** (has only one global minimum value)\n  - The step size for this gradient descent is the same as our learning rate 𝜂\n- The magnitude of the amount to move in gradient descent is the value of the slope weighted by a learning rate 𝜂\n  - w^t+1 = wt - 𝜂 (d/dw L(f(x; w), y))\n\nThe output of each hidden layer in a feedforward NN, the vector *h*, using the sigmoid function, is *h = sigmoid(Wx+b)*\nThis produces a probability distribution *y = softmax(Uh)*\n\nTo compute the gradient for the loss function, we now need to use error back propagation - in which values are computed on the network through a forward pass and weights are updated in a backward pass through backwards differentiation using the chain rule from calculus.\n\n\n```\nfunction SGD(L(), f(), x, y):\n    𝜃 = 0\n    repeat T times:\n        for each training tuple (x^i, y^i) (in random order):\n            compute y-hat^i = f(x^i; 𝜃)\n            compute the loss L(y-hat^i, y^i)\n            g = del_𝜃(L(f(x^i; 𝜃), y^i)\n            𝜃 = 𝜃 - 𝜂g\n    return 𝜃\n```\n\n\n## Module 13 Definitions\n* **$softmax(z_i)$**: $\\frac{e^{z_j}}{\\sum_{j=1}^k e^{z_j}}$ where $1 \\le i \\le k$\n* **$\\frac{\\triangledown(cost(w,b))}{\\triangledown(w_j)}$**: $\\sum_{i=1}^m [\\sigma(w · x^i + b) - y^i] x_j^i$\n\n\n# Module 14: Natural Language Processing\n## Module 13 Lecture Notes\n\nClassifier components required for ML:\n- M observations of input/output pairs (x(i), y(i))\n- A **feature representation** of the input. For each input observation x(i), this will be a vector of features [x1, x2, …, x2]\n- A **classification function** that computes the estimated class y-hat via p(y | x)\n- An **objective function** for learning, usually involving minimizing error on training examples\n- An algorithm for **optimizing** the objective function\n\nLogistic regression solves the task of sentiment classification by learning, from a training set, a vector of weights and a bias term: z = w · x + b\n- This differs from perceptrons only in that it contains z to be in the range [0, 1) through a sigmoid function y-hat = 1 / (1+e-z), and we update the weights for every change, not just mistakes\n- We can then say, for binary classification, that y-hat = 1 if P(y = 1 | x) > 0.5 (the decision boundary) and 0 otherwise\n\nHow do we get the weights of the model? We learn the parameters (weights + bias) from learning. This requires:\n- 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  - L(y-hat, y) = how much y-hat differs from the true y\n  - One example is mean squared error: L_MSE(y-hat, y) = ½ (y-hat - y)^2\n  - Cross-entropy loss is a conditional maximum likelihood estimation: choose parameters w, b that maximize the (log) probabilities of the   true labels in the training data: p(y | x) = y-haty (1 - y-hat)1-y \n  - Or to transform to a loss function in log space, -L_CE(y-hat, y) = -y log(y-hat) - (1 - y)log(1 - y-hat)\n- An algorithm for optimizing the loss function\n  - We use **gradient descent** to find good settings for our weights and bias by minimizing the loss function\n    - 𝜃-hat = argmin_𝜃 1/m * sum_i=1^m L_CE(y(i), x(i); 𝜃)\n    - This 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  - For logistic regression, this loss function is **convex** (has only one global minimum value)\n  - The step size for this gradient descent is the same as our learning rate 𝜂\n- The magnitude of the amount to move in gradient descent is the value of the slope weighted by a learning rate 𝜂\n  - w^t+1 = wt - 𝜂 (d/dw L(f(x; w), y))\n\nThe output of each hidden layer in a feedforward NN, the vector *h*, using the sigmoid function, is *h = sigmoid(Wx+b)*\nThis produces a probability distribution *y = softmax(Uh)*\n\nTo compute the gradient for the loss function, we now need to use error back propagation - in which values are computed on the network through a forward pass and weights are updated in a backward pass through backwards differentiation using the chain rule from calculus.\n\n\n```\nfunction SGD(L(), f(), x, y):\n    𝜃 = 0\n    repeat T times:\n        for each training tuple (x^i, y^i) (in random order):\n            compute y-hat^i = f(x^i; 𝜃)\n            compute the loss L(y-hat^i, y^i)\n            g = del_𝜃(L(f(x^i; 𝜃), y^i)\n            𝜃 = 𝜃 - 𝜂g\n    return 𝜃\n```\n\n\n## Module 14 Definitions\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}