{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Yu_Tang_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": "7ef56f15-e823-44c5-ffc9-2a58eafdfb62"
      },
      "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": 5,
      "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": "2c25466b-f6ef-403a-9bb2-097476c2f88a"
      },
      "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": 6,
      "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": 7,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 8 - Markov Decision Process"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 16, “Making Simple Decisions” (16.1-16.3)\n",
        "\n",
        "# sample_equation = r\"\"\" $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \"\"\"\n",
        "\n",
        "# chapter16_1 = \"\"\" Chapter 16.1 summary. \"\"\"  + sample_equation\n",
        "# chapter16_2 =  \"\"\" Your summary here \"\"\"\n",
        "# chapter16_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# # Russell and Norvig, AIMA Chapter 17, “Making Complex Decision” (17.1-17.2)\n",
        "# chapter17_1 = \"\"\" Your summary here \"\"\"\n",
        "# chapter17_2 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# # Lecture notes \n",
        "module8_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"transition function\":\"T(s, a, s’),p( s’ | s, a), s’ only depends on s (Markovian)\",\n",
        "\"Markov Decision Process\":\"sequential, fully observable,stochastic \\\n",
        "transition(non-deterministic search problem), additive rewards. Solve by expectimax method\",\n",
        "\"MDP Structure\":\"A set of states, actions, a transition function, reward function, initial state, one or more terminal states\",\n",
        "\"Discounting\":\"values of rewards decay exponentially, sooner rewards higher, helps converge\",\n",
        "\"Infinite Utilities\":\" Terminate episodes within T steps/ nonstationary policies(pi changes with time)\",\n",
        "\"V*(s)\":\"expected utility starting in s and acting optimally\",\n",
        "\"Q*(s,a)\":\"expected utility starting out having taken action a from state s and (thereafter) acting optimally\",\n",
        "\"pi* (s)\":\"optimal action from s\",\n",
        "\"Value Iteration\":\"Repeat to find V_{k+1}(s) until convergence,\\\n",
        "  Complexity of each iteratioin O(S^2A)\\\n",
        "  Policy may converge early\",\n",
        "\"Policy Iteration\":\" Policy evaluation:(fixed policy calculate utilities) \\\n",
        "+  Policy improvement, one step looking ahead, may faster\",\n",
        "\"policy extraction\":\"one step looking ahead\",\n",
        "\"Maximum expected utility (MEU) principle:\":\"Select the action that maximizes expected utility. An agent can be entirely rational without it\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Value iteration\n",
        "$$ V^*(s) = max_a Q^*(s,a)$$\n",
        "$$ Q^*(s,a) = \\sum_{s`} T(s,a,s')[R(s,a,s') + γV^*(s)$$\n",
        "$$ V^*(s) = max_a \\sum_{s`} T(s,a,s')[R(s,a,s') + γV^*(s)$$\n",
        "Policy iteration\n",
        "$$ V^{\\pi_i}_{k+1}(s) = \\sum_{s`} T(s,\\pi_i(s),s')[R(s,\\pi_i(s),s') + γV^{\\pi_i}_k(s')]$$\n",
        "One-step look-ahead\n",
        "$$\\pi_{i+1}(s) = arg max_{a}\\sum_{s`}T(s,a,s')[R(s,a,s') + γV^{\\pi_i}(s')$$\n"
      ],
      "metadata": {
        "id": "JL_C1-O4NM8o"
      }
    },
    {
      "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": 418
        },
        "outputId": "160ac880-f8e5-4bca-ce4b-d2e2571cf08f"
      },
      "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",
        "  (\"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": 9,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## Module 8 Lecture Notes\n Your summary here \n\n## Module 8 Definitions\n* **Transition function** - T(s, a, s’),p( s’ | s, a), s’ only depends on s (Markovian)\n* **Markov decision process** - sequential, fully observable,stochastic transition(non-deterministic search problem), additive rewards. Solve by expectimax method\n* **Mdp structure** - A set of states, actions, a transition function, reward function, initial state, one or more terminal states\n* **Discounting** - values of rewards decay exponentially, sooner rewards higher, helps converge\n* **Infinite utilities** -  Terminate episodes within T steps/ nonstationary policies(pi changes with time)\n* **V*(s)** - expected utility starting in s and acting optimally\n* **Q*(s,a)** - expected utility starting out having taken action a from state s and (thereafter) acting optimally\n* **Pi* (s)** - optimal action from s\n* **Value iteration** - Repeat to find V_{k+1}(s) until convergence,  Complexity of each iteratioin O(S^2A)  Policy may converge early\n* **Policy iteration** -  Policy evaluation:(fixed policy calculate utilities) +  Policy improvement, one step looking ahead, may faster\n* **Policy extraction** - one step looking ahead\n* **Maximum expected utility (meu) principle:** - Select the action that maximizes expected utility. An agent can be entirely rational without it\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 9 - Reinforcement Learning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# Russell and Norvig, AIMA Section 17.3 “Bandit Problems”\n",
        "# chapter17_3 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# # Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "# chapter22_1 =  \"\"\" Your summary here \"\"\"\n",
        "# chapter22_2 =  \"\"\" Your summary here \"\"\"\n",
        "# chapter22_3 =  \"\"\" Your summary here \"\"\"\n",
        "# chapter22_4 =  \"\"\" Your summary here \"\"\"\n",
        "# chapter22_5 =  \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# # Lecture notes \n",
        "module9_lecture_notes = \"\"\"  \"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"Reinforcement Learning features\" : \"cannot solve MDP only by computation. Act and figure it out.(Online Planning)\",\n",
        "\"Exploration\":\" try unknown actions\",\n",
        "\"Exploitation\":\"use info\",\n",
        "\"Regret\":\"make mistakes\",\n",
        "\"Sampling\":\"Try same things repeatedly\",\n",
        "\"Difficulty\":\"learning is harder than solving known MDP\",\n",
        "\"Model-Based Learning\":\"Learn an approximate model based on experiences.Learn empirical MDP model count outcomes,normalize,findR(s,a,s')\",\n",
        "\"Passive Reinforcement Learning\":\"fixed policy, no transitions, no rewards. Target: Learn the state values.\",\n",
        "\"Direct Evaluation\":\"Average together observed sample values according to the policy\",\n",
        "\"Direct Evaluation Pros \": \"Pros: No need T, R and fetch correct average values\",\n",
        "\"Direct Evaluation Cons\":\"Cons: ignore state connections, run long, learn each state saparately\",\n",
        "\"Sample-Based Policy Evaluation\":\"Update V(s) <- 1-alpha)V(s) + alpha * sample\",\n",
        "\"Exponential Moving Average\":\"Makes recent samples more important xn = (1-alpha)xn-1 + alpha*xn\",\n",
        "\"Active Reinforcement Learning\":\"no transitions, no rewards, human chooses actions. Goal: learn the optimal policy\",\n",
        "\"Regret(need minimize)\": \"Total mistake cost: the difference between optimal rewards and suboptimal result.\",\n",
        "\"Generalizing Across States\":\"Learn small amount of states from experience.\",\n",
        "}"
      ],
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Q-Value Iteration (Off-policy learning)\n",
        "\n",
        "$$ Q(s,a) = \\sum_{s`} T(s,a,s')[R(s,a,s') + γV(s)]$$\n",
        "$$ Q_{k+1}(s,a) = \\sum_{s`} T(s,a,s')[R(s,a,s') + γ\\ max_{a'}Q_k(s', a')]$$\n",
        "Approximate Q-Learning\n",
        "$$difference\\ = \\ [r + γmaxQ(s',a')_{a'}] - Q(s,a)$$\n",
        "$$ Q(s,a) =  Q(s,a) +\\alpha[difference]$$\n",
        "$$ω_i = ω_i + α[difference]f_i(s,a)$$"
      ],
      "metadata": {
        "id": "_IxDA8e5nlem"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 447
        },
        "outputId": "280b5d33-5b9f-4495-b6e8-f64ef2a2a4e0"
      },
      "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",
        "  (\"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": 11,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## Module 9 Lecture Notes\n  \n\n## Module 9 Definitions\n* **Reinforcement learning features** - cannot solve MDP only by computation. Act and figure it out.(Online Planning)\n* **Exploration** -  try unknown actions\n* **Exploitation** - use info\n* **Regret** - make mistakes\n* **Sampling** - Try same things repeatedly\n* **Difficulty** - learning is harder than solving known MDP\n* **Model-based learning** - Learn an approximate model based on experiences.Learn empirical MDP model count outcomes,normalize,findR(s,a,s')\n* **Passive reinforcement learning** - fixed policy, no transitions, no rewards. Target: Learn the state values.\n* **Direct evaluation** - Average together observed sample values according to the policy\n* **Direct evaluation pros ** - Pros: No need T, R and fetch correct average values\n* **Direct evaluation cons** - Cons: ignore state connections, run long, learn each state saparately\n* **Sample-based policy evaluation** - Update V(s) <- 1-alpha)V(s) + alpha * sample\n* **Exponential moving average** - Makes recent samples more important xn = (1-alpha)xn-1 + alpha*xn\n* **Active reinforcement learning** - no transitions, no rewards, human chooses actions. Goal: learn the optimal policy\n* **Regret(need minimize)** - Total mistake cost: the difference between optimal rewards and suboptimal result.\n* **Generalizing across states** - Learn small amount of states from experience.\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": [
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\"\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"Observed variables (evidence)\" : \"sample states of the world which Agent knows\",\n",
        "\"Unobserved variables (states):\":\"Agent doesn't know\",\n",
        "\"Model\":\"how the known variables relate to the unkown variables\",\n",
        "\"Sample space\":\" possible worlds, mutually exclusive and exhaustive.\",\n",
        "\"Event\":\"a set E of outcomes\",\n",
        "\"Probabilistic Inference\":\"compute a target probability from other known(eg. conditinoal prob)\",\n",
        "\"All variables\":\"Evidence variable + Query variable+ Hidden variables\",\n",
        "\"N-gram\":\"insufficient model because of long-distance dependencies, 0 for unseen words\",\n",
        "\"Maximum Likelihood Estimate\":\"P(a|b) = count(b,a)/count(b)\",\n",
        "\"Solve 0 prob for N-gram\" :\"Fiexd lexicon L of size L, normalize training data replacing word not in L with \\<unk>\"\n",
        "}"
      ],
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 342
        },
        "outputId": "2a4c4962-ed1f-4222-a2c4-c5b220975467"
      },
      "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",
        " \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": 13,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## Module 10 Lecture Notes\n\n\n## Module 10 Definitions\n* **Observed variables (evidence)** - sample states of the world which Agent knows\n* **Unobserved variables (states):** - Agent doesn't know\n* **Model** - how the known variables relate to the unkown variables\n* **Sample space** -  possible worlds, mutually exclusive and exhaustive.\n* **Event** - a set E of outcomes\n* **Probabilistic inference** - compute a target probability from other known(eg. conditinoal prob)\n* **All variables** - Evidence variable + Query variable+ Hidden variables\n* **N-gram** - insufficient model because of long-distance dependencies, 0 for unseen words\n* **Maximum likelihood estimate** - P(a|b) = count(b,a)/count(b)\n* **Solve 0 prob for n-gram** - Fiexd lexicon L of size L, normalize training data replacing word not in L with \\<unk>\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",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"Conditional Independence\" : \"P(x,y|z) = P(x|z)P(y|z), P(x|z,y) = P(x|z)\",    \n",
        "\"Bayes' Net\":\" one var one node + directed, acyclic graph + conditional distribution for each node\",\n",
        "\"Notice\":\"Not every BN can represent every joint distribution. ONLY absolutely independent can have no arcs.\",\n",
        "\"Bayes Net well reflect\":\"simpler parents, easier to think, easier to elicit from experts.BNs need not actually be causal\",\n",
        "\"arrows\":\"encode causal structure + encodes conditional independence\",\n",
        "\"# Joint distribution over N Boolean variables\":\"2^N\",\n",
        "\"# N-node net with k parents\":\"O(N * 2^{k+1})\",\n",
        "\"BN pros\":\"Huge space saving, Easier to elicit local CPTs, faster to answer queries\",\n",
        "\"Causal Chains\":\" X -> Y -> Z\",\n",
        "\"Common Cause\":\"X <- Y -> Z\",\n",
        "\"Common Effect\":\"X -> Z <- Y\",\n",
        "\"Active Paths\":\"All triples should be active\",\n",
        "\"D-Separation\":\"if one or more paths is active, the independence is not valid\",\n",
        "\"Inference by Enumeration in BN\":\"list all hidden cases for mid variables(if unlimited time)\"\n",
        "\n",
        "}\n"
      ],
      "execution_count": 14,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 412
        },
        "outputId": "afedfd25-688f-4d1a-e314-ea9dd54d54c6"
      },
      "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",
        "  (\"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": 15,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## Module 11 Lecture Notes\n\n\n## Module 11 Definitions\n* **Conditional independence** - P(x,y|z) = P(x|z)P(y|z), P(x|z,y) = P(x|z)\n* **Bayes' net** -  one var one node + directed, acyclic graph + conditional distribution for each node\n* **Notice** - Not every BN can represent every joint distribution. ONLY absolutely independent can have no arcs.\n* **Bayes net well reflect** - simpler parents, easier to think, easier to elicit from experts.BNs need not actually be causal\n* **Arrows** - encode causal structure + encodes conditional independence\n* **# joint distribution over n boolean variables** - 2^N\n* **# n-node net with k parents** - O(N * 2^{k+1})\n* **Bn pros** - Huge space saving, Easier to elicit local CPTs, faster to answer queries\n* **Causal chains** -  X -> Y -> Z\n* **Common cause** - X <- Y -> Z\n* **Common effect** - X -> Z <- Y\n* **Active paths** - All triples should be active\n* **D-separation** - if one or more paths is active, the independence is not valid\n* **Inference by enumeration in bn** - list all hidden cases for mid variables(if unlimited time)\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": [
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\"Bayes rule enables doing diagnostic queries with causal probabilitie\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"Naïve Bayes\" : \"All features are independent of the label.P(Y)*...*P(F_{ij}|Y)\",   \n",
        "\"Naïve Bayes for Text\":\"Features: Wi is the word at positon i not the ith word in dict, identically distributed\",\n",
        "\"bag-of-words model\":\"All positions share the same conditional probs P(W|Y) with identically distributed, regardless of order\",\n",
        "\"Overfit\":\"Use smotthing or regularizing operations\",\n",
        "\"Maximum Likelihood\":\"theta_ML = arg max P(X|theta) = arg max ∏P(X_i)\",\n",
        "\"Laplace Smoothing\":\"strength k cal:#red + k/ #totalcount + k * #red\",\n",
        "\"Linear Interpolation\":\"P（x|y) = alphaP(x|y) + (1 - alpha)P(x)\",\n",
        "\"Binary Perceptron Update\":\"correct no change. error: add/sub(y* = -1), w = w + y*f,raise score of right answer\",\n",
        "\"Birnary Perceptron\":\"always converge if training is separable otherwise average weight vectors（perceptron) overt time\",\n",
        "\"Multiclass Decision Rule\":\"arg max_y w_y * f(x)\",\n",
        "\"maximum step size\":\"converges faster than perceptron, better on noise data\",\n",
        "\"Naïve Bayes\":\"Gives prediction probabilities, feature independence,One pass through data(count)\",\n",
        "\"Perceptrons / MIRA\":\"less assumptions about data, Mistake-driven, Multiple passes through data(pred), more accurate\"\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 29,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Laplace Smoothing\n",
        "$$P_{LAP,k}(x) = \\frac{c(X) + k}{N + k|X|}$$\n",
        "Laplace for conditionals\n",
        "$$P_{LAP,k}(x|y) = \\frac{c(x,y) + k}{c(y) + k|X|}$$\n",
        "maximum step size\n",
        "$$τ^* = min(\\frac{(w'_y - w'_{y^*})f + 1}{2f * f}, C)$$"
      ],
      "metadata": {
        "id": "qg5nZyA09jlL"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 401
        },
        "cellView": "form",
        "outputId": "c5d0ca08-c6c7-413a-9e5d-e61a16d16b86"
      },
      "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",
        " \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": 30,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## Module 12 Lecture Notes\nBayes rule enables doing diagnostic queries with causal probabilitie\n\n## Module 12 Definitions\n* **Naïve bayes** - Gives prediction probabilities, feature independence,One pass through data(count)\n* **Naïve bayes for text** - Features: Wi is the word at positon i not the ith word in dict, identically distributed\n* **Bag-of-words model** - All positions share the same conditional probs P(W|Y) with identically distributed, regardless of order\n* **Overfit** - Use smotthing or regularizing operations\n* **Maximum likelihood** - theta_ML = arg max P(X|theta) = arg max ∏P(X_i)\n* **Laplace smoothing** - strength k cal:#red + k/ #totalcount + k * #red\n* **Linear interpolation** - P（x|y) = alphaP(x|y) + (1 - alpha)P(x)\n* **Binary perceptron update** - correct no change. error: add/sub(y* = -1), w = w + y*f,raise score of right answer\n* **Birnary perceptron** - always converge if training is separable otherwise average weight vectors（perceptron) overt time\n* **Multiclass decision rule** - arg max_y w_y * f(x)\n* **Maximum step size** - converges faster than perceptron, better on noise data\n* **Perceptrons / mira** - less assumptions about data, Mistake-driven, Multiple passes through data(pred), more accurate\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 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"logistic regression\" : \"use cross-entropy loss, SGD to min loss function\",  \n",
        "\"cross entropy loss\": \"f(xi, p) = p^xi * (1-p)^{1 - xi}\",\n",
        "\"Multinomial logistic regression\":\"softmax function, generalization of the sigmoid function\",\n",
        "\"The gradient of the loss\": \" error propagation\"\n",
        "}\n"
      ],
      "execution_count": 33,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Cross-Entropy Loss\n",
        "$$L(y',y) = -logp(y|x) = -[ylogy' + (1 - y)log(1-y)]$$"
      ],
      "metadata": {
        "id": "gAkuPCU8Pe7e"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 262
        },
        "outputId": "c4417fb3-ee04-438d-e374-ecbf97715bb4"
      },
      "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": 35,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 13 Definitions\n* **Logistic regression** - use cross-entropy loss, SGD to min loss function\n* **Cross entropy loss** - f(xi, p) = p^xi * (1-p)^{1 - xi}\n* **Multinomial logistic regression** - softmax function, generalization of the sigmoid function\n* **The gradient of the loss** -  error propagation\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": [
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"Neural Language Models\" : \"No need smoothing, handle longer histories, generalize over contexts of similar words, higher accuracy \", \n",
        "\"Neural LMs\": \"input k-gram word, get the prob of next word\",   \n",
        "\"joint distribution over 10 word, 100,000 vocabulary size\":\"100,000 ^ 10 parameters\",\n",
        "\"Unseen sequences\":\"Back-off, Smoothing / interpolation\",\n",
        "\"Term-Document Matrix\":\"col:document, row:term(word), cell: freq in docu\",\n",
        "\" Long (length |V| = 50,000+)\":\" Short (length 200-1000)\",\n",
        "\" Sparse (most elements are zeros)\":\"Dense (most elements are non-zero)\",\n",
        "\"get dense vectors\":\"target word + neighboring context word positive, rand other get neg, train LR model,weights->embeddings \"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 40,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 331
        },
        "outputId": "adeaa7c8-229c-4475-9c6b-e6b65e765914"
      },
      "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 Your summary here \n\n## Module 14 Definitions\n* **Neural language models** - No need smoothing, handle longer histories, generalize over contexts of similar words, higher accuracy \n* **Neural lms** - input k-gram word, get the prob of next word\n* **Joint distribution over 10 word, 100,000 vocabulary size** - 100,000 ^ 10 parameters\n* **Unseen sequences** - Back-off, Smoothing / interpolation\n* **Term-document matrix** - col:document, row:term(word), cell: freq in docu\n* ** long (length |v| = 50,000+)** -  Short (length 200-1000)\n* ** sparse (most elements are zeros)** - Dense (most elements are non-zero)\n* **Get dense vectors** - target word + neighboring context word positive, rand other get neg, train LR model,weights->embeddings \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": 2477
        },
        "id": "T3cm1WV542_a",
        "outputId": "e5baa8bc-a63f-4ab0-c28e-c1c1b32b401b",
        "cellView": "form"
      },
      "source": [
        "#@title\n",
        "# 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## Module 8 Lecture Notes\n Your summary here \n\n## Module 8 Definitions\n* **Transition function** - T(s, a, s’),p( s’ | s, a), s’ only depends on s (Markovian)\n* **Markov decision process** - sequential, fully observable,stochastic transition(non-deterministic search problem), additive rewards. Solve by expectimax method\n* **Mdp structure** - A set of states, actions, a transition function, reward function, initial state, one or more terminal states\n* **Discounting** - values of rewards decay exponentially, sooner rewards higher, helps converge\n* **Infinite utilities** -  Terminate episodes within T steps/ nonstationary policies(pi changes with time)\n* **V*(s)** - expected utility starting in s and acting optimally\n* **Q*(s,a)** - expected utility starting out having taken action a from state s and (thereafter) acting optimally\n* **Pi* (s)** - optimal action from s\n* **Value iteration** - Repeat to find V_{k+1}(s) until convergence,  Complexity of each iteratioin O(S^2A)  Policy may converge early\n* **Policy iteration** -  Policy evaluation:(fixed policy calculate utilities) +  Policy improvement, one step looking ahead, may faster\n* **Policy extraction** - one step looking ahead\n* **Maximum expected utility (meu) principle:** - Select the action that maximizes expected utility. An agent can be entirely rational without it\n\n\n# Module 9: Reinforcement Learning\n## Module 9 Lecture Notes\n  \n\n## Module 9 Definitions\n* **Reinforcement learning features** - cannot solve MDP only by computation. Act and figure it out.(Online Planning)\n* **Exploration** -  try unknown actions\n* **Exploitation** - use info\n* **Regret** - make mistakes\n* **Sampling** - Try same things repeatedly\n* **Difficulty** - learning is harder than solving known MDP\n* **Model-based learning** - Learn an approximate model based on experiences.Learn empirical MDP model count outcomes,normalize,findR(s,a,s')\n* **Passive reinforcement learning** - fixed policy, no transitions, no rewards. Target: Learn the state values.\n* **Direct evaluation** - Average together observed sample values according to the policy\n* **Direct evaluation pros ** - Pros: No need T, R and fetch correct average values\n* **Direct evaluation cons** - Cons: ignore state connections, run long, learn each state saparately\n* **Sample-based policy evaluation** - Update V(s) <- 1-alpha)V(s) + alpha * sample\n* **Exponential moving average** - Makes recent samples more important xn = (1-alpha)xn-1 + alpha*xn\n* **Active reinforcement learning** - no transitions, no rewards, human chooses actions. Goal: learn the optimal policy\n* **Regret(need minimize)** - Total mistake cost: the difference between optimal rewards and suboptimal result.\n* **Generalizing across states** - Learn small amount of states from experience.\n\n\n# Module 10: Probabilies and Language Models\n## Module 10 Lecture Notes\n\n\n## Module 10 Definitions\n* **Observed variables (evidence)** - sample states of the world which Agent knows\n* **Unobserved variables (states):** - Agent doesn't know\n* **Model** - how the known variables relate to the unkown variables\n* **Sample space** -  possible worlds, mutually exclusive and exhaustive.\n* **Event** - a set E of outcomes\n* **Probabilistic inference** - compute a target probability from other known(eg. conditinoal prob)\n* **All variables** - Evidence variable + Query variable+ Hidden variables\n* **N-gram** - insufficient model because of long-distance dependencies, 0 for unseen words\n* **Maximum likelihood estimate** - P(a|b) = count(b,a)/count(b)\n* **Solve 0 prob for n-gram** - Fiexd lexicon L of size L, normalize training data replacing word not in L with \\<unk>\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## Module 11 Lecture Notes\n\n\n## Module 11 Definitions\n* **Conditional independence** - P(x,y|z) = P(x|z)P(y|z), P(x|z,y) = P(x|z)\n* **Bayes' net** -  one var one node + directed, acyclic graph + conditional distribution for each node\n* **Notice** - Not every BN can represent every joint distribution. ONLY absolutely independent can have no arcs.\n* **Bayes net well reflect** - simpler parents, easier to think, easier to elicit from experts.BNs need not actually be causal\n* **Arrows** - encode causal structure + encodes conditional independence\n* **# joint distribution over n boolean variables** - 2^N\n* **# n-node net with k parents** - O(N * 2^{k+1})\n* **Bn pros** - Huge space saving, Easier to elicit local CPTs, faster to answer queries\n* **Causal chains** -  X -> Y -> Z\n* **Common cause** - X <- Y -> Z\n* **Common effect** - X -> Z <- Y\n* **Active paths** - All triples should be active\n* **D-separation** - if one or more paths is active, the independence is not valid\n* **Inference by enumeration in bn** - list all hidden cases for mid variables(if unlimited time)\n\n\n# Module 12: Naive Bayes and Perceptrons\n## Module 12 Lecture Notes\nBayes rule enables doing diagnostic queries with causal probabilitie\n\n## Module 12 Definitions\n* **Naïve bayes** - Gives prediction probabilities, feature independence,One pass through data(count)\n* **Naïve bayes for text** - Features: Wi is the word at positon i not the ith word in dict, identically distributed\n* **Bag-of-words model** - All positions share the same conditional probs P(W|Y) with identically distributed, regardless of order\n* **Overfit** - Use smotthing or regularizing operations\n* **Maximum likelihood** - theta_ML = arg max P(X|theta) = arg max ∏P(X_i)\n* **Laplace smoothing** - strength k cal:#red + k/ #totalcount + k * #red\n* **Linear interpolation** - P（x|y) = alphaP(x|y) + (1 - alpha)P(x)\n* **Binary perceptron update** - correct no change. error: add/sub(y* = -1), w = w + y*f,raise score of right answer\n* **Birnary perceptron** - always converge if training is separable otherwise average weight vectors（perceptron) overt time\n* **Multiclass decision rule** - arg max_y w_y * f(x)\n* **Maximum step size** - converges faster than perceptron, better on noise data\n* **Perceptrons / mira** - less assumptions about data, Mistake-driven, Multiple passes through data(pred), more accurate\n\n\n# Module 13: Neural Networks\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 13 Definitions\n* **Logistic regression** - use cross-entropy loss, SGD to min loss function\n* **Cross entropy loss** - f(xi, p) = p^xi * (1-p)^{1 - xi}\n* **Multinomial logistic regression** - softmax function, generalization of the sigmoid function\n* **The gradient of the loss** -  error propagation\n\n\n# Module 14: Natural Language Processing\n## Module 13 Lecture Notes\n Your summary here \n\n## Module 14 Definitions\n* **Neural language models** - No need smoothing, handle longer histories, generalize over contexts of similar words, higher accuracy \n* **Neural lms** - input k-gram word, get the prob of next word\n* **Joint distribution over 10 word, 100,000 vocabulary size** - 100,000 ^ 10 parameters\n* **Unseen sequences** - Back-off, Smoothing / interpolation\n* **Term-document matrix** - col:document, row:term(word), cell: freq in docu\n* ** long (length |v| = 50,000+)** -  Short (length 200-1000)\n* ** sparse (most elements are zeros)** - Dense (most elements are non-zero)\n* **Get dense vectors** - target word + neighboring context word positive, rand other get neg, train LR model,weights->embeddings \n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}