{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of 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": "481b2a47-acd3-4f1f-e772-564a7b2ad3a4"
      },
      "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": null,
      "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": "c0612de2-9bca-4806-84ab-2490a8dee17e"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": null,
      "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 = \"\"\" Chapter 16.1 summary. \"\"\" + sample_equation + \"\"\" \\n MDP is a sequential decision problem, fully observable environment, stochastic transition model, additive rewards.\n",
        "MDP is a non deterministic search (it is stochastic). Think: millenium Falcon asteroid field grid. There's a percent\n",
        "chance that the falcon will do what you tell it to. ex. 80% chance it does what you say means, [Up, Up, Right, Right, Right] = [0.8*0.8*0.8*0.8] = 0.32776; \n",
        "but you also need to add this value to the mult of values that turn out to take you to the right place despite going the wrong way. \n",
        "Define a utility or reward function for the agent - given immediately for every state moved into; could be positive or negative \n",
        "(if you bump into an asteroid, negative, if you get closer to falcon, positive). In this way, agents can receive a reward at each time step rather than \n",
        "just at the goal step.  \"\"\"\n",
        "\n",
        "chapter16_2 = \"\"\"\n",
        "\n",
        "You need: a set of states S, a set of actions A, a transition function T(s, a s'), probability that executing action a in s will lead to s' P(s' | s, a). \n",
        "This probability is called the model. A reward function R(s, a, s'), initial state s_0, and one or more terminal states.\n",
        "Because there's uncertainty in MDPs, a solution to an MDP is a policy, not just a path. Policies map from a state onto the action to take if the agent\n",
        "is in that state. Even if the same policy is executed multiple times, it made lead to different environment histories. We need to compute the expected \n",
        "utility of all possible paths generated by a policy. Utility function U_h takes in an environment history and returns the sum of the rewards for the \n",
        "transitions it takes: $U_h([s_0, a_0, s_1, a_1, ..., s_n]) = R(s_0, a_0, s_1) + R(s_1, a_1, s_2)+ ... + R(s_{n-1}, a_{n-1}, s_n)$. Maximize rewards, always \n",
        "take the earliest rewards you can get, because later on there's a chance you won't get them (stochastic).\n",
        "Discounting -- rewards decay exponentially with every step. Sooner rewards probably have higher utility than later rewarsd. \n",
        "Ex. discount of 0.5: $U([1,2,3]) = 0.5^0*1 + 0.5^1*2 + 0.5^2*3$. Infinite Utilites (i.e. game lasts forever) - how to deal with it: finite horizon \n",
        "(terminate episodes after a fixed T steps), discounting: use 0 < \\gamma < 1, absorbing state that guarantees that for every policy, a terminal state will \n",
        "eventually be reached. Recursive definition of value: $V*(s) = maxQ*(s,a), Q*(s,a) = \\sum_{s'} T(s,a,s')[R(s,a,s') + \\gammaV*(s'), V*(s) = max \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gammaV*(s')$\n",
        "Value iteration, start at the lowest leaf and work upwards. Ex. the millenium falcon value iteration cruising, punch it, crash. At each level, max(probability of each action * (est. \n",
        "value of each action + future reward -- later down the tree)). V_0 always starts with all values as 0. \n",
        "\n",
        "\\n\n",
        "\n",
        "Six constrains that we require any reasonable preference relation to obey.\n",
        "\\n \n",
        "\n",
        "Computing actions from Q values instead of from the values themselves will help you simplify the decision making process. $\\pi*(s) = arg max Q*(s,a)$\n",
        "Policy Iteration - combine the idea of evaluating a policy, and improving it:\n",
        "Step 1. Policy Evaluation: calculate utilities for some fixed policy (not optimal utilities) until convergence. Step 2: Policy improvement: update policy\n",
        "using one-step look-ahead with resulting converged (but not optimal) utilities as future values. Repeat until policy converges. THIS IS OPTIMAL. \n",
        "\"\"\"\n",
        "chapter16_3= \"\"\"\n",
        "Value iteration: Every iteration updates both the values and (implicitly) the policy. We don't track the policy, but taking the max over actions implicitly recomputes it. \n",
        "\\n \n",
        "Policy iteration: We do several passes that update utilities with fixed policy (each pass is ast because we consider only one action, not all of them). After the policy \n",
        "evaluate, a new policy is chosen (slow like a value iteration pass). The new policy will be better.\n",
        "\\n \n",
        "\n",
        "Summary: \n",
        "\\n 1. So you want to compute the values: use value iteration or policy iteration\n",
        "\\n 2. Compute values for a particular policy: use policy evaluation\n",
        "\\n 3. Turn your values into a policy: use policy extraction (one-step lookahead)\n",
        "\n",
        "\\n Principle of Maximum Expected Utility: \n",
        "For worst-case minimax reasoning, terminal function scale doesn't matter; want better states to have higher evaluations = insensitivity to monotonic transormations.\n",
        "\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\" : \"Captures an agent's preferences, assigns a single number to express the desirability of a state.\",\n",
        "\"expected utility\" : \"Average utility value of the outcomes, weighted by the probability that the outcome occurs. $EU(a|e) = \\sum_s' P(RESULT(a) = s'|s,a)$ \",\n",
        "\"principle of maximum expected utility\": \"a rational agent should choose the action that maximizes the agent's expected utility.\",\n",
        "\"policy\": \"a solution to the MDP.\",\n",
        "\"Lotteries\" : \"The set of outcomes for each action\",\n",
        "\"environment history\": \"sequence of states and actions\",\n",
        "\"Six constraints\": \"Orderability, Transitivity, Continuity, Substitutability, Monotonicity, Decomposability\",\n",
        "\"Orderability\": \"A rational agent must either prefer one to the other or else rate the two as equally preferable\",\n",
        "\"Transitivity\": \"It an agent prefers A to B and prefers B to C, then they must prefer A to C\",\n",
        "\"Continuity\": \"If some lottery B is between A and C, then there is some probability p that the agent will be indifferent.\",\n",
        "\"Substitutability\": \"If an agent is indifferent between two lotteries A and B,then the agent is indifferent between two more complex lotteries\",\n",
        "\"Monotonicity\": \"If 2 lotteries have same outcomes and an agent prefers A to B, then the agent must prefer the lottery that has a higher P(A)\",\n",
        "\"Decomposability\": \"Compound lotteries can be reduced to simpler ones using the laws of probability.\",\n",
        "\"Principle of Maximum Expected Utility\": \"A rational agent should choose the action that maximizes its expected utility, given its knowledge\",\n",
        "\"Normalized utilities\": \"$u_+ = 1.0, u_- = 0.0$\",\n",
        "\"Micromorts\": \"one-millionth chance of death, useful for paying to reduce product risks, etc.\",\n",
        "\"QALYs\": \"quality-adjusted life years, useful for medical decisions involving substantial risk\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 88,
      "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": 1692
        },
        "outputId": "60a31953-7475-4cec-db59-259aafaac58e"
      },
      "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\", chapter16),\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": 89,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$  \n MDP is a sequential decision problem, fully observable environment, stochastic transition model, additive rewards.\nMDP is a non deterministic search (it is stochastic). Think: millenium Falcon asteroid field grid. There's a percent\nchance that the falcon will do what you tell it to. ex. 80% chance it does what you say means, [Up, Up, Right, Right, Right] = [0.8*0.8*0.8*0.8] = 0.32776; \nbut you also need to add this value to the mult of values that turn out to take you to the right place despite going the wrong way. \nDefine a utility or reward function for the agent - given immediately for every state moved into; could be positive or negative \n(if you bump into an asteroid, negative, if you get closer to falcon, positive). In this way, agents can receive a reward at each time step rather than \njust at the goal step.  \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n\n\nYou need: a set of states S, a set of actions A, a transition function T(s, a s'), probability that executing action a in s will lead to s' P(s' | s, a). \nThis probability is called the model. A reward function R(s, a, s'), initial state s_0, and one or more terminal states.\nBecause there's uncertainty in MDPs, a solution to an MDP is a policy, not just a path. Policies map from a state onto the action to take if the agent\nis in that state. Even if the same policy is executed multiple times, it made lead to different environment histories. We need to compute the expected \nutility of all possible paths generated by a policy. Utility function U_h takes in an environment history and returns the sum of the rewards for the \ntransitions it takes: $U_h([s_0, a_0, s_1, a_1, ..., s_n]) = R(s_0, a_0, s_1) + R(s_1, a_1, s_2)+ ... + R(s_{n-1}, a_{n-1}, s_n)$. Maximize rewards, always \ntake the earliest rewards you can get, because later on there's a chance you won't get them (stochastic).\nDiscounting -- rewards decay exponentially with every step. Sooner rewards probably have higher utility than later rewarsd. \nEx. discount of 0.5: $U([1,2,3]) = 0.5^0*1 + 0.5^1*2 + 0.5^2*3$. Infinite Utilites (i.e. game lasts forever) - how to deal with it: finite horizon \n(terminate episodes after a fixed T steps), discounting: use 0 < \\gamma < 1, absorbing state that guarantees that for every policy, a terminal state will \neventually be reached. Recursive definition of value: $V*(s) = maxQ*(s,a), Q*(s,a) = \\sum_{s'} T(s,a,s')[R(s,a,s') + \\gammaV*(s'), V*(s) = max \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gammaV*(s')$\nValue iteration, start at the lowest leaf and work upwards. Ex. the millenium falcon value iteration cruising, punch it, crash. At each level, max(probability of each action * (est. \nvalue of each action + future reward -- later down the tree)). V_0 always starts with all values as 0. \n\n\n\n\nSix constrains that we require any reasonable preference relation to obey.\n\n \n\nComputing actions from Q values instead of from the values themselves will help you simplify the decision making process. $\\pi*(s) = arg max Q*(s,a)$\nPolicy Iteration - combine the idea of evaluating a policy, and improving it:\nStep 1. Policy Evaluation: calculate utilities for some fixed policy (not optimal utilities) until convergence. Step 2: Policy improvement: update policy\nusing one-step look-ahead with resulting converged (but not optimal) utilities as future values. Repeat until policy converges. THIS IS OPTIMAL. \n\n\n## AIMA Chapter 16.3 Utility Functions\n\nValue iteration: Every iteration updates both the values and (implicitly) the policy. We don't track the policy, but taking the max over actions implicitly recomputes it. \n\n \nPolicy iteration: We do several passes that update utilities with fixed policy (each pass is ast because we consider only one action, not all of them). After the policy \nevaluate, a new policy is chosen (slow like a value iteration pass). The new policy will be better.\n\n \n\nSummary: \n\n 1. So you want to compute the values: use value iteration or policy iteration\n\n 2. Compute values for a particular policy: use policy evaluation\n\n 3. Turn your values into a policy: use policy extraction (one-step lookahead)\n\n\n Principle of Maximum Expected Utility: \nFor worst-case minimax reasoning, terminal function scale doesn't matter; want better states to have higher evaluations = insensitivity to monotonic transormations.\n\n  \n\n## Module 8 Definitions\n* **Utility function** - Captures an agent's preferences, assigns a single number to express the desirability of a state.\n* **Expected utility** - Average utility value of the outcomes, weighted by the probability that the outcome occurs. $EU(a|e) = \\sum_s' P(RESULT(a) = s'|s,a)$ \n* **Principle of maximum expected utility** - a rational agent should choose the action that maximizes the agent's expected utility.\n* **Policy** - a solution to the MDP.\n* **Lotteries** - The set of outcomes for each action\n* **Environment history** - sequence of states and actions\n* **Six constraints** - Orderability, Transitivity, Continuity, Substitutability, Monotonicity, Decomposability\n* **Orderability** - A rational agent must either prefer one to the other or else rate the two as equally preferable\n* **Transitivity** - It an agent prefers A to B and prefers B to C, then they must prefer A to C\n* **Continuity** - If some lottery B is between A and C, then there is some probability p that the agent will be indifferent.\n* **Substitutability** - If an agent is indifferent between two lotteries A and B,then the agent is indifferent between two more complex lotteries\n* **Monotonicity** - If 2 lotteries have same outcomes and an agent prefers A to B, then the agent must prefer the lottery that has a higher P(A)\n* **Decomposability** - Compound lotteries can be reduced to simpler ones using the laws of probability.\n* **Principle of maximum expected utility** - A rational agent should choose the action that maximizes its expected utility, given its knowledge\n* **Normalized utilities** - $u_+ = 1.0, u_- = 0.0$\n* **Micromorts** - one-millionth chance of death, useful for paying to reduce product risks, etc.\n* **Qalys** - quality-adjusted life years, useful for medical decisions involving substantial risk\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": [
        "# Lecture notes \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",
        "module9_lecture_notes = \"\"\" \n",
        "Reinforcement Learning - receiving feedback in the form of rewards, agent's utility is defined by the reward function, must learn to act to maximize expected rewards, all learning is based on observed samples of outcomes. \n",
        "\\n Still assume a MDP - set of states, actions, a model T(s, a, s'), and a reward function R(s, a, s'), still looking for policy $\\pi(s)$. But now, we don't know T or R. \n",
        "\\n Model Based Learning: learn an approximate model based on expereinces. Solve for values as if the learning model were correct. \n",
        "\\n Step 1: Learn empirical MDP model - count outcomes s' for each s, a. Normalize to give an estimate of T(s, a, s') discover each R(s, a, s') when we experience (s, a, s').\n",
        "\\n Step 2: Solve the learned MDP - for example, use value iteration, as before. \n",
        "\\n Passive Reinforcement Learning\n",
        "\\n Simplified Task: policy evaluation. Input: A fixed policy \\pi(s). You don't know the transitions or rewards. --> Goal: learn the state values. \n",
        "\\n In this case, learner is \"along for the ride\". Doe not choose actions, just executes from expereinces. NOT offline planning. You take actions in the world.\n",
        "\\n Direct Evaluation --> Goal: computd values for each state under \\pi. \n",
        "\\n idea is to average together observed sample values. \n",
        "\\n pros of direct evaluation: easy to understnad, doesn't reqire knowledge.\n",
        "\\n cons of direct evaluation: wastes information about state onnections, each state must be learned separately = takes a while to learn.ee\n",
        "\\n Q-learning: sample based q-value iteration. $Q_{k+1}(s, a) <= \\sumT(s,a,s')[R(s,a,s') + \\gammamaxQ_k(s', a'())$. Converges to optimal policy, even if acting suboptimally. Called off-policy learning. \n",
        "\"\"\"\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"policy evaluation\" : \"given a policy pi, calculate the utility of each state if $\\pi_i$ were executed\",\n",
        "\"policy improvement\":\"Calculate new max exp. utility policy using one-step look-ahead\",\n",
        "\"Partially observable MDP\":\"same as MDP, but also has a sensor model that specifies the probability of perceiving evidence e in state s.\",\n",
        "\"dynamic beysian network\":\"factored reperesentations; represent transition and sensor models\",\n",
        "\"utility based agent\":\"learns a utility function on states and uses it to select actions that maximize the expected outcome utility\",\n",
        "\"Q learning agent\":\"learns agent-utility function, gives expected utility at each state\",\n",
        "\"reflex agent\":\"learns a policy, makes from states to actions\",\n",
        "\"passive learning\":\"agent's policy is fixd, task it to learn utilities of states\",\n",
        "\"active learning\":\"agent must also learn what to do\",\n",
        "\"exploration\":\"explore the environment to learn how to behave in it\",\n",
        "\n",
        "}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 881
        },
        "outputId": "4c6287b3-1630-4534-f990-60ae773d6575"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## Module 9 Lecture Notes\n \nReinforcement Learning - receiving feedback in the form of rewards, agent's utility is defined by the reward function, must learn to act to maximize expected rewards, all learning is based on observed samples of outcomes. \n\n Still assume a MDP - set of states, actions, a model T(s, a, s'), and a reward function R(s, a, s'), still looking for policy $\\pi(s)$. But now, we don't know T or R. \n\n Model Based Learning: learn an approximate model based on expereinces. Solve for values as if the learning model were correct. \n\n Step 1: Learn empirical MDP model - count outcomes s' for each s, a. Normalize to give an estimate of T(s, a, s') discover each R(s, a, s') when we experience (s, a, s').\n\n Step 2: Solve the learned MDP - for example, use value iteration, as before. \n\n Passive Reinforcement Learning\n\n Simplified Task: policy evaluation. Input: A fixed policy \\pi(s). You don't know the transitions or rewards. --> Goal: learn the state values. \n\n In this case, learner is \"along for the ride\". Doe not choose actions, just executes from expereinces. NOT offline planning. You take actions in the world.\n\n Direct Evaluation --> Goal: computd values for each state under \\pi. \n\n idea is to average together observed sample values. \n\n pros of direct evaluation: easy to understnad, doesn't reqire knowledge.\n\n cons of direct evaluation: wastes information about state onnections, each state must be learned separately = takes a while to learn.ee\n\n Q-learning: sample based q-value iteration. $Q_{k+1}(s, a) <= \\sumT(s,a,s')[R(s,a,s') + \\gammamaxQ_k(s', a'())$. Converges to optimal policy, even if acting suboptimally. Called off-policy learning. \n\n\n## Module 9 Definitions\n* **Policy evaluation** - given a policy pi, calculate the utility of each state if $\\pi_i$ were executed\n* **Policy improvement** - Calculate new max exp. utility policy using one-step look-ahead\n* **Partially observable mdp** - same as MDP, but also has a sensor model that specifies the probability of perceiving evidence e in state s.\n* **Dynamic beysian network** - factored reperesentations; represent transition and sensor models\n* **Utility based agent** - learns a utility function on states and uses it to select actions that maximize the expected outcome utility\n* **Q learning agent** - learns agent-utility function, gives expected utility at each state\n* **Reflex agent** - learns a policy, makes from states to actions\n* **Passive learning** - agent's policy is fixd, task it to learn utilities of states\n* **Active learning** - agent must also learn what to do\n* **Exploration** - explore the environment to learn how to behave in it\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 10 - Probabilities and Language Models"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\"\n",
        "\n",
        "The probability of any possible world is between 0 and 1, the total probability (sum) of the set of all possible worlds is 1. \n",
        "\\n Probabilistic models: \n",
        "\\n - random variables with domains\n",
        "\\n - assignments called outcomes\n",
        "\\n - joint distributions : say whether assignments are likely\n",
        "\\n - normalized: sum to 1\n",
        "\\n - ideally, only certified veriables directly interact.\n",
        "\\n Bayes' -- $P(x, y) = P(x|y)P(y) = P(y|x)P(x)$; \n",
        "\\n $P(x|y) = \\div{p(y|x)}{p(y)} * P(x)$.\n",
        "\\n Probabilistic Language Models (autocomplete text, machine translation, spelling correction , speech recog.)\n",
        "\\n Chain Rule - $P(B|a) = P(A, B)/P(A)$, $P(A,B) = P(A)P(B|A)$\n",
        " \"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"term\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 490
        },
        "outputId": "1100dc93-1e09-4cd6-8213-a5a72a6effde"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## Module 10 Lecture Notes\n\n\nThe probability of any possible world is between 0 and 1, the total probability (sum) of the set of all possible worlds is 1. \n\n Probabilistic models: \n\n - random variables with domains\n\n - assignments called outcomes\n\n - joint distributions : say whether assignments are likely\n\n - normalized: sum to 1\n\n - ideally, only certified veriables directly interact.\n\n Bayes' -- $P(x, y) = P(x|y)P(y) = P(y|x)P(x)$; \n\n $P(x|y) = \\div{p(y|x)}{p(y)} * P(x)$.\n\n Probabilistic Language Models (autocomplete text, machine translation, spelling correction , speech recog.)\n\n Chain Rule - $P(B|a) = P(A, B)/P(A)$, $P(A,B) = P(A)P(B|A)$\n \n\n## Module 10 Definitions\n* **Term** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 11 - Probabilistic Reasoning and Bayes’ Nets"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "chapter13_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter13_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\"\n",
        "The probability of any possible world is between 0 and 1, the total probability (sum) of the set of all possible worlds is 1. \n",
        "\\n Probabilistic models: \n",
        "\\n - random variables with domains\n",
        "\\n - assignments called outcomes\n",
        "\\n - joint distributions : say whether assignments are likely\n",
        "\\n - normalized: sum to 1\n",
        "\\n - ideally, only certified veriables directly interact.\n",
        "\\n Consider two problems using full joint distribution tables as our probabilistic models.\n",
        "\\n Bayes' nets is a technique for describing complex joint distributions using simple, local distributions - graphical models - \n",
        "to describe how variables locally interact to give global indirect interactions.\n",
        "\\n Size of joint distribution over N boolean variables = $2^n$\n",
        "\\n Size of N-node net if nodes have up to k parents - $O(N*2^{k+1})$. \n",
        "\\n Causal Chains - X = low pressure, Y = rain, Z = traffic; $P(x, y, z) = P(x) P(y|x) P(z|y)$\n",
        "\\n inference by enumeration is slow\n",
        "\\n variable elimination is faster, still np-hard.\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"decision theory\" : \"probability theory + utility theory\",    \n",
        "\"maximum expected utility (MEU) theory\" : \"an agent is rational iff it chooses the action twith heighest EU, avgd over all the outcomes of the action.\",    \n",
        "\"full joint probability distribution\" : \"probability model is completely determined by the joint distribution for all the random variables.\",    \n",
        "# \"inclusion-exclusion priniple\" : \"\"\"formula for p(disjunction) - $P(a \\union b) = P(a) + P(b) - P(a \\intersect b)$\"\"\"\n",
        "}\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 906
        },
        "cellView": "form",
        "outputId": "aa129df8-b738-4919-82c4-a1087321ee45"
      },
      "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": null,
      "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\nThe probability of any possible world is between 0 and 1, the total probability (sum) of the set of all possible worlds is 1. \n\n Probabilistic models: \n\n - random variables with domains\n\n - assignments called outcomes\n\n - joint distributions : say whether assignments are likely\n\n - normalized: sum to 1\n\n - ideally, only certified veriables directly interact.\n\n Consider two problems using full joint distribution tables as our probabilistic models.\n\n Bayes' nets is a technique for describing complex joint distributions using simple, local distributions - graphical models - \nto describe how variables locally interact to give global indirect interactions.\n\n Size of joint distribution over N boolean variables = $2^n$\n\n Size of N-node net if nodes have up to k parents - $O(N*2^{k+1})$. \n\n Causal Chains - X = low pressure, Y = rain, Z = traffic; $P(x, y, z) = P(x) P(y|x) P(z|y)$\n\n inference by enumeration is slow\n\n variable elimination is faster, still np-hard.\n\n## Module 11 Definitions\n* **Decision theory** - probability theory + utility theory\n* **Maximum expected utility (meu) theory** - an agent is rational iff it chooses the action twith heighest EU, avgd over all the outcomes of the action.\n* **Full joint probability distribution** - probability model is completely determined by the joint distribution for all the random variables.\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",
        "Machine learning: how to acquire a model from data / experience \n",
        "\\n - learning parameters (e.g. probabilities)\n",
        "\\n - learning structure (e.g. BN graphs)\n",
        "\\n - learning hidden concepts (e.g. clustering)\n",
        "\\n Model-based classification: \n",
        "\\n - build a model (e.g. Bayes' net) where both label and features are common vars\n",
        "\\n - instantiate any observed features\n",
        "\\n - Query for the distribution o thelabl conditioned on the features. \n",
        "\\n Naive Bayes for text - bag of words\n",
        "\\n Insensitive to word order/reordering. Each position is identially distributed, all pos shared the same conditional probability.\n",
        "\\n linear classifiers: inputs are feature values, each features has weight, sum is activation. \n",
        "\\n properties of perceptrons: seperability: true if some parameters get the training set perfectly correct, convergence if the training set is seperable, perceptron will eventually converge(binary case), mistake bound: the maximum number of mistakes (binary case) related to the margin or degree of separability. \n",
        "\\n Comparing Classification Methods:\n",
        "\\n \\tab Naive Bayes:\n",
        "\\n \\tab - Builds a model training data\n",
        "\\n \\tab - Gives prediction probabilities\n",
        "\\n \\tab - Strong assumptions abotu feature independence\n",
        "\\n \\tab - One pass through data (counting)\n",
        "\n",
        "\\n Perceptrons / MIRA\n",
        "\\n \\tab - Makes less assumptions about the data\n",
        "\\n \\tab - mistake-driven learning\n",
        "\\n \\tab - multiple passes through data (prediction)\n",
        "\\n \\tab - more accurate\n",
        "\n",
        "\\n \\n problems with perceptron: \n",
        "\\n If the data isn't seperable, weights might thrash. \n",
        "\\n mediocre generalization: finds a \"barely\" seperating solution.\n",
        "\\n overtraining: test / held-out accuracy usually rises, then falls.\n",
        "\n",
        "\\n non linear separators: original eatures space can always be mapped to some higher-dimensional space where training set is seperable.\n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"training set\" : \"definition\",    \n",
        "\"held out set\" : \"definition\",    \n",
        "\"test set\" : \"definition\",    \n",
        "\"features\" : \"attribute-value pairs which characterize each x\",    \n",
        "\"experimentation cycle\" : \"learn parameters on training set, tune parameters, never peek at test set.\", \n",
        "\"Overfitting\" : \"fitting the data too closely, does not generalize well\",  \n",
        "\"zero sum games\" : \"turn-taking, two-player, deterministic games, perfect information\",\n",
        "\"Pruning\" : \"ignore portions of the search tree\",\n",
        "\"evaluation functions\" : \"approximate the true utility of a state without doing a complete search\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",   \n",
        "}\n",
        "\n"
      ],
      "execution_count": 60,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1100
        },
        "outputId": "1d952005-10fa-4d69-fb88-f0d911e808cb"
      },
      "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": 59,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## Module 12 Lecture Notes\n \nMachine learning: how to acquire a model from data / experience \n\n - learning parameters (e.g. probabilities)\n\n - learning structure (e.g. BN graphs)\n\n - learning hidden concepts (e.g. clustering)\n\n Model-based classification: \n\n - build a model (e.g. Bayes' net) where both label and features are common vars\n\n - instantiate any observed features\n\n - Query for the distribution o thelabl conditioned on the features. \n\n Naive Bayes for text - bag of words\n\n Insensitive to word order/reordering. Each position is identially distributed, all pos shared the same conditional probability.\n\n linear classifiers: inputs are feature values, each features has weight, sum is activation. \n\n properties of perceptrons: seperability: true if some parameters get the training set perfectly correct, convergence if the training set is seperable, perceptron will eventually converge(binary case), mistake bound: the maximum number of mistakes (binary case) related to the margin or degree of separability. \n\n Comparing Classification Methods:\n\n \tab Naive Bayes:\n\n \tab - Builds a model training data\n\n \tab - Gives prediction probabilities\n\n \tab - Strong assumptions abotu feature independence\n\n \tab - One pass through data (counting)\n\n\n Perceptrons / MIRA\n\n \tab - Makes less assumptions about the data\n\n \tab - mistake-driven learning\n\n \tab - multiple passes through data (prediction)\n\n \tab - more accurate\n\n\n \n problems with perceptron: \n\n If the data isn't seperable, weights might thrash. \n\n mediocre generalization: finds a \"barely\" seperating solution.\n\n overtraining: test / held-out accuracy usually rises, then falls.\n\n\n non linear separators: original eatures space can always be mapped to some higher-dimensional space where training set is seperable.\n \n\n## Module 12 Definitions\n* **Training set** - definition\n* **Held out set** - definition\n* **Test set** - definition\n* **Features** - attribute-value pairs which characterize each x\n* **Experimentation cycle** - learn parameters on training set, tune parameters, never peek at test set.\n* **Overfitting** - fitting the data too closely, does not generalize well\n* **** - definition\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "# Module 13 - Neural Networks"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Jurafsky and Martin, Speech and Language Processing Chapter 5 “Logistic Regression” (5.1-5.6)\n",
        "\n",
        "# slp_chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter5_2 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter5_3 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter5_4 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter5_5 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter5_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# # Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "# slp_chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter7_6 = \"\"\" Your summary here \"\"\"\n",
        "# slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" \n",
        "Classifier components: feature representation of input, classification function, objective function, optimizing\n",
        "\\n probabilities: $P(y = q) = \\sigma(w * x + b) = \\frac{1}{1+e^{-(w*x+b)}}\n",
        "\\n Decision boundary: $1 if P(y = 1|x) > 0.5$, $0$ otherwise.\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"feature representation\" : \"for each input observation $x^i$, this will be a vector of features $[x_1, x_2...x_n]$.\",\n",
        "\"Classificiation function\": \"computes the estimated class $\\hat y$ via $p(y|x)$.\",    \n",
        "\"Objective function\": \"for learning, usually involving minimizing error on training examples.\",    \n",
        "\"optimizing\": \"an algo to optimize the objective function\",    \n",
        "\"cross entropy loss function\": \"loss function across which weights are labeled.\",    \n",
        "\"gradient descent to perform optimiation\": \"\",    \n",
        "\"error back propagation to compute the gradient of the loss function\": \"\",    \n",
        "\"logistic regression\": \"fitting the weights of the model to minimize loss on a dataset\",    \n",
        "\"gradient descent\": \"minimizing cost - optimize moving in the direction of steepest descent.\",    \n",
        "\"regularization\": \" tecnique to tune the func by adding penalty term in error function\",    \n",
        "\"multinomial logistic regression\": \"(multiple classes) used when the dependent variable in question is nominal - can fall into any set of categories, cannot be ordered meaningfully.\", \n",
        "\"XOR problem\": \"the problem of using a neural network to predict the outputs of XOR logic gates given two binary inputs.\", \n",
        "\"feedforward neural network\": \"an artificial neural network wherein connections between the nodes do not form a cycle\", \n",
        "\"logistic regression tb\": \"supervised ML classifier that extracts real-valued features from input, multiplies by w, sums, and passes sum through sigmoid to generate prob\", \n",
        "\"softmax function\": \"used to compute probabilities\", \n",
        "\"convez optimization\": \"ex. minimizing loss function\",    \n",
        "\"\": \"\",    \n",
        "\"\": \"\",    \n",
        "\"\": \"\",    \n",
        "}\n"
      ],
      "execution_count": 65,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 654
        },
        "outputId": "c52a7b67-665f-4bae-8123-22e5c19550b0"
      },
      "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": 66,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## Module 13 Lecture Notes\n \nClassifier components: feature representation of input, classification function, objective function, optimizing\n\n probabilities: $P(y = q) = \\sigma(w * x + b) = \frac{1}{1+e^{-(w*x+b)}}\n\n Decision boundary: $1 if P(y = 1|x) > 0.5$, $0$ otherwise.\n\n## Module 13 Definitions\n* **Feature representation** - for each input observation $x^i$, this will be a vector of features $[x_1, x_2...x_n]$.\n* **Classificiation function** - computes the estimated class $\\hat y$ via $p(y|x)$.\n* **Objective function** - for learning, usually involving minimizing error on training examples.\n* **Optimizing** - an algo to optimize the objective function\n* **Cross entropy loss function** - loss function across which weights are labeled.\n* **Gradient descent to perform optimiation** - \n* **Error back propagation to compute the gradient of the loss function** - \n* **Logistic regression** - fitting the weights of the model to minimize loss on a dataset\n* **Gradient descent** - minimizing cost - optimize moving in the direction of steepest descent.\n* **Regularization** -  tecnique to tune the func by adding penalty term in error function\n* **Multinomial logistic regression** - (multiple classes) used when the dependent variable in question is nominal - can fall into any set of categories, cannot be ordered meaningfully.\n* **Xor problem** - the problem of using a neural network to predict the outputs of XOR logic gates given two binary inputs.\n* **Feedforward neural network** - an artificial neural network wherein connections between the nodes do not form a cycle\n* **Logistic regression tb** - supervised ML classifier that extracts real-valued features from input, multiplies by w, sums, and passes sum through sigmoid to generate prob\n* **Softmax function** - used to compute probabilities\n* **Convez optimization** - ex. minimizing loss function\n* **** - \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",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" \n",
        "Word2Vec: instead of counting how often each word w occurs near \"apricot\", train a classifier on a binary prediction task (how likely is w to show up near \"apricot\"?)\n",
        "\\n in Simple RNN sequences are processed one element at a time. Can be trained with straightforward extension o the backpropagation algorithm (BPTT)  \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"self-attention layer\" : \"maps input sequences to output sequences of the same length based on a set of attention heads\", \n",
        "\"probabilistic language modeling\" : \"assigning a probability to a sequence, or to the next selement o a sequence given preceding words\",    \n",
        "\"auto-regressive generation using a trained language model\" : \"definition\",    \n",
        "\"sequence labeling, POS-tagging\" : \"definition\",    \n",
        "\"Sequence classification\" : \"entire text assigned to a category, as spam detection, sentiment, or topic.\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 72,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 416
        },
        "outputId": "b3a86968-58e7-46ee-f559-321ca9298251"
      },
      "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": 74,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## Module 13 Lecture Notes\n \nClassifier components: feature representation of input, classification function, objective function, optimizing\n\n probabilities: $P(y = q) = \\sigma(w * x + b) = \frac{1}{1+e^{-(w*x+b)}}\n\n Decision boundary: $1 if P(y = 1|x) > 0.5$, $0$ otherwise.\n\n## Module 14 Definitions\n* **Self-attention layer** - maps input sequences to output sequences of the same length based on a set of attention heads\n* **Probabilistic language modeling** - assigning a probability to a sequence, or to the next selement o a sequence given preceding words\n* **Auto-regressive generation using a trained language model** - definition\n* **Sequence labeling, pos-tagging** - definition\n* **Sequence classification** - entire text assigned to a category, as spam detection, sentiment, or topic.\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        ""
      ],
      "metadata": {
        "id": "5AYZQZy2g2zn"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "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": 6003
        },
        "id": "T3cm1WV542_a",
        "outputId": "6569d744-b679-418c-e03d-0ff4283ce3a5"
      },
      "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": 92,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 8: Markov Decision Processes\n## AIMA Chapter 16\n Chapter 16.1 summary.  $P(\\textnormal{RESULT}(a)=s') = \\sum_s P(s)P(s'|s,a)$  \n MDP is a sequential decision problem, fully observable environment, stochastic transition model, additive rewards.\nMDP is a non deterministic search (it is stochastic). Think: millenium Falcon asteroid field grid. There's a percent\nchance that the falcon will do what you tell it to. ex. 80% chance it does what you say means, [Up, Up, Right, Right, Right] = [0.8*0.8*0.8*0.8] = 0.32776; \nbut you also need to add this value to the mult of values that turn out to take you to the right place despite going the wrong way. \nDefine a utility or reward function for the agent - given immediately for every state moved into; could be positive or negative \n(if you bump into an asteroid, negative, if you get closer to falcon, positive). In this way, agents can receive a reward at each time step rather than \njust at the goal step.  \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n\n\nYou need: a set of states S, a set of actions A, a transition function T(s, a s'), probability that executing action a in s will lead to s' P(s' | s, a). \nThis probability is called the model. A reward function R(s, a, s'), initial state s_0, and one or more terminal states.\nBecause there's uncertainty in MDPs, a solution to an MDP is a policy, not just a path. Policies map from a state onto the action to take if the agent\nis in that state. Even if the same policy is executed multiple times, it made lead to different environment histories. We need to compute the expected \nutility of all possible paths generated by a policy. Utility function U_h takes in an environment history and returns the sum of the rewards for the \ntransitions it takes: $U_h([s_0, a_0, s_1, a_1, ..., s_n]) = R(s_0, a_0, s_1) + R(s_1, a_1, s_2)+ ... + R(s_{n-1}, a_{n-1}, s_n)$. Maximize rewards, always \ntake the earliest rewards you can get, because later on there's a chance you won't get them (stochastic).\nDiscounting -- rewards decay exponentially with every step. Sooner rewards probably have higher utility than later rewarsd. \nEx. discount of 0.5: $U([1,2,3]) = 0.5^0*1 + 0.5^1*2 + 0.5^2*3$. Infinite Utilites (i.e. game lasts forever) - how to deal with it: finite horizon \n(terminate episodes after a fixed T steps), discounting: use 0 < \\gamma < 1, absorbing state that guarantees that for every policy, a terminal state will \neventually be reached. Recursive definition of value: $V*(s) = maxQ*(s,a), Q*(s,a) = \\sum_{s'} T(s,a,s')[R(s,a,s') + \\gammaV*(s'), V*(s) = max \\sum_{s'}T(s,a,s')[R(s,a,s') + \\gammaV*(s')$\nValue iteration, start at the lowest leaf and work upwards. Ex. the millenium falcon value iteration cruising, punch it, crash. At each level, max(probability of each action * (est. \nvalue of each action + future reward -- later down the tree)). V_0 always starts with all values as 0. \n\n\n\n\nSix constrains that we require any reasonable preference relation to obey.\n\n \n\nComputing actions from Q values instead of from the values themselves will help you simplify the decision making process. $\\pi*(s) = arg max Q*(s,a)$\nPolicy Iteration - combine the idea of evaluating a policy, and improving it:\nStep 1. Policy Evaluation: calculate utilities for some fixed policy (not optimal utilities) until convergence. Step 2: Policy improvement: update policy\nusing one-step look-ahead with resulting converged (but not optimal) utilities as future values. Repeat until policy converges. THIS IS OPTIMAL. \n\n\n## AIMA Chapter 16.3 Utility Functions\n\nValue iteration: Every iteration updates both the values and (implicitly) the policy. We don't track the policy, but taking the max over actions implicitly recomputes it. \n\n \nPolicy iteration: We do several passes that update utilities with fixed policy (each pass is ast because we consider only one action, not all of them). After the policy \nevaluate, a new policy is chosen (slow like a value iteration pass). The new policy will be better.\n\n \n\nSummary: \n\n 1. So you want to compute the values: use value iteration or policy iteration\n\n 2. Compute values for a particular policy: use policy evaluation\n\n 3. Turn your values into a policy: use policy extraction (one-step lookahead)\n\n\n Principle of Maximum Expected Utility: \nFor worst-case minimax reasoning, terminal function scale doesn't matter; want better states to have higher evaluations = insensitivity to monotonic transormations.\n\n  \n\n## Module 8 Definitions\n* **Utility function** - Captures an agent's preferences, assigns a single number to express the desirability of a state.\n* **Expected utility** - Average utility value of the outcomes, weighted by the probability that the outcome occurs. $EU(a|e) = \\sum_s' P(RESULT(a) = s'|s,a)$ \n* **Principle of maximum expected utility** - a rational agent should choose the action that maximizes the agent's expected utility.\n* **Policy** - a solution to the MDP.\n* **Lotteries** - The set of outcomes for each action\n* **Environment history** - sequence of states and actions\n* **Six constraints** - Orderability, Transitivity, Continuity, Substitutability, Monotonicity, Decomposability\n* **Orderability** - A rational agent must either prefer one to the other or else rate the two as equally preferable\n* **Transitivity** - It an agent prefers A to B and prefers B to C, then they must prefer A to C\n* **Continuity** - If some lottery B is between A and C, then there is some probability p that the agent will be indifferent.\n* **Substitutability** - If an agent is indifferent between two lotteries A and B,then the agent is indifferent between two more complex lotteries\n* **Monotonicity** - If 2 lotteries have same outcomes and an agent prefers A to B, then the agent must prefer the lottery that has a higher P(A)\n* **Decomposability** - Compound lotteries can be reduced to simpler ones using the laws of probability.\n* **Principle of maximum expected utility** - A rational agent should choose the action that maximizes its expected utility, given its knowledge\n* **Normalized utilities** - $u_+ = 1.0, u_- = 0.0$\n* **Micromorts** - one-millionth chance of death, useful for paying to reduce product risks, etc.\n* **Qalys** - quality-adjusted life years, useful for medical decisions involving substantial risk\n\n\n# Module 9: Reinforcement Learning\n## Module 9 Lecture Notes\n \nReinforcement Learning - receiving feedback in the form of rewards, agent's utility is defined by the reward function, must learn to act to maximize expected rewards, all learning is based on observed samples of outcomes. \n\n Still assume a MDP - set of states, actions, a model T(s, a, s'), and a reward function R(s, a, s'), still looking for policy $\\pi(s)$. But now, we don't know T or R. \n\n Model Based Learning: learn an approximate model based on expereinces. Solve for values as if the learning model were correct. \n\n Step 1: Learn empirical MDP model - count outcomes s' for each s, a. Normalize to give an estimate of T(s, a, s') discover each R(s, a, s') when we experience (s, a, s').\n\n Step 2: Solve the learned MDP - for example, use value iteration, as before. \n\n Passive Reinforcement Learning\n\n Simplified Task: policy evaluation. Input: A fixed policy \\pi(s). You don't know the transitions or rewards. --> Goal: learn the state values. \n\n In this case, learner is \"along for the ride\". Doe not choose actions, just executes from expereinces. NOT offline planning. You take actions in the world.\n\n Direct Evaluation --> Goal: computd values for each state under \\pi. \n\n idea is to average together observed sample values. \n\n pros of direct evaluation: easy to understnad, doesn't reqire knowledge.\n\n cons of direct evaluation: wastes information about state onnections, each state must be learned separately = takes a while to learn.ee\n\n Q-learning: sample based q-value iteration. $Q_{k+1}(s, a) <= \\sumT(s,a,s')[R(s,a,s') + \\gammamaxQ_k(s', a'())$. Converges to optimal policy, even if acting suboptimally. Called off-policy learning. \n\n\n## Module 9 Definitions\n* **Policy evaluation** - given a policy pi, calculate the utility of each state if $\\pi_i$ were executed\n* **Policy improvement** - Calculate new max exp. utility policy using one-step look-ahead\n* **Partially observable mdp** - same as MDP, but also has a sensor model that specifies the probability of perceiving evidence e in state s.\n* **Dynamic beysian network** - factored reperesentations; represent transition and sensor models\n* **Utility based agent** - learns a utility function on states and uses it to select actions that maximize the expected outcome utility\n* **Q learning agent** - learns agent-utility function, gives expected utility at each state\n* **Reflex agent** - learns a policy, makes from states to actions\n* **Passive learning** - agent's policy is fixd, task it to learn utilities of states\n* **Active learning** - agent must also learn what to do\n* **Exploration** - explore the environment to learn how to behave in it\n\n\n# Module 10: Probabilies and Language Models\n## Module 10 Lecture Notes\n\n\nThe probability of any possible world is between 0 and 1, the total probability (sum) of the set of all possible worlds is 1. \n\n Probabilistic models: \n\n - random variables with domains\n\n - assignments called outcomes\n\n - joint distributions : say whether assignments are likely\n\n - normalized: sum to 1\n\n - ideally, only certified veriables directly interact.\n\n Bayes' -- $P(x, y) = P(x|y)P(y) = P(y|x)P(x)$; \n\n $P(x|y) = \\div{p(y|x)}{p(y)} * P(x)$.\n\n Probabilistic Language Models (autocomplete text, machine translation, spelling correction , speech recog.)\n\n Chain Rule - $P(B|a) = P(A, B)/P(A)$, $P(A,B) = P(A)P(B|A)$\n \n\n## Module 10 Definitions\n* **Term** - your definition here\n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Your summary here \n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n Your summary here \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n Your summary here \n\n## Module 11 Lecture Notes\n\nThe probability of any possible world is between 0 and 1, the total probability (sum) of the set of all possible worlds is 1. \n\n Probabilistic models: \n\n - random variables with domains\n\n - assignments called outcomes\n\n - joint distributions : say whether assignments are likely\n\n - normalized: sum to 1\n\n - ideally, only certified veriables directly interact.\n\n Consider two problems using full joint distribution tables as our probabilistic models.\n\n Bayes' nets is a technique for describing complex joint distributions using simple, local distributions - graphical models - \nto describe how variables locally interact to give global indirect interactions.\n\n Size of joint distribution over N boolean variables = $2^n$\n\n Size of N-node net if nodes have up to k parents - $O(N*2^{k+1})$. \n\n Causal Chains - X = low pressure, Y = rain, Z = traffic; $P(x, y, z) = P(x) P(y|x) P(z|y)$\n\n inference by enumeration is slow\n\n variable elimination is faster, still np-hard.\n\n## Module 11 Definitions\n* **Decision theory** - probability theory + utility theory\n* **Maximum expected utility (meu) theory** - an agent is rational iff it chooses the action twith heighest EU, avgd over all the outcomes of the action.\n* **Full joint probability distribution** - probability model is completely determined by the joint distribution for all the random variables.\n\n\n# Module 12: Naive Bayes and Perceptrons\n## Module 12 Lecture Notes\n \nMachine learning: how to acquire a model from data / experience \n\n - learning parameters (e.g. probabilities)\n\n - learning structure (e.g. BN graphs)\n\n - learning hidden concepts (e.g. clustering)\n\n Model-based classification: \n\n - build a model (e.g. Bayes' net) where both label and features are common vars\n\n - instantiate any observed features\n\n - Query for the distribution o thelabl conditioned on the features. \n\n Naive Bayes for text - bag of words\n\n Insensitive to word order/reordering. Each position is identially distributed, all pos shared the same conditional probability.\n\n linear classifiers: inputs are feature values, each features has weight, sum is activation. \n\n properties of perceptrons: seperability: true if some parameters get the training set perfectly correct, convergence if the training set is seperable, perceptron will eventually converge(binary case), mistake bound: the maximum number of mistakes (binary case) related to the margin or degree of separability. \n\n Comparing Classification Methods:\n\n \tab Naive Bayes:\n\n \tab - Builds a model training data\n\n \tab - Gives prediction probabilities\n\n \tab - Strong assumptions abotu feature independence\n\n \tab - One pass through data (counting)\n\n\n Perceptrons / MIRA\n\n \tab - Makes less assumptions about the data\n\n \tab - mistake-driven learning\n\n \tab - multiple passes through data (prediction)\n\n \tab - more accurate\n\n\n \n problems with perceptron: \n\n If the data isn't seperable, weights might thrash. \n\n mediocre generalization: finds a \"barely\" seperating solution.\n\n overtraining: test / held-out accuracy usually rises, then falls.\n\n\n non linear separators: original eatures space can always be mapped to some higher-dimensional space where training set is seperable.\n \n\n## Module 12 Definitions\n* **Training set** - definition\n* **Held out set** - definition\n* **Test set** - definition\n* **Features** - attribute-value pairs which characterize each x\n* **Experimentation cycle** - learn parameters on training set, tune parameters, never peek at test set.\n* **Overfitting** - fitting the data too closely, does not generalize well\n* **** - definition\n* **Concept** - definition\n\n\n# Module 13: Neural Networks\n## Module 13 Lecture Notes\n \nClassifier components: feature representation of input, classification function, objective function, optimizing\n\n probabilities: $P(y = q) = \\sigma(w * x + b) = \frac{1}{1+e^{-(w*x+b)}}\n\n Decision boundary: $1 if P(y = 1|x) > 0.5$, $0$ otherwise.\n\n## Module 13 Definitions\n* **Feature representation** - for each input observation $x^i$, this will be a vector of features $[x_1, x_2...x_n]$.\n* **Classificiation function** - computes the estimated class $\\hat y$ via $p(y|x)$.\n* **Objective function** - for learning, usually involving minimizing error on training examples.\n* **Optimizing** - an algo to optimize the objective function\n* **Cross entropy loss function** - loss function across which weights are labeled.\n* **Gradient descent to perform optimiation** - \n* **Error back propagation to compute the gradient of the loss function** - \n* **Logistic regression** - fitting the weights of the model to minimize loss on a dataset\n* **Gradient descent** - minimizing cost - optimize moving in the direction of steepest descent.\n* **Regularization** -  tecnique to tune the func by adding penalty term in error function\n* **Multinomial logistic regression** - (multiple classes) used when the dependent variable in question is nominal - can fall into any set of categories, cannot be ordered meaningfully.\n* **Xor problem** - the problem of using a neural network to predict the outputs of XOR logic gates given two binary inputs.\n* **Feedforward neural network** - an artificial neural network wherein connections between the nodes do not form a cycle\n* **Logistic regression tb** - supervised ML classifier that extracts real-valued features from input, multiplies by w, sums, and passes sum through sigmoid to generate prob\n* **Softmax function** - used to compute probabilities\n* **Convez optimization** - ex. minimizing loss function\n* **** - \n\n\n# Module 14: Natural Language Processing\n## Module 13 Lecture Notes\n \nClassifier components: feature representation of input, classification function, objective function, optimizing\n\n probabilities: $P(y = q) = \\sigma(w * x + b) = \frac{1}{1+e^{-(w*x+b)}}\n\n Decision boundary: $1 if P(y = 1|x) > 0.5$, $0$ otherwise.\n\n## Module 14 Definitions\n* **Self-attention layer** - maps input sequences to output sequences of the same length based on a set of attention heads\n* **Probabilistic language modeling** - assigning a probability to a sequence, or to the next selement o a sequence given preceding words\n* **Auto-regressive generation using a trained language model** - definition\n* **Sequence labeling, pos-tagging** - definition\n* **Sequence classification** - entire text assigned to a category, as spam detection, sentiment, or topic.\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        ""
      ],
      "metadata": {
        "id": "DCzD8fSFiMVP"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}