{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "“Template_for 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/"
        },
        "outputId": "0af1d0a6-041b-45d5-9936-ec17d2b0e4e1"
      },
      "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": "65467a79-8c40-4255-d51a-675d92b1e735"
      },
      "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",
        "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 = \"\"\"\n",
        "1.Stochastic Transition Model: the transition function is written as T(s,a,s') as a probability of arriving in state s' given that we are in state s and selct action a.\\n\n",
        "2.Transition are Markovian: the probability only determine by the s not earlier state.\\n\n",
        "3.Reward function will get reward for each step not just at the goal state based on s to s' via action a. R(s,a,s').\\n\n",
        "4.Markov Decision Process is a sequential desicion problem for a fully ovservable envirionemnt with a stochastic transition model that has additive rewards.(Non-deterministic search problems).\\n\n",
        "5.Way of solving MDP is expectimax search.\\n\n",
        "6.MDP we can't give a sequence of actions, but a policy map. $\\pi$(s)=a\\n\n",
        "7.The policy would not guarrantee what action to pick since it is stochastic.\\n\n",
        "8.Stationary preferences: if we assume stationary preferences, there are only two ways to define utilities(additive utility and discounted utility)\\n\n",
        "9.$V^{*}$=max$Q^{*}$(s,a)\\n\n",
        "10.Time-limited values to be the optimal values of s if the game ends in k more time steps.\\n\n",
        "11.Value iteration algorithm: complexity O($S^{2}$A). Will converage to unique optimal value.\\n\n",
        "12.Value of states change more often than the best action from the state.\\n\n",
        "13.Actions are easier to select from qvalues than values.\\n\n",
        "14.Both value iteration and policy iteration compute the same thing. Value iteration updates both values and policy, we don't track policy but take the max over actions.\n",
        "In policy iteration, we do several passes that update utilities with fixed policy(each pass is fast because we consider only one action not all). After the policy is evaluated, a new policy chosen slow like a value iteration pass. New policy will be better. \\n\n",
        "15.MDP summary: compute optimal values use value iteration or policy iteration. compute values for a particular policy use policy evaluation. Turn your values into a policy use policy extraction.\\n\n",
        "16.Principle of Maximum expected utilities: a rational agent should choose the action that maximizes its expected utility given its knowledge.\\n\n",
        "17.For average expectimax reasoning, we need magnitudes to be meaningful.\\n\n",
        "18.Maximum expected utility(MEU) principle, choose action maximizes expected utility.\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"reward function gives to agent for each step\",\n",
        "\"expected utility\" : \"your definition here\",\n",
        "\"define MDP\": \"set of states s, set of actions a, transtion model, reward function, initial state, termainal state(optional)\",\n",
        "\"policy\" : \"choice of action for each state\",\n",
        "\"$\\pi^{*}$\" : \"optimal policy\",\n",
        "\"discounting\" : \"maximize the sum of rewards and prefer rewards now\",\n",
        "\"utility\" : \"sum of (discounted) rewards\",\n",
        "\"Value of state\" : \"expected utility starting in s and acting optimally\",\n",
        "\"the value of q state\" : \"expected utility starting out having taken action a from state s and acting optimally\",\n",
        "\"utilities\" : \"functions from outcomes to real numbers that describe an agent's preferences\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 5,
      "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": 1000
        },
        "outputId": "35c6d904-eea1-4028-bcfb-009c9bb9ddd4"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module8_sections = [\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"AIMA Chapter 17.1 Sequential Decision Problems\", chapter17_1),\n",
        "  (\"AIMA Chapter 17.2 Algorithms for MDPs\", chapter17_2),\n",
        "  (\"Module 8 Lecture Notes\", module8_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 25):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module8_markdown = format_module(8, \"Markov Decision Processes\", module8_sections, module8_definitions)\n",
        "display(Markdown(module8_markdown))"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n\n1.Stochastic Transition Model: the transition function is written as T(s,a,s') as a probability of arriving in state s' given that we are in state s and selct action a.\n\n2.Transition are Markovian: the probability only determine by the s not earlier state.\n\n3.Reward function will get reward for each step not just at the goal state based on s to s' via action a. R(s,a,s').\n\n4.Markov Decision Process is a sequential desicion problem for a fully ovservable envirionemnt with a stochastic transition model that has additive rewards.(Non-deterministic search problems).\n\n5.Way of solving MDP is expectimax search.\n\n6.MDP we can't give a sequence of actions, but a policy map. $\\pi$(s)=a\n\n7.The policy would not guarrantee what action to pick since it is stochastic.\n\n8.Stationary preferences: if we assume stationary preferences, there are only two ways to define utilities(additive utility and discounted utility)\n\n9.$V^{*}$=max$Q^{*}$(s,a)\n\n10.Time-limited values to be the optimal values of s if the game ends in k more time steps.\n\n11.Value iteration algorithm: complexity O($S^{2}$A). Will converage to unique optimal value.\n\n12.Value of states change more often than the best action from the state.\n\n13.Actions are easier to select from qvalues than values.\n\n14.Both value iteration and policy iteration compute the same thing. Value iteration updates both values and policy, we don't track policy but take the max over actions.\nIn policy iteration, we do several passes that update utilities with fixed policy(each pass is fast because we consider only one action not all). After the policy is evaluated, a new policy chosen slow like a value iteration pass. New policy will be better. \n\n15.MDP summary: compute optimal values use value iteration or policy iteration. compute values for a particular policy use policy evaluation. Turn your values into a policy use policy extraction.\n\n16.Principle of Maximum expected utilities: a rational agent should choose the action that maximizes its expected utility given its knowledge.\n\n17.For average expectimax reasoning, we need magnitudes to be meaningful.\n\n18.Maximum expected utility(MEU) principle, choose action maximizes expected utility.\n\n\n## Module 8 Definitions\n* **Utility function** - reward function gives to agent for each step\n* **Expected utility** - your definition here\n* **Define mdp** - set of states s, set of actions a, transtion model, reward function, initial state, termainal state(optional)\n* **Policy** - choice of action for each state\n* **$\\pi^{*}$** - optimal policy\n* **Discounting** - maximize the sum of rewards and prefer rewards now\n* **Utility** - sum of (discounted) rewards\n* **Value of state** - expected utility starting in s and acting optimally\n* **The value of q state** - expected utility starting out having taken action a from state s and acting optimally\n* **Utilities** - functions from outcomes to real numbers that describe an agent's preferences\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",
        "1.Basic idea of reinforced learning: receive feedback in the form of rewards, agent's utility is defined by the reward function, must act so as to maximize the expected utility, all learning is based on observed samples of outcomes.\\n\n",
        "2.Model based learning: learn an approximate model based on experiences. Step 1 learn empirical MDP model, step 2 solve the learned MDP.\\n\n",
        "3.passive reinforcement learning input a fixed policy and don't know transitions and rewards, just learn the state values, not an offline planning.\\n\n",
        "4.direct evaluation average together observed sample values. Benefit: easy to understand, doesn't require any knowledge of T,R, eventually computes the correct average values using just sample transitions. Bad: waste information about state connections, each state must be learned seperately, longer time.\\n\n",
        "5.temporal difference learning: learn from every experience, update each time we experience a transition.\\n\n",
        "6.expoential moving average: decreasing learning rate($\\alpha$) can give converging averages.\\n\n",
        "7.q-learning: receive a sample, consider old estimate, consider new sample estimate(sample = R(s,a,s')+$\\gamma$maxQ(s',a')), incorporate the new estimate into a running average(Q(s,a) <- (1-$\\alpha$)Q(s,a)+$\\alpha$[sample]).\\n\n",
        "8.q-learning converge to an optimal policy. Off-policy learning. caveat: explore enough, make the learning rate small enough eventually but not decreasing quickly, doesn't matter how you select actions.\\n\n",
        "9.Explore: small probability, act randomly, large probability, act on current action. Problems: do eventually explore the space, but keep thrashing around once learning is done, one solution lower $\\epsilon$ another solution exploration functions.\\n\n",
        "10.Improvement: explore areas whose badness is not established, eventually stop exploration.\\n\n",
        "11.Linear value functions: advantage: experience is summed up in a few powerful numbers; disadvantages: states may share features but actually be very different in value.\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"exploration\" : \"try unknown actions to get information\",\n",
        "\"exploitation\" : \"use what you have learned\",\n",
        "\"regret\" : \"even if learn intelligently, will make mistake\",\n",
        "\"sampling\" : \"because of chance, have to try things repeatly\",\n",
        "\"difficulty\" : \"learning can be much harder\",\n",
        "\"regret\" : \"measure of total mistake cost(random exploration has higher)\"\n",
        "}"
      ],
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 979
        },
        "cellView": "form",
        "outputId": "2f69d096-2358-4c70-b887-96244c717fd2"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module9_sections = [\n",
        "  (\"AIMA Chapter 17.3 Bandit Problems\", chapter17_3),\n",
        "  (\"AIMA Chapter 22.1 Learning from Rewards\", chapter22_1),\n",
        "  (\"AIMA Chapter 22.2 Passive Reinforcement Learning\", chapter22_2),\n",
        "  (\"AIMA Chapter 22.3 Active Reinforcement Learning\", chapter22_3),\n",
        "  (\"AIMA Chapter 22.4 Generalization in Reinforcement Learning\", chapter22_4),\n",
        "  (\"Module 9 Lecture Notes\", module9_lecture_notes),\n",
        "]\n",
        "\n",
        "module9_markdown = format_module(9, \"Reinforcement Learning\", module9_sections, module9_definitions)\n",
        "display(Markdown(module9_markdown))"
      ],
      "execution_count": 8,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\n1.Basic idea of reinforced learning: receive feedback in the form of rewards, agent's utility is defined by the reward function, must act so as to maximize the expected utility, all learning is based on observed samples of outcomes.\n\n2.Model based learning: learn an approximate model based on experiences. Step 1 learn empirical MDP model, step 2 solve the learned MDP.\n\n3.passive reinforcement learning input a fixed policy and don't know transitions and rewards, just learn the state values, not an offline planning.\n\n4.direct evaluation average together observed sample values. Benefit: easy to understand, doesn't require any knowledge of T,R, eventually computes the correct average values using just sample transitions. Bad: waste information about state connections, each state must be learned seperately, longer time.\n\n5.temporal difference learning: learn from every experience, update each time we experience a transition.\n\n6.expoential moving average: decreasing learning rate($\u0007lpha$) can give converging averages.\n\n7.q-learning: receive a sample, consider old estimate, consider new sample estimate(sample = R(s,a,s')+$\\gamma$maxQ(s',a')), incorporate the new estimate into a running average(Q(s,a) <- (1-$\u0007lpha$)Q(s,a)+$\u0007lpha$[sample]).\n\n8.q-learning converge to an optimal policy. Off-policy learning. caveat: explore enough, make the learning rate small enough eventually but not decreasing quickly, doesn't matter how you select actions.\n\n9.Explore: small probability, act randomly, large probability, act on current action. Problems: do eventually explore the space, but keep thrashing around once learning is done, one solution lower $\\epsilon$ another solution exploration functions.\n\n10.Improvement: explore areas whose badness is not established, eventually stop exploration.\n\n11.Linear value functions: advantage: experience is summed up in a few powerful numbers; disadvantages: states may share features but actually be very different in value.\n\n\n## Module 9 Definitions\n* **Exploration** - try unknown actions to get information\n* **Exploitation** - use what you have learned\n* **Regret** - measure of total mistake cost(random exploration has higher)\n* **Sampling** - because of chance, have to try things repeatly\n* **Difficulty** - learning can be much harder\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 12 “Quantifying Uncertainty” (Sections 12.1-12.7)\n",
        "chapter12_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Jurafsky and Martin, Speech and Language Processing Chapter 3 “N-Gram Language Models”  (Sections 3.1-3.5,3.7)\n",
        "SLP_chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\"\n",
        "1.Uncentainty: observed variables(evidence), unobserved variables(states), model.\\n\n",
        "2.Probabilistic reasoning gives us a framework for managing our beliefs and knowledge.\\n\n",
        "3.Probabilistic models is a joint distribution over a set of random variables. Random variables with domain, assignment called outcomes, joint distribution, normalized, ideally(only certain variables directly interact)\\n\n",
        "4.Marginal distribution are sub-tables which eliminate variables.\\n\n",
        "5.Conditional distributions are probability distributions over some variables given fixed values of others.\\n\n",
        "6.Probabilistic Inference compute a desired probability from other known probabilities. Probabilities change with new evidence.\\n\n",
        "7.Bayes' Rule: p(x,y) = p(x|y)p(y) = p(y|x)p(x)\\n\n",
        "8.Probabilistic language models one goal is to assign a probability to a sentence. Autocomplete for texting, machine translation, spelling correction, speech recognition.\\n\n",
        "9.Model that computes the probability of sentence or sequence of words or probability of an upcoming word is called language model LM.\\n\n",
        "10.Simplifying assumption, Markov Assumption: the probability only depends on the previous k words not the whole context.\\n\n",
        "11.In general n-gram models is an insufficient model of language becaues laguages has long-distance dependencies.\\n\n",
        "12.Maximum likelihood estimate: P($W_{i}$|$W_{i-1}$)=count($W_{i}$,$W_{i-1}$)/count($W_{i-1}$)\\n\n",
        "13.Problems for MLE: we assign 0 probability to all sentences containing it; Out of Vocabulary items(fixed lexicon L of size V, normalize training data by replacing any word not in L with <unk>)\\n\n",
        "Practical Issue, everything in log space, avoid underflow, adding is faster.\"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"random variable\" : \"some aspect of the world about which we may have uncertainty\",\n",
        "\"distribution\" : \"table of probabilities of values\",\n",
        "\"probabilistic inference\" : \"compute a desired probability from other known probabilities\"\n",
        "\n",
        "\n",
        "}"
      ],
      "execution_count": 9,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "1636508d-a576-4f1c-c737-baa9843fe418"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module10_sections = [\n",
        "  (\"AIMA Chapter 12.1 Acting under Uncertainty\", chapter12_1),\n",
        "  (\"AIMA Chapter 12.2 Basic Probability Notation\", chapter12_2),\n",
        "  (\"AIMA Chapter 12.3 Inference Using Full Joint Distributions\", chapter12_3),\n",
        "  (\"AIMA Chapter 12.4 Independence\", chapter12_4),\n",
        "  (\"AIMA Chapter 12.5 Bayes’ Rule and Its Use\", chapter12_5),\n",
        "  (\"AIMA Chapter 12.6 Naive Bayes Models\", chapter12_6),\n",
        "  (\"AIMA Chapter 12.7 The Wumpus World Revisited\", chapter12_7),\n",
        "  (\"SLP Chapter 3.1 N-Grams\", SLP_chapter3_1),\n",
        "  (\"SLP Chapter 3.2 Evaluating Language Models\", SLP_chapter3_2),\n",
        "  (\"SLP Chapter 3.3 Sampling sentences from a language model\", SLP_chapter3_3),\n",
        "  (\"SLP Chapter 3.4 Generalization and Zeros\", SLP_chapter3_4),\n",
        "  (\"SLP Chapter 3.5 Smoothing\", SLP_chapter3_5),\n",
        "  (\"SLP Chapter 3.7 Huge Language Models and Stupid Backoff\", SLP_chapter3_7),\n",
        "  (\"Module 10 Lecture Notes\", module10_lecture_notes),\n",
        "]\n",
        "\n",
        "module10_markdown = format_module(10, \"Probabilies and Language Models\", module10_sections, module10_definitions)\n",
        "display(Markdown(module10_markdown))"
      ],
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n\n1.Uncentainty: observed variables(evidence), unobserved variables(states), model.\n\n2.Probabilistic reasoning gives us a framework for managing our beliefs and knowledge.\n\n3.Probabilistic models is a joint distribution over a set of random variables. Random variables with domain, assignment called outcomes, joint distribution, normalized, ideally(only certain variables directly interact)\n\n4.Marginal distribution are sub-tables which eliminate variables.\n\n5.Conditional distributions are probability distributions over some variables given fixed values of others.\n\n6.Probabilistic Inference compute a desired probability from other known probabilities. Probabilities change with new evidence.\n\n7.Bayes' Rule: p(x,y) = p(x|y)p(y) = p(y|x)p(x)\n\n8.Probabilistic language models one goal is to assign a probability to a sentence. Autocomplete for texting, machine translation, spelling correction, speech recognition.\n\n9.Model that computes the probability of sentence or sequence of words or probability of an upcoming word is called language model LM.\n\n10.Simplifying assumption, Markov Assumption: the probability only depends on the previous k words not the whole context.\n\n11.In general n-gram models is an insufficient model of language becaues laguages has long-distance dependencies.\n\n12.Maximum likelihood estimate: P($W_{i}$|$W_{i-1}$)=count($W_{i}$,$W_{i-1}$)/count($W_{i-1}$)\n\n13.Problems for MLE: we assign 0 probability to all sentences containing it; Out of Vocabulary items(fixed lexicon L of size V, normalize training data by replacing any word not in L with <unk>)\n\nPractical Issue, everything in log space, avoid underflow, adding is faster.\n\n## Module 10 Definitions\n* **Random variable** - some aspect of the world about which we may have uncertainty\n* **Distribution** - table of probabilities of values\n* **Probabilistic inference** - compute a desired probability from other known probabilities\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, Russell and Norvig, AIMA Chapter 13 “Probabilistic Reasoning” (13.1, 13.2, 13.3)\n",
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\"\n",
        "1.Independent: if p(x,y) = p(x)p(y); Conditionally independent: p(x,y|z) = p(x|z)p(y|z)\\n\n",
        "2.x is conditionally independent of y given z iff p(x,y|z) = p(x|z)p(y|z)/ p(x|z,y) = p(x|z)\\n\n",
        "3.p(a,b,c) = p(a)p(b|a)p(c|a,b)\\n\n",
        "4.Bayes' nets/graphical models help us express conditional independence assumptions. Problems: the joint way is too big, hard to learn anything empirically about more than a few variables at a time. \\n\n",
        "5.No interactions between variables means absolute independence.\\n\n",
        "6.Bayes' Net semantics: a set of nodes; a directed, acyclic graph; a conditional distribution for each node.\\n\n",
        "7.Not every BN can represent every joint distribution.\\n\n",
        "8.When BN reflect the true causal patterns: often simpler/easier to think about/easier to elicit drom experts\\n\n",
        "9.BN need not acctually be causal, sometimes no causal net exists over the domain(especially when variables are missing). Arrows reflect correlation not causation.\\n\n",
        "10.Size of BN: joint distribution over N boolean variables($2^{N}$), N-node net if nodes have up to k parents(O(N*$2^{k+1}$)). Huge space savings, easier to elicit local CPTs, faster to answer queries.\\n\n",
        "11.D seperate gives us an algorithm for answering whether things are independent of each other. The configeration is a causal chain.\\n\n",
        "12.It guarantee x independent of z given y.\\n\n",
        "13.Reachability: check all undirected paths between two variables if one or more active they are not guarranteed independence.\\n\n",
        "14.Inference by enumeration is slow: you join up the whole joint distribution before you sum out the hidden variables.\\n\n",
        "15.Advanced technique: variable elimination. Interleave joining and marginalizing, still NP hard but faster.\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"Bayes' Net/graphical models\" : \"a technique for describing complex joint distributions using simple, local distributions\",\n",
        "\"nodes\" : \"variables with domains can be assigned or unassigned\",\n",
        "\"Arcs\" : \"interactions indicate direct influence between variables\",\n",
        "\"Bayes' Net\" : \"Topology(graph)+local conditional probabilities\",\n",
        "\"inference\" : \"calculate some useful quantitiy from a joint probability distribution\"\n",
        "}\n",
        "\n",
        "\n"
      ],
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 862
        },
        "cellView": "form",
        "outputId": "fc24e3de-c4e5-43b4-b1f1-f296b3c772f9"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module11_sections = [\n",
        "  (\"AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\", chapter13_1),\n",
        "  (\"AIMA Chapter 13.2 The Semantics of Bayesian Networks\", chapter13_2),\n",
        "  (\"AIMA 13.3 Exact Inference in Bayesian Networks\", chapter13_3),\n",
        "  (\"Module 11 Lecture Notes\", module11_lecture_notes),\n",
        "]\n",
        "\n",
        "module11_markdown = format_module(11, \"Probabilistic Reasoning and Bayes’ Nets\", \n",
        "                         module11_sections, \n",
        "                         module11_definitions)\n",
        "display(Markdown(module11_markdown))"
      ],
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\n1.Independent: if p(x,y) = p(x)p(y); Conditionally independent: p(x,y|z) = p(x|z)p(y|z)\n\n2.x is conditionally independent of y given z iff p(x,y|z) = p(x|z)p(y|z)/ p(x|z,y) = p(x|z)\n\n3.p(a,b,c) = p(a)p(b|a)p(c|a,b)\n\n4.Bayes' nets/graphical models help us express conditional independence assumptions. Problems: the joint way is too big, hard to learn anything empirically about more than a few variables at a time. \n\n5.No interactions between variables means absolute independence.\n\n6.Bayes' Net semantics: a set of nodes; a directed, acyclic graph; a conditional distribution for each node.\n\n7.Not every BN can represent every joint distribution.\n\n8.When BN reflect the true causal patterns: often simpler/easier to think about/easier to elicit drom experts\n\n9.BN need not acctually be causal, sometimes no causal net exists over the domain(especially when variables are missing). Arrows reflect correlation not causation.\n\n10.Size of BN: joint distribution over N boolean variables($2^{N}$), N-node net if nodes have up to k parents(O(N*$2^{k+1}$)). Huge space savings, easier to elicit local CPTs, faster to answer queries.\n\n11.D seperate gives us an algorithm for answering whether things are independent of each other. The configeration is a causal chain.\n\n12.It guarantee x independent of z given y.\n\n13.Reachability: check all undirected paths between two variables if one or more active they are not guarranteed independence.\n\n14.Inference by enumeration is slow: you join up the whole joint distribution before you sum out the hidden variables.\n\n15.Advanced technique: variable elimination. Interleave joining and marginalizing, still NP hard but faster.\n\n## Module 11 Definitions\n* **Bayes' net/graphical models** - a technique for describing complex joint distributions using simple, local distributions\n* **Nodes** - variables with domains can be assigned or unassigned\n* **Arcs** - interactions indicate direct influence between variables\n* **Bayes' net** - Topology(graph)+local conditional probabilities\n* **Inference** - calculate some useful quantitiy from a joint probability distribution\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 12 - Naive Bayes and Perceptrons"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 19 “Learning from Examples” (Sections 19.1-19.6)\n",
        "\n",
        "chapter19_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter19_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_7 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_9 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter4_10 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\"\n",
        "1.Examples of classifications: Spam detection, OCR, medical diagnosis, automatic essay grading, fraud detection, customer service email routing.\\n\n",
        "2.Naive Bayes assume all features are independent effects of the label. Step 1: get joint probablity of label and evidence for each label. Step 2: sum to get the probability of evidence. Step 3: Normalize by devide step1 with step2.\\n\n",
        "3.experimentation cycle: learn parameters on training set, tune hyperparameters on held-out set(), compute accuracy of test set, never peek at the test set.\\n\n",
        "4.smooth and regularize to handle overfit.\\n\n",
        "5.We should maximize the likelihood of the data to choose the parameter.\\n\n",
        "6.Relative frequencies are the maximum likelihood estimates. count(x)/total number.(Unseen events).\\n\n",
        "7.Laplace's estimate: pretend you saw every outcome once more than you actually did. $P_{LAP}$(x)=c(x)+1/N+X\\n\n",
        "8.Laplace's estimate extended, $P_{LAP}$(x)=c(x)+k/N+kX\\n\n",
        "9.Laplace perform poorly on p(x|y) when x or y is very large.\n",
        "10.Linear Interpolation: $P_{LIN}$(x|y)=$\\alpha$P(x|y)+(1-$\\alpha$)p(x)\\n\n",
        "11.Deal with errors: need more features, add these information sources as new variables in the NB model\\n\n",
        "12.multiclass decision rule, choose $w_{y}$*f(y) highest. multiclass perceptron: start with all weights 0, pick up training examples one by one and predict with current weights if correct no change if wrong lower score wrong answer raise score of right answer.\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"data\" : \"training, held-out, test set\",   \n",
        "\"feature\" : \"attribute-value pairs which characterize each x\",\n",
        "\"overfit\" : \"fit the training data very closely but not generalizing well\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 13,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "b9d687d8-78dc-4209-f438-058b4f1a8225"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module12_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter19_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter19_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter19_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter19_4),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter19_5),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter19_6),\n",
        "  (\"SLP Chapter 4.1 Naive Bayes Classifiers\", slp_chapter4_1),\n",
        "  (\"SLP Chapter 4.2 Training the Naive Bayes Classifier\", slp_chapter4_2),\n",
        "  (\"SLP Chapter 4.3 Worked Example\", slp_chapter4_3),\n",
        "  (\"SLP Chapter 4.4 Optimizing for Sentiment Analysis\", slp_chapter4_4),\n",
        "  (\"SLP Chapter 4.5 Naive Bayes for other text classification tasks\", slp_chapter4_5),\n",
        "  (\"SLP Chapter 4.6 Naive Bayes as a Language Model\", slp_chapter4_6),\n",
        "  (\"SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\", slp_chapter4_7),\n",
        "  (\"SLP Chapter 4.8 Test sets and Cross-validation\", slp_chapter4_8),\n",
        "  (\"SLP Chapter 4.9 Statistical Significance Testing\", slp_chapter4_9),\n",
        "  (\"SLP Chapter 4.10 Avoiding Harms in Classification\", slp_chapter4_10),\n",
        "  (\"Module 12 Lecture Notes\", module12_lecture_notes),\n",
        "]\n",
        "\n",
        "module12_markdown = format_module(12, \"Naive Bayes and Perceptrons\", \n",
        "                         module12_sections, \n",
        "                         module12_definitions)\n",
        "display(Markdown(module12_markdown))"
      ],
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\n1.Examples of classifications: Spam detection, OCR, medical diagnosis, automatic essay grading, fraud detection, customer service email routing.\n\n2.Naive Bayes assume all features are independent effects of the label. Step 1: get joint probablity of label and evidence for each label. Step 2: sum to get the probability of evidence. Step 3: Normalize by devide step1 with step2.\n\n3.experimentation cycle: learn parameters on training set, tune hyperparameters on held-out set(), compute accuracy of test set, never peek at the test set.\n\n4.smooth and regularize to handle overfit.\n\n5.We should maximize the likelihood of the data to choose the parameter.\n\n6.Relative frequencies are the maximum likelihood estimates. count(x)/total number.(Unseen events).\n\n7.Laplace's estimate: pretend you saw every outcome once more than you actually did. $P_{LAP}$(x)=c(x)+1/N+X\n\n8.Laplace's estimate extended, $P_{LAP}$(x)=c(x)+k/N+kX\n\n9.Laplace perform poorly on p(x|y) when x or y is very large.\n10.Linear Interpolation: $P_{LIN}$(x|y)=$\u0007lpha$P(x|y)+(1-$\u0007lpha$)p(x)\n\n11.Deal with errors: need more features, add these information sources as new variables in the NB model\n\n12.multiclass decision rule, choose $w_{y}$*f(y) highest. multiclass perceptron: start with all weights 0, pick up training examples one by one and predict with current weights if correct no change if wrong lower score wrong answer raise score of right answer.\n\n\n## Module 12 Definitions\n* **Data** - training, held-out, test set\n* **Feature** - attribute-value pairs which characterize each x\n* **Overfit** - fit the training data very closely but not generalizing well\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "slp_chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\"\n",
        "1.Classifier Components: feature representation, classification function, objective function, optmize algorithm. \\n\n",
        "2.sigmoid function: 1/(1+e^(-z)) \\n\n",
        "3.Extract features, compute z and sigmoid, learning in logistic regression(get weight and bias): an objective function or loss function that tells us distance\n",
        "between the system output and the gold output, cross-entropy loss; optimize objective function use stochastic grandient descent to minize the loss function.\n",
        "4.Loss function determine how close a gold standard label for some inputs to their outputs. \\n\n",
        "5.Loss function for probabilistic classification: cross entropy loss or negative log likelihood, which maximize the possitive probability and minimize the negative\n",
        " probability.(maximize the probabilities of the true labels in traning data) \\n\n",
        "6.How to do it? Take the log and minimize the negative log. The result is cross-entropy loss: $L_{ce}$ = -logp(y|x), \n",
        "plug the definition in is $L_{ce}$ = -[ylog$\\sigma$(wx+b)+(1-y)log(1-$\\sigma$(wx+b))] \\n\n",
        "7.Loss on all traning examples, $\\Sigma$ of all $L_{ce}$\\n\n",
        "8.Use gradient descent to find good weights and bias, gradient descent is a method that finds a minimum of a function by figuring out in which direction \n",
        "the function's slope is rising the most steeply and moving in opposite direction.\\n\n",
        "9.The magnitude of the amount of move in grandient descent is the value of the slope weighted by a learning rate $\\eta$, a higher learning rate means we should move\n",
        "w more on each step. $W^{t+1}$ = $W^{t}$ - $\\eta$d/dw*f(x;w)\\n\n",
        "10.activation function include simoid function, tanh function, rectified linear united Relu.\\n\n",
        "11.Advantage of using single matrix W for the weights of the entire layer is the hidden layer computation easily.\\n\n",
        "12.Train NN: a loss function cross-entropy loss, an optimization algorithm gradient descent, a way of computing the gradient of the loss function error propagation.\\n\n",
        "13.Error backpropagation algorithm solve the problem that it the logistic regression only give correctt updates for the last weight layer.\\n\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"feature representation\" : \"input\",\n",
        "\"classification function\" : \"compute the estimated class via p(y|x)\",\n",
        "\"objective function/loss function\" : \"minimize error on training examples\",\n",
        "\"decision boundary\" : \"make desicion based on probability p(y=1|x)\",\n",
        "\"activation value\" : \"a, the output of nonlinear function\",\n",
        "\"feed-forward neural network\" : \"simplest kind of NN, multilayer, fully-connected and no cycles\"\n",
        "}\n"
      ],
      "execution_count": 15,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "4bd1855c-5947-4f2c-d9bc-7ff4a06acb64"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module13_sections = [\n",
        "  (\"SLP Chapter 5.1 Classification: the sigmoid\", slp_chapter5_1),\n",
        "  (\"SLP Chapter 5.2 Learning in Logistic Regression\", slp_chapter5_2),\n",
        "  (\"SLP Chapter 5.3 The cross-entropy loss function\", slp_chapter5_3),\n",
        "  (\"SLP Chapter 5.4 Gradient Descent\", slp_chapter5_4),\n",
        "  (\"SLP Chapter 5.5 Regularization\", slp_chapter5_5),\n",
        "  (\"SLP Chapter 5.6 Multinomial logistic regression\", slp_chapter5_6),\n",
        "\n",
        "  (\"SLP Chapter 7.1 Units\", slp_chapter7_1),\n",
        "  (\"SLP Chapter 7.2 The XOR problem\", slp_chapter7_2),\n",
        "  (\"SLP Chapter 7.3 Feedforward Neural Networks\", slp_chapter7_3),\n",
        "  (\"SLP Chapter 7.4 Feedforward networks for NLP: Classification\", slp_chapter7_4),\n",
        "  (\"SLP Chapter 7.5 Feedforward Neural Language Modeling\", slp_chapter7_5),\n",
        "  (\"SLP Chapter 7.6 Training Neural Nets\", slp_chapter7_6),\n",
        "  (\"SLP Chapter 7.7 Training the neural language model\", slp_chapter7_7),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module13_markdown = format_module(13, \"Neural Networks\", \n",
        "                         module13_sections, \n",
        "                         module13_definitions)\n",
        "display(Markdown(module13_markdown))"
      ],
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\n1.Classifier Components: feature representation, classification function, objective function, optmize algorithm. \n\n2.sigmoid function: 1/(1+e^(-z)) \n\n3.Extract features, compute z and sigmoid, learning in logistic regression(get weight and bias): an objective function or loss function that tells us distance\nbetween the system output and the gold output, cross-entropy loss; optimize objective function use stochastic grandient descent to minize the loss function.\n4.Loss function determine how close a gold standard label for some inputs to their outputs. \n\n5.Loss function for probabilistic classification: cross entropy loss or negative log likelihood, which maximize the possitive probability and minimize the negative\n probability.(maximize the probabilities of the true labels in traning data) \n\n6.How to do it? Take the log and minimize the negative log. The result is cross-entropy loss: $L_{ce}$ = -logp(y|x), \nplug the definition in is $L_{ce}$ = -[ylog$\\sigma$(wx+b)+(1-y)log(1-$\\sigma$(wx+b))] \n\n7.Loss on all traning examples, $\\Sigma$ of all $L_{ce}$\n\n8.Use gradient descent to find good weights and bias, gradient descent is a method that finds a minimum of a function by figuring out in which direction \nthe function's slope is rising the most steeply and moving in opposite direction.\n\n9.The magnitude of the amount of move in grandient descent is the value of the slope weighted by a learning rate $\\eta$, a higher learning rate means we should move\nw more on each step. $W^{t+1}$ = $W^{t}$ - $\\eta$d/dw*f(x;w)\n\n10.activation function include simoid function, tanh function, rectified linear united Relu.\n\n11.Advantage of using single matrix W for the weights of the entire layer is the hidden layer computation easily.\n\n12.Train NN: a loss function cross-entropy loss, an optimization algorithm gradient descent, a way of computing the gradient of the loss function error propagation.\n\n13.Error backpropagation algorithm solve the problem that it the logistic regression only give correctt updates for the last weight layer.\n\n\n\n## Module 13 Definitions\n* **Feature representation** - input\n* **Classification function** - compute the estimated class via p(y|x)\n* **Objective function/loss function** - minimize error on training examples\n* **Decision boundary** - make desicion based on probability p(y=1|x)\n* **Activation value** - a, the output of nonlinear function\n* **Feed-forward neural network** - simplest kind of NN, multilayer, fully-connected and no cycles\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter9_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 6 “Vector Semantics and Embeddings” (6.1-6.4, 6.8, 6.10-6.12)\n",
        "\n",
        "slp_chapter6_1 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_2 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_10 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\"\n",
        "1.neural language models advantage: don't need smoothing, can handle much longer histories, generalize over contexts of similar words, neural LMs tend to have much higher predictive accuracy than n-gram models.\\n\n",
        "2.But it is slower to train than n-gram.\\n\n",
        "3.probability function is expressed the product of conditional probabilities of the next word given the previous word using multi-layer, feed forward neural network.\\n\n",
        "4.input is k-gram of words $W_{1:k}$, output is a probability distribution of next words, k context words are treated as word window, each word associate with an embedding vector\\n\n",
        "5.Training: identities of the first k-1 words as features, last word as target label for the classification.\n",
        "6.NN LMs has better result, larger N, generalize accross contexts, a by-product of training are word embeddings.\\n\n",
        "7.Difficulites of language modeling: too many parameters to accurate estimate, n-gram-based models fail to generalize to related words/word sequence.\\n\n",
        "8.Unseen sequences: back-off, smoothing/interpolation, just stitching together short sequence of observed words.\\n\n",
        "9.Term document matrix: each col represent a document, each row represent a term, the cell is based on how often that term occured in the document, length of the document is the size of vocabulary, document vectors can be sparse(most value 0), measure how similar two documents are by comparing their col\\n\n",
        "10.Term term matrix aka term context matrix, length of row(vector) is now |v| instead of number of document, the cell represent how often a word appeard surrounding a word\\n\n",
        "11.Co-occurrence matrix weighted by TF-IDF or mutual information.\\n\n",
        "12.How to get dense vectors? train a classifier, treat the target word and a neighboring context word as positive example, random sample other words as negative, use logistic regression to train, use the weights to embeddings\\n\n",
        "13.Word2Vec, learn embeddings as part of the process of word prediction, train a classifier to predict neighboring, inspired by nn lm, it is fast and easy to train faster than SVD, available online! Predict rather than count!!!\\n\n",
        "14.Dense vector: short vectors easier to use as features, it may generalize better than storing explicit counts, do better at capturing synonymy.\\n\n",
        "15.skip gram algorithm same as 12. But how to compute p(+|t,c) since the dot product is not a probability? Sigmoid! 1/1+$e^{-t*c}$, p = 乘\\n\n",
        "16.\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"language modeling\" : \"learn a function that returns the joint probability\", \n",
        "\"synonyms\" : \"words with similar meanings\", \n",
        "\"antonyms\" : \"words with opposite meanings\",\n",
        "\"connotations\" : \"words that are positive or negative\",\n",
        "\"semantic roles\" : \"\" ,\n",
        "\"TF-IDF\" : \"Term frequency inverse document frequency\"  ,\n",
        "\"dense\" : \"most elements non-zero\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 17,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "776f7a08-3116-4819-986c-3383530cb4bd"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module14_sections = [\n",
        "  (\"SLP Chapter 9.1 Language Models Revisited\", slp_chapter9_1),\n",
        "  (\"SLP Chapter 9.2 Recurrent Neural Networks\", slp_chapter9_2),\n",
        "  (\"SLP Chapter 9.3 RNNs as Language Models\", slp_chapter9_3),\n",
        "\n",
        "  (\"SLP Chapter 6.1 Lexical Semantics\", slp_chapter6_1),\n",
        "  (\"SLP Chapter 6.2 Vector Semantics\", slp_chapter6_2),\n",
        "  (\"SLP Chapter 6.3 Words and Vectors\", slp_chapter6_3),\n",
        "  (\"SLP Chapter 6.4 Cosine for measuring similarity\", slp_chapter6_4),\n",
        "  (\"SLP Chapter 6.8 Word2vec\", slp_chapter6_8),\n",
        "  (\"SLP Chapter 6.10 Semantic properties of embeddings\", slp_chapter6_10),\n",
        "  (\"SLP Chapter 6.11 Bias and Embeddings\", slp_chapter6_11),\n",
        "  (\"SLP Chapter 6.12 Evaluating Vector Models\", slp_chapter6_12),\n",
        "  (\"Module 13 Lecture Notes\", module13_lecture_notes),\n",
        "]\n",
        "\n",
        "module14_markdown = format_module(14, \"Natural Language Processing\", \n",
        "                         module14_sections, \n",
        "                         module14_definitions)\n",
        "display(Markdown(module14_markdown))"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n\n1.Classifier Components: feature representation, classification function, objective function, optmize algorithm. \n\n2.sigmoid function: 1/(1+e^(-z)) \n\n3.Extract features, compute z and sigmoid, learning in logistic regression(get weight and bias): an objective function or loss function that tells us distance\nbetween the system output and the gold output, cross-entropy loss; optimize objective function use stochastic grandient descent to minize the loss function.\n4.Loss function determine how close a gold standard label for some inputs to their outputs. \n\n5.Loss function for probabilistic classification: cross entropy loss or negative log likelihood, which maximize the possitive probability and minimize the negative\n probability.(maximize the probabilities of the true labels in traning data) \n\n6.How to do it? Take the log and minimize the negative log. The result is cross-entropy loss: $L_{ce}$ = -logp(y|x), \nplug the definition in is $L_{ce}$ = -[ylog$\\sigma$(wx+b)+(1-y)log(1-$\\sigma$(wx+b))] \n\n7.Loss on all traning examples, $\\Sigma$ of all $L_{ce}$\n\n8.Use gradient descent to find good weights and bias, gradient descent is a method that finds a minimum of a function by figuring out in which direction \nthe function's slope is rising the most steeply and moving in opposite direction.\n\n9.The magnitude of the amount of move in grandient descent is the value of the slope weighted by a learning rate $\\eta$, a higher learning rate means we should move\nw more on each step. $W^{t+1}$ = $W^{t}$ - $\\eta$d/dw*f(x;w)\n\n10.activation function include simoid function, tanh function, rectified linear united Relu.\n\n11.Advantage of using single matrix W for the weights of the entire layer is the hidden layer computation easily.\n\n12.Train NN: a loss function cross-entropy loss, an optimization algorithm gradient descent, a way of computing the gradient of the loss function error propagation.\n\n13.Error backpropagation algorithm solve the problem that it the logistic regression only give correctt updates for the last weight layer.\n\n\n\n## Module 14 Definitions\n* **Language modeling** - learn a function that returns the joint probability\n* **Synonyms** - words with similar meanings\n* **Antonyms** - words with opposite meanings\n* **Connotations** - words that are positive or negative\n* **Semantic roles** - \n* **Tf-idf** - Term frequency inverse document frequency\n* **Dense** - most elements non-zero\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": "efcfeea0-1131-4c27-899c-8e2123692ede"
      },
      "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": 19,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$ \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n Your summary here \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n Your summary here \n\n## Module 8 Lecture Notes\n\n1.Stochastic Transition Model: the transition function is written as T(s,a,s') as a probability of arriving in state s' given that we are in state s and selct action a.\n\n2.Transition are Markovian: the probability only determine by the s not earlier state.\n\n3.Reward function will get reward for each step not just at the goal state based on s to s' via action a. R(s,a,s').\n\n4.Markov Decision Process is a sequential desicion problem for a fully ovservable envirionemnt with a stochastic transition model that has additive rewards.(Non-deterministic search problems).\n\n5.Way of solving MDP is expectimax search.\n\n6.MDP we can't give a sequence of actions, but a policy map. $\\pi$(s)=a\n\n7.The policy would not guarrantee what action to pick since it is stochastic.\n\n8.Stationary preferences: if we assume stationary preferences, there are only two ways to define utilities(additive utility and discounted utility)\n\n9.$V^{*}$=max$Q^{*}$(s,a)\n\n10.Time-limited values to be the optimal values of s if the game ends in k more time steps.\n\n11.Value iteration algorithm: complexity O($S^{2}$A). Will converage to unique optimal value.\n\n12.Value of states change more often than the best action from the state.\n\n13.Actions are easier to select from qvalues than values.\n\n14.Both value iteration and policy iteration compute the same thing. Value iteration updates both values and policy, we don't track policy but take the max over actions.\nIn policy iteration, we do several passes that update utilities with fixed policy(each pass is fast because we consider only one action not all). After the policy is evaluated, a new policy chosen slow like a value iteration pass. New policy will be better. \n\n15.MDP summary: compute optimal values use value iteration or policy iteration. compute values for a particular policy use policy evaluation. Turn your values into a policy use policy extraction.\n\n16.Principle of Maximum expected utilities: a rational agent should choose the action that maximizes its expected utility given its knowledge.\n\n17.For average expectimax reasoning, we need magnitudes to be meaningful.\n\n18.Maximum expected utility(MEU) principle, choose action maximizes expected utility.\n\n\n## Module 8 Definitions\n* **Utility function** - reward function gives to agent for each step\n* **Expected utility** - your definition here\n* **Define mdp** - set of states s, set of actions a, transtion model, reward function, initial state, termainal state(optional)\n* **Policy** - choice of action for each state\n* **$\\pi^{*}$** - optimal policy\n* **Discounting** - maximize the sum of rewards and prefer rewards now\n* **Utility** - sum of (discounted) rewards\n* **Value of state** - expected utility starting in s and acting optimally\n* **The value of q state** - expected utility starting out having taken action a from state s and acting optimally\n* **Utilities** - functions from outcomes to real numbers that describe an agent's preferences\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n Your summary here \n\n## AIMA Chapter 22.1 Learning from Rewards\n Your summary here \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Your summary here \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n Your summary here \n\n## Module 9 Lecture Notes\n\n1.Basic idea of reinforced learning: receive feedback in the form of rewards, agent's utility is defined by the reward function, must act so as to maximize the expected utility, all learning is based on observed samples of outcomes.\n\n2.Model based learning: learn an approximate model based on experiences. Step 1 learn empirical MDP model, step 2 solve the learned MDP.\n\n3.passive reinforcement learning input a fixed policy and don't know transitions and rewards, just learn the state values, not an offline planning.\n\n4.direct evaluation average together observed sample values. Benefit: easy to understand, doesn't require any knowledge of T,R, eventually computes the correct average values using just sample transitions. Bad: waste information about state connections, each state must be learned seperately, longer time.\n\n5.temporal difference learning: learn from every experience, update each time we experience a transition.\n\n6.expoential moving average: decreasing learning rate($\u0007lpha$) can give converging averages.\n\n7.q-learning: receive a sample, consider old estimate, consider new sample estimate(sample = R(s,a,s')+$\\gamma$maxQ(s',a')), incorporate the new estimate into a running average(Q(s,a) <- (1-$\u0007lpha$)Q(s,a)+$\u0007lpha$[sample]).\n\n8.q-learning converge to an optimal policy. Off-policy learning. caveat: explore enough, make the learning rate small enough eventually but not decreasing quickly, doesn't matter how you select actions.\n\n9.Explore: small probability, act randomly, large probability, act on current action. Problems: do eventually explore the space, but keep thrashing around once learning is done, one solution lower $\\epsilon$ another solution exploration functions.\n\n10.Improvement: explore areas whose badness is not established, eventually stop exploration.\n\n11.Linear value functions: advantage: experience is summed up in a few powerful numbers; disadvantages: states may share features but actually be very different in value.\n\n\n## Module 9 Definitions\n* **Exploration** - try unknown actions to get information\n* **Exploitation** - use what you have learned\n* **Regret** - measure of total mistake cost(random exploration has higher)\n* **Sampling** - because of chance, have to try things repeatly\n* **Difficulty** - learning can be much harder\n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n Your summary here \n\n## AIMA Chapter 12.2 Basic Probability Notation\n Your summary here \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n Your summary here \n\n## AIMA Chapter 12.4 Independence\n Your summary here \n\n## AIMA Chapter 12.5 Bayes’ Rule and Its Use\n Your summary here \n\n## AIMA Chapter 12.6 Naive Bayes Models\n Your summary here \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n Your summary here \n\n## SLP Chapter 3.2 Evaluating Language Models\n Your summary here \n\n## SLP Chapter 3.3 Sampling sentences from a language model\n Your summary here \n\n## SLP Chapter 3.4 Generalization and Zeros\n Your summary here \n\n## SLP Chapter 3.5 Smoothing\n Your summary here \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n\n1.Uncentainty: observed variables(evidence), unobserved variables(states), model.\n\n2.Probabilistic reasoning gives us a framework for managing our beliefs and knowledge.\n\n3.Probabilistic models is a joint distribution over a set of random variables. Random variables with domain, assignment called outcomes, joint distribution, normalized, ideally(only certain variables directly interact)\n\n4.Marginal distribution are sub-tables which eliminate variables.\n\n5.Conditional distributions are probability distributions over some variables given fixed values of others.\n\n6.Probabilistic Inference compute a desired probability from other known probabilities. Probabilities change with new evidence.\n\n7.Bayes' Rule: p(x,y) = p(x|y)p(y) = p(y|x)p(x)\n\n8.Probabilistic language models one goal is to assign a probability to a sentence. Autocomplete for texting, machine translation, spelling correction, speech recognition.\n\n9.Model that computes the probability of sentence or sequence of words or probability of an upcoming word is called language model LM.\n\n10.Simplifying assumption, Markov Assumption: the probability only depends on the previous k words not the whole context.\n\n11.In general n-gram models is an insufficient model of language becaues laguages has long-distance dependencies.\n\n12.Maximum likelihood estimate: P($W_{i}$|$W_{i-1}$)=count($W_{i}$,$W_{i-1}$)/count($W_{i-1}$)\n\n13.Problems for MLE: we assign 0 probability to all sentences containing it; Out of Vocabulary items(fixed lexicon L of size V, normalize training data by replacing any word not in L with <unk>)\n\nPractical Issue, everything in log space, avoid underflow, adding is faster.\n\n## Module 10 Definitions\n* **Random variable** - some aspect of the world about which we may have uncertainty\n* **Distribution** - table of probabilities of values\n* **Probabilistic inference** - compute a desired probability from other known probabilities\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\n1.Independent: if p(x,y) = p(x)p(y); Conditionally independent: p(x,y|z) = p(x|z)p(y|z)\n\n2.x is conditionally independent of y given z iff p(x,y|z) = p(x|z)p(y|z)/ p(x|z,y) = p(x|z)\n\n3.p(a,b,c) = p(a)p(b|a)p(c|a,b)\n\n4.Bayes' nets/graphical models help us express conditional independence assumptions. Problems: the joint way is too big, hard to learn anything empirically about more than a few variables at a time. \n\n5.No interactions between variables means absolute independence.\n\n6.Bayes' Net semantics: a set of nodes; a directed, acyclic graph; a conditional distribution for each node.\n\n7.Not every BN can represent every joint distribution.\n\n8.When BN reflect the true causal patterns: often simpler/easier to think about/easier to elicit drom experts\n\n9.BN need not acctually be causal, sometimes no causal net exists over the domain(especially when variables are missing). Arrows reflect correlation not causation.\n\n10.Size of BN: joint distribution over N boolean variables($2^{N}$), N-node net if nodes have up to k parents(O(N*$2^{k+1}$)). Huge space savings, easier to elicit local CPTs, faster to answer queries.\n\n11.D seperate gives us an algorithm for answering whether things are independent of each other. The configeration is a causal chain.\n\n12.It guarantee x independent of z given y.\n\n13.Reachability: check all undirected paths between two variables if one or more active they are not guarranteed independence.\n\n14.Inference by enumeration is slow: you join up the whole joint distribution before you sum out the hidden variables.\n\n15.Advanced technique: variable elimination. Interleave joining and marginalizing, still NP hard but faster.\n\n## Module 11 Definitions\n* **Bayes' net/graphical models** - a technique for describing complex joint distributions using simple, local distributions\n* **Nodes** - variables with domains can be assigned or unassigned\n* **Arcs** - interactions indicate direct influence between variables\n* **Bayes' net** - Topology(graph)+local conditional probabilities\n* **Inference** - calculate some useful quantitiy from a joint probability distribution\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Your summary here \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Your summary here \n\n## AIMA Chapter 5.5 Stochastic Games\n Your summary here \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Your summary here \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n Your summary here \n\n## SLP Chapter 4.3 Worked Example\n Your summary here \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n Your summary here \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n Your summary here \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n Your summary here \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n Your summary here \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n Your summary here \n\n## SLP Chapter 4.9 Statistical Significance Testing\n Your summary here \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n Your summary here \n\n## Module 12 Lecture Notes\n\n1.Examples of classifications: Spam detection, OCR, medical diagnosis, automatic essay grading, fraud detection, customer service email routing.\n\n2.Naive Bayes assume all features are independent effects of the label. Step 1: get joint probablity of label and evidence for each label. Step 2: sum to get the probability of evidence. Step 3: Normalize by devide step1 with step2.\n\n3.experimentation cycle: learn parameters on training set, tune hyperparameters on held-out set(), compute accuracy of test set, never peek at the test set.\n\n4.smooth and regularize to handle overfit.\n\n5.We should maximize the likelihood of the data to choose the parameter.\n\n6.Relative frequencies are the maximum likelihood estimates. count(x)/total number.(Unseen events).\n\n7.Laplace's estimate: pretend you saw every outcome once more than you actually did. $P_{LAP}$(x)=c(x)+1/N+X\n\n8.Laplace's estimate extended, $P_{LAP}$(x)=c(x)+k/N+kX\n\n9.Laplace perform poorly on p(x|y) when x or y is very large.\n10.Linear Interpolation: $P_{LIN}$(x|y)=$\u0007lpha$P(x|y)+(1-$\u0007lpha$)p(x)\n\n11.Deal with errors: need more features, add these information sources as new variables in the NB model\n\n12.multiclass decision rule, choose $w_{y}$*f(y) highest. multiclass perceptron: start with all weights 0, pick up training examples one by one and predict with current weights if correct no change if wrong lower score wrong answer raise score of right answer.\n\n\n## Module 12 Definitions\n* **Data** - training, held-out, test set\n* **Feature** - attribute-value pairs which characterize each x\n* **Overfit** - fit the training data very closely but not generalizing well\n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Your summary here \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Your summary here \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Your summary here \n\n## SLP Chapter 5.4 Gradient Descent\n Your summary here \n\n## SLP Chapter 5.5 Regularization\n Your summary here \n\n## SLP Chapter 5.6 Multinomial logistic regression\n Your summary here \n\n## SLP Chapter 7.1 Units\n Your summary here \n\n## SLP Chapter 7.2 The XOR problem\n Your summary here \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Your summary here \n\n## SLP Chapter 7.4 Feedforward networks for NLP: Classification\n Your summary here \n\n## SLP Chapter 7.5 Feedforward Neural Language Modeling\n Your summary here \n\n## SLP Chapter 7.6 Training Neural Nets\n Your summary here \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n\n1.Classifier Components: feature representation, classification function, objective function, optmize algorithm. \n\n2.sigmoid function: 1/(1+e^(-z)) \n\n3.Extract features, compute z and sigmoid, learning in logistic regression(get weight and bias): an objective function or loss function that tells us distance\nbetween the system output and the gold output, cross-entropy loss; optimize objective function use stochastic grandient descent to minize the loss function.\n4.Loss function determine how close a gold standard label for some inputs to their outputs. \n\n5.Loss function for probabilistic classification: cross entropy loss or negative log likelihood, which maximize the possitive probability and minimize the negative\n probability.(maximize the probabilities of the true labels in traning data) \n\n6.How to do it? Take the log and minimize the negative log. The result is cross-entropy loss: $L_{ce}$ = -logp(y|x), \nplug the definition in is $L_{ce}$ = -[ylog$\\sigma$(wx+b)+(1-y)log(1-$\\sigma$(wx+b))] \n\n7.Loss on all traning examples, $\\Sigma$ of all $L_{ce}$\n\n8.Use gradient descent to find good weights and bias, gradient descent is a method that finds a minimum of a function by figuring out in which direction \nthe function's slope is rising the most steeply and moving in opposite direction.\n\n9.The magnitude of the amount of move in grandient descent is the value of the slope weighted by a learning rate $\\eta$, a higher learning rate means we should move\nw more on each step. $W^{t+1}$ = $W^{t}$ - $\\eta$d/dw*f(x;w)\n\n10.activation function include simoid function, tanh function, rectified linear united Relu.\n\n11.Advantage of using single matrix W for the weights of the entire layer is the hidden layer computation easily.\n\n12.Train NN: a loss function cross-entropy loss, an optimization algorithm gradient descent, a way of computing the gradient of the loss function error propagation.\n\n13.Error backpropagation algorithm solve the problem that it the logistic regression only give correctt updates for the last weight layer.\n\n\n\n## Module 13 Definitions\n* **Feature representation** - input\n* **Classification function** - compute the estimated class via p(y|x)\n* **Objective function/loss function** - minimize error on training examples\n* **Decision boundary** - make desicion based on probability p(y=1|x)\n* **Activation value** - a, the output of nonlinear function\n* **Feed-forward neural network** - simplest kind of NN, multilayer, fully-connected and no cycles\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n Your summary here \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n Your summary here \n\n## SLP Chapter 9.3 RNNs as Language Models\n Your summary here \n\n## SLP Chapter 6.1 Lexical Semantics\n Your summary here \n\n## SLP Chapter 6.2 Vector Semantics\n Your summary here \n\n## SLP Chapter 6.3 Words and Vectors\n Your summary here \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n Your summary here \n\n## SLP Chapter 6.8 Word2vec\n Your summary here \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n Your summary here \n\n## SLP Chapter 6.11 Bias and Embeddings\n Your summary here \n\n## SLP Chapter 6.12 Evaluating Vector Models\n Your summary here \n\n## Module 13 Lecture Notes\n\n1.Classifier Components: feature representation, classification function, objective function, optmize algorithm. \n\n2.sigmoid function: 1/(1+e^(-z)) \n\n3.Extract features, compute z and sigmoid, learning in logistic regression(get weight and bias): an objective function or loss function that tells us distance\nbetween the system output and the gold output, cross-entropy loss; optimize objective function use stochastic grandient descent to minize the loss function.\n4.Loss function determine how close a gold standard label for some inputs to their outputs. \n\n5.Loss function for probabilistic classification: cross entropy loss or negative log likelihood, which maximize the possitive probability and minimize the negative\n probability.(maximize the probabilities of the true labels in traning data) \n\n6.How to do it? Take the log and minimize the negative log. The result is cross-entropy loss: $L_{ce}$ = -logp(y|x), \nplug the definition in is $L_{ce}$ = -[ylog$\\sigma$(wx+b)+(1-y)log(1-$\\sigma$(wx+b))] \n\n7.Loss on all traning examples, $\\Sigma$ of all $L_{ce}$\n\n8.Use gradient descent to find good weights and bias, gradient descent is a method that finds a minimum of a function by figuring out in which direction \nthe function's slope is rising the most steeply and moving in opposite direction.\n\n9.The magnitude of the amount of move in grandient descent is the value of the slope weighted by a learning rate $\\eta$, a higher learning rate means we should move\nw more on each step. $W^{t+1}$ = $W^{t}$ - $\\eta$d/dw*f(x;w)\n\n10.activation function include simoid function, tanh function, rectified linear united Relu.\n\n11.Advantage of using single matrix W for the weights of the entire layer is the hidden layer computation easily.\n\n12.Train NN: a loss function cross-entropy loss, an optimization algorithm gradient descent, a way of computing the gradient of the loss function error propagation.\n\n13.Error backpropagation algorithm solve the problem that it the logistic regression only give correctt updates for the last weight layer.\n\n\n\n## Module 14 Definitions\n* **Language modeling** - learn a function that returns the joint probability\n* **Synonyms** - words with similar meanings\n* **Antonyms** - words with opposite meanings\n* **Connotations** - words that are positive or negative\n* **Semantic roles** - \n* **Tf-idf** - Term frequency inverse document frequency\n* **Dense** - most elements non-zero\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KvyVbaaREYhY"
      },
      "source": [
        ""
      ],
      "execution_count": null,
      "outputs": []
    }
  ]
}